0

我目前尝试向用户发送私人通知。我目前拥有的是我的 MS Teams 环境中的连接机器人和连接器。

在我的 c# 后端中,我有一个从 ActivityHandler、租户 ID 和 ms 团队的用户 ID 继承的机器人。

现在的情况是:有人通过 API Post 调用在我的后端创建一个对象(例如一个任务),我想通知 ms 团队中的用户。我现在的想法是在我的 API 控制器(包括 ITurnContext)中实例化 Bot。然后使用机器人找到具有租户 ID 和用户 ID 的正确 ms 团队环境,创建新的聊天/对话并发送消息。但我想这不是正确的方法,或者我做错了什么。因为我认为没有办法从我的代码中初始化 ITurnContext 或者?

这是我的代码,我的想法是在我的 API 控制器中使用 CreatePrivateConversation 方法。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Teams;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Microsoft.Bot.Schema.Teams;

namespace IntegrationsService.Bots
{
    public class ProactiveBot : ActivityHandler
    {
        double _secondsToReply = 3;
        ICredentialProvider _credentialProvider;

        public ProactiveBot(ICredentialProvider credentialProvider)
        {
            _credentialProvider = credentialProvider;
        }

        public async Task<ConversationResourceResponse> CreatePrivateConversation(string message, ITurnContext turnContext)
        {
            ConnectorClient _client = new ConnectorClient(
                new Uri(turnContext.Activity.ServiceUrl),
                await GetMicrosoftAppCredentialsAsync(turnContext),
                new HttpClient());
            var channelData = turnContext.Activity.GetChannelData<TeamsChannelData>();

            var conversationParameter = new ConversationParameters
            {
                Bot = turnContext.Activity.Recipient,
                Members = new[] { new ChannelAccount("userid") },
                // IsGroup = true,
                ChannelData = channelData,
                TenantId = channelData.Tenant.Id,
                Activity = MessageFactory.Text(message)
            };

            var response = await _client.Conversations.CreateConversationAsync(conversationParameter);
            return response;
        }

        protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            try
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"I'll reply to you in {_secondsToReply} seconds."));
                QueueReplyAndSendItProactively(turnContext).Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                throw e;
            }
        }

        public async Task QueueReplyAndSendItProactively(ITurnContext turnContext)
        {
            string conversationMessage = "I created my own conversation.";
            string replyMessage = "I proactively replied to this conversation.";

            var task = Task.Run(async () =>
            {
                await Task.Delay(TimeSpan.FromSeconds(_secondsToReply));
                // Let the Bot Proactively create a a conversation.
                var response = await CreateConversation(conversationMessage, turnContext);

                // Reply to the conversation which the bot created.
                await ProactivelyReplyToConversation(response.Id, replyMessage, turnContext);

                return Task.CompletedTask;
            });
            await task;
        }
        public async Task<ConversationResourceResponse> CreateConversation(string message, ITurnContext turnContext)
        {
            ConnectorClient _client = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), await GetMicrosoftAppCredentialsAsync(turnContext), new HttpClient());
            var channelData = turnContext.Activity.GetChannelData<TeamsChannelData>();

            var conversationParameter = new ConversationParameters
            {
                Bot = turnContext.Activity.Recipient,
                IsGroup = true,
                ChannelData = channelData,
                TenantId = channelData.Tenant.Id,
                Activity = MessageFactory.Text(message)
            };

            var response = await _client.Conversations.CreateConversationAsync(conversationParameter);
            return response;
        }

        public async Task ProactivelyReplyToConversation(string conversationId, string message, ITurnContext turnContext)
        {
            ConnectorClient _client = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), await GetMicrosoftAppCredentialsAsync(turnContext), new HttpClient());
            var reply = MessageFactory.Text(message);
            reply.Conversation = new ConversationAccount(isGroup: true, id: conversationId);
            await _client.Conversations.SendToConversationAsync(reply);
        }

        private async Task<MicrosoftAppCredentials> GetMicrosoftAppCredentialsAsync(ITurnContext turnContext)
        {
            ClaimsIdentity claimsIdentity = turnContext.TurnState.Get<ClaimsIdentity>("BotIdentity");

            Claim botAppIdClaim = claimsIdentity.Claims?.SingleOrDefault(claim => claim.Type == AuthenticationConstants.AudienceClaim)
                ??
                claimsIdentity.Claims?.SingleOrDefault(claim => claim.Type == AuthenticationConstants.AppIdClaim);

            string appPassword = await _credentialProvider.GetAppPasswordAsync(botAppIdClaim.Value).ConfigureAwait(false);
            return new MicrosoftAppCredentials(botAppIdClaim.Value, appPassword);
        }

        protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var member in membersAdded)
            {
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text($"Hello and Welcome!"), cancellationToken);
                }
            }
        }
    }
}

谢谢您的帮助。

4

1 回答 1

0

无法从代码初始化 ITurnContext。因此,如果您想向用户发送私人主动消息,您需要按照以下步骤操作

  1. 用户安装机器人时将调用“OnConversationUpdateActivityAsync”方法。您可以从 turnContext.Activity.From 对象中获取所需的参数,例如 ConversationId、ServiceUrl。当每个用户安装机器人时,您可以将这些详细信息存储在数据库中。

    OnConversationUpdateActivityAsync( ITurnContext turnContext, CancellationToken cancelToken)

  2. 当用户进行 POST API 调用时,您需要传递用户 id 或 AadID,据此您可以查询数据库并获取发送主动消息所需的用户详细信息。现在您可以调用“CreatePrivateConversation”方法并发送主动消息

于 2020-01-28T11:25:16.420 回答