1.需要用到的模块有requests和itchat,itchat是一个开源的微信个人号接口。
import requests import itchat2.使用itchat接受微信收到的文本消息,与图灵机器人形成交互,并将它回复的消息返回给微信用户。其中的key可以使用我这个,也可以上图灵机器人官网注册,https://www.juhe.cn/docs/api/id/112。
KEY = '8edce3ce905a4c1dbb965e6b35c3834d' def get_response(msg): #这里我们使用了图灵机器人的服务,免费版,详情可见官网 # 构造要发送给服务器的数据 apiUrl = 'http://www.tuling123.com/openapi/api' data = { 'key' : KEY, 'info' : msg, 'userid' : 'wechat-robot', } #异常检测机制 try: r = requests.post(apiUrl, data=data).json() return r.get('text') except: return #获取文本微信消息 @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg): # 添加一个默认的回复 defaultReply = 'I received: ' + msg['Text'] reply = get_response(msg['Text']) return reply or defaultReply itchat.auto_login(hotReload=True) itchat.run()
3.运行后会弹出二维码给你登陆,点击允许登陆网页版微信,即可实现聊天机器人的功能。
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Login successfully as Admin.
Start auto replying.