unity下图灵机器人的使用

unity下图灵机器人的使用

这里json的解析与建立使用的是LitJson.dll

一、机器人建立

首先到图灵机器人的官网http://www.tuling123.com/注册一个号并建立机器人(有则可以不用)。

二、配置请求参数结构体和接收数据结构体

请求参数格式为 json
请求示例:
{
“reqType”:0,
“perception”: {
“inputText”: { “text”: “附近的酒店” },
“inputImage”: { “url”: “imageUrl” },
“selfInfo”: {
“location”: {
“city”: “北京”,
“province”: “北京”,
“street”: “信息路” } }
},
“userInfo”: { “apiKey”: “”, “userId”: “” }}

代码如下

public struct Turing2_0CallHead
{
    /// 
    /// 输入类型:0-文本(默认)、1-图片、2-音频
    /// 
    public int reqType;

    #region suserInfo

    /// 
    /// (必须)机器人标识
    /// 
    public string apiKey;

    /// 
    /// (必须)用户唯一标识
    /// 
    public string userId;

    /// 
    /// (非必须)群聊唯一标识
    /// 
    public string groupId;

    /// 
    /// (非必须)群内用户昵称
    /// 
    public string userIdName;

    #endregion

    #region perception

    #region 必须存在其一
    /// 
    /// 文本信息
    /// 
    public string inputText;

    /// 
    /// 图片信息
    /// 
    public string inputImage;

    /// 
    /// 音频信息
    /// 
    public string inputMedia;

    #endregion

    #region selfInfo客户端属性中的location(非必须)

    /// 
    /// 所在城市
    /// 
    public string locationCity;

    /// 
    /// (非必须,存在时locationCity必须存在)省份
    /// 
    public string locationProvince;

    /// 
    /// (非必须,存在时locationCity必须存在)街道
    /// 
    public string locationStreet;

    #endregion

    #endregion
}
public struct Turing2_0intent
{
    /// 
    /// (必须包含)输出功能code
    /// 
    public int code;

    /// 
    /// (必须包含)意图名称
    /// 
    public string intentName;

    /// 
    /// 意图动作名称
    /// 
    public string actionName;

    /// 
    /// 功能相关参数
    /// 
    public Dictionary<string, string> parameters;
}

/// 
/// 输出结果集
/// 
public struct Turing2_0results
{
    /// 
    /// 组’编号:0为独立输出,大于0时可能包含同组相关内容 (如:音频与文本为一组时说明内容一致)
    /// 
    public int groupType;

    /// 
    /// 输出类型,文本(text);连接(url);音频(voice);视频(video);图片(image);图文(news)
    /// 
    public string resultType;

