本文主要介绍微信接入图灵智能机器人实现尬聊的简单方法
一、主要工具
wxpy : 实现微信登录、接收、发送消息等功能
requests : https for humans
图灵机器人 :都说是尬聊机器人了,首先当然是要有个机器人了,去官网tuling123.com注册一个,拿到机器人的apikey,后续调用图灵开放接口时传入即可
二、本项目实现功能
1、回复指定微信好友消息
2、回复微信群@自己的消息
三、实现思路
当收到指定的微信好友或群里@的消息时,自动回复消息。回复的内容通过调用图灵开放接口获得(接口文档地址https://www.kancloud.cn/turing/www-tuling123-com/718227
)。调用接口时会传入自己注册的图灵机器人的apikey,所以可以通过借助图灵平台已有的功能训练自己的机器人,实现回复消息的定制化。比如:
1、通过丰富语料库
2、通过机器人内置的功能实现微信自动智能解答(基本上不需要自己做什么,只要收到的msg包含功能关键词即可触发)
四、代码实现
目录结构
1、constants.py保存图灵机器人的apikey以及调用接口地址
# -*- coding:utf-8 -*-
__author__ = 'wenbin'
TULING_API_V1 = 'http://www.tuling123.com/openapi/api'
TULING_API_V2 = 'http://openapi.tuling123.com/openapi/api/v2'
TULING_TOKEN = ''
2、tuling.py实现调用图灵机器人的方法
# -*- coding:utf-8 -*-
__author__ = 'wenbin'
import requests
import json
import constants
def ai_search_V1(msg,puid):
data = {
'key': constants.TULING_TOKEN,
'info': msg,
'userid': puid,
}
res = requests.post(constants.TULING_API_V1,data=data).json()
return res['text']
def ai_search_V2(msg,puid):
inputText = {
"text": msg
}
userInfo = {
"apiKey": constants.TULING_TOKEN,
"userId": puid
}
data = {
"reqType":0,
"perception": {
"inputText": inputText
},
"userInfo": userInfo
}
res = requests.post(constants.TULING_API_V2,data=json.dumps(data)).json()
return res['results'][0]['values']['text']
3、robot.py实现自动回复的方法
# -*- coding:utf-8 -*-
__author__ = 'wenbin'
from wxpy import *
from tuling import ai_search_V1,ai_search_V2
# 登录微信,启用缓存
bot = Bot(cache_path=True)
# 启用puid属性
bot.enable_puid()
# boring_group = bot.groups().search('6A')[0]
myfriend = bot.friends().search('羊')[0]
puid = myfriend.puid
# @bot.register(myfriend)
# def reply_myfriend(msg):
#
# if '嗨' in msg.text:
#
# reply_msg = ai_search_V1(msg=msg.text[1:],puid=puid)
# msg.reply(reply_msg)
# 自动回复myfriend发来的消息
@bot.register(myfriend)
def reply_myfriend(msg):
"""用 嗨 作为唤醒机器人的热词
当msg第一个字是嗨
则截取嗨之后的text进行搜索
:param msg:
:return:
"""
if '嗨' in msg.text:
reply_msg = ai_search_V2(msg=msg.text[1:],puid=puid)
msg.reply(reply_msg)
@bot.register(Group,TEXT)
def reply_mygroup(msg):
"""当群消息是@自己的消息时
会触发机器人
:param msg:
:return:
"""
if msg.is_at:
print(msg)
reply_msg = ai_search_V2(msg=msg.text,puid=msg.member.puid)
msg.reply(reply_msg)
print(reply_msg)
embed()
embed()方法可以让程序保持运行,同时进入Python命令行。可以理解为保持机器人一直在线。