利用python的werobot庫實(shí)現(xiàn)對微信公眾號后臺的開發(fā):
實(shí)現(xiàn)的簡單功能:
1.訂閱后的回復(fù)
2.機(jī)器人聊天回復(fù)
3.指定關(guān)鍵字回復(fù)音樂,文字,鏈接
3.圖片返回原圖
注意點(diǎn):
1.該后臺基于微信官方提供的接口實(shí)現(xiàn),需要先完成微信公眾服務(wù)平臺的注冊和相關(guān)配置。
2.后臺代碼架設(shè)的服務(wù)器ip信息需要填寫到微信公眾服務(wù)平臺,且端口只能是指定的80(http)或者443(https).
代碼:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
import time
import requests
import werobot
from werobot.replies import ArticlesReply, Article, ImageReply
robot = werobot.WeRoBot(token='******')
# 訂閱后的回復(fù)
@robot.subscribe
def subscribe():
return "***歡迎關(guān)注公眾號[愉快][愉快][愉快]***\n" \
"***輸入任意內(nèi)容開始與我聊天!\n" \
"***輸入'博客'關(guān)注我的博客!\n" \
"***輸入'音樂'為小主送上舒緩的歌曲!\n"
# 關(guān)鍵字 博客 回復(fù)
@robot.filter('博客')
def blog(message):
reply = ArticlesReply(message=message)
article = Article(
title="憂郁的炸醬面",
description="我的個(gè)人博客",
img="https://werobot.readthedocs.io/zh_CN/latest/_static/qq.png",
url="http://www.itdecent.cn/u/3c58aa6164de"
)
reply.add_article(article)
return reply
# 關(guān)鍵字 歌曲源 回復(fù)
@robot.filter('歌曲源')
def music_source():
return "http://59.110.26.62:8888/"
# 用戶發(fā)送圖片
@robot.image
def blog(message, session):
chang_du = str(len(session))
session[chang_du] = message.MediaId
reply = ImageReply(message=message, media_id=message.MediaId)
return reply
# 隨機(jī)一首音樂
def music_data():
music_list = [
['童話鎮(zhèn)', '陳一發(fā)兒', 'https://e.coka.la/wlae62.mp3', 'https://e.coka.la/wlae62.mp3'],
['都選C', '縫紉機(jī)樂隊(duì)', 'https://files.catbox.moe/duefwe.mp3', 'https://files.catbox.moe/duefwe.mp3'],
['花海', '周杰倫', 'http://59.110.26.62:8888/%E5%91%A8%E6%9D%B0%E4%BC%A6-%E8%8A%B1%E6%B5%B7.mp3',
'http://59.110.26.62:8888/%E5%91%A8%E6%9D%B0%E4%BC%A6-%E8%8A%B1%E6%B5%B7.mp3'],
['精彩才剛剛開始', '易烊千璽', 'https://e.coka.la/PdqQMY.mp3', 'https://e.coka.la/PdqQMY.mp3']
]
num = random.randint(0, 2)
return music_list[num]
# 匹配 音樂 回復(fù)一首歌
@robot.filter('音樂')
@robot.filter('歌曲')
def music():
return music_data()
# 調(diào)用智能回復(fù)接口
def get_response(msg: str):
api_url = 'http://www.tuling123.com/openapi/api'
data = {
'key': '43826fe7f1e74add804dd47cf2791228', # Tuling Key,API的值
'info': msg, # 發(fā)出去的消息
'userid': '441670', # 用戶名
}
res = requests.post(api_url, data=data).json() # post請求
if res.get('code') == 40004:
return msg.strip("嗎??") + "!"
return res.get('text')
# 文字智能回復(fù)
@robot.text
def replay(msg):
cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
response = get_response(msg.content)
print(cur_time + ' 公眾號(機(jī)器人)' + ':' + response)
return response
# 讓服務(wù)器監(jiān)聽在 0.0.0.0:80
robot.config['HOST'] = '0.0.0.0'
robot.config['PORT'] = 80
robot.run()
微信展示的功能如下:

圖片發(fā)自簡書App

微信圖片_20190519141247.jpg