/// <summary>
        /// Every conversation turn for our Echo Bot will call this method.
        /// There are no dialogs used, since it's "single turn" processing, meaning a single
        /// request and response.
        /// </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))
        {
            // 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)
            {
                // 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);

                // Echo back to the user whatever they typed.
                var responseMessage = $"Turn {newState.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
                await turnContext.SendActivityAsync(responseMessage);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
            }
        }
        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}");
                }
            }
        }
Beispiel #3
0
        public HeroCard ScatterResponseGenerator(ToneAnalysis postReponse, CounterState state, User currentUser)
        {
            double joy     = 0;
            double anger   = 0;
            double sadness = 0;
            double fear    = 0;
            int    x       = 0;
            int    y       = 0;

            string[] userNames = { "-", "-", "-" };

            foreach (ToneScore tone in postReponse.DocumentTone.Tones)
            {
                if (tone.ToneId == "joy")
                {
                    joy = (double)tone.Score;
                }
                else if (tone.ToneId == "anger")
                {
                    anger = (double)tone.Score;
                }
                else if (tone.ToneId == "sadness")
                {
                    sadness = (double)tone.Score;
                }
                else if (tone.ToneId == "fear")
                {
                    fear = (double)tone.Score;
                }
            }

            int numberOfTones = (int)(Math.Ceiling(joy) + Math.Ceiling(anger) + Math.Ceiling(fear) + Math.Ceiling(sadness));

            if ((Math.Ceiling(joy) + Math.Ceiling(anger) + Math.Ceiling(fear) + Math.Ceiling(sadness)) != 0)
            {
                x = 50 + (int)Math.Ceiling(49 * ((0.5 * joy) + (0.5 * anger) + (0.8 * fear) - (0.6 * sadness)) / numberOfTones);
                y = 50 + (int)Math.Ceiling(49 * ((0.9 * joy) - (0.5 * anger) - (0.6 * fear) - (0.8 * sadness)) / numberOfTones);
            }

            if (currentUser.X == 0)
            {
                currentUser.X += x;
            }
            else
            {
                currentUser.X = (int)((0.4 * x) + (0.6 * currentUser.X));
            }

            if (currentUser.Y == 0)
            {
                currentUser.Y += y;
            }
            else
            {
                currentUser.Y = (int)((0.4 * y) + (0.6 * currentUser.Y));
            }

            List <User> updatedUsers = new List <User>();
            string      finalX       = string.Empty;
            string      finalY       = string.Empty;

            foreach (User user in state.Users)
            {
                if (user.UserId == currentUser.UserId)
                {
                    updatedUsers.Add(currentUser);
                    finalX += currentUser.X + ",";
                    finalY += currentUser.Y + ",";
                }
                else
                {
                    updatedUsers.Add(user);
                    finalX += user.X + ",";
                    finalY += user.Y + ",";
                }

                userNames[state.Users.IndexOf(user)] = user.UserName;
            }

            state.Users = updatedUsers;

            /**
             * List<int> updatedRadius = new List<int>();
             * state.Radius.ForEach(radius => updatedRadius.Add(radius - 10));
             * updatedRadius.Add(100);
             * state.Radius = updatedRadius;
             *
             * string radiusString = string.Empty;
             * state.Radius.ForEach(radius => radiusString += radius + ",");
             *
             * radiusString = radiusString.Remove(radiusString.Length - 1);
             */
            finalX = finalX.Remove(finalX.Length - 1);
            finalY = finalY.Remove(finalY.Length - 1);

            state.ScatterURL = "https://chart.googleapis.com/chart?cht=s&chs=470x400&chm=R,d10300,0,0.5,1|R,ffd800,0,0,0.5|r,008000,0,1,0.5&chco=000000|0c00fc|5700a3,ffffff&chxt=x,x,y,y&chdl=" + userNames[0] + "|" + userNames[1] + "|" + userNames[2] + "&chxr=0,-1,1|1,-1,1|2,-1,1|3,-1,1&chxl=1:|low%20arousal|high%20arousal|3:|displeasure|pleasure&chxs=0,ff0000|1,ff0000|2,0000ff|3,0000ff&chd=t:" + finalX + "|" + finalY;

            HeroCard heroCard = new HeroCard
            {
                Text   = "Your current State: ",
                Images = new List <CardImage> {
                    new CardImage(state.ScatterURL)
                },
            };

            return(heroCard);
        }
Beispiel #4
0
        public HeroCard GraphResponseGenerator(ToneAnalysis postReponse, CounterState state)
        {
            state.TurnCount += 1;
            string graphURL = "https://chart.googleapis.com/chart?cht=lc&chco=FF0000,000000,00FF00,0000FF&chdl=Anger|Fear|Joy|Sadness&chxr=0,0," + state.TurnCount + "|1,0.5,1&chs=250x150&chxt=x,y&chd=t4:";

            int joy     = 0;
            int anger   = 0;
            int sadness = 0;
            int fear    = 0;

            foreach (ToneScore tone in postReponse.DocumentTone.Tones)
            {
                int score = (int)(100 * (tone.Score - 0.5) * 2);

                if (tone.ToneId == "joy")
                {
                    joy = score;
                }
                else if (tone.ToneId == "anger")
                {
                    anger = score;
                }
                else if (tone.ToneId == "sadness")
                {
                    sadness = score;
                }
                else if (tone.ToneId == "fear")
                {
                    fear = score;
                }
            }

            if (state.Joy == string.Empty)
            {
                state.Joy += joy;
            }
            else
            {
                state.Joy += "," + joy;
            }

            if (state.Anger == string.Empty)
            {
                state.Anger += anger;
            }
            else
            {
                state.Anger += "," + anger;
            }

            if (state.Sadness == string.Empty)
            {
                state.Sadness += sadness;
            }
            else
            {
                state.Sadness += "," + sadness;
            }

            if (state.Fear == string.Empty)
            {
                state.Fear += fear;
            }
            else
            {
                state.Fear += "," + fear;
            }

            graphURL = graphURL + state.Anger + '|' + state.Fear + '|' + state.Joy + '|' + state.Sadness;

            HeroCard heroCard = new HeroCard
            {
                Text   = "Your current State: ",
                Images = new List <CardImage> {
                    new CardImage(graphURL)
                },
            };

            return(heroCard);
        }