【python 应用】50行实现微信聊天机器人


开发工具

python3.7

itchat

 

原理讲解

做一个能够与人交流的机器人有很多种方法,最简单的莫过于使用他人提供的接口。

我们这里以图灵机器人为例,演示这一功能。

图灵机器人简单而言就是以一定的规则给图灵的服务器发送数据包(包含你对他说的话)

图灵的服务器会以一定的规则给你返回数据包(包含他回复你的话),图灵机器人的Tyling Key的获取的帮助文档http://www.tuling123.com/help/h_cent_webapi.jhtml

你需要一个Tuling Key来告诉图灵服务器你有权和他对话,我这里免费提供一些:

8edce3ce905a4c1dbb965e6b35c3834d
eb720a8970964f3f855d863d24406576
1107d5601866433dba9599fac1bc0083
71f28bf79c820df10d39b4074345ef8c

下面我做一个配置图灵机器人的简单介绍

请求方式

HTTP POST

请求参数

请求参数格式为 json

 

发送的规则简而言之是这样的:

{
	"reqType":0, "perception": { "inputText": { "text": msg, } }, "userInfo": { "apiKey": KEY, "userId": uid, } } 

其中userId是用户的标志,让机器人知道你是你。(也就是一个Tuling Key可以有多个用户)

而返回的内容基本是这样的:

{
'intent': {'code': xxx}, 'results': [{'groupType': 0, 'resultType': 'text', 'values': {'text': 'xxx'}}] }

我们需要的内容就在values键的text键里面。

这里我们使用requests包完成整个操作(已经包含在itchat包的安装中了)。

最后值得一提的就是这是一个post请求,那么直接上代码应该比我絮絮叨叨的说要直观很多。

# -*- coding: utf-8 -*- import json import time import requests import itchat #Turling_key KEY = '54d7869f48ff4f1f8d856d52d3c7cdf2' def get_response(msg):     '''     发送数据包给图灵服务器     '''     apiUrl = 'http://openapi.tuling123.com/openapi/api/v2'     #动态生成userid     uid = 'rrh'     #字典转json     data ={     "reqType":0,     "perception": {         "inputText": {             "text": msg,         }     },     "userInfo": {         "apiKey": KEY,         "userId": uid,     } }          try:         data_json = json.dumps(data)         response = requests.post(apiUrl,data=data_json).json()         print(response)         return response['results'][0]['values']['text']     except:         return #处理消息并自动回复 @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg):     #默认回复     defaultReply = '【{}】,这句话俺听不懂啦'.format(msg['Text'])     FromUserName = msg['FromUserName']     reply = get_response(msg['Text'])     if reply:         itchat.send(reply,toUserName=FromUserName)     else:         itchat.send(defaultReply,toUserName=FromUserName) if __name__ == '__main__':     itchat.auto_login(hotReload=True)     itchat.run()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM