1 前言
一次偶然的机会,我了解到图灵机器人网站,里面有现成的智能机器人聊天API。正好当时在学tkinter,计划利用tkinter制作一个类似QQ聊天框,与机器人聊天~
具体效果如下(ps:由于在网站的免费额度用完了,这里返回的是“请求次数超限制”):
图灵机器人网站链接:图灵机器人网站
首先需要注册登录,然后点击下图中的“创建机器人”,根据自己的需要创建~
创建完成后,会出现创建数据,其中有apikey!
2 代码分模块讲解
2.1 导入相应的库
首先需要导入相应的库,涉及到tkinter、datetime、time、requests、json等~
from tkinter import * import datetime import time import requests,json from tkinter import scrolledtext
2.2 创建机器人对象
机器人对象实际上是通过request请求访问图灵机器人API!
def computer(self, inquant): userid = 99 #检查一下自己的userid apikey = '' #这里输入自己的apikey startup = '' while True: question = inquant tulingdata1 = json.dumps({ "perception": { "inputText": { "text": question # 将你输入的对话封装成一个字典,再转换成字符串,传给图灵机器人语义系统 }, }, "userInfo": { "apiKey": apikey, # 与图灵语义系统联系 "userId": userid } }) robot1 = requests.post('http://openapi.tuling123.com/openapi/api/v2', tulingdata1) # 因为是人机对话,所以通过post传递信息 jsrobot1 = json.loads(robot1.text)['results'][0]['values']['text'] # 返回图灵机器人的对话 return jsrobot1+'\n'
2.3 创建信息交互过程对象
这里实际上是将发送信息与接收信息的过程进行封装,方便之后的调用。同时使用了时间库,使聊天更加的真实!
def sendmessage(self, text_msglist, text_msg): msgcontent = '我:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n ' text_msglist.insert(END, msgcontent, 'green') text_msglist.insert(END, text_msg.get('0.0', END)) computertent = '图灵机器人:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n ' text_msglist.insert(END, computertent, 'green') computer_talk = text_msg.get('0.0', END) text_msglist.insert(END, (self.computer(computer_talk))) text_msg.delete('0.0', END)
2.4 页面创建对象
通过grid来布局tkinter组件使页面更加的美观
def createPage(self): self.frame_left_top = Frame(width=600, height=220, bg='white') self.frame_left_center = Frame(width=600, height=100, bg='white') self.frame_left_bottom = Frame(width=600, height=20) ##创建需要的几个元素 text_msglist = scrolledtext.ScrolledText(self.frame_left_top) text_msg = Text(self.frame_left_center) button_sendmsg = Button(self.frame_left_bottom, text='发送', command=lambda: self.sendmessage(text_msglist, text_msg)) # 创建一个绿色的tag text_msglist.tag_config('green', foreground='#008B00') # 使用grid设置各个容器位置 self.frame_left_top.grid(row=0, column=0, padx=2, pady=5) self.frame_left_center.grid(row=1, pady=5) self.frame_left_bottom.grid(row=2, column=0) self.frame_left_top.grid_propagate(0) self.frame_left_center.grid_propagate(0) self.frame_left_bottom.grid_propagate(0) # 把元素填充进frame text_msglist.grid() text_msg.grid() button_sendmsg.grid(row=0, column=0, sticky=E)
3 整体代码展示(可直接使用!)
ps:在computer函数中,将改换的换成自己的!
from tkinter import * import datetime import time import requests,json from tkinter import scrolledtext class talk(object): def __init__(self, master=None): self.root = master # 定义内部变量root self.createPage() def computer(self, inquant): userid = 99 apikey = '' #换成自己的apikey startup = '' while True: question = inquant tulingdata1 = json.dumps({ "perception": { "inputText": { "text": question # 将你输入的对话封装成一个字典,再转换成字符串,传给图灵机器人语义系统 }, }, "userInfo": { "apiKey": apikey, # 与图灵语义系统联系 "userId": userid } }) robot1 = requests.post('http://openapi.tuling123.com/openapi/api/v2', tulingdata1) # 因为是人机对话,所以通过post传递信息 jsrobot1 = json.loads(robot1.text)['results'][0]['values']['text'] # 返回图灵机器人的对话 return jsrobot1+'\n' def sendmessage(self, text_msglist, text_msg): msgcontent = '我:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n ' text_msglist.insert(END, msgcontent, 'green') text_msglist.insert(END, text_msg.get('0.0', END)) computertent = '图灵机器人:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n ' text_msglist.insert(END, computertent, 'green') computer_talk = text_msg.get('0.0', END) text_msglist.insert(END, (self.computer(computer_talk))) text_msg.delete('0.0', END) def createPage(self): self.frame_left_top = Frame(width=600, height=220, bg='white') self.frame_left_center = Frame(width=600, height=100, bg='white') self.frame_left_bottom = Frame(width=600, height=20) ##创建需要的几个元素 text_msglist = scrolledtext.ScrolledText(self.frame_left_top) text_msg = Text(self.frame_left_center) button_sendmsg = Button(self.frame_left_bottom, text='发送', command=lambda: self.sendmessage(text_msglist, text_msg)) # 创建一个绿色的tag text_msglist.tag_config('green', foreground='#008B00') # 使用grid设置各个容器位置 self.frame_left_top.grid(row=0, column=0, padx=2, pady=5) self.frame_left_center.grid(row=1, pady=5) self.frame_left_bottom.grid(row=2, column=0) self.frame_left_top.grid_propagate(0) self.frame_left_center.grid_propagate(0) self.frame_left_bottom.grid_propagate(0) # 把元素填充进frame text_msglist.grid() text_msg.grid() button_sendmsg.grid(row=0, column=0, sticky=E) if __name__ == "__main__": root = Tk() root.title('图灵机器人聊天') talk(root) root.mainloop()
最后再次展示一下界面图: