Ejemplo n.º 1
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            // 读取当前群聊中的用户列表
            var members = await TeamsInfo.GetMembersAsync(turnContext);

            // 准备用来访问Microsoft Graph的本地代理
            GraphServiceClient graphClient = new GraphServiceClient(new SimpleAuth(_configuration));

            // 为每个用户发送一个通知,这里解析得到他们的AadObjectId,用来发送
            members.Select(_ => _.AadObjectId).AsParallel().ForAll(async(_) =>
            {
                // 以下代码,其实你可以在官网找到,并且简单地做些修改即可
                // https://docs.microsoft.com/zh-cn/graph/api/chat-sendactivitynotification?view=graph-rest-1.0&tabs=http#example-1-notify-a-user-about-a-task-created-in-a-chat
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = $"https://graph.microsoft.com/beta/me/chats/{turnContext.Activity.Conversation.Id}/messages/{turnContext.Activity.Id}"
                };
                // 这个是通知的自定义模板(在manifest.json文件中要定义)
                var activityType = "metionall";
                // 预览文字
                var previewText = new ItemBody
                {
                    Content = "有人在群聊中提到你了,请点击查看"
                };
                // 收件人的id
                var recipient = new AadUserNotificationRecipient
                {
                    UserId = _
                };
                // 替换掉模板中的值
                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "from",
                        Value = turnContext.Activity.From.Name
                    },
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "message",
                        Value = turnContext.Activity.RemoveMentionText(turnContext.Activity.Recipient.Id)
                    }
                };
                // 调用接口发送通知
                await graphClient.Chats[turnContext.Activity.Conversation.Id]
                .SendActivityNotification(topic, activityType, null, previewText, templateParameters, recipient)
                .Request()
                .PostAsync();
            });
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public async Task NotifyMemberToSetupCourseAsync(Course course, Member member)
        {
            var topic = new TeamworkActivityTopic
            {
                Source = TeamworkActivityTopicSource.Text,
                Value  = $"{course.Name}",
                WebUrl = this.deepLinkCreator.GetPersonalTabConfigureCourseDeepLink(this.appSettings.ManifestAppId, "personalTab", course.TeamAadObjectId),
            };

            var previewText = new ItemBody
            {
                Content = this.localizer.GetString("setupCoursePreviewText"),
            };

            var recipient = new AadUserNotificationRecipient
            {
                UserId = member.AadId,
            };

            await this.SendActivityFeedNotificationAsync(course.TeamAadObjectId, topic, SetupCourseActivityType, previewText, recipient);
        }
