简体   繁体   English

在BotFramework上从机器人向用户发起消息

[英]Initiate a message from bot to user on BotFramework

I have a bot built on BotFramework 3.5 and hosted on Azure as a WebApp. 我有一个在BotFramework 3.5上构建的机器人,并在Azure上将其作为WebApp托管。 I didn't face any problems with implementation of scenarios where the bot needs to respond to user's input. 在机器人需要响应用户输入的场景的实现中,我没有遇到任何问题。 However there is a need to teach him to start conversations by some schedule. 但是,有必要教他按一定的时间表开始对话。 To reach the goal I created a WebJob which is a simple console app basically. 为了实现这一目标,我创建了一个WebJob,它基本上是一个简单的控制台应用程序。 Here is a code used to initiate a message from bot to user: 这是用于启动从机器人到用户的消息的代码:

            var botAccount = new ChannelAccount(id: from);
            var userAccount = new ChannelAccount(id: to);
            var conversation = new ConversationAccount(false, conversationId);

            var connector = new ConnectorClient(serviceUrl);

            IMessageActivity message = Activity.CreateMessageActivity();
            message.From = botAccount;
            message.Recipient = userAccount;
            message.Conversation = conversation;
            message.Text = text;
            message.Locale = locale;
            await connector.Conversations.SendToConversationAsync((Activity)message);

from, to, serviceUrl, conversationId - are taken from the previous conversation, so I'd expect they are valid. from, to, serviceUrl, conversationId从上一个对话中获取,因此我希望它们是有效的。 However on SendToConversationAsync exception is thrown: 但是在SendToConversationAsync会引发异常:

System.UnauthorizedAccessException: Authorization for Microsoft App ID 3a26a4d4-f75a-4feb-b3e0-37a7fa24e5fc failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized)

The app.config file contains the same values as the original bot API, including AppId and AppSecret. app.config文件包含与原始bot API相同的值,包括AppId和AppSecret。 I saw a few questions raised on the same topic, but didn't manage to find an answer. 我看到有关同一主题的几个问题,但没有找到答案。

Am I missing something? 我想念什么吗? Is it a valid approach to send messages on behalf of bot from the console app? 从控制台应用程序代表机器人发送消息是否有效?

According to your description, I followed this tutorial for getting started with the Connector and followed this tutorial for sending and Receiving Activities. 根据您的描述,我按照本教程开始使用连接器,并按照本教程进行发送和接收活动。

Based on your code, I created my console application and I could reproduce the same issue, then I found a git issue about the similar issue. 基于您的代码,我创造了我的控制台应用程序,我可以重现同样的问题,然后我发现了一个混帐问题有关类似的问题。 After some trials, I could make it work as expected on my side, you could refer to it: 经过一番试验后,我可以使它按我的预期工作,您可以参考一下:

MicrosoftAppCredentials.TrustServiceUrl("{ServiceUrl}", DateTime.Now.AddDays(7));
var account=new MicrosoftAppCredentials("MicrosoftAppIdKey", "MicrosoftAppPasswordKey");
var connector = new ConnectorClient(new Uri("{ServiceUrl}"),account);

OR 要么

Implement your DelegatingHandler 实现您的DelegatingHandler

public class MyDelegatingHandler : DelegatingHandler
{
    private string _token;
    public MyDelegatingHandler(string token)
    {
        _token = token;
    }

    protected override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _token);
        return base.SendAsync(request, cancellationToken);
    }
}

Then, you need to build your ConnectorClient as follows: 然后,您需要按照以下方式构建ConnectorClient

var account=new MicrosoftAppCredentials("{MicrosoftAppIdKey}", "{MicrosoftAppPasswordKey}");
var jwtToken=await account.GetTokenAsync();
var connector = new ConnectorClient(new Uri("{serviceUrl}"),handlers:new MyDelegatingHandler(jwtToken));

Here is my console application code snippet, you could refer to it: 这是我的控制台应用程序代码段,您可以参考它:

try
{
    var userAccount = new ChannelAccount() { Id = "default-user", Name = "user" };
    var botAccount = new ChannelAccount() { Id = "934493jn5f6f348f", Name = "console-Bot" };
    string url = "{serviceUrl}";

    MicrosoftAppCredentials.TrustServiceUrl(url, DateTime.Now.AddDays(7));
    var account = new MicrosoftAppCredentials("{MicrosoftAppIdKey}", "{MicrosoftAppPasswordKey}");
    var connector = new ConnectorClient(new Uri(url), account);

    IMessageActivity message = Activity.CreateMessageActivity();
    message.From = botAccount;
    message.Recipient = userAccount;
    message.Conversation = new ConversationAccount() { Id = "{conversationId}" };
    message.Text = "Message sent from console application!!!";
    message.Locale = "en-us";
    var response = await connector.Conversations.SendToConversationAsync((Activity)message);
    Console.WriteLine($"response:{response.Id}");
}
catch (Exception e)
{
    Console.WriteLine($"exception:{e.Message}\r\n{e.StackTrace}");
}

Result 结果

在此处输入图片说明

尝试像这样创建新的对话:

var conversationId = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);

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

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