python实现接入图灵机器人

图灵机器人是一个免费的支持简单对话的机器人。可以到官网注册添加机器人,每个账号最多可以有5个机器人,每个机器人每天可以支持调用api对话一千次。

下面给出调用图灵机器人的示列代码:

import json
import urllib.request
tuling='机器人apikey'
api_url = "http://openapi.tuling123.com/openapi/api/v2"
def get_message(message,userid):
    req = {
    "perception":
    {
        "inputText":
        {
            "text": message
        },

        "selfInfo":
        {
            "location":
            {
                "city": "深圳",
                "province": "广州",
                "street": "XXX"
            }
        }
    },
    "userInfo": 
    {
        "apiKey": tuling,
        "userId": userid
    }
    }
    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)
    results_text = response_dic['results'][0]['values']['text']
    return results_text

函数get_message传入一个字符串和一个用户标识id,用户标识id是一个自定义的字符串,最大32位,用户标识id用于标识对话的连续性,同样的用户标识id的对话会将当前对话和前面的对话连续起来,使每次对话都不是从新开始的独立对话。

可以使用

response_dic = json.loads(response_str)
intent_code = response_dic['intent']['code']

获得一个返回代码,通过官方开发文档判断这个返回代码获得一些当前返回消息的类别,比如机器人apikey调用次数已用完等信息。可以结合上篇接入qqbot实现qq机器人自动对话,准备多个apikey,在一个apikey调用次数用完使自动切换下一个apikey,并且可以结合qqbot的uin等唯一标识qq群和用户实现精准聊天。

猜你喜欢

转载自www.cnblogs.com/tanjianyong/p/9508095.html