示例#1
0
        public async Task <Routine> GetRoutineAsync(Identity owner, bool allowSlaveRoutine, CancellationToken cancellationToken)
        {
            try
            {
                owner = owner.ToNode().ToIdentity();

                var routine = await _bucket.GetAsync <Routine>(owner.ToString(), cancellationToken);

                if (routine == null)
                {
                    routine = new Routine {
                        Owner = owner
                    };
                    await _bucket.SetAsync(owner.ToString(), routine, TimeSpan.FromDays(short.MaxValue), cancellationToken);
                }

                if (routine.PhoneNumberRegistrationStatus != PhoneNumberRegistrationStatus.Confirmed || allowSlaveRoutine)
                {
                    return(routine);
                }

                var phoneNumber = await _bucket.GetAsync <PhoneNumber>(routine.PhoneNumber, cancellationToken);

                if (phoneNumber == null)
                {
                    return(routine);
                }

                var ownerRoutine = await _bucket.GetAsync <Routine>(phoneNumber.Owner, cancellationToken);

                if (!ownerRoutine.Owner.Equals(routine.Owner) && routine.Tasks?.Length > 0)
                {
                    ownerRoutine.Tasks = ownerRoutine.Tasks.Concat(routine.Tasks).ToArray();
                    routine.Tasks      = new RoutineTask[0];
                    await SetRoutineAsync(routine, cancellationToken);
                    await SetRoutineAsync(ownerRoutine, cancellationToken);
                }
                routine = ownerRoutine;

                return(routine);
            }
            catch
            {
                return(new Routine {
                    Owner = owner
                });
            }
        }
 /// <summary>
 /// Gets the last known identity state.
 /// </summary>
 /// <param name="identity">The node.</param>
 /// <returns></returns>
 /// <exception cref="System.ArgumentNullException"></exception>
 public async Task <string> GetStateAsync(Identity identity, CancellationToken cancellationToken)
 {
     if (identity == null)
     {
         throw new ArgumentNullException(nameof(identity));
     }
     return((await _bucket.GetAsync <StateDocument>(GetKey(identity), cancellationToken))?.State ?? Constants.DEFAULT_STATE);
 }
示例#3
0
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            Log.Debug($"Summary Task. From: {message.From} \tContent: {message.Content}");

            var todayDate = DateTime.Now;
            var doc       = await _bucketExtension.GetAsync <JsonDocument>(todayDate.ToString("yyyy-MM-dd"));

            await _sender.SendMessageAsync(doc.ToString(), message.From, cancellationToken);
        }
示例#4
0
 /// <summary>
 /// Gets the last known identity state.
 /// </summary>
 /// <param name="identity">The node.</param>
 /// <returns></returns>
 /// <exception cref="System.ArgumentNullException"></exception>
 public async Task <string> GetStateAsync(Identity identity)
 {
     if (identity == null)
     {
         throw new ArgumentNullException(nameof(identity));
     }
     using (var cts = new CancellationTokenSource(CommandTimeout))
     {
         return((await _bucket.GetAsync <StateDocument>(GetKey(identity), cts.Token))?.State ?? Constants.DEFAULT_STATE);
     }
 }
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            //Store last access date
            var jsonLastAccess = new JsonDocument();

            jsonLastAccess.Add("lastAccessDate", DateTimeOffset.Now);

            await _bucketExtension.SetAsync(message.From.ToString(), jsonLastAccess);

            //Get last access date
            await _bucketExtension.GetAsync <JsonDocument>(message.From.ToString());
        }
