Python + Tornado 搭建自动回复微信公众号
1 通过 pip 安装 wechat-python-sdk , Requests 以及 Tornado
pip install tornado
pip install wechat-sdk
pip install requests
2 订阅号申请
要搭建订阅号,首先需要在微信公众平台官网进行注册,注册网址: 微信公众平台。
目前个人用户可以免费申请微信订阅号,虽然很多权限申请不到,但是基本的消息回复是没有问题的。
- 服务器接入
具体的接入步骤可以参考官网上的接入指南。
本订阅号的配置为:

进行修改配置,提交时,需要验证服务器地址的有效性

wechat.py
import tornado.escape
import tornado.web
from wechat_sdk import WechatConf
conf = WechatConf(
token='your_token', # 你的公众号Token
appid='your_appid', # 你的公众号的AppID
appsecret='your_appsecret', # 你的公众号的AppSecret
encrypt_mode='safe', # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式
encoding_aes_key='your_encoding_aes_key' # 如果传入此值则必须保证同时传入 token, appid
)
from wechat_sdk import WechatBasic
wechat = WechatBasic(conf=conf)
class WX(tornado.web.RequestHandler):
def get(self):
signature = self.get_argument('signature', 'default')
timestamp = self.get_argument('timestamp', 'default')
nonce = self.get_argument('nonce', 'default')
echostr = self.get_argument('echostr', 'default')
if signature != 'default' and timestamp != 'default' and nonce != 'default' and echostr != 'default' \
and wechat.check_signature(signature, timestamp, nonce):
self.write(echostr)
else:
self.write('Not Open')
wechat_main.py
#!/usr/bin/env python
#coding:utf-8
import tornado.web
import tornado.httpserver
from tornado.options import define, options
import os
import wechat
settings = {
'static_path': os.path.join(os.path.dirname(__file__), 'static'),
'template_path': os.path.join(os.path.dirname(__file__), 'view'),
'cookie_secret': 'xxxxxxxxxxx',
'login_url': '/',
'session_secret': "xxxxxxxxxxxxxxxxxxxxxxx",
'session_timeout': 3600,
'port': 8888,
'wx_token': 'your_token',
}
web_handlers = [
(r'/wechat', wechat.WX),
]
#define("port", default=settings['port'], help="run on the given port", type=int)
from tornado.options import define, options
define ("port", default=8888, help="run on the given port", type=int)
if __name__ == '__main__':
app = tornado.web.Application(web_handlers, **settings)
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
cookie_secret session_secret 可以随便填写;
配置好程序源代码后运行,确认运行无误后再在公众号设置页面点击 提交 ,如果程序运行没问题,会显示接入成功。
3 接入图灵机器人
要接入图灵机器人,首先需要在官网申请API Key。
class TulingAutoReply:
def __init__(self, tuling_key, tuling_url):
self.key = tuling_key
self.url = tuling_url
def reply(self, unicode_str):
body = {'key': self.key, 'info': unicode_str.encode('utf-8')}
r = requests.post(self.url, data=body)
r.encoding = 'utf-8'
resp = r.text
if resp is None or len(resp) == 0:
return None
try:
js = json.loads(resp)
if js['code'] == 100000:
return js['text'].replace('<br>', '\n')
elif js['code'] == 200000:
return js['url']
else:
return None
except Exception:
traceback.print_exc()
return None
4 编写公众号自动回复代码
auto_reply = TulingAutoReply(key, url) # key和url填入自己申请到的图灵key以及图灵请求url
class WX(tornado.web.RequestHandler):
def wx_proc_msg(self, body):
try:
wechat.parse_data(body)
except ParseError:
print('Invalid Body Text')
return
if isinstance(wechat.message, TextMessage): # 消息为文本消息
content = wechat.message.content
reply = auto_reply.reply(content)
if reply is not None:
return wechat.response_text(content=reply)
else:
return wechat.response_text(content=u"不知道你说的什么")
return wechat.response_text(content=u'知道了')
def post(self):
signature = self.get_argument('signature', 'default')
timestamp = self.get_argument('timestamp', 'default')
nonce = self.get_argument('nonce', 'default')
if signature != 'default' and timestamp != 'default' and nonce != 'default' \
and wechat.check_signature(signature, timestamp, nonce):
body = self.request.body.decode('utf-8')
try:
result = self.wx_proc_msg(body)
if result is not None:
self.write(result)
except IOError as e:
return
最终 wechat.py 代码如下:
import tornado.escape
import tornado.web
#from goose import Goose, ParseError
import json
import requests
import traceback
from wechat_sdk import WechatConf
conf = WechatConf(
token='your_token', # 你的公众号Token
appid='your_appid', # 你的公众号的AppID
appsecret='your_appsecret', # 你的公众号的AppSecret
encrypt_mode='safe', # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式
encoding_aes_key='your_encoding_aes_key' # 如果传入此值则必须保证同时传入 token, appid
)
from wechat_sdk import WechatBasic
wechat = WechatBasic(conf=conf)
class TulingAutoReply:
def __init__(self, tuling_key, tuling_url):
self.key = tuling_key
self.url = tuling_url
def reply(self, unicode_str):
body = {'key': self.key, 'info': unicode_str.encode('utf-8')}
r = requests.post(self.url, data=body)
r.encoding = 'utf-8'
resp = r.text
if resp is None or len(resp) == 0:
return None
try:
js = json.loads(resp)
if js['code'] == 100000:
return js['text'].replace('<br>', '\n')
elif js['code'] == 200000:
return js['url']
else:
return None
except Exception:
traceback.print_exc()
return None
auto_reply = TulingAutoReply(key, url) # key和url填入自己申请到的图灵key以及图灵请求url
class WX(tornado.web.RequestHandler):
def wx_proc_msg(self, body):
try:
wechat.parse_data(body)
except ParseError:
print('Invalid Body Text')
return
if isinstance(wechat.message, TextMessage): # 消息为文本消息
content = wechat.message.content
reply = auto_reply.reply(content)
if reply is not None:
return wechat.response_text(content=reply)
else:
return wechat.response_text(content=u"不知道你说的什么")
return wechat.response_text(content=u'知道了')
def post(self):
signature = self.get_argument('signature', 'default')
timestamp = self.get_argument('timestamp', 'default')
nonce = self.get_argument('nonce', 'default')
if signature != 'default' and timestamp != 'default' and nonce != 'default' \
and wechat.check_signature(signature, timestamp, nonce):
body = self.request.body.decode('utf-8')
try:
result = self.wx_proc_msg(body)
if result is not None:
self.write(result)
except IOError as e:
return
Python + Tornado 搭建自动回复微信公众号的更多相关文章
- python利用wxpy监控微信公众号
此次利用wxpy可以进行微信公众号的消息推送监测(代码超级简单),这样能进行实时获取链接.但是不光会抓到公众号的消息,好友的消息也会抓到(以后会完善的,毕竟现在能用了,而且做项目的微信号肯定是没有好友 ...
- 教你如何入手用python实现简单爬虫微信公众号并下载视频
主要功能 如何简单爬虫微信公众号 获取信息:标题.摘要.封面.文章地址 自动批量下载公众号内的视频 一.获取公众号信息:标题.摘要.封面.文章URL 操作步骤: 1.先自己申请一个公众号 2.登录自己 ...
- 从Python爬虫到SAE云和微信公众号:二、新浪SAE上搭建微信服务
目的:用PHP在SAE上搭建一个微信公众号的服务器. 1.申请一个SAE云账号 SAE申请地址:http://sae.sina.com.cn/ 可以使用微博账号登陆,SAE是新浪的云服务,时间也比较 ...
- 在新浪SAE上搭建微信公众号的python应用
微信公众平台的开发者文档https://www.w3cschool.cn/weixinkaifawendang/ python,flask,SAE(新浪云),搭建开发微信公众账号http://www. ...
- Azure 项目构建 - 用 Azure 认知服务在微信公众号上搭建智能会务系统
通过完整流程详细介绍了如何在Azure平台上快速搭建基于微信公众号的智慧云会务管理系统. 此系列的全部课程 https://school.azure.cn/curriculums/11 立即访问htt ...
- Python+Tornado开发微信公众号
本文已同步到专业技术网站 www.sufaith.com, 该网站专注于前后端开发技术与经验分享, 包含Web开发.Nodejs.Python.Linux.IT资讯等板块. 本教程针对的是已掌握Pyt ...
- 小机器人自动回复(python,可扩展开发微信公众号的小机器人)
api来之图灵机器人.我们都知道微信公众号可以有自动回复,我们先用python脚本编写一个简单的自动回复的脚本,利用图灵机器人的api. http://www.tuling123.com/help/h ...
- 使用python django快速搭建微信公众号后台
前言 使用python语言,django web框架,以及wechatpy,快速完成微信公众号后台服务的简易搭建,做记录于此. wechatpy是一个python的微信公众平台sdk,封装了被动消息和 ...
- 个人微信公众号搭建Python实现 -接收和发送消息-基本说明与实现(14.2.1)
@ 目录 1.原理 2.接收普通消息 3.接收代码普通消息代码实现 1.原理 2.接收普通消息 其他消息类似参考官方文档 3.接收代码普通消息代码实现 from flask import Flask, ...
随机推荐
- 根据数值获得概率密度pdf和累积密度分布cdf(MATLAB语言)
y=randn(1,3000); % 生成1-by-3000的标准正态分布随机数 ymin=min(y); ymax=max(y); x=linspace(ymin,ymax,20); %将最大最小区 ...
- c#委托中的同步和异步方法即BeginInvoke和EndInvoke
学习多线程之前我们先了解一下电脑的一些概念,比如进程,线程,这个参考https://www.cnblogs.com/loverwangshan/p/10409755.html 这篇文章.今天我们接着来 ...
- 第31章 日志 - Identity Server 4 中文文档(v1.0.0)
IdentityServer使用ASP.NET Core提供的标准日志记录工具.Microsoft文档有一个很好的介绍和内置日志记录提供程序的描述. 我们大致遵循Microsoft使用日志级别的指导原 ...
- 谈下WebSocket介绍,与Socket的区别
这个话题应该是面试中出现频率比较高的吧....不管咋样还是有必要深入了解下两者之间的关联.废话不多说,直接入题吧: WebSocket介绍与原理 目的:即时通讯,替代轮询 网站上的即时通讯是很常见的, ...
- echarts饼图配置模板
var option = { title:{ text:'完成人构成分析--申报', //标题的样式 textSytle:{ //颜色 color : '#FF0000', //粗细 // fontW ...
- C#中的yield return用法演示源码
下边代码段是关于C#中的yield return用法演示的代码. using System;using System.Collections;using System.Collections.Gene ...
- 更新下载库update绝对详解
下载更新apk,基本上每个app都需要的功能,来看看吧,肯定有你想要的,以前都是自己写,近期想借助第三方的一个库来做,功能齐全,感觉不错,记录使用过程,虽然官方也有使用教程,不过毕竟粗略,网上也能搜到 ...
- 如何为 .NET Core CLI 启用 TAB 自动补全功能
如何为 .NET Core CLI 启用 TAB 自动补全功能 Intro 在 Linux 下经常可以发现有些目录/文件名,以及有些工具可以命令输入几个字母之后按 TAB 自动补全,最近发现其实 do ...
- selenium-配置文件定位元素(九)
原文链接:https://mp.weixin.qq.com/s?__biz=MzU5NTgyMTE3Mg==&mid=2247483802&idx=1&sn=3218e34b6 ...
- 从0开始的Python学习001快速上手手册
假设大家已经安装好python的环境了. Windows检查是否可以运行python脚本 Ctrl+R 输入 cmd 在命令行中输入python 如果出现下面结果,我们就可以开始python的学习了. ...