コード例 #1
0
 /// <summary>
 /// Execute after flow process
 /// </summary>
 /// <param name="state"></param>
 /// <param name="message"></param>
 /// <param name="from"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public async Task OnFlowProcessedAsync(State state, Message message, Node from, CancellationToken cancellationToken)
 {
     // Schedule expiration time if input is configured
     if (state.HasInputExpiration())
     {
         var scheduleMessage = CreateInputExirationMessage(message, state.Id);
         var scheduleTime    = DateTimeOffset.UtcNow.AddMinutes(state.Input.Expiration.Value.TotalMinutes);
         await _schedulerExtension.ScheduleMessageAsync(scheduleMessage, scheduleTime, from, cancellationToken);
     }
 }
コード例 #2
0
        //Schedule a message to next 10 minutes
        public async Task ReceiveAsync(Message receivedMessage, CancellationToken cancellationToken)
        {
            var schedullingDate = DateTimeOffset.Now.AddMinutes(10);
            var messageContent  = "tomar remédio";

            var message = new Message
            {
                Id      = Guid.NewGuid().ToString(),
                To      = receivedMessage.From,
                Content = new PlainText {
                    Text = messageContent
                }
            };

            await _schedulerExtension.ScheduleMessageAsync(message, schedullingDate);
        }
