public ConnectorClientFactory(IMessageActivity message, MicrosoftAppCredentials credentials) { SetField.NotNull(out this.message, nameof(message), message); SetField.NotNull(out this.credentials, nameof(credentials), credentials); SetField.CheckNull(nameof(message.ServiceUrl), message.ServiceUrl); this.serviceUri = new Uri(message.ServiceUrl); this.isEmulator = message.ChannelId?.Equals("emulator", StringComparison.OrdinalIgnoreCase); }
public static async Task TranslateMessage(this ITranslator translator, IMessageActivity message, string toLocale) { if (message == null || message.Locale == null || toLocale == null || message.Locale == toLocale) return; try { var translatedText = await translator.Translate(message.Text, message.Locale, toLocale); message.Text = translatedText; //message.Locale = toLocale; return; } catch (Exception e) { return; } }
private async Task<bool> ApplyUserLanguage(IMessageActivity message) { var botState = new StateClient(new Uri(message.ServiceUrl)).BotState; var userData = await botState.GetUserDataAsync(message.ChannelId, message.From.Id); var match = Regex.Match(message.Text, LanguageCommandPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Singleline); if (match.Success) { var locale = match.Groups["locale"].Value; userData.SetProperty("userLocale", locale); await botState.SetUserDataAsync(message.ChannelId, message.From.Id, userData); return false; } var savedLocale = userData.GetProperty<string>("userLocale"); if (savedLocale != null) message.Locale = savedLocale; return true; }
protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result) { var answer = result.Answers.First().Answer; Activity reply = ((Activity)context.Activity).CreateReply(); try { var response = JsonConvert.DeserializeObject <FormattedAnswer>(answer); HeroCard card = new HeroCard { Title = response.Title, Subtitle = response.Description, Buttons = new List <CardAction> { new CardAction(ActionTypes.OpenUrl, response.BoutonText, value: response.Url) }, Images = new List <CardImage> { new CardImage(url: response.Image) } }; reply.Attachments.Add(card.ToAttachment()); } catch (JsonReaderException) { reply.Text = answer; } await context.PostAsync(reply); }
/// <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="taskModuleRequest">Task module invoke request 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>A task that represents a task module response.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); var activity = (Activity)turnContext.Activity; this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext); var valuesforTaskModule = JsonConvert.DeserializeObject <AdaptiveCardAction>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString()); var editTicketDetail = JsonConvert.DeserializeObject <TicketDetail>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString()); switch (valuesforTaskModule.Command.ToUpperInvariant()) { case Constants.UpdateRequestAction: var ticketDetail = await this.ticketDetailStorageProvider.GetTicketAsync(valuesforTaskModule.TicketId); if (TicketHelper.ValidateRequestDetail(editTicketDetail)) { ticketDetail.AdditionalProperties = CardHelper.ValidateAdditionalTicketDetails(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString(), turnContext.Activity.LocalTimestamp.Value.Offset); // Update request card with user entered values. ticketDetail = TicketHelper.GetUpdatedTicketDetails(turnContext, ticketDetail, editTicketDetail); bool result = await this.ticketDetailStorageProvider.UpsertTicketAsync(ticketDetail); if (!result) { this.logger.LogError("Error in storing new ticket details in table storage."); await turnContext.SendActivityAsync(this.localizer.GetString("AzureStorageErrorText")); return(null); } // Send update audit trail message and request details card in personal chat and SME team. this.logger.LogInformation($"Edited the ticket:{ticketDetail.TicketId}"); IMessageActivity smeEditNotification = MessageFactory.Text(string.Format(CultureInfo.InvariantCulture, this.localizer.GetString("SmeEditNotificationText"), ticketDetail.LastModifiedByName)); // Get card item element mappings var cardElementMapping = await this.cardConfigurationStorageProvider.GetCardItemElementMappingAsync(ticketDetail.CardId); IMessageActivity ticketDetailActivity = MessageFactory.Attachment(TicketCard.GetTicketDetailsForPersonalChatCard(cardElementMapping, ticketDetail, this.localizer, true)); ticketDetailActivity.Conversation = turnContext.Activity.Conversation; ticketDetailActivity.Id = ticketDetail.RequesterTicketActivityId; await turnContext.UpdateActivityAsync(ticketDetailActivity); await CardHelper.UpdateSMECardAsync(turnContext, ticketDetail, smeEditNotification, this.appBaseUrl, cardElementMapping, this.localizer, this.logger, cancellationToken); } else { editTicketDetail.AdditionalProperties = CardHelper.ValidateAdditionalTicketDetails(additionalDetails: ((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString(), timeSpan: turnContext.Activity.LocalTimestamp.Value.Offset); return(CardHelper.GetEditTicketAdaptiveCard(cardConfigurationStorageProvider: this.cardConfigurationStorageProvider, ticketDetail: editTicketDetail, localizer: this.localizer, existingTicketDetail: ticketDetail)); } break; case Constants.UpdateExpertListAction: var teamsChannelData = ((JObject)turnContext.Activity.ChannelData).ToObject <TeamsChannelData>(); var expertChannelId = teamsChannelData.Team == null ? this.teamId : teamsChannelData.Team.Id; if (expertChannelId != this.teamId) { this.logger.LogInformation("Invalid team. Bot is not installed in this team."); await turnContext.SendActivityAsync(this.localizer.GetString("InvalidTeamText")); return(null); } var onCallExpertsDetail = JsonConvert.DeserializeObject <OnCallExpertsDetail>(JObject.Parse(taskModuleRequest?.Data?.ToString())?.ToString()); await CardHelper.UpdateManageExpertsCardInTeamAsync(turnContext, onCallExpertsDetail, this.onCallSupportDetailSearchService, this.onCallSupportDetailStorageProvider, this.localizer); await ActivityHelper.SendMentionActivityAsync(onCallExpertsEmails : onCallExpertsDetail.OnCallExperts, turnContext : turnContext, logger : this.logger, localizer : this.localizer, cancellationToken : cancellationToken); this.logger.LogInformation("Expert List has been updated"); return(null); case Constants.CancelCommand: return(null); } return(null); }
public async Task StartAsync(IDialogContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var operationType = CalculationTypes.Statistical; // Performing some type of validation on the incoming data if (InputInts.Length > 2) { decimal median; int size = InputInts.Length; int[] copyArr = InputInts; // Sorting the array Array.Sort(copyArr); if (size % 2 == 0) { median = Convert.ToDecimal(copyArr[size / 2 - 1] + copyArr[size / 2]) / 2; } else { median = Convert.ToDecimal(copyArr[(size - 1) / 2]); } #region Building out the results object and the card var opsResultType = ResultTypes.Median; var opsResult = new OperationResults() { Input = InputString, NumericalResult = decimal.Round(median, 2).ToString(), OutputMsg = $"Given the list: {InputString}; the median = {decimal.Round(median, 2)}", OperationType = operationType.GetDescription(), ResultType = opsResultType.GetDescription() }; IMessageActivity opsReply = context.MakeMessage(); var resultsAdaptiveCard = OperationResultsAdaptiveCard.GetCard(opsResult); opsReply.Attachments = new List <Attachment>() { new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(resultsAdaptiveCard) } }; #endregion await context.PostAsync(opsReply); } else { var errorResType = ResultTypes.Error; var errorResult = new OperationResults() { Input = InputString, NumericalResult = "0", OutputMsg = $"Please double check the input: {InputString} and try again", OperationType = operationType.GetDescription(), ResultType = errorResType.GetDescription() }; IMessageActivity errorReply = context.MakeMessage(); var errorReplyAdaptiveCard = OperationErrorAdaptiveCard.GetCard(errorResult); errorReply.Attachments = new List <Attachment>() { new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(errorReplyAdaptiveCard) } }; await context.PostAsync(errorReply); } // Making sure to return back to the RootDialog context.Done <object>(null); }
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { IMessageActivity activity = (IMessageActivity)await result; await context.Forward(new LuisDialog(), AfterLuis, activity, CancellationToken.None); }
private async Task<IMessageActivity> GetResponse(IContainer container, Func<IDialog<object>> makeRoot, IMessageActivity toBot) { using (var scope = DialogModule.BeginLifetimeScope(container, toBot)) { DialogModule_MakeRoot.Register(scope, makeRoot); // act: sending the message await Conversation.SendAsync(scope, toBot); return scope.Resolve<Queue<IMessageActivity>>().Dequeue(); } }
async Task IBotToUser.PostAsync(IMessageActivity message, CancellationToken cancellationToken) { await this.client.Conversations.ReplyToActivityAsync((Activity)message, cancellationToken); }
private async Task UnregisterSubscription(IMessageActivity message, string group) { var subscriptionFacade = new SubscriptionFacade(); string teamId = message.ChannelData.team.id; await subscriptionFacade.UnregisterBotSubscription(teamId, group); }
public async void Execute(IDialogContext context, IMessageActivity message) { var subscriptionId = message.GetMessageParts().ElementAt(1); await UnregisterSubscription(message, subscriptionId); }
private async Task SendOAuthCardAsync(ITurnContext turnContext, IMessageActivity prompt, CancellationToken cancellationToken = default(CancellationToken)) { BotAssert.ContextNotNull(turnContext); if (!(turnContext.Adapter is IUserTokenProvider adapter)) { throw new InvalidOperationException("OAuthPrompt.Prompt(): not supported by the current adapter"); } // Ensure prompt initialized if (prompt == null) { prompt = Activity.CreateMessageActivity(); } if (prompt.Attachments == null) { prompt.Attachments = new List <Attachment>(); } // Append appropriate card if missing if (!ChannelSupportsOAuthCard(turnContext.Activity.ChannelId)) { if (!prompt.Attachments.Any(a => a.Content is SigninCard)) { var link = await adapter.GetOauthSignInLinkAsync(turnContext, ConnectionName, cancellationToken).ConfigureAwait(false); prompt.Attachments.Add(new Attachment { ContentType = SigninCard.ContentType, Content = new SigninCard { Text = Text, Buttons = new[] { new CardAction { Title = Title, Value = link, Type = ActionTypes.Signin, }, }, }, }); } } else if (!prompt.Attachments.Any(a => a.Content is OAuthCard)) { prompt.Attachments.Add(new Attachment { ContentType = OAuthCard.ContentType, Content = new OAuthCard { Text = Text, ConnectionName = ConnectionName, Buttons = new[] { new CardAction { Title = Title, Text = Text, Type = ActionTypes.Signin, }, }, }, }); } // Set input hint if (string.IsNullOrEmpty(prompt.InputHint)) { prompt.InputHint = InputHints.AcceptingInput; } await turnContext.SendActivityAsync(prompt, cancellationToken).ConfigureAwait(false); }
protected virtual Task <string> GetLuisQueryTextAsync(IDialogContext context, IMessageActivity message) { return(Task.FromResult(message.Text)); }
private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var luisResult = await _luisRecognizer1.RecognizeAsync <mainmenu>(stepContext.Context, cancellationToken); switch (luisResult.TopIntent().intent) { case mainmenu.Intent.activate: IMessageActivity reply = null; count = 1; StringBuilder sb = new StringBuilder("Login to enterProj application through the portal (http://Portal.hanonsystems.com)"); sb.AppendLine(""); sb.AppendLine("Enter the CDS ID – User name & Password."); sb.AppendLine("Click “Login” button."); sb.AppendLine(" Click the enterProj link under Application Menu and click the box “Project Portfolio Management/eFIN"); String s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments = new List <Attachment>() { getImage() }; var reply1 = reply; await stepContext.Context.SendActivityAsync(reply1); sb.Clear(); sb.AppendLine("In the left Menu, Click on My Worklist->My Project"); sb.AppendLine("In the right pane of the window there will be list of projects which you have created and you are assigned as a team member; click on the project which needs to be activated"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImage()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("You will find “Please contact Project Admin to get the Project activated.” on top of the page; click on Project Admin which will in turn open a new mail in outlook as shown below"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImage()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("Click on Send"); sb.AppendLine("The Project Admin will receive this email and will activate the project"); sb.AppendLine("If you have more questions, please refer the training document available in Hanon Portal"); sb.AppendLine("Hanon Portal->Workplace->HBOS & PDS->HPDS->HPDS Training->enterProj Training Material->Module_2: Project Tab"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImage()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("If you have any further clarifications, please submit an request in ServiceNow Portal https://hanon.service-now.com/"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); await stepContext.Context.SendActivityAsync(reply); reply.Attachments.Clear(); reply = MessageFactory.Text("Video Tutorial"); reply.Attachments.Add(getVid()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); break; case mainmenu.Intent.Add_a_team_member: count1 = 1; sb = new StringBuilder("Login to enterProj application through the portal (http://Portal.hanonsystems.com)"); sb.AppendLine(""); sb.AppendLine("1.Enter the CDS ID – User name & Password."); sb.AppendLine("2.Click “Login” button."); sb.AppendLine("3.Click the enterProj link under Application Menu and click the box “Project Portfolio Management/eFIN"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments = new List <Attachment>() { getImageQ2() }; reply1 = reply; await stepContext.Context.SendActivityAsync(reply1); sb.Clear(); sb.AppendLine("In the left Menu, Click on Search and click on the type of project which you are looking for."); sb.AppendLine("1. In the right pane of the window there will be a search page which will ask for a Project number. Enter the Project number and click on Search."); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ2()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("2.The project will be displayed; click on the project number and click on the Team tab."); sb.AppendLine("3.In the Team tab you will find a link ‘Add Team Member’ click on it"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ2()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("4. Enter the user name and click the lookup and then click Add"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ2()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("5.Now the Team member has been added in the project"); sb.AppendLine("If you have more questions, please refer the training document available in Hanon Portal"); sb.AppendLine("Hanon Portal->Workplace->HBOS & PDS->HPDS->HPDS Training->enterProj Training Material->Module_2: Project Tab"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ2()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); reply = MessageFactory.Text("If you have any further clarifications, please submit an request in ServiceNow Portal https://hanon.service-now.com/"); await stepContext.Context.SendActivityAsync(reply); reply.Attachments.Clear(); reply = MessageFactory.Text("Video Tutorial"); reply.Attachments.Add(getVid()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); break; case mainmenu.Intent.Assign_Ownership: count2 = 1; sb = new StringBuilder("Login to enterProj application through the portal (http://Portal.hanonsystems.com)"); sb.AppendLine(""); sb.AppendLine("1.Enter the CDS ID – User name & Password."); sb.AppendLine("2.Click “Login” button."); sb.AppendLine("3.Click the enterProj link under Application Menu and click the box “Project Portfolio Management/eFIN"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments = new List <Attachment>() { getImageQ3() }; await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("In the left Menu, Click on Search and click on the type of project which you are looking for."); sb.AppendLine("In the right pane of the window there will be a search page which will ask for a Project number."); sb.Append("Enter the Project number and click on Search. "); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ3()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("The project will be displayed; click on the project number and click on the Team tab."); sb.AppendLine("In the Team tab you will find the list of team members and you can search the team member whom you are going to assign the ownership"); sb.AppendLine("Next to the member name you will find ‘Owner’ field where you can tick the checkbox corresponding to the team member.Click Save button."); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ3()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("Now the Team member has been assigned as an Owner for that project."); sb.AppendLine("If you have more questions, please refer the training document available in Hanon Portal"); sb.AppendLine("Hanon Portal->Workplace->HBOS & PDS->HPDS->HPDS Training->enterProj Training Material->Module_2: Project Tab"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ3()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("If you have any further clarifications, please submit an request in ServiceNow Portal (https://hanon.service-now.com/)"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); await stepContext.Context.SendActivityAsync(reply); reply.Attachments.Clear(); reply = MessageFactory.Text("Video Tutorial"); reply.Attachments.Add(getVid()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); break; case mainmenu.Intent.New_Project_Creation: count3 = 1; sb = new StringBuilder("Login to enterProj application through the portal (http://Portal.hanonsystems.com)"); sb.AppendLine(""); sb.AppendLine("1.Enter the CDS ID – User name & Password."); sb.AppendLine("2.Click “Login” button."); sb.AppendLine("3.Click the enterProj link under Application Menu and click the box “Project Portfolio Management/eFIN"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments = new List <Attachment>() { getImageQ4() }; await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("A new blank project screen will be displayed as shown"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); reply.Attachments.Add(getImageQ4()); await stepContext.Context.SendActivityAsync(reply); sb.Clear(); sb.AppendLine("If you have any further clarifications, please submit an request in ServiceNow Portal (https://hanon.service-now.com/)"); s1 = sb.ToString(); reply = MessageFactory.Text(s1); reply.Attachments.Clear(); await stepContext.Context.SendActivityAsync(reply); reply.Attachments.Clear(); reply = MessageFactory.Text("Video Tutorial"); reply.Attachments.Add(getVid()); await stepContext.Context.SendActivityAsync(reply); break; case mainmenu.Intent.None: var didntUnderstandMessageText = $"Sorry, I didn't get that. Please try asking in a different way (intent was {luisResult.TopIntent().intent})"; var didntUnderstandMessage = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput); await stepContext.Context.SendActivityAsync(didntUnderstandMessage, cancellationToken); break; } var messageText = $"Do you wish go back to enterproj menu?"; var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput); return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken)); }
private async Task <IMessageActivity> GetResponse(IContainer container, Func <IDialog <object> > makeRoot, IMessageActivity toBot) { using (var scope = DialogModule.BeginLifetimeScope(container, toBot)) { DialogModule_MakeRoot.Register(scope, makeRoot); // act: sending the message //await Conversation.SendAsync(scope, toBot); await Conversation.SendAsync(toBot, makeRoot, CancellationToken.None); return(scope.Resolve <Queue <IMessageActivity> >().Dequeue()); } }
public DetectChannelCapability(IMessageActivity message) { SetField.CheckNull(nameof(message), message); SetField.NotNull(out channelId, nameof(channelId), message.ChannelId); SetField.NotNull(out serviceUrl, nameof(serviceUrl), message.ServiceUrl); }
public static bool IsReactionValid(IMessageActivity message) { var messageParts = message.GetMessageParts().ToArray(); return(messageParts.Count() == 2 && messageParts.First() == "/unregisterBot"); }
async Task IBotToUser.PostAsync(IMessageActivity message, CancellationToken cancellationToken) { await this.inner.PostAsync(message, cancellationToken); await this.writer.WriteLineAsync($"{message.Text}{ButtonsToText(message.Attachments)}"); }
// Override to also include the knowledgebase question with the answer on confident matches protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults results) { if (results.Answers.Count > 0) { var response = "Here is the match from FAQ: \r\n Q: " + results.Answers.First().Questions.First() + " \r\n A: " + results.Answers.First().Answer; await context.PostAsync(response); } context.Done(true); }
async Task IBotToUser.PostAsync(IMessageActivity message, CancellationToken cancellationToken) { this.queue.Enqueue(message); }
private async Task StartOverAsync(IDialogContext context, IMessageActivity message) { await context.PostAsync(message); await this.StartAsync(context); }
private async Task SendOAuthCardAsync(ITurnContext turnContext, IMessageActivity prompt, CancellationToken cancellationToken = default(CancellationToken)) { BotAssert.ContextNotNull(turnContext); if (!(turnContext.Adapter is IExtendedUserTokenProvider adapter)) { throw new InvalidOperationException("OAuthPrompt.Prompt(): not supported by the current adapter"); } // Ensure prompt initialized if (prompt == null) { prompt = Activity.CreateMessageActivity(); } if (prompt.Attachments == null) { prompt.Attachments = new List <Attachment>(); } // Append appropriate card if missing if (!ChannelSupportsOAuthCard(turnContext.Activity.ChannelId)) { if (!prompt.Attachments.Any(a => a.Content is SigninCard)) { var signInResource = await adapter.GetSignInResourceAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, turnContext.Activity.From.Id, null, cancellationToken).ConfigureAwait(false); prompt.Attachments.Add(new Attachment { ContentType = SigninCard.ContentType, Content = new SigninCard { Text = _settings.Text, Buttons = new[] { new CardAction { Title = _settings.Title, Value = signInResource.SignInLink, Type = ActionTypes.Signin, }, }, }, }); } } else if (!prompt.Attachments.Any(a => a.Content is OAuthCard)) { var cardActionType = ActionTypes.Signin; var signInResource = await adapter.GetSignInResourceAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, turnContext.Activity.From.Id, null, cancellationToken).ConfigureAwait(false); var value = signInResource.SignInLink; if (turnContext.TurnState.Get <ClaimsIdentity>("BotIdentity") is ClaimsIdentity botIdentity && SkillValidation.IsSkillClaim(botIdentity.Claims)) { cardActionType = ActionTypes.OpenUrl; } else { value = null; } prompt.Attachments.Add(new Attachment { ContentType = OAuthCard.ContentType, Content = new OAuthCard { Text = _settings.Text, ConnectionName = _settings.ConnectionName, Buttons = new[] { new CardAction { Title = _settings.Title, Text = _settings.Text, Type = cardActionType, Value = value }, }, TokenExchangeResource = signInResource.TokenExchangeResource, }, }); }
public static async Task <string> CreateAgentConversationEx(IDialogContext context, string topicName, AdaptiveCard cardToSend, UserProfile endUserProfile) { string serviceUrl = GetServiceUrl(context); var agentChannelInfo = await IdTable.GetAgentChannelInfo(); ChannelAccount botMsTeamsChannelAccount = context.Activity.ChannelId == ActivityHelper.SmsChannelId ? await IdTable.GetBotId() : context.Activity.From; using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(serviceUrl)) { try { var channelData = new TeamsChannelData { Channel = agentChannelInfo }; IMessageActivity agentMessage = Activity.CreateMessageActivity(); agentMessage.From = botMsTeamsChannelAccount; agentMessage.Recipient = new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]); agentMessage.Type = ActivityTypes.Message; agentMessage.ChannelId = ActivityHelper.MsTeamChannelId; agentMessage.ServiceUrl = serviceUrl; agentMessage.Attachments = new List <Attachment> { new Attachment { ContentType = AdaptiveCard.ContentType, Content = cardToSend } }; var agentMessageActivity = (Activity)agentMessage; ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: null, members: null, topicName: topicName, activity: agentMessageActivity, channelData: channelData); var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync( async() => await connectorClient.Conversations.CreateConversationAsync(conversationParams)); Trace.TraceInformation( $"[SUCCESS]: CreateAgentConversation. response id ={conversationResourceResponse.Id}"); WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string> { { "endUser", agentMessage.From.Name }, { "agentConversationId", conversationResourceResponse.Id }, }); return(conversationResourceResponse.Id); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string> { { "function", "CreateAgentConversation" } }); throw; } } }
/// <summary> /// Call a child dialog, add it to the top of the stack and post the message to the child dialog. /// </summary> /// <typeparam name="R">The type of result expected from the child dialog.</typeparam> /// <param name="stack">The dialog stack.</param> /// <param name="child">The child dialog.</param> /// <param name="resume">The method to resume when the child dialog has completed.</param> /// <param name="message">The message that will be posted to child dialog.</param> /// <param name="token">A cancellation token.</param> /// <returns>A task representing the Forward operation.</returns> public static async Task Forward <R>(this IDialogStack stack, IDialog <R> child, ResumeAfter <R> resume, IMessageActivity message, CancellationToken token) { await stack.Forward <R, IMessageActivity>(child, resume, message, token); }
public static async Task <ConversationResourceResponse> CreateAgentConversation(ChannelInfo targetChannelInfo, AdaptiveCard card, string topicName, ConnectorClient connector, int vsoTicketNumber, IMessageActivity endUserActivity) { try { var channelData = new TeamsChannelData { Channel = targetChannelInfo }; IMessageActivity agentMessage = Activity.CreateMessageActivity(); agentMessage.From = endUserActivity.Recipient; agentMessage.Recipient = new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]); agentMessage.Type = ActivityTypes.Message; agentMessage.ChannelId = ActivityHelper.MsTeamChannelId; agentMessage.ServiceUrl = endUserActivity.ServiceUrl; agentMessage.Attachments = new List <Attachment> { new Attachment { ContentType = AdaptiveCard.ContentType, Content = card } }; var agentMessageActivity = (Activity)agentMessage; ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: null, members: null, topicName: topicName, activity: agentMessageActivity, channelData: channelData); var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() => await connector.Conversations.CreateConversationAsync(conversationParams)); Trace.TraceInformation($"[SUCCESS]: CreateAgentConversation. " + $"response id ={conversationResourceResponse.Id} vsoId={vsoTicketNumber} "); WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string> { { "endUser", agentMessage.From.Name }, { "agentConversationId", conversationResourceResponse.Id }, { "vsoId", vsoTicketNumber.ToString() }, }); return(conversationResourceResponse); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string> { { "function", "CreateAgentConversation" }, { "endUser", endUserActivity.Recipient.Name }, { "vsoId", vsoTicketNumber.ToString() } }); throw; } }
protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result) { // Add code to format QnAMakerResults 'result' // Answer is a string var answer = result.Answers.First().Answer; Activity reply = ((Activity)context.Activity).CreateReply(); string[] qnaAnswerData = answer.Split('|'); string title = qnaAnswerData[0]; string description = qnaAnswerData[1]; string url = qnaAnswerData[2]; string imageURL = qnaAnswerData[3]; if (title == "") { char charsToTrim = '|'; await context.PostAsync(answer.Trim(charsToTrim)); } else { HeroCard card = new HeroCard { Title = title, Subtitle = description, }; card.Buttons = new List <CardAction> { new CardAction(ActionTypes.OpenUrl, "Learn More", value: url) }; card.Images = new List <CardImage> { new CardImage(url = imageURL) }; reply.Attachments.Add(card.ToAttachment()); await context.PostAsync(reply); } }
protected override bool TryParse(IMessageActivity message, out DateTime result) { var quitCondition = message.Text.Equals("Cancel", StringComparison.InvariantCultureIgnoreCase); return(DateTime.TryParseExact(message.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result) || quitCondition); }
public async Task StartAsync(IDialogContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var operationType = CalculationTypes.Geometric; if (InputInts.Length > 2) { var errorResultType = ResultTypes.Error; var errorResults = new OperationResults() { Input = InputString, NumericalResult = "0", OutputMsg = $"The input list: {InputString} is too long. I need only 2 numbers to find the length of the hypotenuse", OperationType = operationType.GetDescription(), ResultType = errorResultType.GetDescription() }; IMessageActivity errorReply = context.MakeMessage(); var errorResultsAdaptiveCard = OperationErrorAdaptiveCard.GetCard(errorResults); errorReply.Attachments = new List <Attachment>() { new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(errorResultsAdaptiveCard) } }; await context.PostAsync(errorReply); } else { // Having the necessary calculations done double a = Convert.ToDouble(InputInts[0]); double b = Convert.ToDouble(InputInts[1]); var hypotenuseSqr = Math.Pow(a, 2) + Math.Pow(b, 2); double c = Math.Sqrt(hypotenuseSqr); var output = $"Given the legs of ${InputInts[0]} and ${InputInts[1]}, the hypotenuse of the right triangle is ${decimal.Round(decimal.Parse(c.ToString()), 2)}"; var resultType = ResultTypes.Hypotenuse; var successResults = new OperationResults() { Input = InputString, NumericalResult = decimal.Round(decimal.Parse(c.ToString()), 2).ToString(), OutputMsg = output, OperationType = operationType.GetDescription(), ResultType = resultType.GetDescription() }; IMessageActivity successReply = context.MakeMessage(); var resultsAdaptiveCard = OperationResultsAdaptiveCard.GetCard(successResults); successReply.Attachments = new List <Attachment>() { new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(resultsAdaptiveCard) } }; await context.PostAsync(successReply); } // Returning back to the root dialog context.Done <object>(null); }
public async Task ConfirmLocation(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result) { try { string state = ""; if (context.UserData.TryGetValue("state", out state) && state == "reporttime") { var message = await activity; bool found = false; double lat, lon; string addr; string id = ""; found = context.UserData.TryGetValue("lat", out lat); if (!found) { context.Wait(this.MessageReceived); return; } found = context.UserData.TryGetValue("lon", out lon); if (!found) { context.Wait(this.MessageReceived); return; } found = context.UserData.TryGetValue("addr", out addr); if (!found) { context.Wait(this.MessageReceived); return; } found = context.UserData.TryGetValue("id", out id); if (!found) { context.Wait(this.MessageReceived); return; } context.UserData.SetValue("state", ""); string msg = Messages.CustomerReportPolice; await context.PostAsync(msg); string ticketnumber = await Backend.CustomerService.FileCase(id, Backend.IncidentType.lost, lat, lon); msg = string.Format(Messages.CustomerReplyCaseNumber, ticketnumber); await context.PostAsync(msg); //send message to employee var employee = await Backend.CustomerService.GetAvailableEmployee(); BotUser user = new BotUser(); user.id = message.From.Id; user.name = message.From.Name; user.serviceUrl = message.ServiceUrl; user.conversationId = message.Conversation.Id; user.location = new GeoLocation(); user.location.latitude = lat; user.location.longitude = lon; user.location.name = addr; employee.customer = user; await Backend.CustomerService.SaveInformation(employee); var userAccount = new ChannelAccount(name: employee.name, id: employee.id); var connector = new ConnectorClient(new Uri(employee.serviceUrl)); IMessageActivity mm = Activity.CreateMessageActivity(); mm.From = message.Recipient; mm.Recipient = userAccount; mm.Text = string.Format(Messages.EmployeeMsg1, employee.name); mm.Locale = "en-Us"; await connector.Conversations.SendToConversationAsync((Activity)mm, employee.conversationId); mm.Text = "NAME: **" + user.name + "**"; await connector.Conversations.SendToConversationAsync((Activity)mm, employee.conversationId); mm.Text = "INCIDENT NUMBER: **" + ticketnumber + "**"; await connector.Conversations.SendToConversationAsync((Activity)mm, employee.conversationId); var deliveraddr = await Backend.BingMapHelper.PointToAddress(lat, lon); mm.Text = string.Format(Messages.EmployeeMsg2, addr, deliveraddr); var mapurl = await Backend.BingMapHelper.StaticMapWith1Pin(lat, lon, addr); if (mapurl != "") { var heroCard = new HeroCard { Images = new List <CardImage> { new CardImage(mapurl) } }; mm.Attachments = new List <Attachment>(); mm.Attachments.Add(heroCard.ToAttachment()); } await connector.Conversations.SendToConversationAsync((Activity)mm, employee.conversationId); mm.Text = Messages.EmployeeMsg3; mm.Attachments = null; await connector.Conversations.SendToConversationAsync((Activity)mm, employee.conversationId); context.Wait(this.MessageReceived); } else { string message = string.Format(Messages.CustomerDefault, result.Query); await context.PostAsync(message); context.Wait(this.MessageReceived); return; } } catch (Exception) { context.Wait(this.MessageReceived); } }
private async Task EchoDialogFlow(IDialog <object> echoDialog) { // arrange var toBot = DialogTestBase.MakeTestMessage(); toBot.From.Id = Guid.NewGuid().ToString(); toBot.Text = "Test"; Func <IDialog <object> > MakeRoot = () => echoDialog; using (new FiberTestBase.ResolveMoqAssembly(echoDialog)) using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, echoDialog)) { // act: sending the message IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot); // assert: check if the dialog returned the right response Assert.IsTrue(toUser.Text.StartsWith("1")); Assert.IsTrue(toUser.Text.Contains("Test")); // act: send the message 10 times for (int i = 0; i < 10; i++) { // pretend we're the intercom switch, and copy the bot data from message to message toBot.Text = toUser.Text; toUser = await GetResponse(container, MakeRoot, toBot); } // assert: check the counter at the end Assert.IsTrue(toUser.Text.StartsWith("11")); toBot.Text = "reset"; toUser = await GetResponse(container, MakeRoot, toBot); // checking if there is any cards in the attachment and promote the card.text to message.text if (toUser.Attachments != null && toUser.Attachments.Count > 0) { var card = (HeroCard)toUser.Attachments.First().Content; toUser.Text = card.Text; } Assert.IsTrue(toUser.Text.ToLower().Contains("are you sure")); toBot.Text = "yes"; toUser = await GetResponse(container, MakeRoot, toBot); Assert.IsTrue(toUser.Text.ToLower().Contains("reset count")); //send a random message and check count toBot.Text = "test"; toUser = await GetResponse(container, MakeRoot, toBot); Assert.IsTrue(toUser.Text.StartsWith("1")); toBot.Text = "/deleteprofile"; toUser = await GetResponse(container, MakeRoot, toBot); Assert.IsTrue(toUser.Text.ToLower().Contains("deleted")); using (var scope = DialogModule.BeginLifetimeScope(container, toBot)) { var botData = scope.Resolve <IBotData>(); await botData.LoadAsync(default(CancellationToken)); var stack = scope.Resolve <IDialogStack>(); Assert.AreEqual(0, stack.Frames.Count); } } }
public static async Task DispatchAsync(this IDialogContext context, IMessageActivity activity) => await ServiceLocator.Current.GetInstance <IMessageDispatcher>().DispatchAsync(context, activity);
public BotDataBase(IBotIdResolver botIdResolver, IMessageActivity message, IBotDataStore <BotData> botDataStore) { SetField.NotNull(out this.botDataStore, nameof(BotDataBase <T> .botDataStore), botDataStore); SetField.CheckNull(nameof(message), message); this.botDataKey = message.GetBotDataKey(botIdResolver.BotId); }
/// <summary> /// Handles the given connection request result. /// </summary> /// <param name="connectionRequestResult">The result to handle.</param> /// <returns>True, if the result was handled. False, if no action was taken.</returns> protected virtual async Task <bool> HandleConnectionRequestResultAsync( ConnectionRequestResult connectionRequestResult) { ConnectionRequest connectionRequest = connectionRequestResult?.ConnectionRequest; if (connectionRequest == null || connectionRequest.Requestor == null) { System.Diagnostics.Debug.WriteLine("No client to inform about the connection request result"); return(false); } switch (connectionRequestResult.Type) { case ConnectionRequestResultType.Created: foreach (ConversationReference aggregationChannel in _messageRouter.RoutingDataManager.GetAggregationChannels()) { ConversationReference botConversationReference = _messageRouter.RoutingDataManager.FindConversationReference( aggregationChannel.ChannelId, aggregationChannel.Conversation.Id, null, true); if (botConversationReference != null) { IMessageActivity messageActivity = Activity.CreateMessageActivity(); messageActivity.Conversation = aggregationChannel.Conversation; messageActivity.Recipient = RoutingDataManager.GetChannelAccount(aggregationChannel); messageActivity.Attachments = new List <Attachment> { CommandCardFactory.CreateConnectionRequestCard( connectionRequest, RoutingDataManager.GetChannelAccount( botConversationReference)?.Name).ToAttachment() }; await _messageRouter.SendMessageAsync(aggregationChannel, messageActivity); } } await _messageRouter.SendMessageAsync( connectionRequest.Requestor, Strings.NotifyClientWaitForRequestHandling); return(true); case ConnectionRequestResultType.AlreadyExists: await _messageRouter.SendMessageAsync( connectionRequest.Requestor, Strings.NotifyClientDuplicateRequest); return(true); case ConnectionRequestResultType.Rejected: if (connectionRequestResult.Rejecter != null) { await _messageRouter.SendMessageAsync( connectionRequestResult.Rejecter, string.Format(Strings.NotifyOwnerRequestRejected, GetNameOrId(connectionRequest.Requestor))); } await _messageRouter.SendMessageAsync( connectionRequest.Requestor, Strings.NotifyClientRequestRejected); return(true); case ConnectionRequestResultType.NotSetup: await _messageRouter.SendMessageAsync( connectionRequest.Requestor, Strings.NoAgentsAvailable); return(true); case ConnectionRequestResultType.Error: if (connectionRequestResult.Rejecter != null) { await _messageRouter.SendMessageAsync( connectionRequestResult.Rejecter, string.Format(Strings.ConnectionRequestResultErrorWithResult, connectionRequestResult.ErrorMessage)); } return(true); default: break; } return(false); }
/// <summary> /// Creates an instance of resumption cookie form a <see cref="Connector.IMessageActivity"/> /// </summary> /// <param name="msg"> The message.</param> public ResumptionCookie(IMessageActivity msg) { UserId = msg.From?.Id; UserName = msg.From?.Name; ChannelId = msg.ChannelId; ServiceUrl = msg.ServiceUrl; BotId = msg.Recipient?.Id; ConversationId = msg.Conversation?.Id; var isGroup = msg.Conversation?.IsGroup; IsGroup = isGroup.HasValue && isGroup.Value; Locale = msg.Locale; }
public static bool IsValidReaction(IMessageActivity message) { var messageParts = message.GetMessageParts().ToArray(); return(messageParts.Count() == 2 && messageParts.First() == "/reportStatus"); }
protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { //var adaptiveCardAttachment = CardsDemoWithTypes(); //await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCardAttachment)); if (turnContext.Activity.Type == ActivityTypes.Message) { // Check if user submitted AdaptiveCard input if (turnContext.Activity.Value != null) { //var activityValue = turnContext.Activity.AsMessageActivity().Value as Newtonsoft.Json.Linq.JObject; //if (activityValue != null) //{ // var categorySelection = activityValue.ToObject<CategorySelection>(); // var category = categorySelection.Category; // await turnContext.SendActivityAsync(category); //} // Convert String to JObject String value = turnContext.Activity.Value.ToString(); JObject results = JObject.Parse(value); // Get type from input field String submitType = results.GetValue("Type").ToString().Trim(); switch (submitType) { case "email": IMessageActivity message = Activity.CreateMessageActivity(); message.Type = ActivityTypes.Message; message.Text = "email \n <br> sent"; message.Locale = "en-Us"; message.TextFormat = TextFormatTypes.Plain; await turnContext.SendActivityAsync(message, cancellationToken); /* */ return; default: await turnContext.SendActivityAsync("No Action Logic Written for this button", cancellationToken : cancellationToken); break; } String name = results.GetValue("Type").ToString().Trim(); //String actionText = results.GetValue("ActionText").ToString(); //await turnContext.SendActivityAsync("Respond to user " + actionText, cancellationToken: cancellationToken); // Get Keywords from input field String userInputKeywords = ""; // if (name == "GetPPT") { if (name == "ViewProfile") { //String DisplayVal = results.GetValue("DisplayText").ToString(); //await turnContext.SendActivityAsync(MessageFactory.Text(DisplayVal), cancellationToken); userInputKeywords = "View Profile"; AdaptiveCard ViewcardAttachment = null; ViewcardAttachment = AdaptiveCardBotHelper.ViewProfile(); var attachment = new Attachment { ContentType = AdaptiveCard.ContentType, Content = ViewcardAttachment }; if (attachment != null) { await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken); //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken); } } else if (name == "UpdateProfile") { userInputKeywords = "Update Profile"; AdaptiveCard UpdatecardAttachment = null; UpdatecardAttachment = AdaptiveCardBotHelper.UpdateProfile(); var attachment = new Attachment { ContentType = AdaptiveCard.ContentType, Content = UpdatecardAttachment }; if (attachment != null) { await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken); //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken); } //userInputKeywords = results.GetValue("GetUserInputKeywords").ToString(); } else if (name == "SendIssue") { AdaptiveCard IssuecardAttachment = null; IssuecardAttachment = AdaptiveCardBotHelper.ReportIssue(); var attachment = new Attachment { ContentType = AdaptiveCard.ContentType, Content = IssuecardAttachment }; if (attachment != null) { await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken); //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken); } userInputKeywords = "Report Issue"; } else if (name == "Update") { userInputKeywords = "Update Info"; userInputKeywords = results.GetValue("GetUserInputKeywords").ToString(); } // // Make Http request to api with paramaters //String myUrl = $"http://myurl.com/api/{userInputKeywords}"; //... // Respond to user await turnContext.SendActivityAsync("Respond to user" + userInputKeywords, cancellationToken : cancellationToken); } else { //Conversation Text:- hi, "*****@*****.**", "i want to raise an issue", "hardware", "software" turnContext.Activity.RemoveRecipientMention(); var text = turnContext.Activity.Text.Trim().ToLower(); Body.Text = text; apiHelperObj = new BotAPIHelper(); CreateResponseBody responseBody = apiHelperObj.CreateApiPostCall(Body); if (responseBody != null) { if (responseBody.OutputStack != null && responseBody.OutputStack.Count() > 0) { foreach (var OutputStack in responseBody.OutputStack) { if (!string.IsNullOrEmpty(OutputStack.Text)) { await turnContext.SendActivityAsync(MessageFactory.Text(OutputStack.Text), cancellationToken); //IMessageActivity message = Activity.CreateMessageActivity(); //message.Type = ActivityTypes.Message; //message.Text = "your \n <br> text"; //message.Locale = "en-Us"; //message.TextFormat = TextFormatTypes.Plain; //await turnContext.SendActivityAsync(message); } else { var mainCard = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0)); if (OutputStack.Data.type == "buttons") { //===========================Add DropDownList //AdaptiveChoiceSetInput choiceSet = AdaptiveCardBotHelper.AddDropDownList(); AdaptiveChoiceSetInput choiceSet = AdaptiveCardHelper.AddDropDownToAdaptiveCard(OutputStack); mainCard.Body.Add(choiceSet); //=========================== Add Button var adaptiveButtonList = AdaptiveCardHelper.AddButtonsToAdaptiveCard(OutputStack); if (adaptiveButtonList != null && adaptiveButtonList.Count() > 0) { mainCard.Body.Add(AdaptiveCardHelper.AddTextBlock(OutputStack.Data._cognigy._default._buttons.text)); mainCard.Actions = adaptiveButtonList; } //var card = AdaptiveCardBotHelper.GetCard(OutputStack); } if (mainCard != null) { var cardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = mainCard, Name = "CardName" }; await turnContext.SendActivityAsync(MessageFactory.Attachment(cardAttachment), cancellationToken); } } } } } } } }
public void AttachmentNull() { IMessageActivity message = MessageFactory.Attachment((Attachment)null); Assert.Fail("Exception not thrown"); }
public AlwaysSendDirect_BotToUser(IMessageActivity toBot, IConnectorClient client) { SetField.NotNull(out this.toBot, nameof(toBot), toBot); SetField.NotNull(out this.client, nameof(client), client); }
public void AttachmentMultipleNull() { IMessageActivity message = MessageFactory.Attachment((IList <Attachment>)null); Assert.Fail("Exception not thrown"); }
public BotToUserQueue(IMessageActivity toBot, Queue<IMessageActivity> queue) { SetField.NotNull(out this.toBot, nameof(toBot), toBot); SetField.NotNull(out this.queue, nameof(queue), queue); }
public void CarouselNull() { IMessageActivity message = MessageFactory.Carousel((IList <Attachment>)null); Assert.Fail("Exception not thrown"); }
public static ILifetimeScope BeginLifetimeScope(ILifetimeScope scope, IMessageActivity message) { var inner = scope.BeginLifetimeScope(LifetimeScopeTag); inner.Resolve<IMessageActivity>(TypedParameter.From(message)); return inner; }
async Task IBotToUser.PostAsync(IMessageActivity message, CancellationToken cancellationToken) { await translator.TranslateMessage(message, Thread.CurrentThread?.CurrentCulture?.Name); await this.inner.PostAsync(message, cancellationToken); }