用python配合微信API接口将微信个人号变为聊天机器人

操作系统:Ubuntu16.04

  首先我们先安装itchat:

这里我之前安装过了,先在又安装了一边

使用 python3 -c "import itchat" 检查是否安装成功了

如果没有任何输出,则表明安装成功了

然后我们需要去图灵注册一个账号,来获取key,这里给出链接图灵

现在开始编辑代码

新建一个文件:robot.py

 完整代码+注释

 1   1 import requests
 2   2 import itchat
 3   3 
 4   4 KEY = '××××××××××c24144a5e54b××××××××××'   #这里我们用的就是上图中的key,这里我打码了
 5   5 
 6   6 def get_response(msg):
 7   7     apiUrl = 'http://www.tuling123.com/openapi/api'
 8   8     data = { 
 9   9         'key'    : KEY,
10  10         'info'   : msg,
11  11         'userid' : 'wechat-robot',
12  12     }
13  13     try:
14  14         r = requests.post(apiUrl, data=data).json()
15  15         return r.get('text')
16  16     except:                                               #这里为了防止服务器无响应,所以用try-exc    ept捕获异常
17  17         return
18  18 
19  19 @itchat.msg_register(itchat.content.TEXT)
20  20 def tuling_reply(msg):
21  21     defaultReply = 'I received: ' + msg['Text']           #为保证图灵出现问题仍可修复,这里设置一>    个默认恢复
22  22     reply = get_response(msg['Text'])
23  23     return reply or defaultReply     #a or b:若a有内容则返回a,否则返回b
24  24     
25  25 itchat.auto_login(hotReload=True)
26  26 itchat.run()
27 ~                                      

 然后输入python3 robot.py运行程序

会让你扫码,微信扫码后就登陆了

这就是登录后的结果

然后你就可以用别人微信给你自己发信息试试了

下面是别人与我微信聊天的测试结果

这是在实验楼学习的,所以就在这里记录下来了学习过程

原文出:实验楼

猜你喜欢

转载自www.cnblogs.com/rcat/p/9339154.html
今日推荐