示例#6
0
        public async Task <DocumentCollection> GetFavoritesGasStationsAsync(Identity userIdentity)
        {
            var myContextKey = $"{userIdentity}:context";

            var favoritesGasStationsIds = await _bucketExtension.GetAsync <JsonDocument>(myContextKey);

            //foreach (var item in collection)

            var favoriteList = new List <GasStation>
            {
                new GasStation
                {
                    Id            = Guid.NewGuid().ToString(),
                    Address       = "Rua Mais bonita da cidade",
                    AlcoholPrice  = 2.89f,
                    GasolinePrice = 3.81f,
                    LastUpdated   = DateTimeOffset.Now,
                    Latitude      = -19.9292403f,
                    Longitude     = -43.9543158f
                }
            };

            return(GetCarouselFromGasStationList(favoriteList, true));
        }
        public async Task <UserContext> GetUserContextAsync(Node user, CancellationToken cancellationToken)
        {
            try
            {
                var context = await _bucket.GetAsync <UserContext>(GetBucketKey(user), cancellationToken);

                if (context == null)
                {
                    context = new UserContext();
                    await _bucket.SetAsync(GetBucketKey(user), context, cancellationToken : cancellationToken);
                }

                return(context);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            var receivedText = (message.Content as PlainText).Text;
            var currentState = await _stateManager.GetStateAsync(message.From, cancellationToken);

            var myContextKey = $"{message.From.ToIdentity()}:context";

            var contextDocument = await _bucketExtension.GetAsync <JsonDocument>(myContextKey);

            var gasStationId = contextDocument["lastSelectedGasStationId"] as string;

            switch (currentState)
            {
            case "3.1.1":
                //Extract gasoline price
                var gasolinePrice = float.Parse(receivedText);

                await _gasStationService.UpdateGasolinePriceAsync(gasStationId, gasolinePrice);

                //Change user state
                await _stateManager.SetStateAsync(message.From, "3.1.1A", cancellationToken);

                //Send Alcohol message
                var alcoholText = new PlainText {
                    Text = "E o etanol?"
                };
                await _sender.SendMessageAsync(alcoholText, message.From, cancellationToken);

                break;

            case "3.1.1A":

                //Extract alcohol price
                var alcoholPrice = float.Parse(receivedText);

                await _gasStationService.UpdateAlcoholPriceAsync(gasStationId, alcoholPrice);

                var actionsQuickReply = new Select
                {
                    Text    = "O que você quer fazer?",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Text  = "📍 Postos próximos",
                            Value = new Trigger {
                                StateId = "3.1.0"
                            }
                        },
                        new SelectOption
                        {
                            Text  = "⭐ Meus favoritos",
                            Value = new Trigger {
                                StateId = "3.2.0"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(actionsQuickReply, message.From, cancellationToken);

                break;
            }
        }
        public static async Task <string> GetStringAsync(this IBucketExtension bucket, string id, CancellationToken cancellationToken)
        {
            var content = await bucket.GetAsync <PlainText>(id, cancellationToken);

            return(content?.Text);
        }
 public Task <NavigationSession> GetSessionAsync(Node node, CancellationToken cancellationToken)
 => _bucketExtension.GetAsync <NavigationSession>(GetSessionKey(node), cancellationToken);
示例#11
0
        public async Task ProcessState(Trigger trigger, Node fromNode, CancellationToken cancellationToken = default(CancellationToken))
        {
            var currentContext = await _bucketExtension.GetAsync <JsonDocument>($"{fromNode.ToIdentity()}:context", cancellationToken) ?? GetInitialContext();

            switch (trigger.StateId)
            {
            case "welcome-seeing":
                await _sender.SendMessageAsync(new PlainText { Text = $"Eu também! 👀" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var quickReply = new Select
                {
                    Text    = $"Essas opções te ajudam ter uma conversa mais objetiva. Você pode falar, mas o quanto mais direto ao ponto, melhor 🎯",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "OK! 🎯",
                            Value = new Trigger {
                                StateId = "welcome-ok"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(quickReply, fromNode, cancellationToken);

                break;

            case "welcome-ok":

                await _sender.SendMessageAsync(new PlainText { Text = $"Falando em direto ao ponto.. 🎯" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                quickReply = new Select
                {
                    Text    = $"Gostaria de receber avisos, desafios e slides das apresentações por aqui? ⬇️",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Sim",
                            Value = new Trigger {
                                StateId = "welcome-notification-yes"
                            }
                        },
                        new SelectOption
                        {
                            Order = 1,
                            Text  = "Não",
                            Value = new Trigger {
                                StateId = "welcome-notification-no"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(quickReply, fromNode, cancellationToken);

                break;

            case "welcome-notification-yes":

                currentContext["receiveAlert"] = true;

                await _sender.SendMessageAsync(new PlainText { Text = $"Beleza! Vou te enviar os slides (pdf) por aqui. 😊" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var onboardingQuickReply = new Select
                {
                    Text    = $"Gostaria de conhecer o espaço do evento e um pouco do que preparamos para você?",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Sim",
                            Value = new Trigger {
                                StateId = "onboarding-yes"
                            }
                        },
                        new SelectOption
                        {
                            Order = 1,
                            Text  = "Não",
                            Value = new Trigger {
                                StateId = "onboarding-no"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(onboardingQuickReply, fromNode, cancellationToken);

                break;

            case "welcome-notification-no":

                currentContext["receiveAlert"] = false;

                await _sender.SendMessageAsync(new PlainText { Text = $"Sem problemas! 😅" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                onboardingQuickReply = new Select
                {
                    Text    = $"Gostaria de conhecer o espaço do evento e um pouco do que preparamos para você?",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Sim",
                            Value = new Trigger {
                                StateId = "onboarding-yes"
                            }
                        },
                        new SelectOption
                        {
                            Order = 1,
                            Text  = "Não",
                            Value = new Trigger {
                                StateId = "onboarding-no"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(onboardingQuickReply, fromNode, cancellationToken);

                break;

            case "onboarding-yes":

                await _sender.SendMessageAsync(new PlainText { Text = $"Confira algumas dicas ➡️" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var carouselTips = new DocumentCollection
                {
                    ItemType = DocumentSelect.MediaType,
                    Items    = new DocumentSelect[4]
                    {
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/localiza%C3%A7%C3%A3o-18.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Todo o espaço oferece experiências.",
                                    Text  = "Veja o mapa no seu crachá 🗺️"
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/messenger+code-17.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Ganhe brindes! Basta escanear imagens parecidas com essa 📱",
                                    Text  = "Dica: use o Messenger 😉"
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/camisa.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Precisando de ajuda?",
                                    Text  = "Procure por alguém usando essa camisa 👕 ",
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/freeBeer.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Fique para nossa festa no final evento.",
                                    Text  = "A cerveja é por nossa conta 🍻",
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        }
                    }
                };

                await _sender.SendMessageAsync(carouselTips, fromNode, cancellationToken);

                await Task.Delay(6000);

                var moreAboutEventMenu = new Select
                {
                    Text    = $"Saiba mais sobre o evento:",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Ver programação 📅",
                            Value = new Trigger {
                                StateId = "menu-scheduler"
                            }
                        },
                        new SelectOption
                        {
                            Order = 1,
                            Text  = "Chatbot4Devs 🤖",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(moreAboutEventMenu, fromNode, cancellationToken);

                break;

            case "onboarding-no":

                var menu = new Select
                {
                    Text    = $"Ok!Esperamos que você curta essa imersão com chatbots.Qualquer coisa, tô aqui 😉",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Chatbot4Devs 🤖",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(menu, fromNode, cancellationToken);

                break;

            case "menu":

                await _sender.SendMessageAsync(new PlainText { Text = $"Veja essas opções ➡️" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var carouselMenu = new DocumentCollection
                {
                    ItemType = DocumentSelect.MediaType,
                    Items    = new DocumentSelect[3]
                    {
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/chatbot4devs.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Chatbots4Devs",
                                    Text  = "Entenda nosso evento e veja como ter a melhoror experiência."
                                }
                            },
                            Options = new DocumentSelectOption[]
                            {
                                new DocumentSelectOption
                                {
                                    Label = new DocumentContainer {
                                        Value = "🤖 Conhecer evento"
                                    },
                                    Value = new DocumentContainer {
                                        Value = new Trigger {
                                            StateId = "menu"
                                        }
                                    }
                                }
                            }
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/programa%C3%A7%C3%A3o.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Programação e Palestrantes",
                                    Text  = "Confira o conteúdo de todas as palestras do evento."
                                }
                            },
                            Options = new DocumentSelectOption[]
                            {
                                new DocumentSelectOption
                                {
                                    Label = new DocumentContainer {
                                        Value = "📆 Ver programação"
                                    },
                                    Value = new DocumentContainer {
                                        Value = new Trigger {
                                            StateId = "menu-scheduler"
                                        }
                                    }
                                }
                            }
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/notifica%C3%A7%C3%B5es.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Notificações e avisos",
                                    Text  = "Recebimento de notificações.",
                                }
                            },
                            Options = new DocumentSelectOption[]
                            {
                                new DocumentSelectOption
                                {
                                    Label = new DocumentContainer {
                                        Value = "⚙ Configurar"
                                    },
                                    Value = new DocumentContainer {
                                        Value = new Trigger {
                                            StateId = "menu-settings"
                                        }
                                    }
                                }
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(carouselMenu, fromNode, cancellationToken);

                await Task.Delay(6000);

                break;

            case "menu-event":

                await _sender.SendMessageAsync(new PlainText { Text = $"Criamos o evento para unir pessoas que desenvolvem e influenciam várias áreas de empreendedorismo e tech." }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var menuEvent = new Select
                {
                    Text    = $"Assim, o Chatbot4Devs trouxe conteúdos e interações no espaço do Sebrae MG para quem deseja saber tudo sobre chatbots.",
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Conhecer mais",
                            Value = new WebLink {
                                Uri = new Uri("http://chatbot4devs.take.net/")
                            }
                        },
                        new SelectOption
                        {
                            Order = 1,
                            Text  = "Menu Inicial",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(menuEvent, fromNode, cancellationToken);

                break;

            case "menu-scheduler":

                await _sender.SendMessageAsync(new PlainText { Text = $"Olha só o pessoal que vai palestrar:" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                var speakersMenu = new DocumentCollection
                {
                    ItemType = DocumentSelect.MediaType,
                    Items    = new DocumentSelect[2]
                    {
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/Rafael.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "⏰ 10h00 | Desenvolvimento de chatbots com a plataforma BLiP",
                                }
                            },
                            Options = new DocumentSelectOption[]
                            {
                            }
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/Caio.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "⏰ 12h00 | Como desenhar conversas com chatbots?",
                                }
                            },
                            Options = new DocumentSelectOption[]
                            {
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(speakersMenu, fromNode, cancellationToken);

                await Task.Delay(2000);

                var menuSchedule = new Select
                {
                    Text    = $"Confira nossa agenda ➡️",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Chatbot4Devs 🤖",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(menuSchedule, fromNode, cancellationToken);

                break;

            case "menu-settings":

                var receiveAlert = bool.Parse(currentContext["receiveAlert"].ToString());

                string text;
                string optionText;
                var    optionPayload = new JsonDocument();

                if (receiveAlert)
                {
                    text                  = "${contact.name}, você está recebendo avisos, lembretes e slides 🔔";
                    optionText            = "Não receber 🔕";
                    optionPayload["mute"] = true;
                }
                else
                {
                    text                  = "${contact.name}, você não está recebendo avisos, lembretes e slides 🔕";
                    optionText            = "Receber 🔔";
                    optionPayload["mute"] = false;
                }

                var menuAlert = new Select
                {
                    Text    = text,
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Text  = optionText,
                            Order = 0,
                            Value = new Trigger {
                                StateId = "menu-settings-update", Payload = optionPayload
                            }
                        },
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Chatbot4Devs 🤖",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(menuAlert, fromNode, cancellationToken);

                break;

            case "menu-settings-update":

                var mute = bool.Parse(trigger.Payload["mute"].ToString());
                currentContext["receiveAlert"] = !mute;

                await _sender.SendMessageAsync(new PlainText { Text = $"Combinado 😉" }, fromNode, cancellationToken);

                await Task.Delay(2000);

                menuAlert = new Select
                {
                    Text    = "Espero que esteja curtindo o evento 🤖",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Order = 0,
                            Text  = "Chatbot4Devs 🤖",
                            Value = new Trigger {
                                StateId = "menu"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(menuAlert, fromNode, cancellationToken);

                break;

            case "speaker1":
                break;

            case "speaker2":
                break;

            case "qrCode":

                var hasScanned = currentContext.ContainsKey("hasScanned");

                if (hasScanned)
                {
                    var gif = new MediaLink
                    {
                        Uri  = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/brindeErro3-Shaq.gif"),
                        Type = new MediaType("image", "gif")
                    };

                    await _sender.SendMessageAsync(gif, fromNode, cancellationToken);

                    await Task.Delay(2000);

                    var hasScannedMenu = new Select
                    {
                        Text    = "Aparentemente você já ganhou seu prêmio. Já olhou nos outros estandes ? 😎",
                        Scope   = SelectScope.Immediate,
                        Options = new SelectOption[]
                        {
                            new SelectOption
                            {
                                Order = 0,
                                Text  = "Chatbot4Devs 🤖",
                                Value = new Trigger {
                                    StateId = "menu"
                                }
                            }
                        }
                    };

                    await _sender.SendMessageAsync(hasScannedMenu, fromNode, cancellationToken);
                }
                else
                {
                    await _sender.SendMessageAsync(new PlainText { Text = "Hum… me parece que você ganhou um brinde 😁" }, fromNode, cancellationToken);

                    var img = new MediaLink
                    {
                        Uri  = new Uri("https://s3.amazonaws.com/elasticbeanstalk-us-east-1-405747350567/c4d/brinde-camisa.png"),
                        Type = new MediaType("image", "png")
                    };

                    await _sender.SendMessageAsync(img, fromNode, cancellationToken);

                    await Task.Delay(2000);

                    var scannedMenu = new Select
                    {
                        Text    = "Apresente essa imagem num estande próximo a você.",
                        Scope   = SelectScope.Immediate,
                        Options = new SelectOption[]
                        {
                            new SelectOption
                            {
                                Order = 0,
                                Text  = "Chatbot4Devs 🤖",
                                Value = new Trigger {
                                    StateId = "menu"
                                }
                            }
                        }
                    };

                    await _sender.SendMessageAsync(scannedMenu, fromNode, cancellationToken);
                }

                currentContext["hasScanned"] = true;
                break;
            }

            //Update user state
            await _stateManager.SetStateAsync(fromNode.ToIdentity(), trigger.StateId, cancellationToken);

            //Update user context
            await _bucketExtension.SetAsync($"{fromNode.ToIdentity()}:context", currentContext, cancellationToken : cancellationToken);
        }
示例#12
0
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            var fromIdentity = message.From.ToIdentity();

            // Gets the stored document for the identity
            var userSession = await _bucketExtension.GetAsync <JsonDocument>(
                fromIdentity,
                cancellationToken);

            var text = message.Content.ToString().ToLowerInvariant();

            // Creates the response
            var responseMessage = new Message()
            {
                Id      = EnvelopeId.NewId(),
                To      = message.From,
                Content = "Pong!!!"
            };

            // If there is a stored session
            if (userSession != null)
            {
                if (text == "ping")
                {
                    // Removes the session
                    await _bucketExtension.DeleteAsync(fromIdentity, cancellationToken);
                }
                else
                {
                    var state = userSession["state"].ToString();
                    switch (state)
                    {
                    case "cachorro":
                        responseMessage.Content = "Au Au Au!!!";
                        break;

                    case "gato":
                        responseMessage.Content = "Miau Miau Miau!!!";
                        break;

                    case "EscolherAnimal":
                        if (new[] { "cachorro", "gato" }.Contains(text))
                        {
                            // Sets the current state as the animal name
                            await _bucketExtension.SetAsync(
                                fromIdentity,
                                new JsonDocument
                            {
                                { "state", text }
                            },
                                cancellationToken : cancellationToken);

                            if (text == "cachorro")
                            {
                                responseMessage.Content =
                                    new MediaLink
                                {
                                    Title = "Cachorro",
                                    Text  = "Agora sou um cachorro",
                                    Type  = "image/jpeg",
                                    Uri   = new Uri("http://tudosobrecachorros.com.br/wp-content/uploads/cachorro-independente-766x483.jpg"),
                                };
                            }
                            else if (text == "gato")
                            {
                                responseMessage.Content =
                                    new MediaLink
                                {
                                    Title = "Gato",
                                    Text  = "Agora sou um gato",
                                    Type  = "image/jpeg",
                                    Uri   = new Uri("http://www.gatosmania.com/Uploads/gatosmania.com/ImagensGrandes/linguagem-corporal-gatos.jpg"),
                                };
                            }
                        }

                        break;
                    }
                }
            }
            else if (text == "animal")
            {
                await _bucketExtension.SetAsync(
                    fromIdentity,
                    new JsonDocument
                {
                    { "state", "EscolherAnimal" }
                },
                    cancellationToken : cancellationToken);

                responseMessage.Content =
                    new Select
                {
                    Text    = "Escolha uma opção",
                    Options = new[]
                    {
                        new SelectOption {
                            Order = 1, Text = "Cachorro"
                        },
                        new SelectOption {
                            Order = 2, Text = "Gato"
                        }
                    }
                };
            }

            await _sender.SendMessageAsync(responseMessage, cancellationToken);
        }
示例#13
0
        /// <summary>
        /// Gets an existing text from the bucket by the id.
        /// </summary>
        /// <param name="bucketExtension"></param>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task <string> GetTextAsync(this IBucketExtension bucketExtension, string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            var document = await bucketExtension.GetAsync <PlainText>(id, cancellationToken);

            return(document?.Text);
        }
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            var trigger = message.Content as Trigger;

            //Update user state
            await _stateManager.SetStateAsync(message.From.ToIdentity(), trigger.StateId, cancellationToken);

            switch (trigger.StateId)
            {
            //Tips
            case "2.0.0":
                var textDocument = new PlainText {
                    Text = "Mandou bem, ${contact.name}! 😄"
                };

                var textMessage = new Message
                {
                    To       = message.From,
                    Content  = textDocument,
                    Id       = EnvelopeId.NewId(),
                    Metadata = new Dictionary <string, string>
                    {
                        { "#message.replaceVariables", "true" }
                    }
                };

                await _sender.SendMessageAsync(textMessage, cancellationToken);

                await Task.Delay(2000);

                textDocument = new PlainText {
                    Text = "Deslize ⬅️➡️ para saber mais:"
                };
                await _sender.SendMessageAsync(textDocument, message.From, cancellationToken);

                await Task.Delay(2000);

                //Carousel with tips
                var carouselDocument = new DocumentCollection
                {
                    ItemType = DocumentSelect.MediaType,
                    Items    = new DocumentSelect[3]
                    {
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("http://www.botsbrasil.com.br/wp-content/uploads/2016/12/take.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Eu sou um robô, sempre que possível utilize os botões",
                                    Text  = "Consigo te entender melhor assim"
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("http://www.botsbrasil.com.br/wp-content/uploads/2016/12/take.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Se o preço não estiver correto, corrija no mesmo instante",
                                    Text  = "A sua ajuda é essencial"
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        },
                        new DocumentSelect
                        {
                            Header = new DocumentContainer
                            {
                                Value = new MediaLink
                                {
                                    Uri   = new Uri("http://www.botsbrasil.com.br/wp-content/uploads/2016/12/take.png"),
                                    Type  = new MediaType("image", "png"),
                                    Title = "Favorite seus postos prediletos",
                                    Text  = "Assim você não precisa informar o endereço. Crie atalhos!",
                                }
                            },
                            Options = new DocumentSelectOption[] {}
                        }
                    }
                };

                await _sender.SendMessageAsync(carouselDocument, message.From, cancellationToken);

                await Task.Delay(6000);

                var quickReply = new Select
                {
                    Text    = "Já estou pronto! Assim que terminar de ler clique no botão abaixo:",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Text  = "Começar",
                            Value = new Trigger
                            {
                                StateId = "3.0.0"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(quickReply, message.From, cancellationToken);

                break;

            //Options
            case "3.0.0":

                var actionsQuickReply = new Select
                {
                    Text    = "O que você quer fazer?",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Text  = "📍 Postos próximos",
                            Value = new Trigger {
                                StateId = "3.1.0"
                            }
                        },
                        new SelectOption
                        {
                            Text  = "⭐ Meus favoritos",
                            Value = new Trigger {
                                StateId = "3.2.0"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(actionsQuickReply, message.From, cancellationToken);

                break;

            //Near GasStations
            case "3.1.0":

                var locationInput = new Input
                {
                    Label = new DocumentContainer
                    {
                        Value = "Clique no botão abaixo para me enviar a sua localização ou digite o endereço:"
                    },
                    Validation = new InputValidation
                    {
                        Type = Location.MediaType,
                        Rule = InputValidationRule.Type
                    }
                };

                await _sender.SendMessageAsync(locationInput, message.From, cancellationToken);

                break;

            //Favorites
            case "3.2.0":

                var waitingTextDocument = new PlainText {
                    Text = "Um instante... ⏳"
                };
                await _sender.SendMessageAsync(waitingTextDocument, message.From, cancellationToken);

                //Get Favorites GasStations
                var carousel = await _gasStationService.GetFavoritesGasStationsAsync(message.From.ToIdentity());

                //Carousel with favorites gas stations
                var readyTextDocument = new PlainText {
                    Text = "Pronto!Os postos favoritos são: ⬅️➡️"
                };
                await _sender.SendMessageAsync(readyTextDocument, message.From, cancellationToken);

                await _sender.SendMessageAsync(carousel, message.From, cancellationToken);

                break;

            //Update GasStation prices
            case "3.1.1":

                var currentState = await _stateManager.GetStateAsync(message.From, cancellationToken);

                var myContextKey = $"{message.From.ToIdentity()}:context";

                var contextDocument = await _bucketExtension.GetAsync <JsonDocument>(myContextKey);

                contextDocument["lastSelectedGasStationId"] = trigger.Payload;
                await _bucketExtension.SetAsync(myContextKey, contextDocument);

                var helpText = new PlainText {
                    Text = "Ops!Ainda bem que você está aqui para me ajudar 😅"
                };
                await _sender.SendMessageAsync(helpText, message.From, cancellationToken);

                await Task.Delay(2000);

                helpText.Text = "Quanto está a gasolina ?";
                await _sender.SendMessageAsync(helpText, message.From, cancellationToken);

                break;

            //Favorite GasStation
            case "3.1.2":

                await _gasStationService.FavoriteGasStationAsync(message.From, trigger.Payload);

                var confirmationText = new PlainText {
                    Text = "🌟 Posto favoritado!"
                };
                await _sender.SendMessageAsync(confirmationText, message.From, cancellationToken);

                await Task.Delay(2000);

                actionsQuickReply = new Select
                {
                    Text    = "O que você quer fazer?",
                    Scope   = SelectScope.Immediate,
                    Options = new SelectOption[]
                    {
                        new SelectOption
                        {
                            Text  = "📍 Postos próximos",
                            Value = new Trigger {
                                StateId = "3.1.0"
                            }
                        },
                        new SelectOption
                        {
                            Text  = "⭐ Meus favoritos",
                            Value = new Trigger {
                                StateId = "3.2.0"
                            }
                        }
                    }
                };

                await _sender.SendMessageAsync(actionsQuickReply, message.From, cancellationToken);

                break;

            //Get the route
            case "3.1.3":

                var gasStation = await _gasStationService.GetAsync(trigger.Payload);

                var locationRoute = new Location
                {
                    Latitude  = gasStation.Latitude,
                    Longitude = gasStation.Longitude,
                    Text      = gasStation.Address
                };

                await _sender.SendMessageAsync(locationRoute, message.From, cancellationToken);

                break;

            default:
                break;
            }
        }