需要安装itchat,
在命令行输入 pip3 install itchat安装
或者直接在线安装,去官网下载itchat包都可以
key值需要经常换的。
import requests
import itchat
# pip3 install itchat
KEY = 'eb720a8970964f3f855d863d24406576'
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()
# 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常
return r.get('text')
except:
return
# 这里实现微信消息的获取
@itchat.msg_register(itchat.content.TEXT, itchat.content.PICTURE)
def tuling_reply(msg):
defaultReply = 'I received: ' + msg['Text']
# 如果图灵Key出现问题,那么reply将会是None
reply = get_response(msg['Text'])
# a or b的意思是,如果a有内容,那么返回a,否则返回b
# 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试
return reply or defaultReply
# 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动
itchat.auto_login(hotReload=True)
itchat.run()
欢迎加入python交流群:873376961一起交流python相关问题