简体   繁体   English

Microsoft Bot Framework Analytics API 调用不起作用

[英]Microsoft Bot Framework Analytics API call not working

I'm trying to create a translator bot but when I send a message, the bot keeps telling me that the bot code is having an issue.我正在尝试创建一个翻译机器人,但是当我发送消息时,机器人一直告诉我机器人代码有问题。 For the moment, I'm just trying to detect the user language and print it in the the chat.目前,我只是尝试检测用户语言并将其打印在聊天中。 Here's the code I've writen:这是我写的代码:

    async Task DetectLanguage(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;
        string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";

        // create request to Text Analytics API
        HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
        detectLanguageWebRequest.Method = "POST";

        // create and send body of request
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string jsonText = serializer.Serialize(activity);

        string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
        byte[] data = Encoding.UTF8.GetBytes(body);
        detectLanguageWebRequest.ContentLength = data.Length;

        using (var requestStream = detectLanguageWebRequest.GetRequestStream())
            requestStream.Write(data, 0, data.Length);

        HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

        // read and and parse JSON response
        var responseStream = response.GetResponseStream();
        var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
        dynamic jsonResponse = serializer.DeserializeObject(jsonString);

        // fish out the detected language code
        var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
        if (languageInfo["score"] > (decimal)0.5)
            await context.PostAsync(languageInfo["iso6391Name"]);
        else
            await context.PostAsync("No language detected");

        context.Wait(DetectLanguage);
    }

When I'm trying to debug, the line causing problem is this one :当我尝试调试时,导致问题的线路是这样的:

    HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

And here is the error I have in the console :这是我在控制台中的错误:

    iisexpress.exe Warning: 0 : Service url localhost:63556 is not trusted and JwtToken cannot be sent to it.

Exception thrown: 'System.Net.WebException' in mscorlib.dll抛出异常:mscorlib.dll 中的“System.Net.WebException”

Has somebody ever seen this problem ?有人见过这个问题吗?

Thanks forward for the help :)感谢您的帮助:)

First, a few details about your implementation:首先,关于您的实施的一些细节:

  • I would highly suggest using HttpClient instead of HttpWebRequest (you can read why here )我强烈建议使用HttpClient而不是HttpWebRequest (你可以在这里阅读原因)
  • You have good samples of implementing the call of TextAnalytics in the API documentation provided by Microsoft (see at the end of this page )您在 Microsoft 提供的 API 文档中有很好的实现TextAnalytics调用的TextAnalytics (参见本页末尾)
  • Another option will be to use the Nuget package as indicated in their documentation here .另一种选择将是使用NuGet包作为他们的文档中表示这里 Be careful, it's still in prerelease as the time of writing this answer.请注意,在撰写此答案时,它仍处于预发布阶段。

Working answer without needing to define the classes corresponding to the objects used in the API:无需定义与 API 中使用的对象对应的类即可工作答案:

private async Task DetectLanguage(IDialogContext context, IAwaitable<IMessageActivity> result)
{
    var msg = await result;
        
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "PUT YOU KEY HERE");

    // Request parameters
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString["numberOfLanguagesToDetect"] = "1";

    // HERE BE CAREFUL ABOUT THE REGION USED, IT MUST BE CONSISTENT WITH YOUR API KEY DECLARATION
    var uri = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/languages?" + queryString;

    // Request body
    var serializer = new JavaScriptSerializer();
    var body = "{ \"documents\": [ { \"id\": \"string\", \"text\": " + serializer.Serialize(msg.Text) + " } ]}";
    var byteData = Encoding.UTF8.GetBytes(body);
    var responseString = "";

    using (var content = new ByteArrayContent(byteData))
    {
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await client.PostAsync(uri, content);
        responseString = await response.Content.ReadAsStringAsync();
    }

    // fish out the detected language code
    dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
    var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
    var returnText = "No language detected";

    if (languageInfo["score"] > (decimal) 0.5)
    {
        returnText = languageInfo["iso6391Name"].ToString();
    }
    await context.PostAsync(returnText);

    context.Wait(DetectLanguage);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM