版权声明:希望转载的小伙伴注明来源哦!欢迎大家转载,更好的传递知识! https://blog.csdn.net/qq_38161040/article/details/84875338
首先你需要itchat库
进入cmd,先pip install itchat安装itchat
python机器人代码
开启的时候会弹出一个二维码,微信扫描后就会登陆了。
原理是网页版微信,那个二维码就是你网页版微信登陆的二维码。
我们调用的机器人接口来自图灵,想要了解调用的原理请看我的这个博客:
https://blog.csdn.net/qq_38161040/article/details/85162931
# -*- coding: UTF8 -*-
import itchat
import requests
# 这个参数的msg就是接收到的消息内容,这个函数是调用图灵的api获得一个回复
def get_response(msg):
apiUrl = 'http://www.tuling123.com/openapi/api'
data={
'key' : 'bd0a1aafaafd418bbdb6aa0a40f73859',
'info' : msg,
'userid': '小爱',
}
try:
r = requests.post(apiUrl, data=data).json()
return r.get("text")
except:
return
# 开启群消息和好友消息监控
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True,isGroupChat=True)
# 这个msg包括很多内容,我们接受到的消息是存在'Text'这个字段中
def tuling_reply(msg):
if 'ActualNickName' in msg:
# 当检测到有人@自己时,才会在群里回复
if msg['isAt']:
reply=get_response(msg['Text'])
else:
reply=""
else:
reply=get_response(msg['Text'])
return reply
# hotReload=Rrue就是记录你的登陆状态,省的每次都登陆,不想保留状态可以去掉这个参数
itchat.auto_login(hotReload=True)
itchat.run()