您的位置:首页 > 移动开发 > 微信开发

微信聊天机器人

2019-06-12 00:52 1626 查看
版权声明:litianci https://blog.csdn.net/qq_40165417/article/details/91488356

前提

  • 调用图灵机器人api进行智能聊天
  • 若没有先去官网注册http://www.tuling123.com/
  • 要个人认证才可以正常使用,免费100条/天(以前10000的,可以是为了给同行一条生路,感觉这100根本不够用)
  • 在机器人管理那可以看到api

原理

原理和爬虫差不多,获得好友发来的信息,强求到机器人的网页,获取答案,再发送给好友

源代码

import itchat
import requests
import re

def getHtmlText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""

# 自动回复
# 封装好的装饰器,当接收到的消息是Text,即文字消息
@itchat.msg_register(['Text', 'Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
# 当消息不是由自己发出的时候
print(msg)
if not msg['FromUserName'] == Name["Can it be can be unable to"]:
# 回复给好友
url = "http://www.tuling123.com/openapi/api?key=填机器人的api&info="
url = url + msg['Text']
html = getHtmlText(url)
message = re.findall(r'\"text\"\:\".*?\"', html)
reply = eval(message[0].split(':')[1])
return reply

if __name__ == '__main__':
itchat.auto_login()

# 获取好友信息
friends = itchat.get_friends(update=True)[0:]
Name = {}
Nic = []
User = []
for i in range(len(friends)):
Nic.append(friends[i]["NickName"])
User.append(friends[i][
4000
"UserName"])

for i in range(len(friends)):
Name[Nic[i]] = User[i]
#保持运行
itchat.run()
```
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: