练习---接入图灵机器人+itchat回复好友消息

先去http://www.tuling123.com/member/robot/index.jhtml创建一个机器人,记住这个apikey

可以查看https://www.kancloud.cn/turing/www-tuling123-com/718227 api2.0接入文档

下面是在终端运行与图灵机器人对话

import requests
import json

#图灵机器人的回复
def ask(content): 
	url='http://openapi.tuling123.com/openapi/api/v2'
	data={
	"reqType":0,
    "perception": {
        "inputText": {
            "text":content
        },
        "selfInfo": {
            "location": {
                "city": "广州",
                "province": "广东",
            }
        }
    },
    "userInfo": {
        "apiKey": "你申请的机器人key",
        "userId": "胡乱写的"
    }
}
	res=requests.post(url=url,data=json.dumps(data))
	answer=res.json()['results'][0]['values']['text']
	print("小梦同学:"+answer)
	return answer

#输入'q'停止对话
while True:
	content=input("我:")
	if content=='q':
		break
	else:
		ask(content)

 

接下来是将图灵机器人接入微信

import requests
import json
import itchat

#还是图灵机器人的回复
def ask(content):
	url='http://openapi.tuling123.com/openapi/api/v2'
	data={
	"reqType":0,
    "perception": {
        "inputText": {
            "text":content
        },
        "selfInfo": {
            "location": {
                "city": "广州",
                "province": "广东",
            }
        }
    },
    "userInfo": {
        "apiKey": "你申请的机器人key",
        "userId": "乱填的"
    }
}
	res=requests.post(url=url,data=json.dumps(data))
	answer=res.json()['results'][0]['values']['text']
	print(answer)
	return answer

itchat.auto_login(hotReload=True) 
#加上这个参数是热启动,不用每次扫码登录,不加会每次都要扫码登录
#itchat.auto_login()

nickname='浅棔' #你要发给某个好友的好友昵称
username = itchat.search_friends(name=nickname)[0]['UserName'] 
itchat.send('我是机器人,给我发条消息哦',toUserName=username)  #给这个好友发个消息

@itchat.msg_register(itchat.content.TEXT)  #通过装饰符将print_content注册为处理文本消息的函数。

def print_content(msg): #收到微信的回复
	try:
		answer=ask(msg['Text']) #图灵机器人的回复
		return answer
	except TypeError:  #收到对方发的文本之外的内容
		itchat.send('不要给我发图片,我会打人的!',toUserName=username)
		#有个问题是自己发图片也会提示这行字

这个写的有点缺陷,只能判断好友发来的文字和表情符号,好友如果发表情包、图片、语音啥的,就统一回复他们“不要给我发图片...”。因为现在还不知道怎么处理对方发来的图片,然后回复给他相应的内容,如果有大神知道,求指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值