internal async Task OnDeleteActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string activityId, CancellationToken cancellationToken = default) { var skillConversationReference = await GetSkillConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false); var callback = new BotCallbackHandler(async(turnContext, ct) => { turnContext.TurnState.Add(_skillConversationReferenceKey, skillConversationReference); await turnContext.DeleteActivityAsync(activityId, cancellationToken).ConfigureAwait(false); }); await _adapter.ContinueConversationAsync(claimsIdentity, skillConversationReference.ConversationReference, skillConversationReference.OAuthScope, callback, cancellationToken).ConfigureAwait(false); }
private async Task <ResourceResponse> ProcessActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string replyToActivityId, Activity activity, CancellationToken cancellationToken) { SkillConversationReference skillConversationReference; try { skillConversationReference = await _conversationIdFactory.GetSkillConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false); } catch (NotImplementedException) { // Attempt to get SkillConversationReference using deprecated method. // this catch should be removed once we remove the deprecated method. // We need to use the deprecated method for backward compatibility. #pragma warning disable 618 var conversationReference = await _conversationIdFactory.GetConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false); #pragma warning restore 618 skillConversationReference = new SkillConversationReference { ConversationReference = conversationReference, OAuthScope = ChannelProvider != null && ChannelProvider.IsGovernment() ? GovernmentAuthenticationConstants.ToChannelFromBotOAuthScope : AuthenticationConstants.ToChannelFromBotOAuthScope }; } if (skillConversationReference == null) { throw new KeyNotFoundException(); } ResourceResponse resourceResponse = null; var callback = new BotCallbackHandler(async(turnContext, ct) => { turnContext.TurnState.Add(SkillConversationReferenceKey, skillConversationReference); activity.ApplyConversationReference(skillConversationReference.ConversationReference); turnContext.Activity.Id = replyToActivityId; turnContext.Activity.CallerId = $"{CallerIdConstants.BotToBotPrefix}{JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims)}"; switch (activity.Type) { case ActivityTypes.EndOfConversation: await _conversationIdFactory.DeleteConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false); ApplyEoCToTurnContextActivity(turnContext, activity); await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false); break; case ActivityTypes.Event: ApplyEventToTurnContextActivity(turnContext, activity); await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false); break; default: resourceResponse = await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false); break; } }); await _adapter.ContinueConversationAsync(claimsIdentity, skillConversationReference.ConversationReference, skillConversationReference.OAuthScope, callback, cancellationToken).ConfigureAwait(false); return(resourceResponse ?? new ResourceResponse(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture))); }
private void CreateTimerForConversation(DialogContext dc, string timerId, CancellationToken cancellationToken) { BotAdapter adapter = dc.Context.Adapter; var identity = dc.Context.TurnState.Get <ClaimsIdentity>("BotIdentity"); var appId = identity?.Claims?.FirstOrDefault(c => c.Type == AuthenticationConstants.AudienceClaim)?.Value; ConversationReference conversationReference = dc.Context.Activity.GetConversationReference(); int timeout = TimeOutInMilliseconds.GetValue(dc.State); //Question remaining to be answered: Will this task get garbage collected? If so, we need to maintain a handle for it. Task.Run(async() => { await Task.Delay(timeout).ConfigureAwait(false); string msAppId = appId; // If the channel is the Emulator, and authentication is not in use, // the AppId will be null. We generate a random AppId for this case only. // This is not required for production, since the AppId will have a value. if (string.IsNullOrEmpty(msAppId)) { msAppId = Guid.NewGuid().ToString(); //if no AppId, use a random Guid } //if we aren't already complete, go ahead and timeout await stateMatrix.RunForStatusAsync(timerId, StateStatus.Running, async() => { await adapter.ContinueConversationAsync( msAppId, conversationReference, BotWithLookup.OnTurn, //Leverage dirty hack to achieve Bot lookup from component cancellationToken).ConfigureAwait(false); }).ConfigureAwait(false); }); }
// Sends a proactive message to the user. private async Task CompleteJobAsync( BotAdapter adapter, string botId, JobLog.JobData jobInfo, CancellationToken cancellationToken = default(CancellationToken)) { await adapter.ContinueConversationAsync(botId, jobInfo.Conversation, CreateCallback(jobInfo), cancellationToken); }
private async Task CompleteNotificationAsync( BotAdapter adapter, string botId, ChannelLog.ChannelData channelInfo, string message, CancellationToken cancellationToken = default(CancellationToken)) { await adapter.ContinueConversationAsync(botId, channelInfo.Conversation, CreateCallback(channelInfo, message), cancellationToken); }
private async Task SendNotificationsAsync( BotAdapter adapter, string botId, PasswordNotfications.NotificationData notification, PasswordEventNotification passwordEventNotification, CancellationToken cancellationToken = default(CancellationToken) ) { await adapter.ContinueConversationAsync(botId, notification.Conversation, CreateCallback(notification, passwordEventNotification), cancellationToken); }
private async Task ProactiveMessageCallbackAsync(BotAdapter adapter, ConversationReference conversationReference, string message, int seconds, CancellationToken cancellationToken) { // Pause on the background thread for the number of seconds specified, then load the conversationi and message the user. // This simulates a long running process. Thread.Sleep(TimeSpan.FromSeconds(seconds)); await adapter.ContinueConversationAsync(_botId, conversationReference, async (innerContext, innerCancellationToken) => { await innerContext.SendActivityAsync(string.IsNullOrWhiteSpace(message) ? $"background notice after {seconds} seconds" : $"background msg {seconds} {message}"); // Could load a dialog stack here, and resume }, cancellationToken); }
private async Task CompleteJobAsync(BotAdapter adapter, string botId, JobStorage jobStorage, UiPathJobResponse uiPathJobResponse, CancellationToken cancellationToken) { jobStorage.TryGetValue(uiPathJobResponse.JobId, out var jobInfo); if (jobInfo != null) { await adapter.ContinueConversationAsync(botId, jobInfo.ConversationReference, CompleteJobHandler(uiPathJobResponse), cancellationToken); } }
/// <summary> /// Send a card to a user in direct conversation /// </summary> /// <param name="botFrameworkAdapter">Bot adapter</param> /// <param name="serviceUrl">Service url</param> /// <param name="teamsChannelId">Team channel id where the bot is installed</param> /// <param name="cardToSend">The actual welcome card (for the team)</param> /// <param name="user">User channel account</param> /// <param name="tenantId">Tenant id</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>True/False operation status</returns> public async Task <bool> NotifyUserAsync(BotAdapter botFrameworkAdapter, string serviceUrl, string teamsChannelId, IMessageActivity cardToSend, ChannelAccount user, string tenantId, CancellationToken cancellationToken) { this.telemetryClient.TrackTrace($"Sending notification to user {user.Id}"); try { // conversation parameters var conversationParameters = new ConversationParameters { Bot = new ChannelAccount { Id = this.botId }, Members = new[] { user }, ChannelData = new TeamsChannelData { Tenant = new TenantInfo(tenantId), }, }; if (!this.isTesting) { // shoot the activity over await((BotFrameworkAdapter)botFrameworkAdapter).CreateConversationAsync( teamsChannelId, serviceUrl, this.appCredentials, conversationParameters, async(newTurnContext, newCancellationToken) => { // Get the conversationReference var conversationReference = newTurnContext.Activity.GetConversationReference(); await botFrameworkAdapter.ContinueConversationAsync( this.appCredentials.MicrosoftAppId, conversationReference, async(conversationTurnContext, conversationCancellationToken) => { await conversationTurnContext.SendActivityAsync(cardToSend, conversationCancellationToken); }, cancellationToken); }, cancellationToken).ConfigureAwait(false); } return(true); } catch (Exception ex) { this.telemetryClient.TrackTrace($"Error sending notification to user: {ex.Message}", SeverityLevel.Warning); this.telemetryClient.TrackException(ex); return(false); } }
private Action <ServiceMessageProcessingEvent> CreateCallback(BotAdapter adapter, ConversationReference conversationReference, string agentId, string connectionId) { return(async message => { var agentContext = await _agentContextProvider.GetContextAsync(agentId); var connection = await _connectionService.GetAsync(agentContext, connectionId); await adapter.ContinueConversationAsync(AppId, conversationReference, async (turnContext, cancellationToken) => { await turnContext.SendActivityAsync($"You are now connected to {connection.Alias?.Name ?? "[unspecified]"}"); }, CancellationToken.None); }); }
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default) { if (turnContext.Activity.Type == ActivityTypes.Message) { await ResendUserMessage(turnContext, cancellationToken); } if (turnContext.Activity.Type == ActivityTypes.Event) { if (turnContext.Activity.Name == "webchat/join") { var reference = turnContext.Activity.GetConversationReference(); _ucs.AddConvIdReference(turnContext.Activity.From.Name, turnContext.Activity.Conversation.Id, reference); } } if (turnContext.Activity.Type != ActivityTypes.Event) { turnContext.OnSendActivities(async(ctx, activities, nextSend) => { // run full pipeline var responses = await nextSend().ConfigureAwait(false); foreach (var activity in activities) { foreach (var cr in _ucs.GetOtherUserConversations(activity.Conversation.Id)) { if (ctx.Activity.Conversation.Id != cr.Key) { await _adapter.ContinueConversationAsync(_configuration["MicrosoftAppId"], cr.Value, CreateCallback(activity), CancellationToken.None); } } } return(responses); }); } await next(cancellationToken).ConfigureAwait(false); //turnContext.OnUpdateActivity(async (ctx, activities, nextUpdate) => //{ // //Save Conversation Reference // var reference = ctx.Activity.GetConversationReference(); // _ucs.AddConvIdReference(ctx.Activity.From.Name, ctx.Activity.Conversation.Id, reference); // var responses = await nextUpdate().ConfigureAwait(false); // return responses; //}); }
/// <summary> /// Create a new turn context and execute callback parameter to do desired function /// </summary> /// <param name="botAdapter">Bot adapter.</param> /// <param name="teamInfo">The team that the bot has been installed to</param> /// <param name="callback">The method to call for the resulting bot turn.</param> /// <returns>A task that represents the work queued to execute.</returns> private async Task ExecuteInNewTurnContext(BotAdapter botAdapter, TeamInstallInfo teamInfo, BotCallbackHandler callback) { var conversationReference = new ConversationReference { ServiceUrl = teamInfo.ServiceUrl, Conversation = new ConversationAccount { Id = teamInfo.TeamId, }, }; await botAdapter.ContinueConversationAsync( this.botId, conversationReference, callback, default(CancellationToken)).ConfigureAwait(false); }
private async Task <ResourceResponse> ProcessActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string replyToActivityId, Activity activity, CancellationToken cancellationToken) { var conversationReference = await _conversationIdIdFactory.GetConversationReferenceAsync(conversationId, CancellationToken.None).ConfigureAwait(false); if (conversationReference == null) { throw new KeyNotFoundException(); } var skillConversationReference = activity.GetConversationReference(); var callback = new BotCallbackHandler(async(turnContext, ct) => { turnContext.TurnState.Add(SkillConversationReferenceKey, skillConversationReference); activity.ApplyConversationReference(conversationReference); turnContext.Activity.Id = replyToActivityId; switch (activity.Type) { case ActivityTypes.EndOfConversation: await _conversationIdIdFactory.DeleteConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false); ApplyEoCToTurnContextActivity(turnContext, activity); await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false); break; case ActivityTypes.Event: ApplyEventToTurnContextActivity(turnContext, activity); await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false); break; default: await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false); break; } }); await _adapter.ContinueConversationAsync(claimsIdentity, conversationReference, callback, cancellationToken).ConfigureAwait(false); return(new ResourceResponse(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture))); }
private async Task HandleChatStateEvent(string body) { var webhookData = JsonConvert.DeserializeObject <Models.ChatStateEvent.WebhookData>(body); foreach (var change in webhookData.body.changes) { if (change?.@event?.chatState == "COMPOSING") { if (await ConversationHandoffRecordMap.GetByRemoteConversationId(change.conversationId) is LivePersonHandoffRecord handoffRecord) { var typingActivity = new Activity { Type = ActivityTypes.Typing }; await _adapter.ContinueConversationAsync( _credentials.MsAppId, handoffRecord.ConversationReference, (turnContext, cancellationToken) => turnContext.SendActivityAsync(typingActivity, cancellationToken), default); } } } }
public async Task SendReminderChat(IBotFrameworkHttpAdapter adapter) { try { TelemetryClient.TrackTrace("Sending reminder from Bot", Severity.Information, null); var team = await this.tableService.getDailyChallengeTeamInfo(); var dailyChallenge = await tableService.GetDailyChallenge(); // If no photo selected, send update if (dailyChallenge.winnerName == null) { MicrosoftAppCredentials.TrustServiceUrl(team.ServiceUrl); TelemetryClient.TrackTrace("Sending MicrosoftAppId: " + Configuration["MicrosoftAppId"], Severity.Information, null); ConnectorClient connectorClient = new ConnectorClient(new Uri(team.ServiceUrl), Configuration["MicrosoftAppId"], Configuration["MicrosoftAppPassword"]); var teamName = await this.GetTeamNameAsync(connectorClient, team.TeamId); var bot = new ChannelAccount(team.BotId); string replyText = $"<at>@{teamName}</at> "; var activity = MessageFactory.Text(replyText); var mentioned = JObject.FromObject(new { id = team.TeamId, name = teamName }); var mentionedEntity = new Entity("mention") { Properties = JObject.FromObject(new { mentioned = mentioned, text = replyText }), }; activity.Entities = new[] { mentionedEntity }; activity.Text = "It's reminder time, " + replyText; var convParams = new ConversationParameters() { TenantId = team.TenantId, Bot = bot, IsGroup = true, ChannelData = team.ChannelData, Activity = (Activity)activity }; TelemetryClient.TrackTrace("ConvParams: " + JsonConvert.SerializeObject(convParams), Severity.Information, null); var conversation = await connectorClient.Conversations.CreateConversationAsync(convParams); BotAdapter ba = (BotAdapter)adapter; var conversationReference = new ConversationReference(conversation.ActivityId); conversationReference.Bot = bot; conversationReference.ChannelId = team.ChannelId; conversationReference.Conversation = new ConversationAccount(); var convAccount = new ConversationAccount(true, null, conversation.Id); convAccount.TenantId = team.TenantId; conversationReference.Conversation = convAccount; conversationReference.ServiceUrl = team.ServiceUrl; TelemetryClient.TrackTrace("Sending to Conversation", Severity.Information, null); await ba.ContinueConversationAsync(Configuration["MicrosoftAppId"], conversationReference, ReminderBotCallback, default(CancellationToken)); } } catch (Exception ex) { TelemetryClient.TrackTrace("Error sending reminder: " + ex.Message + ex.StackTrace, Severity.Error, null); Logger.LogError(ex, $"Error making pairups: {ex.Message}"); } }