爬虫 和机器人聊天

作者: gavin 分类: Python,爬虫技术 发布时间: 2020-10-22 18:53

基础版聊天

import requests, json
url = 'http://openapi.tuling123.com/openapi/api/v2'
robotName = 'Robot'
apiKey = '61f2cfc8b00b41c4a2605b11671367a2'
while True:
    text=(input('发言:'))
    data = {
        "reqType":0,
        "perception": {
            "inputText": {
                "text": text
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "北京",
                    "province": "北京",
                    "street": "信息路"
                }
            }
        },
        "userInfo": {
            "apiKey": apiKey,
            "userId": robotName
        }
    }
    data = json.dumps(data).encode('utf8')
    res = requests.post(url, data=data)
    res = res.json()
    print(robotName+':'+res['results'][0]['values']['text'])

两个机器人对聊

import json
import urllib.request
import time

api_url = "http://openapi.tuling123.com/openapi/api/v2"
api_key_1 = "9673a0ad88b244b0a7fa36728fd5b929"
api_key_2 = "61f2cfc8b00b45c4a2603b11671367a2"
tag = 0

api_key = api_key_1
text_input = input('对话起点:')

while True:
    req = {
        "perception":
            {
                "inputText":
                    {
                        "text": text_input
                    },

                "selfInfo":
                    {
                        "location":
                            {
                                "city": "长沙",
                                "province": "湖南",
                                "street": "四方坪"
                            }
                    }
            },

        "userInfo":
            {
                "apiKey": api_key,
                "userId": "hexinjiyi"
            }
    }

    if tag == 0:
        api_key = api_key_1
        tag = 1
    else:
        api_key = api_key_2
        tag = 0

    req = json.dumps(req).encode('utf8')
    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)
    response_str = response.read().decode('utf8')
    response_dic = json.loads(response_str)
    intent_code = response_dic['intent']['code']
    results_text = response_dic['results'][0]['values']['text']
    if tag == 1:
        print('图灵机器人1的回答:' + results_text)
    else:
        print('图灵机器人2的回答:' + results_text)
    text_input = results_text
    time.sleep(3)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注