Ejemplo n.º 3
0
        /// <inheritdoc/>
        public async Task NotifyAnsweredAcceptedAsync(Course course, QBot.Domain.Models.Channel channel, Question question, Answer answer)
        {
            var topic = new TeamworkActivityTopic
            {
                Source = TeamworkActivityTopicSource.Text,
                Value  = $"{course.Name} > {channel.Name}",
                WebUrl = this.deepLinkCreator.GetTeamsMessageDeepLink(course.TeamId, channel.Id, question.MessageId, answer.MessageId),
            };

            var previewText = new ItemBody
            {
                Content = answer.GetSanitizedMessage(),
            };

            var recipient = new AadUserNotificationRecipient
            {
                UserId = answer.AuthorId,
            };

            await this.SendActivityFeedNotificationAsync(course.TeamAadObjectId, topic, AnswerAcceptedActivityType, previewText, recipient);
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> sendNotificationToTeam(TaskInfo taskInfo)
        {
            TaskHelper.AddTaskToFeed(taskInfo);
            var graphClient    = SimpleGraphClient.GetGraphClient(taskInfo.access_token);
            var graphClientApp = SimpleGraphClient.GetGraphClientforApp(_configuration["AzureAd:MicrosoftAppId"], _configuration["AzureAd:MicrosoftAppPassword"], _configuration["AzureAd:TenantId"]);
            var user           = await graphClient.Users[taskInfo.userName]
                                 .Request()
                                 .GetAsync();

            if (taskInfo.taskInfoAction == "customTopic")
            {
                ChatMessageHelper chatMessage = new ChatMessageHelper(_configuration);
                var getChannelMessage         = await chatMessage.CreateChatMessageForChannel(taskInfo, taskInfo.access_token);

                var customTopic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.Text,
                    Value  = "Deployment Approvals Channel",
                    WebUrl = getChannelMessage.WebUrl
                };

                var CustomActivityType = "approvalRequired";

                var CustomPreviewText = new ItemBody
                {
                    Content = "New deployment requires your approval"
                };
                var customRecipient = new AadUserNotificationRecipient
                {
                    UserId = user.Id
                };
                var CustomTemplateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "approvalTaskId",
                        Value = "5654653"
                    }
                };
                try
                {
                    await graphClientApp.Teams[taskInfo.teamId]
                    .SendActivityNotification(customTopic, CustomActivityType, null, CustomPreviewText, CustomTemplateParameters, customRecipient)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            else if (taskInfo.taskInfoAction == "channelTab")
            {
                ChatMessageHelper chatMessage = new ChatMessageHelper(_configuration);
                var getChannelMessage         = chatMessage.CreateChannelMessageAdaptiveCard(taskInfo, taskInfo.access_token);

                var tabs = await graphClient.Teams[taskInfo.teamId].Channels[taskInfo.channelId].Tabs
                           .Request()
                           .Expand("teamsApp")
                           .GetAsync();
                var tabId = tabs.Where(a => a.DisplayName == "NotifyFeedApp").Select(x => x.Id).ToArray()[0];
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = "https://graph.microsoft.com/beta/teams/" + taskInfo.teamId + "/channels/" + taskInfo.channelId + "/tabs/" + tabId
                };

                var activityType = "reservationUpdated";

                var previewText = new ItemBody
                {
                    Content = "Your Reservation Updated:"
                };
                var recipient = new AadUserNotificationRecipient
                {
                    UserId = user.Id
                };

                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "reservationId",
                        Value = taskInfo.reservationId
                    },
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "currentSlot",
                        Value = taskInfo.currentSlot
                    }
                };
                try
                {
                    await graphClientApp.Teams[taskInfo.teamId]
                    .SendActivityNotification(topic, activityType, null, previewText, templateParameters, recipient)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            else
            {
                ChatMessageHelper chatMessage = new ChatMessageHelper(_configuration);
                var getChannelMessage         = await chatMessage.CreatePendingFinanceRequestCard(taskInfo, taskInfo.access_token);

                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.Text,
                    WebUrl = getChannelMessage.WebUrl,
                    Value  = "Deep Link to Chat"
                };

                var activityType = "pendingFinanceApprovalRequests";
                var previewText  = new ItemBody
                {
                    Content = "These are the count of pending request pending request:"
                };
                var recipient = new AadUserNotificationRecipient
                {
                    UserId = user.Id
                };

                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "pendingRequestCount",
                        Value = "5"
                    }
                };
                try
                {
                    await graphClientApp.Teams[taskInfo.teamId]
                    .SendActivityNotification(topic, activityType, null, previewText, templateParameters, recipient)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            return(View("teamnotification"));
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> SendNotificationToGroupChat(TaskInfo taskInfo)
        {
            TaskHelper.AddTaskToFeed(taskInfo);
            var graphClient    = SimpleGraphClient.GetGraphClient(taskInfo.access_token);
            var graphClientApp = SimpleGraphClient.GetGraphClientforApp(_configuration["AzureAd:MicrosoftAppId"], _configuration["AzureAd:MicrosoftAppPassword"], _configuration["AzureAd:TenantId"]);
            var user           = await graphClient.Users[taskInfo.userName]
                                 .Request()
                                 .GetAsync();

            if (taskInfo.taskInfoAction == "customTopic")
            {
                ChatMessageHelper chatMessage = new ChatMessageHelper(_configuration);
                var getChatMessage            = chatMessage.CreateGroupChatMessage(taskInfo, taskInfo.access_token);
                var customTopic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = "https://graph.microsoft.com/beta/chats/" + taskInfo.chatId + "/messages/" + getChatMessage.Id
                };

                var CustomActivityType = "approvalRequired";

                var CustomPreviewText = new ItemBody
                {
                    Content = "Deployment requires your approval"
                };
                var customRecipient = new AadUserNotificationRecipient
                {
                    UserId = user.Id
                };
                var CustomTemplateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "approvalTaskId",
                        Value = "2020AAGGTAPP"
                    }
                };
                try
                {
                    await graphClientApp.Chats[taskInfo.chatId]
                    .SendActivityNotification(customTopic, CustomActivityType, null, CustomPreviewText, CustomTemplateParameters, customRecipient)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            else
            {
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = "https://graph.microsoft.com/beta/chats/" + taskInfo.chatId
                };

                var activityType = "taskCreated";

                var previewText = new ItemBody
                {
                    Content = "Hello:"
                };
                var recipient = new AadUserNotificationRecipient
                {
                    UserId = user.Id
                };

                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "taskName",
                        Value = taskInfo.title
                    }
                };
                try
                {
                    await graphClientApp.Chats[taskInfo.chatId]
                    .SendActivityNotification(topic, activityType, null, previewText, templateParameters, recipient)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            return(View("groupchatnotification"));
        }
Ejemplo n.º 6
0
        private async Task SendActivityFeedNotificationAsync(string teamId, TeamworkActivityTopic topic, string activityType, ItemBody previewText, AadUserNotificationRecipient recipient)
        {
            try
            {
                await this.graphServiceClient
                .Teams[teamId]
                .SendActivityNotification(topic, activityType, null /*chainId*/, previewText, null, recipient)
                .Request()
                .WithAppOnly()
                .WithMaxRetry(MaxRetry)
                .PostAsync();
            }
            catch (ServiceException exception)
            {
                this.logger.LogWarning(exception, "Failed to send activity feed notification.");

                // No permission granted.
                if (exception.StatusCode == HttpStatusCode.Forbidden)
                {
                    var message = "Make sure the app has permission (TeamsActivity.Send) to send activity feed notifications.";
                    this.logger.LogWarning(exception, message);
                    throw new QBotException(HttpStatusCode.Forbidden, ErrorCode.Forbidden, message, exception);
                }

                this.logger.LogWarning(exception, $"Something went wrong.");
                throw new QBotException(HttpStatusCode.InternalServerError, ErrorCode.Unknown, $"Something went wrong.", exception);
            }
        }