public void MessagingExtensionActionInitsNoArgs() { var msgExtAction = new MessagingExtensionAction(); Assert.NotNull(msgExtAction); Assert.IsType <MessagingExtensionAction>(msgExtAction); }
private MessagingExtensionActionResponse GetTaskModuleBasedOnCommand(MessagingExtensionAction action, string customAPIAuthenticationToken) { if (action.CommandId == CompanyResponseTaskModuleCommandId) { return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Url = $"{this.options.Value.AppBaseUri}/company-responses?token={customAPIAuthenticationToken}&telemetry={this.telemetrySettings.Value.InstrumentationKey}&theme=" + "{theme}&locale=" + "{locale}", Height = TaskModuleHeight, Width = TaskModuleWidth, Title = this.localizer.GetString("ManageYourResponsesTitleText"), }, }, }); } else { return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Url = $"{this.options.Value.AppBaseUri}/user-responses?token={customAPIAuthenticationToken}&telemetry={this.telemetrySettings.Value.InstrumentationKey}&theme=" + "{theme}&locale=" + "{locale}", Height = TaskModuleHeight, Width = TaskModuleWidth, Title = this.localizer.GetString("ManageYourResponsesTitleText"), }, }, }); } }
public void MessagingExtensionActionInits() { var data = new Dictionary <string, string>() { { "key", "value" } }; var context = new TaskModuleRequestContext("theme"); var commandId = "commandId"; var commandContext = "message"; var botMessagePreviewAction = "send"; var botActivityPreview = new List <Activity>() { new Activity(text: "hi"), new Activity(text: "yo yo yo") }; var messagePayload = new MessageActionsPayload("msgId", "1234", "message"); var state = "secureOAuthState1234"; var msgExtAction = new MessagingExtensionAction(data, context, commandId, commandContext, botMessagePreviewAction, botActivityPreview, messagePayload) { State = state }; Assert.NotNull(msgExtAction); Assert.IsType <MessagingExtensionAction>(msgExtAction); Assert.Equal(data, msgExtAction.Data); Assert.Equal(context, msgExtAction.Context); Assert.Equal(commandId, msgExtAction.CommandId); Assert.Equal(commandContext, msgExtAction.CommandContext); Assert.Equal(botMessagePreviewAction, msgExtAction.BotMessagePreviewAction); Assert.Equal(botActivityPreview, msgExtAction.BotActivityPreview); Assert.Equal(messagePayload, msgExtAction.MessagePayload); Assert.Equal(state, msgExtAction.State); }
/// <summary> /// Invoked when the user submits a response/suggests a response/updates a response. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamsmessagingextensionsubmitactionasync?view=botbuilder-dotnet-stable. /// </remarks> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { try { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); this.RecordEvent(nameof(this.OnTeamsMessagingExtensionSubmitActionAsync), turnContext); action = action ?? throw new ArgumentNullException(nameof(action)); var valuesfromTaskModule = JsonConvert.DeserializeObject <TaskModuleResponseDetails>(action.Data.ToString()); if (valuesfromTaskModule.Command.ToUpperInvariant() == Constants.SaveNominatedDetailsAction) { var mentionActivity = await CardHelper.GetMentionActivityAsync(valuesfromTaskModule.NominatedToPrincipalName.Split(",").Select(row => row.Trim()).ToList(), turnContext.Activity.From.AadObjectId, valuesfromTaskModule.TeamId, turnContext, this.localizer, this.logger, MentionActivityType.Nomination, cancellationToken); var notificationCard = (Activity)MessageFactory.Attachment(EndorseCard.GetEndorseCard(this.appBaseUrl, this.localizer, valuesfromTaskModule)); await this.SendMentionedCardAsync(turnContext, notificationCard, mentionActivity); this.logger.LogInformation("Nominated an award"); return(null); } return(null); } catch (Exception ex) { this.logger.LogError(ex, $"Error at OnTeamsMessagingExtensionSubmitActionAsync(): {ex.Message}", SeverityLevel.Error); await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage")); throw; } }
/// <summary> /// Method overridden to send card in team after awarding badge. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { var activity = turnContext.Activity as Activity; var badgeDetails = JsonConvert.DeserializeObject <ViewBadge>(action.Data.ToString()); var awardRecipients = badgeDetails.AwardRecipients.ToList(); var awardedBy = badgeDetails.AwardedBy; // Get team members in Team. var teamsDetails = turnContext.Activity.TeamsGetTeamInfo(); var channelMembers = await TeamsInfo.GetTeamMembersAsync(turnContext, teamsDetails.Id, cancellationToken); for (var recipientCount = 0; recipientCount < badgeDetails.AwardRecipients.Count; recipientCount++) { var memberEmail = badgeDetails.AwardRecipients[recipientCount]; badgeDetails.AwardRecipients[recipientCount] = channelMembers.Where(member => member.Email == memberEmail).Select(member => member.Name).FirstOrDefault(); } badgeDetails.AwardedBy = channelMembers.Where(member => member.Email == badgeDetails.AwardedBy).Select(member => member.Name).FirstOrDefault(); var channelData = activity.GetChannelData <TeamsChannelData>(); var conversationParameters = new ConversationParameters { Activity = (Activity)MessageFactory.Attachment(AwardCard.GetAwardBadgeAttachment(badgeDetails)), Bot = activity.Recipient, IsGroup = true, ChannelData = channelData, TenantId = channelData.Tenant.Id, }; // Get activity for mentioning members who are awarded with badge. var mentionActivity = await this.GetMentionActivityAsync(awardRecipients, awardedBy, turnContext, cancellationToken); await this.botAdapter.CreateConversationAsync( "msteams", turnContext.Activity.ServiceUrl, this.microsoftAppCredentials, conversationParameters, async (newTurnContext, newCancellationToken) => { await this.botAdapter.ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, newTurnContext.Activity.GetConversationReference(), async(conversationTurnContext, conversationCancellationToken) => { mentionActivity.ApplyConversationReference(conversationTurnContext.Activity.GetConversationReference()); await conversationTurnContext.SendActivityAsync(mentionActivity, conversationCancellationToken); }, newCancellationToken); }, cancellationToken).ConfigureAwait(false); return(default);
protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { Random random = new Random(); dynamic data = JObject.Parse(action.Data.ToString()); string message = (string)data["message"]; string replyText = respondToCall(message, random); var replyActivity = MessageFactory.Text($"_{turnContext.Activity.From.Name} : {message}_\n\n{replyText}"); addCritImage(random, replyActivity); await turnContext.SendActivityAsync(replyActivity, cancellationToken); return(new MessagingExtensionActionResponse()); }
public static SubmitExampleData ToSubmitExampleData(this MessagingExtensionAction action) { var activityPreview = action.BotActivityPreview[0]; var attachmentContent = activityPreview.Attachments[0].Content; var previewedCard = JsonConvert.DeserializeObject <AdaptiveCard>(attachmentContent.ToString(), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string userText = (previewedCard.Body[1] as AdaptiveTextBlock).Text; var choiceSet = previewedCard.Body[3] as AdaptiveChoiceSetInput; return(new SubmitExampleData() { Question = userText, MultiSelect = choiceSet.IsMultiSelect ? "true" : "false", Option1 = choiceSet.Choices[0].Title, Option2 = choiceSet.Choices[1].Title, Option3 = choiceSet.Choices[2].Title, }); }
/// <summary> /// Handle message extension submit action task received by the bot. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action value payload.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Response of messaging extension action.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamsmessagingextensionfetchtaskasync?view=botbuilder-dotnet-stable. /// </remarks> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { AddConversationReference(turnContext.Activity as Activity); var asJobject = JObject.FromObject(action.Data); var title = (string)asJobject.ToObject <TaskDetails <string> >()?.Title; var description = (string)asJobject.ToObject <TaskDetails <string> >()?.Description; var dateTime = (DateTime)asJobject.ToObject <TaskDetails <DateTime> >()?.DateTime; var date = dateTime.ToLocalTime(); var currentTaskList = new List <SaveTaskDetail>(); List <SaveTaskDetail> taskList = new List <SaveTaskDetail>(); _taskDetails.TryGetValue("taskDetails", out currentTaskList); var taskDetails = new SaveTaskDetail() { Description = description, Title = title, DateTime = new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0, TimeSpan.Zero), }; if (currentTaskList == null) { taskList.Add(taskDetails); _taskDetails.AddOrUpdate("taskDetails", taskList, (key, newValue) => taskList); } else { currentTaskList.Add(taskDetails); _taskDetails.AddOrUpdate("taskDetails", currentTaskList, (key, newValue) => currentTaskList); } TaskScheduler taskSchedule = new TaskScheduler(); taskSchedule.Start(date.Year, date.Month, date.Day, date.Hour, date.Minute, _applicationBaseUrl); await turnContext.SendActivityAsync("Task submitted successfully. You will get reminder for the task at scheduled time"); return(null); }
/// <summary> /// When OnTurn method receives a submit invoke activity on bot turn, it calls this method. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Provides context for a turn of a bot and.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A task that represents a task module response.</returns> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { var title = string.Empty; var description = string.Empty; if (action.MessagePayload.Subject != null && turnContext.Activity.Conversation.ConversationType != "personal" && action.MessagePayload.Subject != "") { description = action.MessagePayload.Body.Content; title = action.MessagePayload.Subject; } else { title = action.MessagePayload.Body.Content; } return(this.GetTaskModuleResponse(title, description)); }
/// <summary> /// Invoked when the user submits a response/suggests a response/updates a response. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamsmessagingextensionsubmitactionasync?view=botbuilder-dotnet-stable. /// </remarks> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { try { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); this.RecordEvent(nameof(this.OnTeamsMessagingExtensionSubmitActionAsync), turnContext); action = action ?? throw new ArgumentNullException(nameof(action)); var activity = turnContext.Activity; var userRequestDetails = JsonConvert.DeserializeObject <AddUserResponseRequestDetail>(action.Data.ToString()); // Generate custom JWT token to authenticate in application API controller. var customAPIAuthenticationToken = this.tokenHelper.GenerateInternalAPIToken(new Uri(activity.ServiceUrl), activity.From.AadObjectId, jwtExpiryMinutes: 60); switch (userRequestDetails.CommandContext) { case AddUserResponseCommand: return(await this.AddUserResponseResultAsync(turnContext, userRequestDetails, customAPIAuthenticationToken)); case AddNewSuggestionCommand: return(await this.AddNewSuggestionResultAsync(turnContext, userRequestDetails, customAPIAuthenticationToken, cancellationToken)); case EditUserResponseCommand: return(await this.EditUserResponseResultAsync(turnContext, userRequestDetails, customAPIAuthenticationToken)); } return(null); } catch (Exception ex) { this.logger.LogError(ex, $"Error at OnTeamsMessagingExtensionSubmitActionAsync(): {ex.Message}", SeverityLevel.Error); await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage")); throw; } }
/// <summary> /// Method overridden to show task module response. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { try { var activity = turnContext.Activity; var activityState = ((JObject)activity.Value).GetValue("state")?.ToString(); // Check for Badgr token. var userBadgrToken = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, this.connectionName, activityState, cancellationToken); if (userBadgrToken == null) { // Token is not present in bot framework. Create sign in link and send sign in card to user. return(await this.CreateSignInCardAsync(turnContext, cancellationToken, Strings.SignInButtonText)); } // Validate user's Microsoft Teams email ID against Badgr account email ID. var validationResponse = await this.ValidateUserEmailId(turnContext, userBadgrToken); if (validationResponse != null) { // Non empty response represents email validation failed. Return validation error response. return(validationResponse); } return(await this.CreateSignInSuccessResponse(turnContext, action.Context.Theme)); } catch (UnauthorizedAccessException ex) { // If token for Badgr expires, sign out user from bot and send sign in card. this.logger.LogError(ex, ex.Message); return(await this.SignOutUserFromBotAsync(turnContext, cancellationToken)); } }
/// <summary> /// Handles "Add new question" button via messaging extension. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Action to be performed.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>Response of messaging extension action.</returns> public async Task <MessagingExtensionActionResponse> FetchTaskAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } else if (action == null) { throw new ArgumentNullException(nameof(action)); } try { turnContext.Activity.TryGetChannelData <TeamsChannelData>(out var teamsChannelData); string expertTeamId = this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.TeamId).GetAwaiter().GetResult(); if (teamsChannelData?.Team?.Id != expertTeamId) { var unauthorizedUserCard = MessagingExtensionQnaCard.UnauthorizedUserActionCard(); return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = unauthorizedUserCard ?? throw new ArgumentNullException(nameof(unauthorizedUserCard)), Height = 250, Width = 300, Title = Strings.AddQuestionSubtitle, }, }, }); }
/// <summary> /// Method overridden to show task module response. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> #pragma warning disable CS1998 // Method is overridden from Microsoft Bot Framework. protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) #pragma warning restore CS1998 // Method is overridden from Microsoft Bot Framework. { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); this.RecordEvent(nameof(this.OnTeamsMessagingExtensionFetchTaskAsync), turnContext); return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Type = "continue", Value = new TaskModuleTaskInfo() { Url = $"{this.botOptions.Value.AppBaseUri}/configure", Height = this.taskModuleHeight, Width = this.taskModuleWidth, Title = this.localizer.GetString("configureTaskModuleTitle"), }, }, }); }
/// <summary> /// Invoked when the user submits a response from messaging extension. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="action">Messaging extension action commands.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamsmessagingextensionsubmitactionasync?view=botbuilder-dotnet-stable. /// </remarks> protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); action = action ?? throw new ArgumentNullException(nameof(action)); this.RecordEvent(nameof(this.OnTeamsMessagingExtensionSubmitActionAsync), turnContext); var valuesFromTaskModule = JsonConvert.DeserializeObject <TaskModuleResponseDetails>(action.Data.ToString()); if (valuesFromTaskModule.Command.ToUpperInvariant() == Constants.SaveNominatedDetailsAction) { var mentionActivity = await CardHelper.GetMentionActivityAsync( valuesFromTaskModule.NomineeUserPrincipalNames.Split(",").Select(row => row.Trim()).ToList(), turnContext.Activity.From.AadObjectId, valuesFromTaskModule.TeamId, turnContext, this.localizer, this.logger, MentionActivityType.Nomination, cancellationToken); var notificationCard = EndorseCard.GetEndorseCard(this.options.Value.AppBaseUri, this.localizer, valuesFromTaskModule); await this.SendCardAndMentionsAsync(turnContext, notificationCard, mentionActivity); this.logger.LogInformation("Award nomination card sent successfully."); return(null); } this.logger.LogWarning($"Unsupported bot command: {valuesFromTaskModule.Command}"); return(null); }
public async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionBotMessagePreviewSendAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { var activityPreview = action.BotActivityPreview[0]; var attachmentContent = activityPreview.Attachments[0].Content; var previewedCard = JsonConvert.DeserializeObject <AdaptiveCard>(attachmentContent.ToString(), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); previewedCard.Version = "1.0"; var responseActivity = Activity.CreateMessageActivity(); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = previewedCard }; responseActivity.Attachments.Add(attachment); await turnContext.SendActivityAsync(responseActivity); return(new MessagingExtensionActionResponse()); }
protected override Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { Record.Add(MethodBase.GetCurrentMethod().Name); return(Task.FromResult(new MessagingExtensionActionResponse())); }
protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { if (action.CommandId.ToUpper() == "SHOWPROFILE") { var state = action.State; // Check the state value var tokenResponse = await GetTokenResponse(turnContext, state, cancellationToken); if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token)) { // There is no token, so the user has not signed in yet. // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions var signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false); return(new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { Type = "auth", SuggestedActions = new MessagingExtensionSuggestedAction { Actions = new List <CardAction> { new CardAction { Type = ActionTypes.OpenUrl, Value = signInLink, Title = "Bot Service OAuth", }, }, }, }, }); } var client = new SimpleGraphClient(tokenResponse.Token); var profile = await client.GetMyProfile(); return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = GetProfileCard(profile), Height = 250, Width = 400, Title = "Adaptive Card: Inputs", }, }, }); } if (action.CommandId.ToUpper() == "SIGNOUTCOMMAND") { var userTokenClient = turnContext.TurnState.Get <UserTokenClient>(); await userTokenClient.SignOutUserAsync(turnContext.Activity.From.Id, _connectionName, turnContext.Activity.ChannelId, cancellationToken).ConfigureAwait(false); return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = new Attachment { Content = new AdaptiveCard(new AdaptiveSchemaVersion("1.0")) { Body = new List <AdaptiveElement>() { new AdaptiveTextBlock() { Text = "You have been signed out." } }, Actions = new List <AdaptiveAction>() { new AdaptiveSubmitAction() { Title = "Close" } }, }, ContentType = AdaptiveCard.ContentType, }, Height = 200, Width = 400, Title = "Adaptive Card: Inputs", }, }, }); } return(null); }
protected override Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { // This method is to handle the 'Close' button on the confirmation Task Module after the user signs out. return(Task.FromResult(new MessagingExtensionActionResponse())); }
private MessagingExtensionActionResponse CreateCardCommand(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { // The user has chosen to create a card by choosing the 'Create Card' context menu command. var createCardData = ((JObject)action.Data).ToObject <CardResponse>(); var card = new HeroCard { Title = createCardData.Title, Subtitle = createCardData.Subtitle, Text = createCardData.Text, }; var attachments = new List <MessagingExtensionAttachment>(); attachments.Add(new MessagingExtensionAttachment { Content = card, ContentType = HeroCard.ContentType, Preview = card.ToAttachment(), }); return(new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { AttachmentLayout = "list", Type = "result", Attachments = attachments, }, }); }
private MessagingExtensionActionResponse RazorViewResponse(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { // The user has chosen to create a card by choosing the 'Create Card' context menu command. RazorViewResponse cardData = JsonConvert.DeserializeObject <RazorViewResponse>(action.Data.ToString()); var card = new HeroCard { Title = "Requested User: "******"list", Type = "result", Attachments = attachments, }, }); }
private MessagingExtensionActionResponse EmpDetails(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { var response = new MessagingExtensionActionResponse() { Task = new TaskModuleContinueResponse() { Value = new TaskModuleTaskInfo() { Height = 300, Width = 450, Title = "Task Module WebView", Url = baseUrl + "/Home/CustomForm", }, }, }; return(response); }
protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { switch (action.CommandId) { case "createCard": return(CreateCardCommand(turnContext, action)); case "shareMessage": return(ShareMessageCommand(turnContext, action)); case "webView": return(WebViewResponse(turnContext, action)); case "createAdaptiveCard": return(CreateAdaptiveCardResponse(turnContext, action)); case "razorView": return(RazorViewResponse(turnContext, action)); } return(new MessagingExtensionActionResponse()); }
private MessagingExtensionActionResponse TaskModuleHTMLPage(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { var response = new MessagingExtensionActionResponse() { Task = new TaskModuleContinueResponse() { Value = new TaskModuleTaskInfo() { Height = 200, Width = 400, Title = "Task Module HTML Page", Url = baseUrl + "/htmlpage.html", }, }, }; return(response); }
private MessagingExtensionActionResponse DateDayInfo(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { var response = new MessagingExtensionActionResponse() { Task = new TaskModuleContinueResponse() { Value = new TaskModuleTaskInfo() { Height = 175, Width = 300, Title = "Task Module Razor View", Url = baseUrl + "/Home/RazorView", }, }, }; return(response); }
protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { switch (action.CommandId) { case "webView": return(EmpDetails(turnContext, action)); case "HTML": return(TaskModuleHTMLPage(turnContext, action)); case "razorView": return(DateDayInfo(turnContext, action)); default: // we are handling two cases within try/catch block //if the bot is installed it will create adaptive card attachment and show card with input fields string memberName; try { // Check if your app is installed by fetching member information. var member = await TeamsInfo.GetMemberAsync(turnContext, turnContext.Activity.From.Id, cancellationToken); memberName = member.Name; } catch (ErrorResponseException ex) { if (ex.Body.Error.Code == "BotNotInConversationRoster") { return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = GetAdaptiveCardAttachmentFromFile("justintimeinstallation.json"), Height = 200, Width = 400, Title = "Adaptive Card - App Installation", }, }, }); } throw; // It's a different error. } return(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = GetAdaptiveCardAttachmentFromFile("adaptiveCard.json"), Height = 200, Width = 400, Title = $"Welcome {memberName}", }, }, }); } }
private MessagingExtensionActionResponse CreateAdaptiveCardResponse(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { var createCardResponse = ((JObject)action.Data).ToObject <CardResponse>(); var attachments = CardHelper.CreateAdaptiveCardAttachment(action, createCardResponse); return(new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { AttachmentLayout = "list", Type = "result", Attachments = attachments, }, }); }
private MessagingExtensionActionResponse WebViewResponse(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { // The user has chosen to create a card by choosing the 'Web View' context menu command. CustomFormResponse cardData = JsonConvert.DeserializeObject <CustomFormResponse>(action.Data.ToString()); var imgUrl = baseUrl + "/MSFT_logo.jpg"; var card = new ThumbnailCard { Title = "ID: " + cardData.EmpId, Subtitle = "Name: " + cardData.EmpName, Text = "E-Mail: " + cardData.EmpEmail, Images = new List <CardImage> { new CardImage { Url = imgUrl } }, }; var attachments = new List <MessagingExtensionAttachment>(); attachments.Add(new MessagingExtensionAttachment { Content = card, ContentType = ThumbnailCard.ContentType, Preview = card.ToAttachment(), }); return(new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { AttachmentLayout = "list", Type = "result", Attachments = attachments, }, }); }
protected override Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionDispatchAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { Record.Add(MethodBase.GetCurrentMethod().Name); return(base.OnTeamsMessagingExtensionSubmitActionDispatchAsync(turnContext, action, cancellationToken)); }
/// <summary> /// Handle message extension action fetch task received by the bot. /// </summary> /// <param name="turnContext">turn context.</param> /// <param name="action">action.</param> /// <param name="cancellationToken">cancellation token.</param> /// <returns>MessagingExtensionActionResponse.</returns> protected override Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { try { var adaptiveCardEditor = this.cards.AddQuestionActionCard(isValid: true); return(Task.FromResult(new MessagingExtensionActionResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo { Card = adaptiveCardEditor, Height = "medium", Width = "medium", Title = Strings.AddQuestionTaskTitle, }, }, })); } catch (Exception ex) { this.telemetryClient.TrackException(ex); } return(default);
private MessagingExtensionActionResponse ShareMessageCommand(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action) { // The user has chosen to share a message by choosing the 'Share Message' context menu command. var heroCard = new HeroCard { Title = $"{action.MessagePayload.From?.User?.DisplayName} orignally sent this message:", Text = action.MessagePayload.Body.Content, }; if (action.MessagePayload.Attachments != null && action.MessagePayload.Attachments.Count > 0) { // This sample does not add the MessagePayload Attachments. This is left as an // exercise for the user. heroCard.Subtitle = $"({action.MessagePayload.Attachments.Count} Attachments not included)"; } // This Messaging Extension example allows the user to check a box to include an image with the // shared message. This demonstrates sending custom parameters along with the message payload. var includeImage = ((JObject)action.Data)["includeImage"]?.ToString(); if (string.Equals(includeImage, bool.TrueString, StringComparison.OrdinalIgnoreCase)) { heroCard.Images = new List <CardImage> { new CardImage { Url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU" }, }; } return(new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { Type = "result", AttachmentLayout = "list", Attachments = new List <MessagingExtensionAttachment>() { new MessagingExtensionAttachment { Content = heroCard, ContentType = HeroCard.ContentType, Preview = heroCard.ToAttachment(), }, }, }, }); }