python搭建微信公众平台

python基于新浪sae开发的微信公众平台,实现功能:

输入段子---回复笑话
输入开源+文章---发送消息到开源中国
输入快递+订单号---查询快递信息
输入天气---查询南京最近五天天气状况
输入微博热点---回复微博当前热门话题
输入电影+名称---回复百度云盘中搜索的链接

具体实现代码:

# -*- 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

class 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.signature
    timestamp=data.timestamp
    nonce=data.nonce
    echostr=data.echostr
    #自己的token
    token="weixin9047" #这里改写你在微信公众平台里输入的token
    #字典序排序
    list=[token,timestamp,nonce]
    list.sort()
    sha1=hashlib.sha1()
    map(sha1.update,list)
    hashcode=sha1.hexdigest()
    #sha1加密算法
    #如果是来自微信的请求,则回复echostr
    if hashcode == signature:
      return echostr

  def POST(self):
    str_xml = web.data() #获得post来的数据
    xml = etree.fromstring(str_xml)#进行XML解析
    content=xml.find("Content").text#获得用户所输入的内容
    msgType=xml.find("MsgType").text
    fromUser=xml.find("FromUserName").text
    toUser=xml.find("ToUserName").text
    if(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="+keyword
      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'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="+keyword
      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()
      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="+keyword
      html_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(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"我不想理你了~") 

以上就是本文的全部内容,希望对大家的学习有所帮助。

(0)

相关推荐

  • python轻松查到删除自己的微信好友

    前言 相信各位一定有收到过这样的群发短信,据说还被归类为玩转微信的五大技巧之一╮(╯▽╰)╭但,其实,只要跑一下脚本,就轻松找出删除自己的好友(轻松摔碎玻璃心,逃 原理 新建群组,如果加不进来就是被删好友了(不要在群组里讲话,别人是看不见的). 用的是微信网页版的接口,还有些小问题,不过现在结果好像有疏漏一小部分,原因不明--也没试过被拉黑的情况.最终会遗留下一个只有自己的群组,需要手工删一下. 方法 下载 python 脚本,跑一下.启动 Terminal,切到文件目录下: python wd

  • Python版微信红包分配算法

    红包分配算法代码实现发给大家,祝红包大丰收! #coding=gbk import random import sys #print random.randint(0, 99) #print "====", random.uniform(0, 0.99) def calRandomValue(min, max, total, num): print min, max, total, num total = float(total) num = int(num) min = 0.01 i

  • Python开发微信公众平台的方法详解【基于weixin-knife】

    本文实例讲述了Python开发微信公众平台的方法.分享给大家供大家参考,具体如下: 这两天将之前基于微信公众平台的代码重构了下,基础功能以库的方式提供,提供了demo使用的是django,看着之前为赶进度写的代码真的惨不忍睹,所以weixin-knife产生了,正如其名,提供的是必要的功能,而不是完整的应用.weixin-knife可以很方便的处理关注,取关注事件,处理文本消息,回复用户信息,jssdk处理,oauth认证,以及微信支付. github地址:https://github.com/

  • Python调用微信公众平台接口操作示例

    本文实例讲述了Python调用微信公众平台接口操作.分享给大家供大家参考,具体如下: 这里使用的是Django,其他类似 # coding=utf-8 from django.http import HttpResponse import hashlib, time, re from xml.etree import ElementTree as ET def weixin(request): token = "your token here" params = request.GET

  • python3简单实现微信爬虫

    使用ghost.py 通过搜搜 的微信搜索来爬取微信公共账号的信息 # -*- coding: utf-8 -*- import sys reload(sys) import datetime import time sys.setdefaultencoding("utf-8") from ghost import Ghost ghost = Ghost(wait_timeout=20) url="http://weixin.sogou.com/gzh?openid=oIWs

  • 利用Python开发微信支付的注意事项

    前言 微信支付是由微信及财付通联合推出的移动支付创新产品.如今,随着微信支付的全面开放,相关需求也越来越多,很多开发人员进行微信支付开发及商家申请微信支付时,面临着诸多疑惑. 要想开发顺利进行,首先要对业务流程有个清晰的认识.这里以微信公众号支付为例,因此也借用微信支付官方文档中的业务流程图: 接下来来关注几个开发过程中的关键点,包括: 1.生成商户订单与调用统一下单 API 2.微信服务器交互的数据格式 3.公众号支付下网页内通过 JS-API 调起支付 4.异步通知商户支付结果(回调) 一.

  • Python开发之快速搭建自动回复微信公众号功能

    在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天机器人微信订阅号 中用 aiml 实现了一个简单的英文聊天机器人订阅号.但是只能处理英文消息,现在用 图灵机器人 来实现一个中文的聊天机器人订阅号. 这里主要介绍如何利用 Python 的 Tornado Web框架以及wechat-python-sdk微信公众平台 Python 开发包来快速搭建微信公众号. 完整的公众号代码 GitHub 地址:green ,由于目前此公众号有一些功能正在开发中,此完整代码会与下文所描述

  • 基于Python实现通过微信搜索功能查看谁把你删除了

    场景:查找who删了我,直接copy代码保存到一个python文件who.py,在python环境下运行此文件 代码如下,copy保存到who.py文件在python环境直接运行: #!/usr/bin/env python # coding=utf-8 from __future__ import print_function import os try: from urllib import urlencode, quote_plus except ImportError: from url

  • 轻松实现python搭建微信公众平台

    本文主要是一步一步教大家如何利用python搭建微信公众平台,有兴趣的朋友可以参考一下 使用的工具,python 新浪SAE平台,微信的公众平台 你需要先在微信的公众平台与新浪SAE平台上各种注册,微信平台注册的时候需要你拍张手持身份证的照片,还有几天的审核期 微信公众平台:http://mp.weixin.qq.com 新浪SAE:http://sae.sina.com.cn/ 等待微信公众审核通过后,登录公众平台后,点击高级功能.将会看到需要提供一个接入信息: 微信接口配置 那么我们需要一个

  • 基于python实现微信模板消息

    我的风格,废话不多说了,直接给大家贴代码了,并在一些难点上给大家附了注释,具体代码如下所示: #!/usr/bin/env python #-*- coding:utf-8 -*- import urllib2,json import datetime,time from config import * import sys reload(sys) sys.setdefaultencoding("utf-8") class WechatPush(): def __init__(self

  • Python实现微信公众平台自定义菜单实例

    首先先获取access_token,并保存与全局之中 def token(requset): url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % ( Config.AppID, Config.AppSecret) result = urllib2.urlopen(url).read() Config.access_token = json.load

随机推荐