欢迎来到Louis的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

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)

 

posted on 2018-09-04 11:14  Louiszj  阅读(426)  评论(0编辑  收藏  举报

导航