API聊天机器人
import requests
import itchat
itchat.auto_login()
##时刻监控好友发送的文本消息,并给予一个回复
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
##获取好友发送的消息内容
content = msg['Content']
##将好友的消息发送给机器人处理,处理结果iuo就是返回给好友的信息
returnContent = get_tuling_reponse(content)
return returnContent
def get_tuling_reponse(_info):
print(_info)
#图灵机器人的网址
api_url = "http://www.tuling123.com/openapi/api"
data = {
'key':'077cbff1b4534d44bb2896ea37b5c47d',
'info':_info,
'userid':'wechat-robot'
}
#发送数据到指定网址,获取网址返回的数据(字符数据类型)
res = requests.post(api_url,data).json()
print(res['text'])
return res['text']
itchat.run()
结果:
给指定用户发送消息
import itchat
itchat.auto_login()
info = itchat.get_friends('李佳')
info_lijia = info[0]['UserName']
itchat.send('hello',toUsername = info_lijia)
通过手机控制电脑
import itchat
import os
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
print(msg)
if msg['ToUserName'] == 'filehelper':
command = msg['Content']
print(command)
if os.system(command) == 0:
res = os.popen(command).read()
result = '命令执行成功,执行结果:' + res
itchat.send(result,'filehelper')
else:
result = '命令%s执行失败,请重试' %(command)
itchat.send(result,'filehelper')
if __name__ == "__main__":
itchat.auto_login(hotReload=True)
itchat.run()
结果: