public async Task TranscriptsEmptyTest()
        {
            var unusedChannelId = Guid.NewGuid().ToString();
            var transcripts     = await _transcriptStore.ListTranscriptsAsync(unusedChannelId);

            Assert.AreEqual(transcripts.Items.Length, 0);
        }
Ejemplo n.º 2
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            await _myTranscripts.LogActivityAsync(turnContext.Activity);

            List <string> storedTranscripts = new List <string>();
            PagedResult <Microsoft.Bot.Builder.TranscriptInfo> pagedResult = null;
            var pageSize = 0;

            do
            {
                pagedResult = await _myTranscripts.ListTranscriptsAsync("emulator", pagedResult?.ContinuationToken);

                pageSize = pagedResult.Items.Count();

                // transcript item contains ChannelId, Created, Id.
                // save the channelIds found by "ListTranscriptsAsync" to a local list.
                foreach (var item in pagedResult.Items)
                {
                    storedTranscripts.Add(item.Id);
                }
            } while (pagedResult.ContinuationToken != null);

            var httpClient = _httpClientFactory.CreateClient();

            var qnaMaker = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                EndpointKey     = _configuration["QnAEndpointKey"],
                Host            = _configuration["QnAEndpointHostName"]
            },
                                        null,
                                        httpClient);

            _logger.LogInformation("Calling QnA Maker");

            var options = new QnAMakerOptions {
                Top = 1
            };

            // The actual call to the QnA Maker service.
            var response = await qnaMaker.GetAnswersAsync(turnContext, options);

            if (response != null && response.Length > 0)
            {
                await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("I'll just pass your information to a human and we'll get look into your query. Please wait..."), cancellationToken);
            }
        }
Ejemplo n.º 3
0
        public async Task TranscriptsEmptyTest()
        {
            var transcripts = await _transcriptStore.ListTranscriptsAsync(ChannelId);

            Assert.AreEqual(transcripts.Items.Length, 0);
        }
        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}");
                }
            }
        }
Ejemplo n.º 5
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (ConversationData.PromptedUserForName)
            {
                ConversationData.PromptedUserForName = false;
                await turnContext.SendActivityAsync($"Bye");
            }
            else
            {
                // preserve user input.
                var utterance = turnContext.Activity.Text;
                // make empty local logitems list.
                UtteranceLog logItems = null;

                // see if there are previous messages saved in storage.
                try
                {
                    string[] utteranceList = { "UtteranceLog" };
                    logItems = _myStorage.ReadAsync <UtteranceLog>(utteranceList).Result?.FirstOrDefault().Value;
                }
                catch
                {
                    // Inform the user an error occured.
                    await turnContext.SendActivityAsync("Sorry, something went wrong reading your stored messages!");
                }
                // If no stored messages were found, create and store a new entry.
                if (logItems is null)
                {
                    // add the current utterance to a new object.
                    logItems = new UtteranceLog();
                    logItems.UtteranceList.Add(utterance);
                    // set initial turn counter to 1.
                    logItems.TurnNumber++;

                    // Show user new user message.
                    //  await turnContext.SendActivityAsync($"{logItems.TurnNumber}: The list is now: {string.Join(", ", logItems.UtteranceList)}");

                    // Create Dictionary object to hold received user messages.
                    var changes = new Dictionary <string, object>();
                    {
                        changes.Add("UtteranceLog", logItems);
                    }
                    try
                    {
                        // Save the user message to your Storage.
                        await _myStorage.WriteAsync(changes, cancellationToken);
                    }
                    catch
                    {
                        // Inform the user an error occured.
                        await turnContext.SendActivityAsync("Sorry, something went wrong storing your message!");
                    }
                }
                // Else, our Storage already contained saved user messages, add new one to the list.
                else
                {
                    // add new message to list of messages to display.
                    logItems.UtteranceList.Add(utterance);
                    // increment turn counter.
                    logItems.TurnNumber++;

                    // show user new list of saved messages.
                    //  await turnContext.SendActivityAsync($"{logItems.TurnNumber}: The list is now: {string.Join(", ", logItems.UtteranceList)}");

                    // Create Dictionary object to hold new list of messages.
                    var changes = new Dictionary <string, object>();
                    {
                        changes.Add("UtteranceLog", logItems);
                    };

                    try
                    {
                        // Save new list to your Storage.
                        await _myStorage.WriteAsync(changes, cancellationToken);
                    }
                    catch
                    {
                        // Inform the user an error occured.
                        await turnContext.SendActivityAsync("Sorry, something went wrong storing your message!");
                    }
                }
                await _myTranscripts.LogActivityAsync(turnContext.Activity);

                List <string> storedTranscripts = new List <string>();
                PagedResult <Microsoft.Bot.Builder.TranscriptInfo> pagedResult = null;
                var pageSize = 0;
                do
                {
                    pagedResult = await _myTranscripts.ListTranscriptsAsync("emulator", pagedResult?.ContinuationToken);

                    pageSize = pagedResult.Items.Count();

                    // transcript item contains ChannelId, Created, Id.
                    // save the channelIds found by "ListTranscriptsAsync" to a local list.
                    foreach (var item in pagedResult.Items)
                    {
                        storedTranscripts.Add(item.Id);
                    }
                } while (pagedResult.ContinuationToken != null);


                Logger.LogInformation("Running dialog with Message Activity.");

                // Run the Dialog with the new message Activity.
                await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);
            }
        }