• 实战:搭建在线聊天机器人


    思路:首先,客户端和服务端建立socket连接,然后客户端向服务端发送消息,服务端接收消息,并调用 图灵机器人API接口,获取回复返回给客户端。

    server端:
    import socket
    import time
    import threading
    import requests
    import json
    
    class ChatServer:
        def __init__(self, port):
    # 绑定服务器的ip和端口,注意以tuple的形式
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.bind(("0.0.0.0", port))
            self.socket.listen(5)
            # 图灵机器人,授权码
            self.key = "6fd2ff147c794ecfb2fbb40ecb3df4d3"
            print("正在监听 127.0.0.1 :{}...".format(port))
    
        def tcplink(self, sock, addr):
            # 每次连接,开始聊天前,先欢迎下。
            sock.send("你好,欢迎来到机器人聊天器!".encode("utf-8"))
            while True:
                data = sock.recv(1024).decode("utf-8")
                print(sock.getpeername())
                print(sock.getsockname())
                print(sock.fileno())
                username = data.split("::")[0]
                msg = data.split("::")[1]
                if msg == "exit":
                   break
                if msg:
                    print(""+username+""+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time())))
                    print(msg)
                    response = self.get_response(msg)
                    sock.send(response.encode("utf-8"))
            sock.close()
            print("与 {} 结束聊天!".format(username))
    
        def get_response(self, info):
            # 调用图灵机器人API
            url = 'http://www.tuling123.com/openapi/api?key=' + self.key + '&info=' + info
            res = requests.get(url)
            res.encoding = 'utf-8'
            jd = json.loads(res.text)
            return jd['text']
    
        def main(self):
            while True:
                sock, addr = self.socket.accept()
                t=threading.Thread(target=self.tcplink, args=(sock, addr))
                t.start()
    
    if __name__ == '__main__':
        cs = ChatServer(port=9999)
        cs.main()
    client端:
    
    import socket
    import time
    
    class ChatClient:
        def __init__(self, username, port):
            self.username = username
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect(("127.0.0.1", port))
    
        def send_msg(self, msg):
            self.socket.send("{username}::{msg}".format(username=self.username,msg=msg).encode("utf-8"))
    
        def recv_msg(self):
            data=self.socket.recv(1024)
            if data:
                print("
    【机器人小图】"+" "+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time())))
                print(data.decode("utf-8"))
                return True
            return False
    
        def main(self):
            data = self.socket.recv(1024)
            print(data.decode("utf-8"))
            msg = input("请输入消息:")
            self.send_msg(msg)
            while True:
                if self.recv_msg():
                    msg=input("
    我:")
                    self.send_msg(msg)
                    if msg == "exit":
                        print("聊天室已关闭")
                        break
    
    if __name__ == '__main__':
        cc = ChatClient(username="小明", port=9999)
        cc.main()
  • 相关阅读:
    七牛上传图片视频demo
    JavaScript数组及相关方法
    Math对象产生随机数一个小应用
    JavaScript 开发进阶:理解 JavaScript 作用域和作用域链
    HTML5 中的meter 标签的样式设置
    jQuery报错:Uncaught ReferenceError: $ is not defined
    每次打开office 2013都提示配置进度,必须得等他下完然后重启,重启完了在打开,还是提示配置进度,怎么解决
    CSS小技巧收藏
    DOM中元素节点、属性节点、文本节点的理解13.3
    (转)如果知道dll文件是面向32位系统还是面向64位系统的?
  • 原文地址:https://www.cnblogs.com/zcok168/p/9290996.html
Copyright © 2020-2023  润新知