Flask结合werobot实现微信公众号自动回复

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',# 对应公众号的token设置
    encoding_aes_key='xxxxxx',# 明文传输不需要填写
    app_id='xxxxx'#明文传输不需要填写
)

import random
# 明文模式不需要下面三项
#robot.config["APP_ID"]=''
#robot.config["APP_SECRET"]=''
#robot.config['ENCODING_AES_KEY'] = ''


timeout=30                                                       # 超时时间
bdkey = 'xxxxxxx'      # 百度天气ak
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[
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值