Flask结合werobot实现微信公众号自动回复
下载依赖包
-
pip install werobot
-
pip install Flask
建立项目文件夹<flask_project>
- 建立项目文件app.py flask项目的启动入口
- 建立robot.py文件,关于公众号自动回复的逻辑判断文件
编写robot.py文件
- 单文件编辑需要设定端口和host,并且需要在最后run执行,依赖flask则不需要
from werobot import WeRoBot
from werobot.replies import WeChatReply, TextReply, ImageReply, MusicReply,ArticlesReply, Article
import re
import urllib
import logging
import json
from flask import Flask
import requests
robot = WeRoBot(
token='xxxxxx',
encoding_aes_key='xxxxxx',
app_id='xxxxx'
)
import random
timeout=30
bdkey = 'xxxxxxx'
def get_citys_in_msg(msg):
api_url = 'http://www.yangyingming.com/api/parse_city?%s'%(urllib.parse.urlencode({
'msg':msg}))
citys = urllib.request.urlopen(api_url).read().decode('utf8')
return citys
def get_weather(city):
url = 'http://wthrcdn.etouch.cn/weather_mini'
param = urllib.parse.urlencode({
'city':city,
})
api_url = '%s?%s'%(url,param)
wdata = requests.get(api_url).text
return wdata
@robot.subscribe
def subscribe(message):
return '你好~\n我是xxxx的管家机器人,我叫xxxx T_T\n有什么能帮您的吗?/::$'
@robot.handler
def echo(message):
try:
msg = message.content
if re.compile(".*?天气.*?").match(msg):
res_msg = ''
citys = get_citys_in_msg(msg).split(',')
if citys[0]=='':
return '亲爱的,你想知道哪座城市的天气呢?'
else:
for city in citys:
if res_msg!='':
res_msg += '\n\n'
wdata = get_weather(city)
wdata = json.loads(wdata)
if wdata['desc']=='OK':
wdata=wdata['data']
res_msg += '当前位置:%s\n温馨提示: %s\n当前温度: %s+℃\n昨天: %s\n风力:%s \n风向: %s\n%s,%s\n天气: %s\n ----------------------------' % (
wdata[