Ejemplo n.º 1
0
 public RootTopic(IBotContext context) : base(context)
 {
     // User state initialization should be done once in the welcome
     //  new user feature. Placing it here until that feature is added.
     if (context.GetUserState <BotUserState>().Alarms == null)
     {
         context.GetUserState <BotUserState>().Alarms = new List <Alarm>();
     }
 }
Ejemplo n.º 2
0
        public override Task OnReceiveActivity(IBotContext context)
        {
            if ((context.Request.Type == ActivityTypes.Message) && (context.Request.AsMessageActivity().Text.Length > 0))
            {
                var message = context.Request.AsMessageActivity();

                // If the user wants to change the topic of conversation...
                if (message.Text.ToLowerInvariant() == "add alarm")
                {
                    // Set the active topic and let the active topic handle this turn.
                    this.SetActiveTopic(ADD_ALARM_TOPIC)
                    .OnReceiveActivity(context);
                    return(Task.CompletedTask);
                }

                if (message.Text.ToLowerInvariant() == "delete alarm")
                {
                    this.SetActiveTopic(DELETE_ALARM_TOPIC, context.GetUserState <BotUserState>().Alarms)
                    .OnReceiveActivity(context);
                    return(Task.CompletedTask);
                }

                if (message.Text.ToLowerInvariant() == "show alarms")
                {
                    this.ClearActiveTopic();

                    AlarmsView.ShowAlarms(context, context.GetUserState <BotUserState>().Alarms);
                    return(Task.CompletedTask);
                }

                if (message.Text.ToLowerInvariant() == "help")
                {
                    this.ClearActiveTopic();

                    this.ShowHelp(context);
                    return(Task.CompletedTask);
                }

                // If there is an active topic, let it handle this turn until it completes.
                if (HasActiveTopic)
                {
                    ActiveTopic.OnReceiveActivity(context);
                    return(Task.CompletedTask);
                }

                ShowDefaultMessage(context);
            }

            return(Task.CompletedTask);
        }
        public async Task <bool> FindAlarm(IBotContext context)
        {
            var userState = context.GetUserState <UserData>();

            // var userState = UserState<UserAlarms>.Get(context);
            if (userState.Alarms == null)
            {
                userState.Alarms = new List <Alarm>();
            }

            // Ensure there are alarms to delete
            if (userState.Alarms.Count == 0)
            {
                DeleteAlarmTopicResponses.ReplyWithNoAlarms(context);
                return(false);
            }

            // Validate title
            if (!String.IsNullOrWhiteSpace(this.AlarmTitle))
            {
                if (int.TryParse(this.AlarmTitle.Split(' ').FirstOrDefault(), out int index))
                {
                    if (index > 0 && index <= userState.Alarms.Count)
                    {
                        index--;
                        // Delete selected alarm and end topic
                        var alarm = userState.Alarms.Skip(index).First();
                        userState.Alarms.Remove(alarm);
                        DeleteAlarmTopicResponses.ReplyWithDeletedAlarm(context, alarm);
                        return(false); // cancel topic
                    }
                }
                else
                {
                    var parts   = this.AlarmTitle.Split(' ');
                    var choices = userState.Alarms.Where(alarm => parts.Any(part => alarm.Title.Contains(part))).ToList();

                    if (choices.Count == 0)
                    {
                        DeleteAlarmTopicResponses.ReplyWithNoAlarmsFound(context, this.AlarmTitle);
                        return(false);
                    }
                    else if (choices.Count == 1)
                    {
                        // Delete selected alarm and end topic
                        var alarm = choices.First();
                        userState.Alarms.Remove(alarm);
                        DeleteAlarmTopicResponses.ReplyWithDeletedAlarm(context, alarm);
                        return(false); // cancel topic
                    }
                }
            }

            // Prompt for title
            DeleteAlarmTopicResponses.ReplyWithTitlePrompt(context, userState.Alarms);
            return(true);
        }
        public static Task ShowAlarms(IBotContext context)
        {
            var userState = context.GetUserState <UserData>();

            // var userState = UserState<UserAlarms>.Get(context);

            if (userState.Alarms == null)
            {
                userState.Alarms = new List <Alarm>();
            }

            ShowAlarmsTopicResponses.ReplyWithShowAlarms(context, userState.Alarms);
            return(Task.CompletedTask);
        }