    /// 
    /// 输出值
    /// 
    public Dictionary<string, string> values;

三、以HttpWebRequest发送自定义POST请求

通过HttpWebRequest发送自定义POST请求,代码如下:

/// 
    /// HttpWebRequest发送自定义POST请求
    /// 
    /// 地址
    /// 方法
    /// json参数
    /// 
    public static string HttpRequestPOST(string url, string param)
    {
        //转换输入参数的编码类型,获取bytep[]数组 
        byte[] byteArray = Encoding.UTF8.GetBytes(param);
        //初始化新的webRequst
        //1. 创建httpWebRequest对象
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
        //2. 初始化HttpWebRequest对象
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json;charset=UTF-8";
        webRequest.ContentLength = byteArray.Length;
        //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
        Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
        newStream.Write(byteArray, 0, byteArray.Length);
        newStream.Close();
        //4. 读取服务器的返回信息
        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string phpend = php.ReadToEnd();
        return phpend;

    }

转化json 并请求

将结构体通过LitJson转化json,代码如下:

/// 
    /// 召唤图灵机器人
    /// 
    /// 
    /// 
    public Turing2_0ReturnResult CallTuringWeb2_0(Turing2_0CallHead turing2_0CallHead,string url)
    {
        Turing2_0ReturnResult returnResult = null;
        if (turing2_0CallHead.apiKey == null || turing2_0CallHead.userId == null)
            return null;
        if ( !string.IsNullOrEmpty(turing2_0CallHead.inputText) ||  !string.IsNullOrEmpty(turing2_0CallHead.inputImage) ||  !string.IsNullOrEmpty(turing2_0CallHead.inputMedia))
        {
            JsonData jd = new JsonData();
            jd["reqType"] = turing2_0CallHead.reqType;

            JsonData perceptionJd = new JsonData();

            if (!string.IsNullOrEmpty(turing2_0CallHead.inputText))
            {
                JsonData inputTextJd = new JsonData();
                inputTextJd["text"] = turing2_0CallHead.inputText;
                perceptionJd["inputText"] = inputTextJd;
            }
            if (!string.IsNullOrEmpty(turing2_0CallHead.inputImage))
            {
                JsonData inputImageJd = new JsonData();
                inputImageJd["url"] = turing2_0CallHead.inputImage;
                perceptionJd["inputImage"] = inputImageJd;
            }

            if (!string.IsNullOrEmpty(turing2_0CallHead.inputMedia))
            {
                JsonData inputMediaJd = new JsonData();
                inputMediaJd["url"] = turing2_0CallHead.inputMedia;
                perceptionJd["inputMedia"] = inputMediaJd;
            }

            if (!string.IsNullOrEmpty(turing2_0CallHead.locationCity))
            {
                JsonData selfInfoJd = new JsonData();
                JsonData locationCityJd = new JsonData();
                locationCityJd["city"] = turing2_0CallHead.locationCity;
                if (string.IsNullOrEmpty(turing2_0CallHead.locationProvince))
                {
                    locationCityJd["province"] = turing2_0CallHead.locationProvince;
                }
                if (string.IsNullOrEmpty(turing2_0CallHead.locationStreet))
                {
                    locationCityJd["street"] = turing2_0CallHead.locationStreet;
                }

                selfInfoJd["location"] = locationCityJd;
                perceptionJd["selfInfo"] = selfInfoJd;
            }
            jd["perception"] = perceptionJd;

            JsonData userInfoJd = new JsonData();
            userInfoJd["apiKey"] = turing2_0CallHead.apiKey;
            userInfoJd["userId"] = turing2_0CallHead.userId;

            if (!string.IsNullOrEmpty(turing2_0CallHead.groupId))
            {
                userInfoJd["groupId"] = turing2_0CallHead.groupId;
            }
            if (!string.IsNullOrEmpty(turing2_0CallHead.userIdName))
            {
                userInfoJd["userIdName"] = turing2_0CallHead.userIdName;
            }

            jd["userInfo"] = userInfoJd;

            string content = HttpRequestPOST(url, jd.ToJson());
            print(content);
            returnResult = new Turing2_0ReturnResult(content);
        }
        return returnResult;
    }

五、对返回的数据进行解析

对post请求返回的数据解析,代码:

public class Turing2_0ReturnResult
{
    public Turing2_0intent intent;
    public Turing2_0results[] results;

    public Turing2_0ReturnResult(string json)
    {

        JsonData jsonData = JsonMapper.ToObject(json);
        JsonData intentjd = jsonData["intent"];
        intent.code = int.Parse(intentjd["code"].ToString());
        intent.intentName = intentjd.Keys.Contains("intentName") ? intentjd["intentName"].ToString() : null;
        intent.actionName = intentjd.Keys.Contains("actionName") ? intentjd["actionName"].ToString() : null;

        intent.parameters = null;
        if (intentjd.Keys.Contains("parameters"))
        {
            intent.parameters = new Dictionary<string, string>();
            List<string> keys = new List<string>(intentjd["parameters"].Keys);
            for(int i = 0; i < keys.Count;i++)
            {
                intent.parameters[keys[i]] = intentjd["parameters"][keys[i]].ToString();
            }
        }
        results = null;
        if (jsonData.Keys.Contains("results"))
        {
            JsonData resultsjd = jsonData["results"];
            results = new Turing2_0results[resultsjd.Count];
            for (int i = 0; i < resultsjd.Count; i++)
            {
                results[i].groupType = int.Parse(resultsjd[i]["groupType"].ToString());
                results[i].resultType = resultsjd[i]["resultType"].ToString();
                results[i].values = new Dictionary<string, string>();

                List<string> valueslist = new List<string>(resultsjd[i]["values"].Keys);

                for (int j = 0; j < valueslist.Count; j++)
                {
                    results[i].values[valueslist[j]] = resultsjd[i]["values"][valueslist[j]].ToString();
                }
            }

        }
    }
}

HttpWebRequest发送自定义POST请求参考:https://www.cnblogs.com/tangge/p/4998007.html

源码工程[有一些改动](https://download.csdn.net/download/u014716849/10343176)

你可能感兴趣的:(Unity3D游戏开发,人工智能)