
[Python 原创] python接入AI 实现微信自动回复接入deepseek 也没问题
【Python+AI微信智能回复助手】这是一款基于Python uiautomation库开发的微信自动化工具,深度融合AI语义理解能力,可实现无人值守的智能消息应答系统。程序通过精准绑定微信窗口控件,实时扫描会话列表中的未读消息,并调用第三方API(兼容DeepSeek等主流AI平台)进行智能语义解析,自动生成拟人化回复内容。核心功能包含:窗口自动化控制、多线程消息监听、AI对话引擎无缝对接、动
import numpy as np # 引入numpy库,目的是将读取的数据转换为列表
from uiautomation import WindowControl # 引入uiautomation库中的WindowControl类,用来进行图像识别和模拟操作
import requests
import json
# 绑定微信主窗口
wx = WindowControl(
Name='微信',
searchDepth=1
)
# 切换窗口
# wx.ListControl()
wx.SwitchToThisWindow()
# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')
# 通过pd读取数据
# df = pd.read_excel(r'C:\Users\whz\Desktop\test.xls')
# print(df)
# 死循环接收消息
while True:
# 从查找未读消息
we = hw.TextControl(searchDepth=4)
# 死循环维持,没有超时报错
while not we.Exists():
pass
# 存在未读消息
if we.Name:
# 点击未读消息
we.Click(simulateMove=False)
# 读取最后一条消息
last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
print(last_msg)
sess = requests.get(
('http://route.showapi.com/60-27?&showapi_appid=102421&userid=userid&showapi_sign=77760de9bbc640f68433718f807b3e42&info=' + last_msg))
js = sess.text
js = json.loads(js)
print('原主人不在机器人自动回复:', js['showapi_res_body']['text'])
replyMsg='原主人不在机器人自动回复:', js['showapi_res_body']['text']
result = ' '.join(map(str, replyMsg))
wx.SendKeys(result.replace('{br}', '{Shift}{Enter}'), waitTime=1)
# 发送消息 回车键
wx.SendKeys('{Enter}', waitTime=1)
# 通过消息匹配检索会话栏的联系人
wx.TextControl(SubName=result[:5]).RightClick()
一、贾维斯机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('http://tool.mkblog.cn/robot/new.php?word=' + msg))
js = sess.text
js = json.loads(js)
print('贾维斯机器人:', js['text'])
测试:
我:你好
机器人:嘿嘿,你好我好大家好!
二、微梦机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('https://open.drea.cc/bbsapi/chat/get?keyWord=' + msg + '&userName=type%3Dbbs'))
js = sess.text
js = json.loads(js)
print('微梦机器人:', js['data']['reply'])
测试:
我:你好
机器人:呵呵,都好!
三、海知机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(('http://api.ruyi.ai/v1/message?app_key=d8eafc3b-6392-4465-8abc-f780ee8f2452&user_id=test123&q=' + msg))
js = sess.text
js = json.loads(js)
js = js['result']['intents']
js = js[0]['result']['text']
print('海知机器人:', js)
请替换上面的api,api申请地址:http://ruyi.ai/official.html,上面的api站长免费提供
测试:
我:你好
机器人:你好!好久不见
四、飔拓机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('http://open.stormorai.com/api-v2/?key=07d66440351a3cbddf9b2f91ea48938e&query=' + msg))
js = sess.text
js = json.loads(js)
print('飔拓机器人:', js['data']['answer'])
请替换上面的api,api申请地址:http://open.stormorai.com,上面的api站长免费提供
测试:
我:你好
机器人:我很好呀
五、万维易源机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('http://route.showapi.com/60-27?&showapi_appid=102421&userid=userid&showapi_sign=77760de9bbc640f68433718f807b3e42&info=' + msg))
js = sess.text
js = json.loads(js)
print('万维易源机器人:', js['showapi_res_body']['text'])
请替换上面的api,api申请地址:https://www.showapi.com/apiGateway/view?apiCode=60,上面的api站长免费提供
测试:
我:你好
机器人:啦啦啦,每天都是好心情
六、阿凡达机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('http://api.avatardata.cn/Tuling/Ask?key=8e35be39afae4a4b9d57d531f707f5b0&info=' + msg))
js = sess.text
js = json.loads(js)
print('阿凡达机器人:', js['result']['text'])
请替换上面的api,api申请地址:https://avatardata.cn/Docs/Api/4068ce58-df2d-4836-a4af-86abc1974d27,上面的api站长免费提供
测试:
我:武汉
机器人:武汉,简称“汉”,现为湖北省省会,华中地区最大都市及中心城市,中国长江中下游特大城市
七、进制机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('https://api.binstd.com/iqa/query?appkey=db02abf71800fd05&question=' + msg))
js = sess.text
js = json.loads(js)
print('进制机器人:', js['result']['content'])
请替换上面的api,api申请地址:https://www.binstd.com/api/iqa.html,上面的api站长免费提供
测试:
我:你好
机器人:你好,我是小i机器人,很高兴认识你。
八、极速机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(('https://api.jisuapi.com/iqa/query?appkey=c0e4885a90566a7b&question=' + msg))
js = sess.text
js = json.loads(js)
print('极速机器人:', js['result']['content'])
请替换上面的api,api申请地址:https://www.jisuapi.com/api/iqa,上面的api站长免费提供
测试:
我:你好
机器人:你好,我是小i机器人,很高兴认识你。
九、腾讯智能闲聊
import optparse
import time
import json
import hashlib
import urllib
import urllib.request
import base64
#接口api
url_preffix = 'https://api.ai.qq.com/fcgi-bin/'
def setParams(array, key, value):
array[key] = value
def genSignString(parser):
uri_str = ''
for key in sorted(parser.keys()):
if key == 'app_key':
continue
uri_str += "%s=%s&" % (key,
urllib.parse.quote(str(parser[key]), safe=''))
sign_str = uri_str + 'app_key=' + parser['app_key']
hash_md5 = hashlib.md5(sign_str.encode("latin1"))
return hash_md5.hexdigest().upper()
class AiPlat(object):
def __init__(self, app_id, app_key):
self.app_id = app_id
self.app_key = app_key
self.data = {}
def invoke(self, params):
self.url_data = urllib.parse.urlencode(params).encode(encoding='utf-8')
req = urllib.request.Request(self.url, self.url_data)
try:
rsp = urllib.request.urlopen(req)
str_rsp = rsp.read()
dict_rsp = json.loads(str_rsp.decode('utf-8'))
return dict_rsp
except urllib.error.URLError as e:
dict_error = {}
if hasattr(e, "code"):
dict_error = {}
dict_error['ret'] = -1
dict_error['httpcode'] = e.code
dict_error['msg'] = "sdk http post err"
return dict_error
if hasattr(e, "reason"):
dict_error['msg'] = 'sdk http post err'
dict_error['httpcode'] = -1
dict_error['ret'] = -1
return dict_error
else:
dict_error = {}
dict_error['ret'] = -1
dict_error['httpcode'] = -1
dict_error['msg'] = "system error"
return dict_error
def getNlpTextChat(self, session, question):
self.url = url_preffix + 'nlp/nlp_textchat'
setParams(self.data, 'app_id', self.app_id)
setParams(self.data, 'app_key', self.app_key)
setParams(self.data, 'time_stamp', int(time.time()))
setParams(self.data, 'nonce_str', int(time.time()))
setParams(self.data, 'session', session)
setParams(self.data, 'question', question)
sign_str = genSignString(self.data)
setParams(self.data, 'sign', sign_str)
return self.invoke(self.data)
app_key = '6MSRsOCMaX3WIQoG'
app_id = '2130771105'
def anso(questionS):
str_question = questionS
session = 10000
ai_obj = AiPlat(app_id, app_key)
rsp = ai_obj.getNlpTextChat(session, str_question)
if (rsp['ret'] == 0):
ask = rsp['data']['answer']
print(('腾讯智能闲聊机器人:' + ask))
else:
print('腾讯智能闲聊机器人:你说什么?我听不见。')
if (__name__ == '__main__'):
while True:
questionS = input('我:')
anso(questionS)
请替换上面的api,api申请地址:https://ai.qq.com/product/nlpchat.shtml,上面的api站长免费提供
测试:
我:你好
机器人:嗯嗯,你好啊
十、百度翻译机器人
import requests
import string
import time
import hashlib
import json
#init
api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
my_appid = '20190808000325141'
cyber = 'eRu9_46h6KBXhyf3XyE2'
lower_case = list(string.ascii_lowercase)
def requests_for_dst(word):
#init salt and final_sign
salt = str(time.time())[:10]
final_sign = str(my_appid)+word+salt+cyber
final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest()
#区别en,zh构造请求参数
if list(word)[0] in lower_case:
paramas = {
'q': word,
'from': 'en',
'to': 'zh',
'appid': '%s' % my_appid,
'salt': '%s' % salt,
'sign': '%s' % final_sign
}
my_url = api_url+'?appid=' + \
str(my_appid)+'&q='+word+'&from='+'en'+'&to=' + \
'zh'+'&salt='+salt+'&sign='+final_sign
else:
paramas = {
'q': word,
'from': 'zh',
'to': 'en',
'appid': '%s' % my_appid,
'salt': '%s' % salt,
'sign': '%s' % final_sign
}
my_url = api_url+'?appid=' + \
str(my_appid)+'&q='+word+'&from='+'zh'+'&to=' + \
'en'+'&salt='+salt+'&sign='+final_sign
response = requests.get(api_url, params=paramas).content
content = str(response, encoding="utf-8")
json_reads = json.loads(content)
print('小度机器人:这句话翻译为中文是',json_reads['trans_result'][0]['dst'])
while True:
word = input("我: ")
requests_for_dst(word)
请替换上面的api,api申请地址:http://api.fanyi.baidu.com/product/11,上面的api站长免费提供
测试:
我:hello
机器人:这句话翻译为中文是 你好
十一、AIML机器人
import aiml
import sys
import os
def get_module_dir(name):
print("module", sys.modules[name])
path = getattr(sys.modules[name], '__file__', None)
print(path)
if not path:
raise AttributeError('module %s has not attribute __file__' % name)
return os.path.dirname(os.path.abspath(path))
alice_path = get_module_dir('aiml') + '\\botdata\\alice'
os.chdir(alice_path)
alice = aiml.Kernel()
alice.learn("startup.xml")
alice.respond('LOAD ALICE')
while True:
message = input("我:")
if("exit" == message):
exit()
response = alice.respond(message)
print('AIML机器人:',response)
测试:
我:你好
机器人:你最喜欢的科幻作家是谁?
十二、小气机器人
import urllib.request
import gzip
import json
import time
print('小气机器人:你好哦,我就是很爱发火的小气机器人哟(^U^)ノ~YO~')
time.sleep(2)
print('小气机器人:我可不是一个小气的人,你可不能说我小气哟~')
time.sleep(2)
print('小气机器人:快告诉我你想要查询的城市吧!')
def get_weather_data():
city_name = input('我:')
time.sleep(0.3)
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + \
urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(url1)
weather_data = urllib.request.urlopen(url1).read()
#读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
#解压网页数据
weather_dict = json.loads(weather_data)
#将json数据转换为dict数据
return weather_dict
def show_weather(weather_data):
weather_dict = weather_data
#将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
time.sleep(1)
print('小气机器人:咦?你输入的城市名可能有误哦,也有可能是天气中心没有收录这个城市哦~再输入一遍吧~')
elif weather_dict.get('desc') == 'OK':
forecast = weather_dict.get('data').get('forecast')
print('小气机器人:好滴,下面将由我来播报今天的天气情况哦,记得要竖起耳朵认真听哟~')
time.sleep(1)
print('小气机器人:你查询的城市名称叫', weather_dict.get('data').get('city'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的这个城市的温度是', weather_dict.get('data').get('wendu')+'℃ ', '哦!')
time.sleep(0.3)
print('小气机器人:你所查询的城市天气', weather_dict.get('data').get('ganmao'))
time.sleep(0.3)
print('小气机器人:你查询的城市今天的风向是', forecast[0].get('fengxiang'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的城市今天的风级是', forecast[0].get('fengli'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的城市今天的最高温度是', forecast[0].get('high'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的城市今天的最低温度是', forecast[0].get('low'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的城市今天的风向是', forecast[0].get('type'), '哦!')
time.sleep(0.3)
print('小气机器人:你查询的天气的日期是', forecast[0].get('date'), '哦!')
time.sleep(0.3)
print('小气机器人:主人,你想要查询未来四天的天气吗?回复我是(Y)或者否(N)哦~')
time.sleep(0.3)
four_day_forecast = input('我:')
time.sleep(0.3)
if four_day_forecast == '是' or 'Y' or 'y':
for i in range(1,5):
print('小气机器人:你查询的天气的日期是', forecast[i].get('date'))
time.sleep(0.3)
print('小气机器人:你查询的城市未来的风向是', forecast[i].get('fengxiang'))
time.sleep(0.3)
print('小气机器人:你查询的城市未来的风级是', forecast[i].get('fengli'))
time.sleep(0.3)
print('小气机器人:你查询的城市未来的最高温度是', forecast[i].get('high'))
time.sleep(0.3)
print('小气机器人:你查询的城市未来的最低温度是', forecast[i].get('low'))
time.sleep(0.3)
print('小气机器人:你查询的城市未来的天气是', forecast[i].get('type'))
time.sleep(0.3)
print('----------下一天----------')
time.sleep(0.3)
print('小气机器人:主人,天气播报完毕,是否还要查询其他城市呢?如果没有就再见~')
while True:
show_weather(get_weather_data())
测试:
我:武汉
机器人:好滴,下面将由我来播报今天的天气情况哦,记得要竖起耳朵认真听哟~
十三、天行机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(('http://api.tianapi.com/txapi/robot/index?key=1aab447a6be202ff7c8b22e0c8c2ce3f&question=' + msg))
js = sess.text
js = json.loads(js)
print('天行机器人:', js['newslist'])
请替换上面的api,api申请地址:https://www.tianapi.com/apiview/47,上面的api站长免费提供
测试:
我:你好
机器人:好!
十四、小豆机器人
import requests,json
while True:
msg = input('我:')
sess = requests.get(
('http://api.douqq.com/?key=NT14dVFlRlFGeU8yRFhJek5ncz1hNFozcWhjQUFBPT0&msg=' + msg))
js = sess.text
print('小豆机器人:', js)
请替换上面的api,api申请地址:http://xiao.douqq.com,上面的api站长免费提供
测试:
我:你好
机器人:我在这里好久了,终于等到你来啦
十五、小P机器人
print('Hello!我是小P')
ans = input('你中午吃了什么啊?')
print('哎,反正我是一台电脑,什么也吃不着!')
print('其实我也想吃', ans)
测试:
我:汉堡
机器人:其实我也想吃 汉堡
十六、小爱机器人
name = '小爱'
age = '10岁'
hobby = '聊天'
hello = '你好, 嗨, 在吗, 在吗?, 哈喽, 哈喽?'
for i in range(5):
message = input('我:')
if (message in hello):
print(name, '说:', '嗨!我是', name, sep='')
elif (message == '你多大了呀'):
print(name, '说:', '我', age, '了', sep='')
elif (message == '你喜欢做什么'):
print(name, '说:', '我喜欢', hobby, '~', sep='')
else:
print(name, '说:', '哎呀,你说什么?', sep='')
测试:
我:你喜欢做什么
机器人:我喜欢聊天~
十七、模拟机器人
while 1:
print('模拟机器人:'+input('我: ').strip('吗??')+'!')
测试:
我:你好
机器人:你好!
十八、小i机器人
import urllib.request,re
while True:
msg = input("我:")
msg = urllib.parse.quote(msg)
link = urllib.request.urlopen(
"http://nlp.xiaoi.com/robot/webrobot?&callback=__webrobot_processMsg&data=%7B%22sessionId%22%3A%22ff725c236e5245a3ac825b2dd88a7501%22%2C%22robotId%22%3A%22webbot%22%2C%22userId%22%3A%227cd29df3450745fbbdcf1a462e6c58e6%22%2C%22body%22%3A%7B%22content%22%3A%22" + msg + "%22%7D%2C%22type%22%3A%22txt%22%7D")
html_doc = link.read().decode()
reply_list = re.findall(r'\"content\":\"(.+?)\\r\\n\"', html_doc)
print("小i机器人:" + reply_list[-1])
测试:
我:你好
机器人:你好,我是小i机器人,很高兴认识你。
十九、青云客机器人
import requests,json
while True:
msg = input("我:")
js = requests.get("http://api.qingyunke.com/api.php",{'key': 'free', 'appid': 0, 'msg': msg})
js.encoding = 'utf8'
js = js.json()
print('青云客机器人:', js['content'])
测试:
我:你好
机器人:我很好,你呢,你怎么样
二十、茉莉机器人
import requests,json
conversation = "你好!"
msg = "我:"
robot = "茉莉机器人:"
while True:
moli_data = {
"question": conversation,
"api_key": "9d607f075997e4684a59f7675a37a658",
"api_secret": "26f3e0604hzz"
}
moli_api_url = 'http://i.itpk.cn/api.php'
return_json = requests.post(
moli_api_url, data=moli_data)
if '笑话' == conversation:
if return_json.text.startswith(u'\ufeff'):
str = return_json.text.encode('utf8')[3:].decode('utf8')
json_change_wordbook = json.loads(str)
title = json_change_wordbook['title']
content = json_change_wordbook['content']
print(robot + title + "\n" + content)
elif '观音灵签' == conversation:
if return_json.text.startswith(u'\ufeff'):
str = return_json.text.encode('utf8')[3:].decode('utf8')
json_change_wordbook = json.loads(str)
number1 = json_change_wordbook['number1']
number2 = json_change_wordbook['number2']
haohua = json_change_wordbook['haohua']
qianyu = json_change_wordbook['qianyu']
shiyi = json_change_wordbook['shiyi']
jieqian = json_change_wordbook['jieqian']
type = json_change_wordbook['type']
print(number1 + "\n" + number2 + "\n" + haohua + "\n" +
qianyu + "\n" + shiyi + "\n" + jieqian + "\n" + type)
elif '月老灵签' == conversation:
if return_json.text.startswith(u'\ufeff'):
str = return_json.text.encode('utf8')[3:].decode('utf8')
json_change_wordbook = json.loads(str)
number1 = json_change_wordbook['number1']
number2 = json_change_wordbook['number2']
haohua = json_change_wordbook['haohua']
shiyi = json_change_wordbook['shiyi']
jieqian = json_change_wordbook['jieqian']
zhushi = json_change_wordbook['zhushi']
baihua = json_change_wordbook['baihua']
type = json_change_wordbook['type']
print(number1 + "\n" + number2 + "\n" + haohua + "\n" + shiyi +
"\n" + jieqian + "\n" + zhushi + "\n" + baihua + "\n" + type)
elif '财神爷灵签' == conversation:
if return_json.text.startswith(u'\ufeff'):
str = return_json.text.encode('utf8')[3:].decode('utf8')
json_change_wordbook = json.loads(str)
number1 = json_change_wordbook['number1']
number2 = json_change_wordbook['number2']
qianyu = json_change_wordbook['qianyu']
zhushi = json_change_wordbook['zhushi']
jieqian = json_change_wordbook['jieqian']
jieshuo = json_change_wordbook['jieshuo']
jieguo = json_change_wordbook['jieguo']
hunyin = json_change_wordbook['hunyin']
jiaoyi = json_change_wordbook['jiaoyi']
type = json_change_wordbook['type']
print(number1 + "\n" + number2 + "\n" + qianyu + "\n" + zhushi + "\n" + jieqian +
"\n" + jieshuo + "\n" + jieguo + "\n" + hunyin + "\n" + jiaoyi + "\n" + type)
else:
print(robot + return_json.text)
conversation = input(msg)
请替换上面的api,api申请地址:http://www.itpk.cn,上面的api站长免费提供
测试:
我:你好
机器人:你你好,很高兴认识你
二十一、思知机器人
import requests,json
while True:
msg = input('我:')
sess = requests.get(('https://api.ownthink.com/bot?spoken=' + msg))
js = sess.text
js = json.loads(js)
print('思知机器人:', js['data']['info']['text'])
测试:
我:你好
机器人:你好呀。
二十二、图灵机器人
import requests,json
while True:
msg = input("我:")
key = {
"key":"238061b41e4b4d7cbba29f2fac58173C",
"info":msg
}
url = "http://www.tuling123.com/openapi/api"
request = requests.post(url,data=key)
js = json.loads(request.text)
print("图灵机器人:"+js["text"])
请替换上面的api,api申请地址:http://www.turingapi.com,上面的api站长免费提供
测试:
我:你好
机器人:我们每天都打招呼吧
二十三、QQ机器人
# -*- coding: utf-8 -*-
from qqbot import QQBotSlot as qqbotslot, RunBot
@qqbotslot
def onQQMessage(bot, contact, member, content):
if content == '-hello':
bot.SendTo(contact, '你好,我是QQ机器人')
elif content == '在':
bot.SendTo(contact, '我一直在呢,嘻嘻')
elif content == '-stop':
bot.SendTo(contact, 'QQ机器人已关闭')
bot.Stop()
if __name__ == '__main__':
RunBot()
测试:
无
二十四、图灵机器人和茉莉机器人对话
# coding=utf8
from time import sleep
import requests
chedan = "让我们开始对话吧!^_^"
tuling = "图灵机器人: "
moli = "茉莉机器人: "
print (moli + chedan)
while True:
tuling_data = {
"key": "238061b41e4b4d7cbba29f2fac58173C",
"info": chedan,
}
tuling_api_url = 'http://www.tuling123.com/openapi/api'
t = requests.post(tuling_api_url, data=tuling_data)
print (tuling + eval(t.text)["text"])
chedan = eval(t.text)["text"]
moli_data = {
"question": chedan,
"api_key": "9d607f075997e4684a59f7675a37a658",
"api_secret": "26f3e0604hzz"
}
moli_api_url = 'http://i.itpk.cn/api.php'
m = requests.post(moli_api_url, data=moli_data)
print (moli + m.text)
chedan = m.text
请替换上面的api,上面的api站长免费提供
测试:
茉莉机器人:太好了。
图灵机器人:我觉得简直完美啊。
二十五、图灵机器人与青云客机器人对话
from time import sleep
import requests
s = input("请主人输入话题:")
while True:
resp = requests.post("http://www.tuling123.com/openapi/api",data={"key": "4fede3c4384846b9a7d0456a5e1e2943", "info": s, })
resp = resp.json()
print('图灵机器人:', resp['text'])
s = resp['text']
resp = requests.get("http://api.qingyunke.com/api.php", {'key': 'free', 'appid': 0, 'msg': s})
resp.encoding = 'utf8'
resp = resp.json()
print('青云客机器人:', resp['content'])
请替换上面的api,api申请地址:http://www.turingapi.com,上面的api站长免费提供
测试:
图灵机器人:到学校里就是为了学习知识呀。
青云客机器人:就是为了这样的目的吗
二十六、两个图灵机器人互相对话
import json
import urllib.request
import time
api_url = "http://openapi.tuling123.com/openapi/api/v2"
api_key_1 = "4fede3c4384846b9a7d0456a5e1e2943"
api_key_2 = "238061b41e4b4d7cbba29f2fac58173C"
tag = 0
api_key = api_key_1
text_input = input('对话起点:')
while True:
req = {
"perception":
{
"inputText":
{
"text": text_input
},
"selfInfo":
{
"location":
{
"city": "鄂州",
"province": "湖北",
"street": "古城路"
}
}
},
"userInfo":
{
"apiKey": api_key,
"userId": "hexinjiyi"
}
}
if tag == 0:
api_key = api_key_1
tag = 1
else:
api_key = api_key_2
tag = 0
req = json.dumps(req).encode('utf8')
http_post = urllib.request.Request(api_url, data=req, headers={
'content-type': 'application/json'})
response = urllib.request.urlopen(http_post)
response_str = response.read().decode('utf8')
response_dic = json.loads(response_str)
intent_code = response_dic['intent']['code']
results_text = response_dic['results'][0]['values']['text']
if tag == 1:
print('图灵机器人①:' + results_text)
else:
print('图灵机器人②:' + results_text)
text_input = results_text
请替换上面的api,上面的api站长免费提供
测试:
图灵机器人①:有本事就一直学下去。
图灵机器人②:我有点儿傻。
二十七、青云客机器人与思知机器人对话
# -*- coding: utf-8 -*-
import requests
import datetime
if __name__ == "__main__":
talk = input("请输入第一句消息开启对话:")
while True:
res = requests.post(
"http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + talk)
res = res.json()
print("青云客机器人:",(res["content"]))
talk = res["content"]
res = requests.post("https://api.ownthink.com/bot?spoken=" + talk)
res = res.json()
print("思知机器人:",res["data"]["info"]["text"] )
talk = res["data"]["info"]["text"]
测试:
青云客机器人:跟看我是不是有肉吃?
思知机器人:也许可能大概未必不一定是
二十八、聚合机器人
import requests
import json
while True:
msg = input('我:')
sess = requests.get(
('http://op.juhe.cn/iRobot/index?info=' + msg + '&key=d7033f634d2d1f9960eb244d8c71d87c'))
js = sess.text
js = json.loads(js)
print('聚合机器人:', js['result']['text'])
二十九、智能训练机器人
from chatterbot import ChatBot
bot = ChatBot(
'Sakura',
storage_adapter='chatterbot.storage.MongoDatabaseAdapter'
)
def r(s):return bot.get_response(s).text
while True:
i = input('>>> ').strip()
if i != 'exit':
print(r(i))
else:
break
三十、日本聊天机器人
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
import types
KEY = '314d5453595743683648644b5a695043426176546b5277664b6572374457623557634c4f486e5046506242'
#エンドポイントの設定
endpoint = 'https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY=REGISTER_KEY'
url = endpoint.replace('REGISTER_KEY', KEY)
#1回目の会話の入力
utt_content = raw_input('>>')
payload = {'utt': utt_content, 'context': ''}
headers = {'Content-type': 'application/json'}
#送信
r = requests.post(url, data=json.dumps(payload), headers=headers)
data = r.json()
#jsonの解析
response = data['utt']
context = data['context']
#表示
print ("response: "%s % (response))
#2回目以降の会話(Ctrl+Cで終了)
while True:
utt_content = raw_input('>>')
payload['utt'] = utt_content
payload['context'] = data['context']
r = requests.post(url, data=json.dumps(payload), headers=headers)
data = r.json()
response = data['utt']
context = data['context']
print ("response: %s" % (response))
三十一、微软小冰
from wxpy import *
bot = Bot()
xiaobin = bot.mps().search('小冰')[0]
group = bot.groups()
chat = 0
@bot.register()
def forward_others(msg):
global chat
global group
if msg.chat != xiaobin and msg.chat not in group:
chat = msg.chat
msg.forward(xiaobin)
else:
if msg.chat == xiaobin:
msg.forward(chat, suffix='--小冰')
bot.join()
三十二、itchat微信机器人
import itchat
import asyncio
channel_input_to_think = []
channel_think_to_output = []
running = True
@itchat.msg_register(itchat.content.TEXT, isFriendChat=True)
def some_one_say_something(msg):
if msg["FromUserName"] == "newsapp":
return
channel_input_to_think.append(msg)
async def think_system():
while running:
if len(channel_input_to_think) == 0:
await asyncio.sleep(1)
else:
think()
return
async def output_system():
while running:
if len(channel_think_to_output) == 0:
await asyncio.sleep(1)
else:
output()
return
def think():
while len(channel_input_to_think) > 0:
msg = channel_input_to_think.pop()
if msg["Type"] == itchat.content.TEXT:
channel_think_to_output.append(
{"action": "send_text", "to": msg["FromUserName"], "content": "你好"}
)
pass
return
def output():
while len(channel_think_to_output) > 0:
event = channel_think_to_output.pop()
if event["action"] == "send_text":
to = event["to"]
content = event["content"]
itchat.send_msg(msg=content, toUserName=to)
pass
return
if __name__ == "__main__":
itchat.auto_login(hotReload=True)
itchat.run(blockThread=False)
loop = asyncio.get_event_loop()
system_list = [output_system(), think_system()]
loop.run_until_complete(asyncio.wait(system_list))
更多推荐
所有评论(0)