Ejemplo n.º 5
0
        public RootTopic(IBotContext context) : base(context)
        {
            // User state initialization should be done once in the welcome
            //  new user feature. Placing it here until that feature is added.
            if (context.GetUserState <BotUserState>().Alarms == null)
            {
                context.GetUserState <BotUserState>().Alarms = new List <Alarm>();
            }

            this.SubTopics.Add(ADD_ALARM_TOPIC, (object[] args) =>
            {
                var addAlarmTopic = new AddAlarmTopic();

                addAlarmTopic.Set
                .OnSuccess((ctx, alarm) =>
                {
                    this.ClearActiveTopic();

                    ctx.GetUserState <BotUserState>().Alarms.Add(alarm);

                    context.SendActivity($"Added alarm named '{ alarm.Title }' set for '{ alarm.Time }'.");
                })
                .OnFailure((ctx, reason) =>
                {
                    this.ClearActiveTopic();

                    context.SendActivity("Let's try something else.");

                    this.ShowDefaultMessage(ctx);
                });

                return(addAlarmTopic);
            });

            this.SubTopics.Add(DELETE_ALARM_TOPIC, (object[] args) =>
            {
                var alarms = (args.Length > 0) ? (List <Alarm>)args[0] : null;

                var deleteAlarmTopic = new DeleteAlarmTopic(alarms);

                deleteAlarmTopic.Set
                .OnSuccess((ctx, value) =>
                {
                    this.ClearActiveTopic();

                    if (!value.DeleteConfirmed)
                    {
                        context.SendActivity($"Ok, I won't delete alarm '{ value.Alarm.Title }'.");
                        return;
                    }

                    ctx.GetUserState <BotUserState>().Alarms.RemoveAt(value.AlarmIndex);

                    context.SendActivity($"Done. I've deleted alarm '{ value.Alarm.Title }'.");
                })
                .OnFailure((ctx, reason) =>
                {
                    this.ClearActiveTopic();

                    context.SendActivity("Let's try something else.");

                    this.ShowDefaultMessage(context);
                });

                return(deleteAlarmTopic);
            });
        }
        private async Task <bool> ProcessTopicState(IBotContext context)
        {
            string utterance = (((Activity)context.Request).Text ?? "").Trim();
            var    userState = context.GetUserState <UserData>();

            // var userState = UserState<UserData>.Get(context);

            // we ar eusing TopicState to remember what we last asked
            switch (this.TopicState)
            {
            case TopicStates.AddingCard:
            {
                dynamic payload = ((Activity)context.Request).Value;
                if (payload != null)
                {
                    if (payload.Action == "Submit")
                    {
                        this.Alarm.Title = payload.Title;
                        if (DateTimeOffset.TryParse((string)payload.Day, out DateTimeOffset date))
                        {
                            if (DateTimeOffset.TryParse((string)payload.Time, out DateTimeOffset time))
                            {
                                this.Alarm.Time = new DateTimeOffset(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second, date.Offset);
                                if (userState.Alarms == null)
                                {
                                    userState.Alarms = new List <Alarm>();
                                }
                                userState.Alarms.Add(this.Alarm);
                                AddAlarmTopicResponses.ReplyWithAddedAlarm(context, this.Alarm);
                                // end topic
                                return(false);
                            }
                        }
                    }
                    else if (payload.Action == "Cancel")
                    {
                        AddAlarmTopicResponses.ReplyWithTopicCanceled(context, this.Alarm);
                        // End current topic
                        return(false);
                    }
                }
            }
                return(true);

            case TopicStates.CancelConfirmation:
            {
                dynamic payload = ((Activity)context.Request).Value;
                switch ((string)payload.Action)
                {
                case "Yes":
                {
                    AddAlarmTopicResponses.ReplyWithTopicCanceled(context, this.Alarm);
                    // End current topic
                    return(false);
                }

                case "No":
                {
                    this.TopicState = TopicStates.AddingCard;
                    return(await this.ContinueTopic(context));
                }

                default:
                {
                    AddAlarmTopicResponses.ReplyWithCancelReprompt(context, this.Alarm);
                    return(true);
                }
                }
            }

            default:
                return(true);
            }
        }
Ejemplo n.º 7
0
        public async Task OnProcessRequest(IBotContext context, MiddlewareSet.NextDelegate next)
        {
            var activity = context.Request.AsMessageActivity();

            if (activity == null)
            {
                await next();
            }

            // Handle the message from functions contains ChatPlus's webhook response
            if (activity?.Type == ActivityTypes.Event)
            {
                Debug.WriteLine("*************************");
                Debug.WriteLine("Got event type message");
                Debug.WriteLine("*************************");
                string userId = "default-user"; // TODO hiroaki-honda remove this line and replace userId used as key to extract ConversationInformation from table storage. ("default-user" is the userId just for Hackfest).
                // string userId = Deserialize<Visitor>("visitor", (Activity)activity).visitor_id;
                ConversationReference conversationReference = await GetConversationReferenceByUserId(userId);

                switch (activity.From.Id)
                {
                case "WebhookStartChat":
                    string messageForSuccessToConnect = "Success to make a connection with call center agent. Please let us know what makes you in trouble.";
                    await SendProactiveMessage(context, conversationReference, messageForSuccessToConnect);

                    break;

                case "WebhookSendMessage":
                    string messageFromAgent = JsonConvert.DeserializeObject <ChatPlusInformation>(activity.Value.ToString()).message.text;
                    await SendProactiveMessage(context, conversationReference, messageFromAgent);

                    break;

                default:
                    throw new Exception("unexpected event type message");
                }
            }

            // Enqueue the message to hook the function which passes the message to agent if "IsConnectedToAgent" is true.
            var userState = context.GetUserState <BotUserState>();

            if (userState != null && userState.IsConnectedToAgent)
            {
                CloudStorageAccount account          = buildStorageAccount();
                CloudQueueClient    cloudQueueClient = account.CreateCloudQueueClient();
                CloudQueue          queue            = cloudQueueClient.GetQueueReference("message-from-user");
                var item = new ConversationInformation()
                {
                    ConversationReference = JsonConvert.SerializeObject(GetConversationReference((Microsoft.Bot.Schema.Activity)activity)),
                    MessageFromUser       = context.Request.Text
                };
                var message = new CloudQueueMessage(JsonConvert.SerializeObject(item));
                await queue.AddMessageAsync(message);

                return;
            }

            // Request to make a connection between user and agent
            if (activity != null &&
                !string.IsNullOrEmpty(activity.Text) &&
                activity.Text.ToLower().Contains(Commands.CommandRequestConnection))
            {
                // Store conversation reference (Use this info when send a proactive message to user after).
                await StoreConversationInformation(context);

                // TODO hiroaki-honda Implement the logic to hook the function which request connection to ChatPlus
                // Status: Ask chatplus to prepare the API which receive the request to connect to agent

                // Set connecting state true
                var state = context.GetUserState <BotUserState>();
                state.IsConnectedToAgent = true;

                await context.SendActivity("Now make a request for connection. Please wait a minutes.");
            }
            else
            {
                await next();
            }
        }