/// <summary> /// Every conversation turn will call this method. The method either echoes the message activity or uploads the history to the channel. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } var activity = turnContext.Activity; if (activity.Type == ActivityTypes.Message) { if (activity.Text == "!history") { // Download the activities from the Transcript (blob store) and send them over to the channel when a request to upload history arrives. // This could be an event or a special message acctivity as above. var connectorClient = turnContext.TurnState.Get <ConnectorClient>(typeof(IConnectorClient).FullName); // Get all the message type activities from the Transcript. string continuationToken = null; var count = 0; do { var pagedTranscript = await _transcriptStore.GetTranscriptActivitiesAsync(activity.ChannelId, activity.Conversation.Id, continuationToken); var activities = pagedTranscript.Items .Where(a => a.Type == ActivityTypes.Message) .Select(ia => (Activity)ia) .ToList(); // DirectLine only allows the upload of at most 500 activities at a time. The limit of 1500 below is // arbitrary and up to the Bot author to decide. count += activities.Count(); if (activities.Count() > 500 || count > 1500) { throw new InvalidOperationException("Attempt to upload too many activities"); } var transcript = new Transcript(activities); await connectorClient.Conversations.SendConversationHistoryAsync(activity.Conversation.Id, transcript, cancellationToken : cancellationToken); continuationToken = pagedTranscript.ContinuationToken; }while (continuationToken != null); await turnContext.SendActivityAsync("Transcript sent", cancellationToken : cancellationToken); } else { // Echo back to the user whatever they typed. await turnContext.SendActivityAsync($"You sent '{activity.Text}'\n", cancellationToken : cancellationToken); } } else if (activity.Type == ActivityTypes.ConversationUpdate) { if (activity.MembersAdded != null) { await SendWelcomeMessageAsync(turnContext, cancellationToken); } } }
static async Task Main(string[] args) { if (args.Length < 3) { Console.WriteLine("getBlobTranscripts container channel conversationId"); Console.WriteLine(); Console.WriteLine("set TRANSCRIPT_CONNECTIONSTRING to blob storage connection string"); return; } var container = args[0]; var channelId = args[1]; var conversationId = args[2]; var connectionString = Environment.GetEnvironmentVariable("TRANSCRIPT_CONNECTIONSTRING"); var transcriptStore = new AzureBlobTranscriptStore(connectionString, container); string continuationToken = null; Console.WriteLine("["); do { var result = await transcriptStore.GetTranscriptActivitiesAsync(channelId, conversationId, continuationToken); foreach (var item in result.Items) { Console.WriteLine(JsonConvert.SerializeObject(item, Formatting.Indented)); } continuationToken = result.ContinuationToken; } while (continuationToken != null); Console.WriteLine("]"); }
public async Task ActivityEmptyTest() { foreach (var convoId in ConversationSpecialIds) { var activities = await _transcriptStore.GetTranscriptActivitiesAsync(ChannelId, convoId); Assert.AreEqual(activities.Items.Length, 0); } }
public async Task NullBlobTest() { AzureBlobTranscriptStore store = null; await Assert.ThrowsExceptionAsync <NullReferenceException>(async() => await store.LogActivityAsync(CreateActivity(0, 0, ConversationIds))); await Assert.ThrowsExceptionAsync <NullReferenceException>(async() => await store.GetTranscriptActivitiesAsync(ChannelId, ConversationIds[0])); }
public async Task NullBlobTest() { if (StorageEmulatorHelper.CheckEmulator()) { ContainerInit(); AzureBlobTranscriptStore store = null; await Assert.ThrowsExceptionAsync <NullReferenceException>(async() => await store.LogActivityAsync(CreateActivity(0, 0, ConversationIds))); await Assert.ThrowsExceptionAsync <NullReferenceException>(async() => await store.GetTranscriptActivitiesAsync(ChannelId, ConversationIds[0])); } }
/// <summary> /// Every conversation turn will call this method. The method either echoes the message activity or uploads the history to the channel. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } var activity = turnContext.Activity; if (activity.Type == ActivityTypes.Message) { if (activity.Text == "!history") { // Download the activities from the Transcript (blob store) and send them over to the channel when a request to upload history arrives. // This could be an event or a special message acctivity as above. var connectorClient = turnContext.TurnState.Get<ConnectorClient>(typeof(IConnectorClient).FullName); // Get all the message type activities from the Transcript. string continuationToken = null; var count = 0; do { <<<<<<< HEAD var pagedTranscript = await _transcriptStore.GetTranscriptActivitiesAsync(activity.ChannelId, activity.Conversation.Id);
/// <summary> /// Every conversation turn will call this method. The method either echoes the message activity or uploads the history to the channel. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } var activity = turnContext.Activity; if (activity.Type == ActivityTypes.Message) { if (activity.Text == "!history") { // Download the activities from the Transcript (blob store) and send them over to the channel when a request to upload history arrives. // This could be an event or a special message acctivity as above. var connectorClient = turnContext.TurnState.Get <ConnectorClient>(typeof(IConnectorClient).FullName); // Get all the message type activities from the Transcript. string continuationToken = null; var count = 0; // WebChat and Emulator require modifying the activity.Id to display the same activity again within the same chat window bool updateActivities = new[] { Channels.Webchat, Channels.Emulator, Channels.Directline, }.Contains(activity.ChannelId); var incrementId = 0; if (updateActivities && activity.Id.Contains("|")) { int.TryParse(activity.Id.Split('|')[1], out incrementId); } do { var pagedTranscript = await _transcriptStore.GetTranscriptActivitiesAsync(activity.ChannelId, activity.Conversation.Id, continuationToken); var activities = pagedTranscript.Items .Where(a => a.Type == ActivityTypes.Message) .Select(ia => (Activity)ia) .ToList(); if (updateActivities) { foreach (var a in activities) { incrementId++; a.Id = string.Concat(activity.Conversation.Id, "|", incrementId.ToString().PadLeft(7, '0')); a.Timestamp = DateTimeOffset.UtcNow; a.ChannelData = string.Empty; // WebChat uses ChannelData for id comparisons, so we clear it here } } // DirectLine only allows the upload of at most 500 activities at a time. The limit of 1500 below is // arbitrary and up to the Bot author to decide. count += activities.Count(); if (activities.Count() > 500 || count > 1500) { throw new InvalidOperationException("Attempt to upload too many activities"); } var transcript = new Transcript(activities); await connectorClient.Conversations.SendConversationHistoryAsync(activity.Conversation.Id, transcript, cancellationToken : cancellationToken); continuationToken = pagedTranscript.ContinuationToken; }while (continuationToken != null); await turnContext.SendActivityAsync("Transcript sent", cancellationToken : cancellationToken); } else { // Echo back to the user whatever they typed. await turnContext.SendActivityAsync($"You sent '{activity.Text}'\n", cancellationToken : cancellationToken); } } else if (activity.Type == ActivityTypes.ConversationUpdate) { if (activity.MembersAdded != null) { await SendWelcomeMessageAsync(turnContext, cancellationToken); } } }
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { // Handle Message activity type, which is the main activity type for shown within a conversational interface // Message activities may contain text, speech, interactive cards, and binary or unknown attachments. // see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types if (turnContext.Activity.Type == ActivityTypes.Message) { await _myStorage.ReadAsync(new string[] { " " }); Console.WriteLine("Do i send request?"); // IT WORKS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //var testDic = new Dictionary<string, object>(); //testDic.Add("test", "19"); //_myStorage.WriteAsync(testDic); var activity = turnContext.Activity; // Get the conversation state from the turn context. var oldState = await _accessors.CounterState.GetAsync(turnContext, () => new CounterState()); // Bump the turn count for this conversation. var newState = new CounterState { TurnCount = oldState.TurnCount + 1 }; // Set the property using the accessor. await _accessors.CounterState.SetAsync(turnContext, newState); // Save the new turn count into the conversation state. await _accessors.ConversationState.SaveChangesAsync(turnContext); if (State.UserPromptedForName) { string[] words = turnContext.Activity.Text.Split(" "); string name = words[words.Length - 1]; State.User.name = name; State.UserPromptedForName = false; State.UserReadyToSave = true; } if (State.UserPromptedForEmail) { if (activity.Text.Contains("@")) { string[] words = activity.Text.Split(" "); foreach (string word in words) { if (word.Contains("@")) { userEmail = word; State.GotEmail = true; break; } } } State.UserPromptedForEmail = false; } if (activity.Text == "!history") { // Download the activities from the Transcript (blob store) when a request to upload history arrives. var connectorClient = turnContext.TurnState.Get <ConnectorClient>(typeof(IConnectorClient).FullName); // Get all the message type activities from the Transcript. string continuationToken = null; var count = 0; do { var pagedTranscript = await _transcriptStore.GetTranscriptActivitiesAsync(activity.ChannelId, activity.Conversation.Id); var activities = pagedTranscript.Items .Where(a => a.Type == ActivityTypes.Message) .Select(ia => (Activity)ia) .ToList(); var transcript = new Transcript(activities); await connectorClient.Conversations.SendConversationHistoryAsync(activity.Conversation.Id, transcript, cancellationToken : cancellationToken); continuationToken = pagedTranscript.ContinuationToken; }while (continuationToken != null); List <string> storedTranscripts = new List <string>(); PagedResult <TranscriptInfo> pagedResult = null; var pageSize = 0; do { pagedResult = await _transcriptStore.ListTranscriptsAsync("emulator", pagedResult?.ContinuationToken); // transcript item contains ChannelId, Created, Id. // save the converasationIds (Id) found by "ListTranscriptsAsync" to a local list. foreach (var item in pagedResult.Items) { // Make sure we store an unescaped conversationId string. var strConversationId = item.Id; storedTranscripts.Add(Uri.UnescapeDataString(strConversationId)); } } while (pagedResult.ContinuationToken != null); var numTranscripts = storedTranscripts.Count(); for (int i = 0; i < numTranscripts; i++) { PagedResult <IActivity> pagedActivities = null; do { string thisConversationId = storedTranscripts[i]; // Find all inputs in the last 24 hours. DateTime yesterday = DateTime.Now.AddDays(-1); // Retrieve iActivities for this transcript. var story = ""; pagedActivities = await _transcriptStore.GetTranscriptActivitiesAsync("emulator", thisConversationId, pagedActivities?.ContinuationToken, yesterday); foreach (var item in pagedActivities.Items) { // View as message and find value for key "text" : var thisMessage = item.AsMessageActivity(); var userInput = thisMessage.Text; story += userInput; } await turnContext.SendActivityAsync(story); } while (pagedActivities.ContinuationToken != null); for (int j = 0; j < numTranscripts; j++) { // Remove all stored transcripts except the last one found. if (i > 0) { string thisConversationId = storedTranscripts[i]; await turnContext.SendActivityAsync(storedTranscripts[i]); await _transcriptStore.DeleteTranscriptAsync("emulator", thisConversationId); } } } // Save new list to your Storage. // Echo back to the user whatever they typed. } else { var responseMessage = ""; if (State.User == null || !State.Registered) { if (!State.GotEmail) { responseMessage = "Hello!\nI'd like to know who you are. Could you give me your e-mail address, please?"; await turnContext.SendActivityAsync($"{responseMessage}"); State.UserPromptedForEmail = true; } else { string[] usersBlobNames = { " ", "/" }; var users = new List <UserData>(); var usersFromDb = await _myStorage.ReadAsync(usersBlobNames).ConfigureAwait(true); //var usersFromDb2 = new Dictionary<string, object>(); foreach (object u in usersFromDb) { UserData dbUser = (UserData)u; users.Add(dbUser); if (dbUser.emailnormalized == userEmail.ToUpper()) { State.User = dbUser; State.Registered = true; } } if (State.User == null && !State.UserPromptedForName) { State.User = new UserData(userEmail); responseMessage = "Great!, What's your name?"; State.UserPromptedForName = true; await turnContext.SendActivityAsync(responseMessage); } if (State.UserReadyToSave) { users.Add(State.User); State.UserReadyToSave = false; // Update Users in DB await _myStorage.DeleteAsync(usersBlobNames); var usersDic = new Dictionary <string, object>(); foreach (UserData u in users) { usersDic.Add(u.emailnormalized, u); } await _myStorage.WriteAsync(usersDic); State.Registered = true; responseMessage = $"Hello, {State.User.name}!"; await turnContext.SendActivityAsync($"{responseMessage}"); } } } else { responseMessage = $"Hello, {State.User.name}!"; await turnContext.SendActivityAsync($"{responseMessage}"); } responseMessage = $"Turn {newState.TurnCount}: You sent '{turnContext.Activity.Text}'\n"; await turnContext.SendActivityAsync($"{responseMessage}"); } } }