- #coding=utf8
- import requests
- import itchat
- #key 自己到图灵注册一个
- KEY = ****************************************
- def get_response(msg):
- # 这里我们就像在 3. 实现最简单的与图灵机器人的交互中做的一样
- # 构造了要发送给服务器的数据
- 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)
- # 为了防止服务器没有正常响应导致程序异常退出, 这里用 try-except 捕获了异常
- # 如果服务器没能正常交互 (返回非 json 或无法连接), 那么就会进入下面的 return
- except: # 将会返回一个 None
- return
- # 这里是我们在 1. 实现微信消息的获取中已经用到过的同样的注册方法
- @itchat.msg_register(itchat.content.TEXT)
- def tuling_reply(msg):
- # 为了保证在图灵 Key 出现问题的时候仍旧可以回复, 这里设置一个默认回复
- 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() #运行
来源: http://www.bubuko.com/infodetail-2491658.html