智能机器人的简单聊天

robot.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import demjson

API_KEY = '5e0b241b7507443ca4a9eac826d0620f'


def send_msg(msg, userID):
    url = "http://openapi.tuling123.com/openapi/api/v2"  # 接口地址
    json_params = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": msg
            },
        },
        "userInfo": {
            "apiKey": API_KEY,
            "userId": userID
        }
    }
    response = requests.post(url, json=json_params)
    json_obj = demjson.decode(response.text)
    print(json_obj)
    return json_obj['results'][0]['values']['text']


# if __name__ == '__main__':
#     send_msg('hello world', '123456789')

# 参考图灵机器人 Web API

server.py 

​
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from tcpdemo.robot import send_msg
import redis
import socket
import time

cache = redis.Redis()  # 用redis缓存

sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)  # 创建socket对象, SOCK_STREAM tcp, SOCK_DGRAM udp

sock.bind(('127.0.0.1', 8001))  # 绑定本地ip和端口
sock.listen()  # 监听
client_sock, (client_ip, client_port) = sock.accept()  # 接收客户端发来的请求, 如果没有则会一直阻塞直到有为止(参数:socket对象, 地址, 我将client_address拆分为ip和port)

# 判断userID是否在缓存中, userID需要是个额整数
if cache.exists(client_ip):
    userID = int(cache.get(client_ip))
else:
    userID = str(int(time.time()))
    cache.set(client_ip, userID)  # 保存userID

# 循环读写操作
while True:
    try:
        client_msg = client_sock.recv(1024)  # 保存客户端传过来的数据
        client_sock.send(send_msg(client_msg.decode(), userID).encode())
        print('接收到的客户端的消息: ', client_msg.decode())

    except ConnectionResetError as e:
        print('客户端下线了')
        break

client_sock.close()  # 关闭

​

client.py 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket

sock = socket.socket()  # 创建socket对象
sock.connect(('127.0.0.1', 8001))  # 连接ip
while True:
    msg = input('请输入内容: ')
    sock.send(msg.encode())
    server_msg = sock.recv(1024)  # 把服务端传过来的数据保存
    print('接收到的服务端的消息: ', server_msg.decode())  # 解码服务端传过来的数据

sock.close()  # 关闭

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值