python3 socket接入图灵机器人自动聊天
使用python3的socket模块
server.py
import socket import requests, json def get_tuling(info): post_json = { "reqType": 0, "perception": { "inputText": { "text": info }, }, "userInfo": { "apiKey": "xxx", "userId": "xxx" } } dat = json.dumps(post_json) #访问接口需要提供一个标准的json
#https://www.kancloud.cn/turing/www-tuling123-com/718227 API接入文档
url = 'http://openapi.tuling123.com/openapi/api/v2' response = requests.post(url, data=dat).json() return response['results'][0]['values']['text'] server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', 9000)) server.listen(5) while True: conn, address = server.accept() while True: data = conn.recv(1024).decode('utf-8') print(data) response = get_tuling(data) conn.send(response.encode('utf-8'))
client.py
import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 9000)) while True: user_input = input('>>>') client.send(user_input.encode('utf-8')) response = client.recv(1024).decode('utf-8') print(response)