本次使用图灵机器人接口实现个人微信的自动回复。
一:首先申请图灵账号
http://www.tuling123.com/
申请完在后台创建机器人
得到apikey
二:
使用python提供的itchat实现个人微信登录和自动回复
(1)微信登录和消息监听
# -*- coding=utf-8 -*-
import requests
import itchat
import random
from Tuling import Tuling
import sys
reload(sys)
sys.setdefaultencoding('utf8')
tuling = Tuling('http://openapi.tuling123.com/openapi/api/v2') #图灵机器人2版本
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
#msg['Text'] = unicode(msg['Text'], 'utf - 8')
defaultReply = 'I received: ' + msg['Text']
print defaultReply
robots=["\n——-(机器人小黄)","\n——-(机器人大奔)"]
reply = tuling.getTextByV2(msg['Text'])+random.choice(robots)
return reply or defaultReply
itchat.auto_login(enableCmdQR=2)
itchat.run()
(2)图灵机器人回复
# -*- coding:utf-8 -*-
import requests
import json
import random
#图灵机器人实现聊天自动回复
class Tuling():
key = ['k1','k2']
url = 'http://openapi.tuling123.com/openapi/api/v2'
def __init__(self,url):
self.url = url
def getKey(self):
return random.randint(0, len(self.key)-1)
def getTextByV2(self,text):
data = {
"reqType": 0,
"perception": {
"inputText": {
"text": text
},
},
"userInfo": {
"apiKey": self.getKey(),
"userId": "111"
}
}
data = json.dumps(data).encode('utf8')
try:
r = requests.post(self.url, data=data, headers={'content-type': 'application/json'}).json()
return r.get('results')[0]['values']['text']
except Exception as e:
return e
三:运行代码 扫码登录微信,开始愉快聊天吧