python实现个人订阅号自动回复功能

ERROR:tornado.application:Uncaught exception GET /index?signature=1b63cbf1e1e6f08f05f16d0a2fa057da66ae8366&echostr=6930114309908643647&timestamp=1524907821&nonce=1505847200 (127.0.0.1)
HTTPServerRequest(protocol='http', host='python.zxb8.cc', method='GET', uri='/index?signature=1b63cbf1e1e6f08f05f16d0a2fa057da66ae8366&echostr=6930114309908643647&timestamp=1524907821&nonce=1505847200', version='HTTP/1.0', remote_ip='127.0.0.1', headers={'Host': 'python.zxb8.cc', 'X-Real-Ip': '103.7.30.104', 'Connection': 'close', 'User-Agent': 'Mozilla/4.0', 'Accept': '*/*', 'Pragma': 'no-cache'})
Traceback (most recent call last):
  File "/usr/local/python36/lib/python3.6/site-packages/tornado/web.py", line 1443, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "web.py", line 31, in get
    if checksignature(signature, timestamp, nonce):
  File "web.py", line 21, in checksignature
    mysig = hashlib.sha1(''.join(args)).hexdigest()
TypeError: Unicode-objects must be encoded before hashing
ERROR:tornado.access:500 GET /index?signature=1b63cbf1e1e6f08f05f16d0a2fa057da66ae8366&echostr=6930114309908643647&timestamp=1524907821&nonce=1505847200 (127.0.0.1) 3.34ms
ERROR:tornado.application:Uncaught exception GET /index?signature=7c196c7ab1706dded826967eadd69ad5b60a414d&echostr=8769862630416727935&timestamp=1524907825&nonce=2495484385 (127.0.0.1)
HTTPServerRequest(protocol='http', host='python.zxb8.cc', method='GET', uri='/index?signature=7c196c7ab1706dded826967eadd69ad5b60a414d&echostr=8769862630416727935&timestamp=1524907825&nonce=2495484385', version='HTTP/1.0', remote_ip='127.0.0.1', headers={'Host': 'python.zxb8.cc', 'X-Real-Ip': '103.7.30.104', 'Connection': 'close', 'User-Agent': 'Mozilla/4.0', 'Accept': '*/*', 'Pragma': 'no-cache'})
Traceback (most recent call last):
  File "/usr/local/python36/lib/python3.6/site-packages/tornado/web.py", line 1443, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "web.py", line 31, in get
    if checksignature(signature, timestamp, nonce):
  File "web.py", line 21, in checksignature
    mysig = hashlib.sha1(''.join(args)).hexdigest()
TypeError: Unicode-objects must be encoded before hashing
ERROR:tornado.access:500 GET /index?signature=7c196c7ab1706dded826967eadd69ad5b60a414d&echostr=8769862630416727935&timestamp=1524907825&nonce=2495484385 (127.0.0.1) 1.27ms
个人订阅号自动回复功能

 

# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
import hashlib
import xml.etree.ElementTree as ET
import time
import requests
import json


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


def checksignature(signature, timestamp, nonce):
    args = []
    args.append('weixin')  ####这里输入你的 Token
    args.append(timestamp)
    args.append(nonce)
    args.sort()
    # TypeError: Unicode-objects must be encoded before hashing  encode("utf8")
    mysig = hashlib.sha1(''.join(args).encode("utf8")).hexdigest()
    return mysig == signature


def get_robot(info,fromusername):
    api = "http://www.tuling123.com/openapi/api"
    data = {
        "key": "6fc82932046e4b7a8198767abe04e31a",
        "info": info.encode('utf-8'),
        "userid":fromusername
    }
    r = requests.post(api, data=data)
    resp = r.text
    # https://www.kancloud.cn/turing/web_api/522989
    f = open('test1.log', 'w+')
    f.write(str(r.status_code))
    f.write(resp)
    if r.status_code == 200:
        re = json.loads(resp)
        if re['code'] == 100000:  # 文本类
            return re['text']
        elif re['code'] == 200000:  # 链接类
            return '链接类'
        elif re['code'] == 302000:  # 新闻类
            return '新闻类'
        elif re['code'] == 308000:  # 菜谱类
            return '菜谱类'
        elif re['code'] == 313000:  # 儿歌类
            return '儿歌类'
        elif re['code'] == 314000:  # 诗词类
            return '诗词类'
    else:
        return '接口异常' + r.status_code


class IndexHandler(tornado.web.RequestHandler):
    def get(self):  ########验证时用
        signature = self.get_argument('signature')
        timestamp = self.get_argument('timestamp')
        nonce = self.get_argument('nonce')
        echostr = self.get_argument('echostr')
        if checksignature(signature, timestamp, nonce):
            self.write(echostr)
        else:
            self.write('fail')

    def post(self):
        body = self.request.body
        data = ET.fromstring(body)
        tousername = data.find('ToUserName').text
        fromusername = data.find('FromUserName').text
        createtime = data.find('CreateTime').text
        msgtype = data.find('MsgType').text
        content = data.find('Content').text
        msgid = data.find('MsgId').text
        # print 'fromusername: %s' % fromusername
        # print 'tousername: %s' % tousername
        # print 'createtime: %s' % createtime
        # print 'msgtype: %s' % msgtype
        # print 'msgid: %s' % msgid

        # 获取图灵机器人返回的数据
        result = get_robot(content.strip(),fromusername)

        if result == None:
            result = "亲,你太帅气了,随然我不知道你在说什么 \n 可以关注我们的学习交流社区进行学习\n\n <a href=\"http://www.zxb8.cc\">点击一起学习吧</a>\n"

        f = open('test.log', 'w+')
        f.write(result)

        textTpl = """<xml>
                   <ToUserName><![CDATA[%s]]></ToUserName>
                   <FromUserName><![CDATA[%s]]></FromUserName>
                   <CreateTime>%s</CreateTime>
                   <MsgType><![CDATA[%s]]></MsgType>
                   <Content><![CDATA[%s]]></Content>
                   </xml>"""
        out = textTpl % (fromusername, tousername, str(int(time.time())), msgtype, result)

        f.write(out)

        self.write(out)


if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/index", IndexHandler),
    ])
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()
 

使用 nginx 反向代理到 tornado 服务的 8888 端口

http://python.zxb8.cc/index

 

在 nginx.conf 配置文件里添加

 

 

upstream tornados{
server 127.0.0.1:8888;
}

 

vim /usr/local/nginx/conf/nginx.conf

 
#user  nobody;
worker_processes  1;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
    include       mime.types;
    default_type  application/octet-stream;
 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    #access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
#反向代理设置
    upstream tornados{
         server 127.0.0.1:8888;
     }
 
    #gzip  on;
 
     include conf.d/*.conf;
 
}
 
 
server {
listen 80;
server_name python.zxb8.cc;

# 静态文件直接由 Nginx 处理
location /static/{
alias /www/img/;
expires 24h;
}

location /{
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
# 把请求方向代理传给 tornado 服务器,负载均衡
proxy_pass http://tornados;
}
}
~
~
~

复制代码

阅读原文请访问

www.zxb8.cc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值