美文网首页
python3 调用图灵机器人API实现语音聊天

python3 调用图灵机器人API实现语音聊天

作者: 爱猫猫的老狗 | 来源:发表于2018-11-26 22:11 被阅读0次

首先需要在www.tuling123.com注册,
然后创建一个机器人,设置机器人的基本信息。
导入pyttsx3 库 实现语音功能

import json  导入json库
import urllib.request
import pyttsx3 #导入语音库
engine=pyttsx3.init() #初始化语音库
#语速
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-50)

api_url = "http://openapi.tuling123.com/openapi/api/v2" #图灵机器人api网址
while 1:
    
    text_input = input('我:')

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

            "selfInfo":
            {
                "location":
                {
                    "city": "咸阳",
                    "province": "咸阳",
                    "street": "人民路"
                }
            }
        },

        "userInfo": 
        {
            "apiKey": "a4fbaea97---------------------980c2",#你的apiKey
            "userId": "OnlyUseAlphabet" #不知道用途
        }
    }
    # print(req)
    # 将字典格式的req编码为utf8
    req = json.dumps(req).encode('utf8')
    # print(req)

    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')
    # print(response_str)
    response_dic = json.loads(response_str)
    # print(response_dic)

    intent_code = response_dic['intent']['code']
    results_text = response_dic['results'][0]['values']['text']
    print('Turing的回答:')
    #print('code:' + str(intent_code))
    print(' ' + results_text) #打印机器人的回复
    engine.say(results_text)#合成语音
    engine.runAndWait()

相关文章

网友评论

      本文标题:python3 调用图灵机器人API实现语音聊天

      本文链接:https://www.haomeiwen.com/subject/tpwiqqtx.html