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, ...
随机推荐
- Spring Boot (七)MyBatis代码自动生成和辅助插件
一.简介 1.1 MyBatis Generator介绍 MyBatis Generator 是MyBatis 官方出品的一款,用来自动生成MyBatis的 mapper.dao.entity 的框架 ...
- Linux基础(Ubuntu16.04):安装vim及配置
1.进入终端 Ctrl + Alt +T 出现终端窗口 2.输入命令: sudo apt-get install vim-gtk 3.验证是否成功 安装完vim后查看命令 vi tab键,就会关联出 ...
- Web 性能优化: 图片优化让网站大小减少 62%
摘要: 压缩各种格式的图片. 原文:Web 性能优化: 图片优化让网站大小减少 62% 作者:前端小智 Fundebug经授权转载,版权归原作者所有. 这是 Web 性能优化的第二篇,上一篇在下面看点 ...
- 纯CSS实现点击事件展现隐藏div菜单列表/元素切换
在写移动端导航的时候经常用到点击按钮出现/隐藏导航条的情况,最常见的方法当然还是前端框架直接调用,省心省力,不易出错:当然还有使用纯JS实现的小代码段.我这里整理了纯CSS实现方式,给需要的人和给自己 ...
- #WEB安全基础 : HTML/CSS | 文章索引
本系列讲解WEB安全所需要的HTML和CSS #WEB安全基础 : HTML/CSS | 0x0 我的第一个网页 #WEB安全基础 : HTML/CSS | 0x1初识CSS #WEB安全基础 : H ...
- XSS 漏洞介绍
概念: XSS 攻击:跨站脚本攻击 (Cross Site Scripting),为不和层叠样式表 (Cascading Style Sheets, CSS) 的缩写混淆.故将跨站脚本攻击缩写为 XS ...
- 利用OpenStreetMap(OSM)数据搭建一个地图服务
http://www.cnblogs.com/LBSer/p/4451471.html 图 利用OSM数据简单发布的北京地图服务 一.OSM是什么 开放街道图(OpenStreetMap,简称O ...
- ABP大型项目实战(1) - 目录
前面我写了<如何用ABP框架快速完成项目>系列文章,讲述了如何用ABP快速完成项目. 然后我收到很多反馈,其中一个被经常问到的问题就是,“看了你的课程,发现ABP的优势是快速开发,那么 ...
- DevOps 工程师实际上是做什么的
DevOps 工程师实际上是做什么的? 我们之前已经讨论过许多关于DevOps和DevOps世界的最新趋势了.但是DevOps工程师到底是做什么的? DevOps工程师以最纯粹的方式弥合了软件开发和运 ...
- [Android framework学习] ViewGroup的addView函数分析
博客首页:http://www.cnblogs.com/kezhuang/p/ Android中整个的View的组装是采用组合模式. ViewGroup就相当与树根,各种Layout就相当于枝干,各种 ...