【问题标题】:Calling a WebAPI from an Azure Bot从 Azure 机器人调用 Web API
【发布时间】:2017-03-09 14:38:06
【问题描述】:

我是 Azure Bot 编程 (C#) 的新手,找不到关于此主题的好文章。

我想让用户使用机器人“订阅”邮件列表。我构建了一个表单对话框和表单流。它要求用户提供他们的电子邮件地址。

我需要做的是将其发布到外部 WebAPI (json) 并获得响应并处理响应。

谁能给我一些关于如何从 Bot 调用 WebAPI 的指示?

    public async Task Subscribe(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
    {
        context.Call(SubscribeForm.BuildFormDialog(FormOptions.PromptInStart), SubscribeFormComplete);
    }

    private async Task SubscribeFormComplete(IDialogContext context, IAwaitable<SubscribeForm> result)
    {
        try
        {
            var form = await result;
            if (form != null)
            {
                await context.PostAsync("Thanks for subscribing! You can always remove yourself by typing unsubscribe.");
            }
            else
            {
                await context.PostAsync("Form returned empty response!");
            }
        }
        catch (OperationCanceledException)
        {
            await context.PostAsync("I am sorry you decided not to subscribe! If you change your mind just type 'subscribe' again.");
        }

        context.Wait(this.MessageReceived);
    }


        [Serializable]
public class SubscribeForm
{
    [Prompt("What is your email address?")]
    [Required()]
    [DataType(DataType.EmailAddress)]
    public string EmailAddress { get; set; }

    public static IForm<SubscribeForm> BuildForm()
    {
        // Builds an IForm<T> based on BasicForm
        return new FormBuilder<SubscribeForm>()
            .Message("We often send out updates on new features. We don't spam.  You can type 'quit' to cancel this.")
           .Build();
    }

    public static IFormDialog<SubscribeForm> BuildFormDialog(FormOptions options = FormOptions.PromptInStart)
    {
        // Generated a new FormDialog<T> based on IForm<BasicForm>
        return FormDialog.FromForm(BuildForm, options);
    }
}

【问题讨论】:

  • 为什么从机器人完成时会有所不同?您可以像往常一样提出请求。
  • 机器人和表单流对它们有“堆栈”和父/子细微差别。只是寻找有关在何处放置 WebAPI 调用代码的建议。比如在formcompleted方法或者其他地方,以及如何处理异步和回调。

标签: c# azure asp.net-web-api bots botframework


【解决方案1】:

这是我如何调用 Microsoft 的认知服务 LUIS 的示例,我在静态类上有方法,并且方法是异步的。

方法:

 public static class CognitiveHelper
    {
        private const string UrlLuis = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/a267a797-9584-41a5-83f3-xxxxxxxxx?subscription-key=xxxxxxxxxxxxxxxxxxxxxxx&q=";
    public static async Task<LuisObjects> GetLuisAnswer(string textToEvaluate)
            {
                if (string.IsNullOrWhiteSpace(textToEvaluate)) throw new ArgumentException("Null argument");

                textToEvaluate= HttpUtility.UrlEncode(textToEvaluate);
                var urlLuisWithRequest = UrlLuis + textToEvaluate;

                var client = new HttpClient();
                var body = new { };

                var serializedBody = new JavaScriptSerializer().Serialize(body);
                byte[] bodyByte = Encoding.UTF8.GetBytes(serializedBody );

                using (var content = new ByteArrayContent(bodyByte))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var response= await client.GetAsync(urlLuisWithRequest );
                    var responseContent= await respuesta.Content.ReadAsStringAsync();

                    var javaScriptSerializer = new JavaScriptSerializer();
                    var resultTextAnalysis= javaScriptSerializer.Deserialize<LuisResult>(responseContent);
                    return new LuisObjects()
                    {
                        Entities= resultTextAnalysis.entities.ToList(),
                        TopScoringIntent = resultTextAnalysis.topScoringIntent
                    };
                }
            }
}

呼叫:

  var luisResponse = await CognitiveHelper.GetLuisAnswer(activity.Text);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多