Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
0
        public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());

            JObject         dataObject = eventGridEvent.Data as JObject;
            ActivityDetails details    = dataObject.ToObject <ActivityDetails>();

            string clientId     = Environment.GetEnvironmentVariable("ClientId");
            string clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
            string tenantId     = Environment.GetEnvironmentVariable("TenantId");

            string authority       = $"https://login.microsoftonline.com/{tenantId}/v2.0";
            string userId          = details.userId;
            string taskId          = details.taskId;
            string notificationUrl = details.notificationUrl;

            var cca = ConfidentialClientApplicationBuilder.Create(clientId)
                      .WithClientSecret(clientSecret)
                      .WithAuthority(authority)
                      .Build();

            List <string> scopes = new List <string>();

            scopes.Add("https://graph.microsoft.com/.default");

            MSALAuthenticationProvider authenticationProvider = new MSALAuthenticationProvider(cca, scopes.ToArray());
            GraphServiceClient         graphServiceClient     = new GraphServiceClient(authenticationProvider);

            var topic = new TeamworkActivityTopic
            {
                Source = TeamworkActivityTopicSource.Text,
                Value  = "New Task Created",
                WebUrl = notificationUrl
            };

            var activityType = "taskCreated";

            var previewText = new ItemBody
            {
                Content = "A new task has been created for you"
            };

            var templateParameters = new List <KeyValuePair>()
            {
                new KeyValuePair
                {
                    Name  = "taskId",
                    Value = taskId
                }
            };

            await graphServiceClient.Users[userId].Teamwork
            .SendActivityNotification(topic, activityType, null, previewText, templateParameters)
            .Request()
            .PostAsync();
        }
 /// <summary>
 /// The deserialization information for the current model
 /// </summary>
 public IDictionary <string, Action <IParseNode> > GetFieldDeserializers()
 {
     return(new Dictionary <string, Action <IParseNode> > {
         { "activityType", n => { ActivityType = n.GetStringValue(); } },
         { "chainId", n => { ChainId = n.GetLongValue(); } },
         { "previewText", n => { PreviewText = n.GetObjectValue <ItemBody>(ItemBody.CreateFromDiscriminatorValue); } },
         { "templateParameters", n => { TemplateParameters = n.GetCollectionOfObjectValues <ApiSdk.Models.KeyValuePair>(ApiSdk.Models.KeyValuePair.CreateFromDiscriminatorValue).ToList(); } },
         { "topic", n => { Topic = n.GetObjectValue <TeamworkActivityTopic>(TeamworkActivityTopic.CreateFromDiscriminatorValue); } },
     });
 }
Exemplo n.º 4
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();
            });
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        public async Task <ActionResult> SendNotificationToUser(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();
            var installedApps = await graphClient.Users[user.Id].Teamwork.InstalledApps
                                .Request()
                                .Expand("teamsAppDefinition")
                                .GetAsync();
            var installationId = installedApps.Where(id => id.TeamsAppDefinition.DisplayName == "NotifyFeedApp").Select(x => x.Id);
            var userName       = user.UserPrincipalName;

            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 = "deploymentApprovalRequired";

                var CustomPreviewText = new ItemBody
                {
                    Content = "New deployment requires your approval"
                };

                var CustomTemplateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "deploymentId",
                        Value = "6788662"
                    }
                };
                try
                {
                    await graphClientApp.Users[user.Id].Teamwork
                    .SendActivityNotification(customTopic, CustomActivityType, null, CustomPreviewText, CustomTemplateParameters)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            else
            {
                ViewBag.taskID = new Guid();
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.EntityUrl,
                    Value  = "https://graph.microsoft.com/beta/users/" + user.Id + "/teamwork/installedApps/" + installationId.ToList()[0]
                };

                var activityType = "taskCreated";

                var previewText = new ItemBody
                {
                    Content = "New Task Created"
                };

                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "taskName",
                        Value = taskInfo.title
                    }
                };
                try
                {
                    await graphClientApp.Users[user.Id].Teamwork
                    .SendActivityNotification(topic, activityType, null, previewText, templateParameters)
                    .Request()
                    .PostAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            return(View("Index"));
        }
Exemplo n.º 8
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"));
        }
Exemplo n.º 9
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"));
        }
Exemplo n.º 10
0
        public async Task <ActionResult> SendNotificationToManager(RequestInfo taskInfo)
        {
            try
            {
                var currentTaskList         = new List <RequestInfo>();
                List <RequestInfo> taskList = new List <RequestInfo>();
                _taskList.TryGetValue("taskList", out currentTaskList);

                taskInfo.taskId = Guid.NewGuid();
                taskInfo.status = "Pending";

                if (currentTaskList == null)
                {
                    taskList.Add(taskInfo);
                    _taskList.AddOrUpdate("taskList", taskList, (key, newValue) => taskList);
                    ViewBag.TaskList = taskList;
                }
                else
                {
                    currentTaskList.Add(taskInfo);
                    _taskList.AddOrUpdate("taskList", currentTaskList, (key, newValue) => currentTaskList);
                    ViewBag.TaskList = currentTaskList;
                }

                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.managerName]
                                     .Request()
                                     .GetAsync();

                var installedApps = await graphClient.Users[user.Id].Teamwork.InstalledApps
                                    .Request()
                                    .Expand("teamsApp")
                                    .GetAsync();

                var installationId = installedApps.Where(id => id.TeamsApp.DisplayName == "Tab Request Approval").Select(x => x.TeamsApp.Id);
                var userName       = user.UserPrincipalName;

                var url   = "https://teams.microsoft.com/l/entity/" + installationId.ToList()[0] + "/request?context={\"subEntityId\":\"" + taskInfo.taskId + "\"}";
                var topic = new TeamworkActivityTopic
                {
                    Source = TeamworkActivityTopicSource.Text,
                    Value  = $"{taskInfo.title}",
                    WebUrl = url
                };

                var previewText = new ItemBody
                {
                    Content = $"Request By: {taskInfo.userName}"
                };

                var templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                {
                    new Microsoft.Graph.KeyValuePair
                    {
                        Name  = "approvalTaskId",
                        Value = taskInfo.title
                    }
                };

                await graphClientApp.Users[user.Id].Teamwork
                .SendActivityNotification(topic, "approvalRequired", null, previewText, templateParameters)
                .Request()
                .PostAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(View("Index"));
        }