コード例 #3
0
        public static async Task <bool> UpdateBroadcastMessagesAsync(this ISchedulerExtension schedulerExtension, IOWLFilter _owlFilter, Settings settings)
        {
            try
            {
                foreach (TeamIds t in MyConstants.AllTeams)
                {
                    var futureMatches = await _owlFilter.GetFutureMatchesAsync(t);

                    foreach (ScheduleResponse s in futureMatches)
                    {
                        var message = BuildBroadcastMessage(t, s, settings);
                        var time    = GetDateTimeOffset(s);
                        await schedulerExtension.ScheduleMessageAsync(message, time);
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #4
0
        private async Task ConfigureScheduleAsync(Identity owner, RoutineTaskTimeValue time, CancellationToken cancellationToken)
        {
            Trace.WriteLine($"Start scheduling reminder for {owner} at {time}!");
            try
            {
                var routine = await _routineRepository.GetRoutineAsync(owner, false, cancellationToken);

                // Will send a message to itself, the next day only, reminding it to send a message with the routine for the given days and time for each client

                var currentTime = GetCurrentTime();

                var isBeforeMorning   = currentTime.Hour < 6;
                var isBeforeAfternoon = currentTime.Hour < 12;
                var isBeforeEvening   = currentTime.Hour < 18;

                var today = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 0, 0, 0);

                var nextMorningSchedule   = isBeforeMorning ? today.AddHours(6) : today.AddHours(6).AddDays(1);
                var nextAfternoonSchedule = isBeforeAfternoon ? today.AddHours(12) : today.AddHours(12).AddDays(1);
                var nextEveningSchedule   = isBeforeEvening ? today.AddHours(18) : today.AddHours(18).AddDays(1);

                var shouldScheduleAtMorning = time == RoutineTaskTimeValue.Morning &&
                                              routine.LastMorningReminder < nextMorningSchedule;
                var shouldScheduleAtAfternoon = time == RoutineTaskTimeValue.Afternoon &&
                                                routine.LastAfternoonReminder < nextAfternoonSchedule;
                var shouldScheduleAtEvening = time == RoutineTaskTimeValue.Evening &&
                                              routine.LastEveningReminder < nextEveningSchedule;

                if (shouldScheduleAtMorning || shouldScheduleAtAfternoon || shouldScheduleAtEvening)
                {
                    await
                    _delegation.DelegateAsync(Identity.Parse("*****@*****.**"),
                                              new[] { EnvelopeType.Message }, cancellationToken);

                    var identity = new Node(_application.Identifier, _application.Domain, null);
                    var schedule = new Message
                    {
                        Id      = Guid.NewGuid().ToString(),
                        To      = identity,
                        Content = new IdentityDocument(routine.Owner.ToString())
                    };

                    if (shouldScheduleAtMorning)
                    {
                        routine.LastMorningReminder = nextMorningSchedule;
                    }
                    if (shouldScheduleAtAfternoon)
                    {
                        routine.LastAfternoonReminder = nextAfternoonSchedule;
                    }
                    if (shouldScheduleAtEvening)
                    {
                        routine.LastEveningReminder = nextEveningSchedule;
                    }

                    switch (time)
                    {
                    case RoutineTaskTimeValue.Morning:
                        await _scheduler.ScheduleMessageAsync(schedule, nextMorningSchedule, cancellationToken);

                        break;

                    case RoutineTaskTimeValue.Afternoon:
                        await _scheduler.ScheduleMessageAsync(schedule, nextAfternoonSchedule, cancellationToken);

                        break;

                    case RoutineTaskTimeValue.Evening:
                        await _scheduler.ScheduleMessageAsync(schedule, nextEveningSchedule, cancellationToken);

                        break;
                    }

                    await _routineRepository.SetRoutineAsync(routine, cancellationToken);
                }
                Trace.WriteLine($"Finished scheduling reminder for {owner} at {time}!");
            }
            catch (Exception e)
            {
                Trace.WriteLine($"Failed scheduling reminder for {owner} at {time}: {e}");
                throw;
            }
        }
コード例 #5
0
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            Trace.TraceInformation($"From: {message.From} \tContent: {message.Content}");

            var user = await _directory.GetDirectoryAccountAsync(message.From, cancellationToken);

            var msg = message.Content.ToString().ToLower();

            if (msg.Equals("ok") || msg.Equals("obrigada") || msg.Equals("blz") || msg.Equals("vlw") || msg.Equals("até lá") || msg.Equals("até") ||
                msg.Equals("tchau") || msg.Equals("flw"))
            {
                await _sender.SendMessageAsync(":)", message.From);
            }

            switch (SState)
            {
            case "initialState":
                await _sender.SendMessageAsync(new Select
                {
                    Text    = $"Olá, { user.FullName.Split(' ')[0] }! Bem-vindo(a) ao Pills Reminder. Eu vou lembrar você de tomar os seus medicamentos sempre no horário! Está pronto(a) para começar?",
                    Options = new[] {
                        new SelectOption {
                            Text  = "Sim",
                            Value = new PlainText {
                                Text = "Sim"
                            }
                        },
                        new SelectOption
                        {
                            Text  = "Não",
                            Value = new PlainText {
                                Text = "Não"
                            }
                        }
                    },
                    Scope = SelectScope.Immediate
                },
                                               message.From,
                                               cancellationToken);

                SState = "iniciado";
                break;

            case "iniciado":
                if (message.Content.ToString().Equals("Não"))
                {
                    SState = "cadastroPendente";
                    await _sender.SendMessageAsync("Tudo bem! Podemos fazer depois então. Pode me chamar aqui quando quiser iniciar o cadastro. Até mais!", message.From);
                }
                else if (message.Content.ToString().Equals("Sim"))
                {
                    SState = "cadastrarMedicamentos";
                    await _sender.SendMessageAsync("Oba! Então vamos começar. Qual o nome do seu medicamento?", message.From);
                }
                else
                {
                    SState = "iniciado";
                    await _sender.SendMessageAsync(new Select
                    {
                        Text    = "Desculpe, não entendi. Você quer iniciar o cadasatro dos seus medicamentos agora?",
                        Options = new[] {
                            new SelectOption {
                                Text  = "Sim",
                                Value = new PlainText {
                                    Text = "Sim"
                                }
                            },
                            new SelectOption
                            {
                                Text  = "Não",
                                Value = new PlainText {
                                    Text = "Não"
                                }
                            }
                        },
                        Scope = SelectScope.Immediate
                    },
                                                   message.From,
                                                   cancellationToken);
                }
                break;

            case "cadastrarMedicamentos":
                Medicine = message.Content.ToString();
                await _sender.SendMessageAsync("Anotado! E que horas você quer que eu te lembre de tomá-lo?", message.From);

                SState = "agendarHorario";
                break;

            case "cadastroPendente":
                await _sender.SendMessageAsync(new Select
                {
                    Text    = $"Olá, { user.FullName.Split(' ')[0] }! Bem-vindo(a) de volta. Está pronto(a) para começar?",
                    Options = new[] {
                        new SelectOption {
                            Text  = "Sim",
                            Value = new PlainText {
                                Text = "Sim"
                            }
                        },
                        new SelectOption
                        {
                            Text  = "Não",
                            Value = new PlainText {
                                Text = "Não"
                            }
                        }
                    },
                    Scope = SelectScope.Immediate
                },
                                               message.From,
                                               cancellationToken);

                SState = "iniciado";
                break;

            case "agendarHorario":
                if (!Regex.IsMatch(message.Content.ToString(), "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"))
                {
                    await _sender.SendMessageAsync("Opa! Esse não me parece um horário válido. Escolha um horário entre 00:00 e 23:59. Como, por exemplo, 12:00 ou 18:30.", message.From);

                    SState = "agendarHorario";
                }
                else
                {
                    await _sender.SendMessageAsync("Combinado! Pode ficar tranquilo(a) que vou te avisar quando chegar a hora! Até lá!", message.From);

                    await _scheduler.ScheduleMessageAsync(new Message
                    {
                        Id      = Guid.NewGuid().ToString(),
                        From    = message.To,
                        Content = new PlainText {
                            Text = $"Olá, { user.FullName.Split(' ')[0] }! Está na hora de tomar o seu remédio { Medicine }."
                        },
                        To = message.From
                    }, DateTimeOffset.Parse(message.Content.ToString()), cancellationToken);

                    SState = "initialState";
                }
                break;
            }

            //states:
            //cadastrarMedicamentos
            //cadastroPendente
            //estadoInicial

            //switch (["sessionState"])
            //{
            //    case "cadastrarMedicamentos":
            //        break;

            //    default:
            //        break;
            //}

            //await _bucket.SetAsync("users", _directory.GetDirectoryAccountAsync(message.From, cancellationToken));

            //await _sender.SendMessageAsync("Pong!", message.From, cancellationToken);

            //var newUser = new Command
            //{
            //    Method = CommandMethod.Set,
            //    Uri = new LimeUri("/contacts/" + message.From)
            //};

            //var response = await _sender.SendCommandAsync(newUser);

            //await _contacts.SetAsync(new Identity { Domain = message.From, Name = "message.Content.ToString()" }, new Lime.Messaging.Resources.Contact { Name = message.Content.ToString() }, cancellationToken);

            //var user = new Command
            //{
            //    Method = CommandMethod.Get,
            //    Uri = new LimeUri("/contacts/" + message.From)
            //};

            //await _sender.SendMessageAsync(new Resource { Key = "HelloWorld" }, message.From, cancellationToken);

            //await _sender.SendMessageAsync("Qual o seu nome?", message.From, cancellationToken);

            //var newUser = new Command
            //{
            //    Method = CommandMethod.Set,
            //    Uri = new LimeUri("/contacts/" + message.From)
            //};

            //var response = await _sender.SendCommandAsync(newUser);

            //var user = new Command
            //{
            //    Method = CommandMethod.Get,
            //    Uri = new LimeUri("/contacts/" + message.From)
            //};

            //var response2 = await _sender.SendCommandAsync(user);

            //await _sender.SendMessageAsync("Prazer em conhecê-la  ${contact.name}", message.From, cancellationToken);

            //var command = new Command
            //{
            //    Method = CommandMethod.Get,
            //    Uri = new LimeUri("/account")
            //};

            //var response = await _sender.SendCommandAsync(command);

            //await _sender.SendMessageAsync("Pong!", message.From, cancellationToken);

            //await _sender.SendMessageAsync("Oi!", message.From, cancellationToken);
        }