c# - 从 Web 服务向机器人发送消息

标签 c# botframework

我正在从我的 .NET 机器人启动网页。该页面与来 self 们后端系统之一的用户进行交互。交互结束后,我需要向机器人发送状态更新消息 - 它位于上下文中。在等待该消息时等待。

目前机器人正在使用 Facebook channel 并通过 Facebook Url 按钮启动页面,但最终它需要跨多个 channel 工作。

我可以从网站轻松地向用户发送消息,但尽管花了数小时搜索和尝试不同的机制,但我还没有找到向机器人发送消息的方法。

基于 https://docs.botframework.com/en-us/csharp/builder/sdkreference/d1/df2/_conversation_reference_ex_8cs_source.html 的最新尝试,(cr 已缓存对话详细信息):

string MicrosoftAppId = ConfigurationManager.AppSettings["MicrosoftAppId"];
            string MicrosoftAppPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];

            var account = new MicrosoftAppCredentials(MicrosoftAppId, MicrosoftAppPassword);
            MicrosoftAppCredentials.TrustServiceUrl(cr.serviceUrl);

            var connector = new ConnectorClient(new Uri(cr.serviceUrl), account);

            Activity activity = new Activity
            {
                Type = ActivityTypes.Message,
                Id = Guid.NewGuid().ToString(),
                Recipient = new ChannelAccount
                {
                    Id = cr.bot.id,
                    Name = cr.bot.name
                },
                ChannelId = cr.channelId,
                ServiceUrl = cr.serviceUrl,
                Conversation = new ConversationAccount
                {
                    Id = cr.conversation.id,
                    IsGroup = false,
                    Name = null
                },
                From = new ChannelAccount
                {
                    Id = cr.bot.id,
                    Name = cr.bot.name
                },
                Text = "Test send message to bot from web service"
            };

            try
            {
                await connector.Conversations.SendToConversationAsync(activity);
            }
            catch (Exception ex)
            {
                var s = ex.Message;
            }

但是 From/Recipient 的组合似乎没有发送到机器人。

我确定我遗漏了一些简单的东西,你们可以告诉我它是什么!

最佳答案

这是从另一个应用程序向机器人发送消息的示例。在这种情况下,我是通过 Web API 执行此操作的,该 API 是一个代理,拦截来自用户的消息并将它们发送给机器人。此代码中未包含如何构建事件,但看起来您已经对这部分进行了排序。请注意,在这个辅助应用程序中,我使用了 Bot.Builder,因此我可以使用事件对象和其他功能。

//get a token (See below)
var token = GetToken();

//set the service url where you want this activity to be replied to
activity.ServiceUrl = "http://localhost:4643/api/return";

//convert an activity to json to send to bot
var jsonActivityAltered = JsonConvert.SerializeObject(activity);

//send a Web Request to the bot
using (var client = new WebClient())
{
    //add your headers
    client.Headers.Add("Content-Type", "application/json");
    client.Headers.Add("Authorization", $"Bearer {token}");

    try
    {
        //set where to to send the request {Your Bots Endpoint}
        var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

获取 token :

private static string GetToken()
{
    string token;
    using (var client = new WebClient())
    {
        var values = new NameValueCollection();
        values["grant_type"] = "client_credentials";
        values["client_id"] = "{MS APP ID}";
        values["client_secret"] = "{MS APP SECRET}";
        values["scope"] = "{MS APP ID}/.default";

        var response =
            client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);

        var responseString = Encoding.Default.GetString(response);
        var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
        token = result.access_token;
    }

    return token;
}

响应对象类:

public class ResponseObject
{
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public int ext_expires_in { get; set; }
    public string access_token { get; set; }
}

关于c# - 从 Web 服务向机器人发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040452/

相关文章:

c# - 用于异常处理和报告的 SmartAssembly 的替代方案?

c# - 如何让鼠标点击新位置

azure - 使用 ARM 完全自动化 Microsoft bot 框架部署(应用程序设置被删除且功能缺失)

JavaScript:当所有类型的对象都相同时,按对象类型访问数组中的哈希值

c# - 如何使用Microsoft Bot框架通过Facebook Messenger(C#)向用户发送音频

c# - 为什么 BotConnector 的行为与模拟器不同?

c# - 为什么 Entity Framework 需要 30 秒来加载记录,而生成的查询只需要 1/2 秒?

c# - 如何获得目标 ListView 项目?

c# - 如何让游戏玩法忽略 Unity3D 中 UI 按钮的点击?

azure - 为什么 Microsoft Bot Framework 机器人需要 Azure AD 应用 ID 和 key ?