Python公众号开发部分代码开源
這是一年前寫的代碼了,看看就好了,很多不規范的代碼,并且完全沒有面向對象(這是因為新浪sae限制太多)等等。由于在這個問題下面回答了之后很多人問我要源代碼,于是分享出來。你有哪些用計算機技能解決生活問題的經歷? - 路人甲的回答
主要功能目錄:
python基于新浪sae開發的微信公眾平臺,實現功能:
輸入任意內容---會有小黃人機器人聊天
輸入段子---回復笑話
輸入開源+文章---發送消息到開源中國
輸入快遞+訂單號---查詢快遞信息
輸入天氣---查詢南京最近五天天氣狀況
輸入微博熱點---回復微博當前熱門話題
輸入電影+名稱---回復百度云盤中搜索的鏈接
以及抓取美拍、秒拍、新浪熱門視頻在最后。
如何下載以下源碼以及獲取更多編程資源?只需要簡單兩步:
1、關注訂閱號:smcode2016
2、回復關鍵詞公眾號源碼即可獲得
最后如果你想學習如果做這個訂閱號,可以加我個人微信:18362983803 , 最近正在籌辦爬蟲零基礎課程,不完全免費,謝謝!
# -*- coding: utf-8 -*- import hashlib import web import lxml import time import os import urllib2,json import urllib import re import random import hashlib import cookielib from urllib import urlencode from lxml import etree from smtplib import SMTP_SSL from email.header import Header from email.mime.text import MIMETextclass WeixinInterface:def __init__(self):self.app_root = os.path.dirname(__file__)self.templates_root = os.path.join(self.app_root, 'templates')self.render = web.template.render(self.templates_root)def GET(self):#獲取輸入參數data = web.input()signature=data.signaturetimestamp=data.timestampnonce=data.nonceechostr=data.echostr#自己的tokentoken="weixin9047" #這里改寫你在微信公眾平臺里輸入的token#字典序排序list=[token,timestamp,nonce]list.sort()sha1=hashlib.sha1()map(sha1.update,list)hashcode=sha1.hexdigest()#sha1加密算法 #如果是來自微信的請求,則回復echostrif hashcode == signature:return echostrdef POST(self): str_xml = web.data() #獲得post來的數據xml = etree.fromstring(str_xml)#進行XML解析content=xml.find("Content").text#獲得用戶所輸入的內容msgType=xml.find("MsgType").textfromUser=xml.find("FromUserName").texttoUser=xml.find("ToUserName").textif(content == u"天氣"):url = "http://m.ip138.com/21/nanjing/tianqi/"headers = {'Connection': 'Keep-Alive','Accept': 'text/html, application/xhtml+xml, */*','Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3','User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}req = urllib2.Request(url, headers = headers)opener = urllib2.urlopen(req)html = opener.read()rex = r'(?<=img src="/image/s[0-9].gif" alt=").{1,6}(?=" />)'rexx = r'(?<=div class="temperature">).{5,15}(?=</div>)'n = re.findall(rex,html)m = re.findall(rexx,html)str_wether = ""for (i,j) in zip(m,n):str_wether = str_wether + j + " " +i + "\n"return self.render.reply_text(fromUser,toUser,int(time.time()),"最近五天天氣:\n"+str_wether)elif(content[0:2] == u"電影"):keyword = urllib.quote(content[2:].encode("utf-8"))url = "http://www.wangpansou.cn/s.php?q="+keywordheaders = {'Connection': 'Keep-Alive','Accept': 'text/html, application/xhtml+xml, */*','Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3','User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}req = urllib2.Request(url, headers = headers)opener = urllib2.urlopen(req)html = opener.read()rex = r'https?://pan.baidu.com.*\?uk=[0-9]{10}.*[\d+?]"'m = re.findall(rex,html) string = u""for i in m:string = string + i + "\n"return self.render.reply_text(fromUser,toUser,int(time.time()),u"以下是電影鏈接:\n"+string)elif(u"段子" in content):url_8 = "http://www.qiushibaike.com/"url_24 = "http://www.qiushibaike.com/hot/"headers = {'Connection': 'Keep-Alive','Accept': 'text/html, application/xhtml+xml, */*','Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3','User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}req_8 = urllib2.Request(url_8, headers = headers)req_24 = urllib2.Request(url_24,headers = headers)opener_8 = urllib2.urlopen(req_8)opener_24 = urllib2.urlopen(req_24)html_8 = opener_8.read()html_24 = opener_24.read()rex = r'(?<=div class="content">).*?(?=<!--)'m_8 = re.findall(rex,html_8,re.S)m_24 = re.findall(rex, html_24, re.S)m_8.extend(m_24)random.shuffle(m_8)return self.render.reply_text(fromUser,toUser,int(time.time()),m_8[0].replace('<br/>','')) elif(content[0:2] == u"開源"):url = "https://www.oschina.net/action/user/hash_login"urll = "http://www.oschina.net/action/tweet/pub"username = "904727147@qq.com"passw = ""#密碼肯定不會給你們的password = hashlib.sha1(passw).hexdigest()cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')]urllib2.install_opener(opener)data = {'email':username,'pwd':password}data_post = urllib.urlencode(data)opener.open(url, data_post)user = "2391943"msg = content[2:].encode("utf-8")user_code = "lPFz26r3ZIa1e3KyIWlzPNpJlaEmZqyh6dAWAotd"post = {'user_code':user_code,'user':user,'msg':msg}msg_post = urllib.urlencode(post)html = urllib2.urlopen(urll,msg_post).read()return self.render.reply_text(fromUser,toUser,int(time.time()),u"發送到開源中國動彈成功!") elif(content[0:2] == u"快遞"):keyword = content[2:]url = "http://www.kuaidi100.com/autonumber/autoComNum?text="+keywordcj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')]urllib2.install_opener(opener)html = urllib2.urlopen(url).read()jo = json.loads(html)typ = jo["auto"][0]['comCode']if(typ is None):return self.render.reply_text(fromUser,toUser,int(time.time()),u"請檢查你的定單號!") urll = "http://www.kuaidi100.com/query?type="+typ+"&postid="+keywordhtml_end = urllib2.urlopen(urll).read()jo_end = json.loads(html_end)if(jo_end["status"] == "201"):return self.render.reply_text(fromUser,toUser,int(time.time()),u"訂單號輸入有誤,請重新輸入!") text = jo_end["data"]string = u""for i in text:string = string + i["time"] + i["context"] + "\n"return self.render.reply_text(fromUser,toUser,int(time.time()),string) elif(content == u"微博熱點"):url = "http://weibo.cn/pub/?tf=5_005"headers = {'Connection': 'Keep-Alive','Accept': 'text/html, application/xhtml+xml, */*','Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3','User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}req = urllib2.Request(url, headers = headers)opener = urllib2.urlopen(req)html = opener.read().decode("utf-8")rex = r'(?<=div class="c"><a href=").{60,79}(?=</a>)'ss = re.findall(rex,html)string = u""for i in ss:string = string + i.replace('>','\n')+"\n"return self.render.reply_text(fromUser,toUser,int(time.time()),string.replace('"',''))elif(content == u"知乎信息"):username = '18362983803'password = ''#這是以前的密碼別嘗試了_xsrf='558c1b60725377c5810ae2484b26781e'url = r'https://www.zhihu.com/login/phone_num'cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')]data = urllib.urlencode({"phone_num":username,"password":password,'_xsrf':_xsrf})opener.open(url,data)html = opener.open('https://www.zhihu.com/noti7/new?r=1454793308655').read()jo = json.loads(html)data = jo[1]string = "增長了:"+str(data[0])+"個評論"+str(data[1])+"個粉絲"+str(data[2])+"個贊同"return self.render.reply_text(fromUser,toUser,int(time.time()),string)elif(content[0:2] == u"鬧鐘"):string = str(time.strftime("%H:%M", time.localtime()))if(string == content[2:]):mail_info = {"from": "904727147@qq.com","to": "904727147@qq.com","hostname": "smtp.qq.com","username": "904727147@qq.com","password": "himnbtwxa","mail_subject": "懶豬起床!","mail_text": "起床了,豬","mail_encoding": "utf-8"}smtp = SMTP_SSL(mail_info["hostname"])smtp.set_debuglevel(1)smtp.ehlo(mail_info["hostname"])smtp.login(mail_info["username"], mail_info["password"])msg = MIMEText(mail_info["mail_text"], "plain", mail_info["mail_encoding"])msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"])msg["from"] = mail_info["from"]msg["to"] = mail_info["to"]i = 0while(i<20):j = 0while(j<2): smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string())j = j + 1i = i + 1time.sleep(10)smtp.quit()return self.render.reply_text(fromUser,toUser,int(time.time()),string)return self.render.reply_text(fromUser,toUser,int(time.time()),string+u"879")elif(u"鐘志遠" in content):return self.render.reply_text(fromUser,toUser,int(time.time()),u"你想找全世界最帥的人干嘛?如果你是妹子,請加微信18362983803!漢子繞道!")elif(u"使用" in content):return self.render.reply_text(fromUser,toUser,int(time.time()),u"搜電影:電影+電影名,最近天氣:天氣,微博熱門:微博熱點,知乎信息:知乎信息,快遞查詢:快遞+單號,看笑話:段子,發送動彈到開源中國:開源+內容")else:url = r'http://www.xiaohuangji.com/ajax.php'cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')]string = urllib.quote(content.encode("utf-8"))try:data = urllib.urlencode({"para":string})html = opener.open(url,data).read() string = html+"\n----[回復[使用]]"return self.render.reply_text(fromUser,toUser,int(time.time()),string)except Exception,ex:return self.render.reply_text(fromUser,toUser,int(time.time()),u"我不想理你了~")提取視頻:
#encoding:utf-8 import urllib2 import cookielib import json import re def search():url = "http://www.miaopai.com/miaopai/index_api?cateid=2002&per=20&page=1"url2 = "http://www.meipai.com/medias/hot"cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.3.0')]urllib2.install_opener(opener)html = urllib2.urlopen(url).read()html2 = urllib2.urlopen(url2).read()rex = r'http://mvvideo2.meitudata.com/.*?mp4'rexx = r'http://mvimg1.meitudata.com/.*?320'value = re.findall(rex, html2)value2 = re.findall(rexx, html2)jo = json.loads(html)f = open('/root/Desktop/sp.html','wb')text = jo["result"]f.write('<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>24小時最熱視頻</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! --> <title>全網24小時最熱視頻</title> <!-- Bootstrap --> <link href="dist/css/bootstrap.min.css" rel="stylesheet"> <link href="css/css.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesnt work if you view the page via file:// --> <!--[if lt IE 9]> <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script><![endif]--><style>body {font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;background:#F4F2ED none repeat scroll 0% 0%;}</style></head><body class = "home-tempate"><div class = "container">')f.write('<center><div class="gradient"><div class="header"><h2>路人甲的視頻小站</h2><p>以下視頻收集新浪、美拍、秒拍網24小時內最熱視頻,如有侵權必刪</p><div class="clearfix"><a href="http://stchat.cn/zhihu.html" class="btn btn-success btn-lg">Try it now!</a></div></div></div><br><div class="container-fluid">')for i in text:f.write('<div class="row-fluid">')f.write('<video src="'+i["channel"]["stream"]["base"]+'" controls="controls" width="320" height="240"' + 'poster="' + i["channel"]["pic"]["base"] + '.jpg"></video></div>')for (i,j) in zip(value,value2):f.write('<div class="row-fluid">')f.write('<video src="'+i+'" controls="controls" width="320" height="240"' + 'poster="' + j+ '"></video></div>')f.write("</div><center></div></html>")f.flush()f.close()if __name__=='__main__':search()如何下載以上源碼以及獲取更多編程資源?只需要簡單兩步:
1、關注訂閱號:smcode2016
2、回復關鍵詞公眾號源碼即可獲得
最后看了這么多源碼?難道你不想關注我的專欄,看更多的源碼學習編程?:學習編程 - 知乎專欄
如果你想了解我,點擊這里:路人甲
作者:路人甲
鏈接:https://zhuanlan.zhihu.com/p/21284127
來源:知乎
總結
以上是生活随笔為你收集整理的Python公众号开发部分代码开源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一图看懂学位服:学位帽、学位袍、流苏、垂
- 下一篇: KMeans聚类算法Hadoop实现