从网络服务向机器人发送消息 [英] Send message to bot from web service

查看:90
本文介绍了从网络服务向机器人发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm launching a web page from my .NET bot. The page interacts with the user from one of our back end systems. Once the interaction is over I need to message the bot with a status update - it sits in a context.Wait whilst awaiting that message.

当前,该机器人正在使用Facebook频道,并通过Facebook Url按钮启动页面,但最终它将需要跨多个渠道工作.

Currently the bot is using the Facebook channel and launches the page via the Facebook Url button but ultimately it will need to work across multiple channels.

从网站上,我可以轻松地将消息发送给用户,但是尽管花了很多时间进行搜索和尝试各种机制,但我仍未找到向机器人发送消息的方法.

From the web site I can easily send messages which go to the user but despite having spent hours searching and trying different mechanisms I haven't found a way to send a message to the bot.

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

Latest attempt based on https://docs.botframework.com/en-us/csharp/builder/sdkreference/d1/df2/_conversation_reference_ex_8cs_source.html, (cr has cached conversation details):

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;
            }

但是似乎没有发自/收件人"的组合发送到bot.

But no combination of From / Recipient seems to send to bot.

我确定我缺少简单的东西,你们可以告诉我它是什么!

I'm sure I'm missing something simple and that you guys can tell me what it is!

推荐答案

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

Here is an example of sending a message to a bot from another application. In this case I was doing this from a web API which was a proxy intercepting messages from the user and sending them to the bot. Not included in this code is how to construct an activity, but it looks like you have that part sorted our already. Note that in this secondary application I was using Bot.Builder so I could use activity objects and other features.

//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;
    }
}

获取令牌:

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; }
}

这篇关于从网络服务向机器人发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