使用WeRoBot实现公众号自动回复

菠萝饭 351 2022-01-10

前言

无聊用WeRoBot框架对自己公众号进行了简单开发,实现了简单的回复各类消息的功能,现做总结如下。

官方文档

Github地址

步骤

安装WeRoBot
pip安装
pip install werobot
编写测试代码 hello.py
import werobot
# 公众号后台设置的token
robot = werobot.WeRoBot(token='tokenhere')

@robot.handler
def hello(message):
    return 'Hello World!'

# 自定义服务器监听端口 80
robot.config['HOST'] = '0.0.0.0'
robot.config['PORT'] = 80
robot.run()
运行测试

python hello.py

部署后台运行

nohup python3 hello.py &

完整代码示例autoResponse.py

from werobot import WeRoBot
import random
from werobot.replies import ArticlesReply, Article
import requests
import json
import re
from werobot.utils import to_text
from werobot.client import Client
# 公众号设置token
robot = WeRoBot(token='XXXX')
# 明文模式不需要下面三项
#robot.config["APP_ID"]=''
#robot.config["APP_SECRET"]=''
#robot.config['ENCODING_AES_KEY'] = ''

# 被关注事件
@robot.subscribe
def subscribe(message):
    return '''感谢关注!!!
    这是本人测试用公众号,暂有以下功能:
    发送【笑话】,随机回复一条笑话;
    发送【电影】,随机推荐一部IMDB排行Top250电影;
    发送【豆瓣电影】,随机推荐一部豆瓣排行Top250电影;
    发送【音乐】,随机推送一首网易云音乐;
    发送【毒鸡汤】,随机回复一条毒鸡汤;
    发送【博客】,回复我的博客地址;
    发送【网盘】,回复我的网盘地址
'''
# ————————————————接口——————————————

# 笑话接口
def joke_data():
	# 笑话接口
	url = "https://api.vvhan.com/api/xh"
	res = requests.post(url)
	if res.status_code == 200:
		comment = res.text
	else:
		comment = '接口获取异常,请重试'
	return comment
	
# 毒鸡汤接口
def chicken_soup_data():
	# 毒鸡汤接口
	url = "https://api.muxiaoguo.cn/api/dujitang"
	headers = {'content-type': 'application/json'}
	res = requests.post(url,headers=headers)
	
	if res.status_code == 200:
		text = json.loads(res.text)
		data = text['data']
		comment = data['comment']
	else:
		comment = '接口获取异常,请重试'
	return comment

# 获取一个豆瓣top250电影接口
def get_top_movie(type,topNumStr):
    url = "http://api.wmdb.tv/api/v1/top?type="+type+"&skip="+topNumStr+"&limit=1&lang=Cn"
    #print('---url: '+url)
    headers = {'content-type': 'application/json'}
    res = requests.post(url,headers=headers)
    movie_info = {}
    #print('status_code: '+str(res.status_code))
    if res.status_code == 200:
        json_obj = json.loads(res.text)
        text = json_obj[0]
        data = text['data'][0]
        movie_info['name'] = data['name']
        movie_info['poster'] = data['poster']
        movie_info['doubanRating'] = text['doubanRating']
        movie_info['imdbRating'] = text['imdbRating']
        movie_info['doubanUrl'] = "https://movie.douban.com/subject/"+text['doubanId']
        movie_info['imdbUrl'] = "https://www.imdb.com/title/"+text['imdbId']
    return movie_info


# 随机选一首音乐接口
def music_data():
	#qq音乐接口
	#url = "http://lkaa.top/API/qqsjyy/api.php?msg=%E7%83%AD%E6%AD%8C%E6%A6%9C"
	#网易云音乐接口 
	url = "https://api.uomg.com/api/rand.music?sort=%E6%96%B0%E6%AD%8C%E6%A6%9C&format=json"
	headers = {'content-type': 'application/json'}
	res = requests.post(url,headers=headers)
	
	if res.status_code == 200:
		text = json.loads(res.text)
		data = (text['data'])
		#print('-------------')
		music_url = data['url']
		music_name = data['name']
		music_artis = data['artistsname']
		musicData = []
		musicData.append(music_name)
		musicData.append(music_artis)
		musicData.append(music_url)
		musicData.append(music_url)
	else:
		musicData = '接口获取异常,请重试'
	return musicData

# ————————————————filter——————————————

@robot.filter(re.compile(to_text(".*?呵呵.*?")))
def _2():
    return "呵呵泥煤!"

# 匹配 笑话 回复糗百笑话
@robot.filter('笑话')
def joke(message):
    data = joke_data()
    return data
	
# 匹配 毒鸡汤 回复毒鸡汤
@robot.filter('毒鸡汤')
def chicken_soup(message):
    data = chicken_soup_data()
    return data	


# 匹配 博客 回复博客地址
@robot.filter('博客')
def movie(message):
    return 'www.boluofan.top'

# 匹配 网盘 回复网盘地址
@robot.filter('网盘')
def movie(message):
    return 'https://drive.boluofan.top'

# 电影 回复IMDB top250电影
@robot.filter('电影')
def blog(message):
    reply = ArticlesReply(message=message)
    topNumStr = str(random.randint(0, 249))
    movie_info = get_top_movie('Imdb',topNumStr)
    if movie_info:
        article = Article(
            title=str(movie_info['name']),
            description="Imdb评分: "+str(movie_info['imdbRating']),
            img=str(movie_info['poster']),
            url=str(movie_info['imdbUrl'])
        )
        reply.add_article(article)
        return reply
    else:
        return '接口获取异常,请稍后重试'

# 豆瓣电影 回复豆瓣top250电影
@robot.filter('豆瓣电影')
def blog(message):
    reply = ArticlesReply(message=message)
    topNumStr = str(random.randint(0, 249))
    movie_info = get_top_movie('Douban',topNumStr)
    if movie_info:
        article = Article(
            title=str(movie_info['name']),
            description="豆瓣评分: "+str(movie_info['doubanRating']),
            img=str(movie_info['poster']),
            url=str(movie_info['doubanUrl'])
        )
        reply.add_article(article)
        return reply
    else:
        return '接口获取异常,请稍后重试'


# 匹配 音乐 回复一首歌
@robot.filter('音乐')
def music(message):
    music1 = music_data()
    return music1

# 其他文本消息返回原文
@robot.text
def echo(message):
    return message.content


# 其他消息返回
@robot.handler
def hello(message):
    return '(O_o)??'

robot.config['HOST'] = '0.0.0.0'
robot.config['PORT'] = 8080
robot.run()

总结

  1. 本文只简单实现了自动回复和代码部署。实际可参考官方文档做nginx反代和服务注册;
  2. 我的公众号是个人订阅号,功能权限较少。但该框架是可以实现消息模板/自定义菜单等功能的。如有需要,可自行研究;

# 微信公众号