【问题标题】:How to make a rest api call in microsoft bot framework如何在 microsoft bot 框架中进行 rest api 调用
【发布时间】:2018-01-18 16:49:56
【问题描述】:

我需要一个机器人来接收用户输入,将其用作某个第三方 rest api 调用的 id 并回发响应。我查看了 Microsoft 文档,但没有找到任何关于如何编写请求-响应过程的示例。

任何示例或有用的链接将不胜感激

【问题讨论】:

  • 这与在任何 C# 应用程序中发出 Web 请求相同。不过我可以提供一个样本。是 GET 请求还是 POST 请求?
  • 这是一个获取请求

标签: rest botframework


【解决方案1】:

添加到 Jason 的回答中,既然您想进行 REST api 调用,请查看以下代码:

public class RootDialog : IDialog<object>
{
    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;

        // User message
        string userMessage = activity.Text;
        try
        {
            using (HttpClient client = new HttpClient())
            {
                //Assuming that the api takes the user message as a query paramater
                string RequestURI = "YOUR_THIRD_PARTY_REST_API_URL?query=" + userMessage ;
                HttpResponseMessage responsemMsg = await client.GetAsync(RequestURI);
                if (responsemMsg.IsSuccessStatusCode)
                {
                    var apiResponse = await responsemMsg.Content.ReadAsStringAsync();

                    //Post the API response to bot again
                    await context.PostAsync($"Response is {apiResponse}");

                }
            }
        }
        catch (Exception ex)
        {

        }
        context.Wait(MessageReceivedAsync);
    }
}

从用户那里获得输入后,您可以进行 REST 调用,然后在从 API 获得响应后,使用 context.PostAsync 方法将其发送回用户。

【讨论】:

  • 你把这个放在什么文件里?怎么称呼?
  • 如何存储安全凭证,例如 oauth2 令牌?当您调用外部 API 时,必须有身份验证机制,但不清楚应该如何实现,尤其是在多租户场景中。假设机器人是无服务器的,我不明白如何存储长期数据。
【解决方案2】:

正如 Ashwin 所说,机器人只是一个 Web API,您只是像使用任何 Web API 一样发送/接收请求。下面是一些可以帮助您入门的文档。

Basic Overview
Create a bot with the Bot Connector service
API Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多