Beispiel #1
0
        public async Task RemoveKeyboard(string chatId)
        {
            var removeKeyboard = new ReplyKeyboardRemove();
            var message        = await _telegramMethods.SendMessage(chatId, TextCommand.DELETE_MSG_MARK, null, false, false, null, removeKeyboard);

            await _telegramMethods.DeleteMessage(chatId, message.MessageId);
        }
Beispiel #2
0
        internal static async Task SendMessageAsync(ChatId chatId,
                                                    string text,
                                                    IReplyMarkup keyboard = null)
        {
            if (keyboard == null)
            {
                keyboard = new ReplyKeyboardRemove();
            }

            try
            {
                Message message = await Program.botClient.SendTextMessageAsync(
                    chatId : chatId,
                    text : text,
                    parseMode : ParseMode.Markdown,
                    disableNotification : true,
                    replyMarkup : keyboard
                    );
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException exception)
            {
                if (exception.Message == "Forbidden: bot was blocked by the user")
                {
                    Logger.Logger.Log(exception.Message);
                    return;
                }
            }
        }
Beispiel #3
0
        private static async Task SendDialog(ITelegramBotClient bot, Session session, Dialog dialog)
        {
            for (var i = 0; i < dialog.Phrases.Length; i++)
            {
                await bot.SendChatActionAsync(session.Id, ChatAction.Typing);

                await Task.Delay(500);

                IReplyMarkup reply;
                if (i == dialog.Phrases.Length - 1 && dialog.Dialogs.Count > 0)
                {
                    var keyboard = new List <KeyboardButton>();
                    foreach (var choice in dialog.Dialogs)
                    {
                        keyboard.Add(new KeyboardButton(choice.Label));
                    }
                    reply = new ReplyKeyboardMarkup(keyboard.ToArray(), oneTimeKeyboard: true, resizeKeyboard: true);
                }
                else
                {
                    reply = new ReplyKeyboardRemove();
                }

                await bot.SendTextMessageAsync(
                    chatId : session.Id,
                    text : dialog.Phrases[i],
                    parseMode : ParseMode.Html,
                    replyMarkup : reply
                    );
            }
        }
 public async override void Execute(Message message, TelegramBotClient client)
 {
     var ChatId         = message.Chat.Id;
     var MessageId      = message.MessageId;
     var removeKeyboard = new ReplyKeyboardRemove();
     await client.SendTextMessageAsync(ChatId, "Ожидайте подтверждения авторизации от администратора системы", Telegram.Bot.Types.Enums.ParseMode.Default, false, true, replyToMessageId : MessageId, removeKeyboard);
 }
Beispiel #5
0
        internal static async Task <Telegram.Bot.Types.Message> Send(string message, long id, bool clearKeyboard = false,
                                                                     InlineKeyboardMarkup customMenu             = null,
                                                                     Werewolf game = null, bool notify = false)
        {
            MessagesSent++;
            //message = message.FormatHTML();
            //message = message.Replace("`",@"\`");
            if (clearKeyboard)
            {
                var menu = new ReplyKeyboardRemove {
                    RemoveKeyboard = true
                };
                return(await Bot.SendTextMessageAsync(id, message, replyMarkup : menu, disableWebPagePreview : true,
                                                      parseMode : ParseMode.Html, disableNotification : notify));
            }

            if (customMenu != null)
            {
                return(await Bot.SendTextMessageAsync(id, message, replyMarkup : customMenu, disableWebPagePreview : true,
                                                      parseMode : ParseMode.Html, disableNotification : notify));
            }

            return(await Bot.SendTextMessageAsync(id, message, disableWebPagePreview : true,
                                                  parseMode : ParseMode.Html, disableNotification : notify));
        }
        public async override Task ExecuteAsync(CommandContext context)
        {
            EnterMessage    = Localizer["AddBookshelfEnter"];
            NoExitstMessage = Localizer["AddBookshelfSuccess"];
            ExistMessage    = Localizer["AddBookshelfError"];

            IReplyMarkup keyboard = new ReplyKeyboardRemove();

            if (InputData(context, out Bookshelf bookshelf))
            {
                if (bookshelf == null)
                {
                    bookshelf = new Bookshelf {
                        Name = context.Parameters ?? context.Data, User = context.User
                    };
                    context.AddBookshelf(bookshelf);
                    context.CommandName = null;

                    keyboard = CommandKeyboards.GetMainMenu(Localizer);
                }
                else
                {
                    context.CommandName = Name;
                }
            }
            await BotClient.SendTextMessageAsync(context.Message.Chat, Message, replyMarkup : keyboard);
        }
Beispiel #7
0
        public static void Main(string[] args)
        {
            replyKeyboard       = new[] { Texts.ACCEPT, Texts.CANCEL };
            replyKeyboardRemove = new ReplyKeyboardRemove();

            replyKeyboard.OneTimeKeyboard = true;
            replyKeyboard.ResizeKeyboard  = true;

            botClient       = new TelegramBotClient("---BOT API HERE---");
            usersDictionary = new ConcurrentDictionary <long, User>();

            var me = botClient.GetMeAsync().Result;

            Console.WriteLine("Connected: " + me.FirstName);

            botClient.OnMessage += Bot_OnMessage;
            botClient.StartReceiving();

            while (true)
            {
                foreach (User user in usersDictionary.Values)
                {
                    user.CheckFinishedBlock();
                }
            }
        }
Beispiel #8
0
        private async Task <bool> _sendMessageAsync(long telegramClientId, string text, IReplyMarkup replyMarkup = null, string userNameToHide = "")
        {
            try
            {
                if (text == null)
                {
                    return(false);
                }

                if (replyMarkup == null)
                {
                    replyMarkup = new ReplyKeyboardRemove()
                    {
                    };
                }

                var messageSent = await bot.SendTextMessageAsync(telegramClientId, text, Telegram.Bot.Types.Enums.ParseMode.Markdown, false, false, 0, replyMarkup);

                if (string.IsNullOrWhiteSpace(userNameToHide) == false)
                {
                    text = text.Replace(userNameToHide, "[nome do usuário]");
                }

                await HubSendMessage(new MessageSystem("Sistema", text, DateTime.Now), false);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError($"{DateTime.Now} : {e.ToString()}");
                return(false);
            }
        }
        public async override Task ExecuteAsync(CommandContext context)
        {
            EnterMessage    = Localizer["RemoveBookshelfEnter"];
            NoExitstMessage = Localizer["RemoveBookshelfError"];
            ExistMessage    = Localizer["RemoveBookshelfSuccess"];

            Message = ExistMessage;
            IReplyMarkup keyboard = new ReplyKeyboardRemove();

            var bookshelf = context.SelectedBookshelf;

            if (bookshelf != null || InputData(context, out bookshelf))
            {
                if (bookshelf != null)
                {
                    context.RemoveBookshelf(bookshelf);
                    context.CommandName = null;

                    keyboard = CommandKeyboards.GetMainMenu(Localizer);
                }
                else
                {
                    context.CommandName = Name;
                }
            }
            await BotClient.SendTextMessageAsync(context.Message.Chat, Message, replyMarkup : keyboard);
        }
        public async override Task ExecuteAsync(CommandContext context)
        {
            EnterMessage    = Localizer["RemoveBookEnter"];
            NoExitstMessage = Localizer["RemoveBookError"];
            ExistMessage    = Localizer["RemoveBookSuccess"];

            Message = ExistMessage;
            IReplyMarkup keyboard = new ReplyKeyboardRemove();

            if (InputData(context, out Book book))
            {
                if (book != null)
                {
                    context.RemoveBook(book);
                    context.CommandName = null;

                    keyboard = CommandKeyboards.GetBookMenu(Localizer);
                }
                else
                {
                    context.CommandName = Name;
                }
            }
            await BotClient.SendTextMessageAsync(context.Message.Chat, Message, replyMarkup : keyboard);
        }
        public async override Task ExecuteAsync(CommandContext context)
        {
            string       message  = Localizer["EditBookshelfEnter"];
            IReplyMarkup keyboard = CommandKeyboards.GetMainMenu(Localizer);

            if (context.SelectedBookshelf == null || CheckParameters(context))
            {
                context.SelectedBookshelf = FindItem(context);
                if (context.SelectedBookshelf == null)
                {
                    message = Localizer["EditBookshelfNoExist"];
                }
            }
            else if (context.Data != null && context.SelectedBookshelf != null)
            {
                if (!context.Bookshelves.Any(b => b.Name == context.Data))
                {
                    context.SelectedBookshelf.Name = context.Data;
                    context.SelectedBookshelf      = null;

                    message = Localizer["EditBookshelfSuccess"];
                }
                else
                {
                    message = Localizer["EditBookshelfErrorName"];
                }
            }

            if (message == Localizer["EditBookshelfEnter"])
            {
                keyboard = new ReplyKeyboardRemove();
            }

            await BotClient.SendTextMessageAsync(context.Message.Chat, message, replyMarkup : keyboard);
        }
Beispiel #12
0
        public Keyboard(int messageId)
        {
            using (BotDB db = new BotDB())
            {
                Logger.Wright("Тип клавиатуры: " + db.Messages.Find(messageId).KType, "Keyboard", LogLevel.Info);

                switch (db.Messages.Find(messageId).KType)
                {
                case MessageKeyboardType.none:
                    Remove = new ReplyKeyboardRemove
                    {
                        RemoveKeyboard = true
                    };

                    break;

                case MessageKeyboardType.Reply:
                    Reply = new ReplyKeyboardMarkup();

                    Message  message = db.Messages.Find(messageId);
                    Button[] btns    = db.Buttons.Where <Button>(b => b.MessageId == messageId).ToArray <Button>();

                    Logger.Wright("Количество кнопок: " + btns.Length, "ReplyKeyboard", LogLevel.Info);

                    int rows = (int)Math.Ceiling((Decimal)btns.Length / 2);

                    Reply.ResizeKeyboard  = true;
                    Reply.OneTimeKeyboard = true;
                    Reply.Keyboard        = new Telegram.Bot.Types.KeyboardButton[rows][];
                    int n = 0;

                    for (int r = 0; r < rows && n < btns.Length; r++)
                    {
                        int columns = 2;
                        if ((btns.Length - n) == 1)
                        {
                            columns = 1;
                        }

                        Reply.Keyboard[r] = new Telegram.Bot.Types.KeyboardButton[columns];

                        for (int c = 0; c < columns && n < btns.Length; c++, n++)
                        {
                            Reply.Keyboard[r][c] = new Telegram.Bot.Types.KeyboardButton(btns[n].Text)
                            {
                                RequestContact  = btns[n].Contact,
                                RequestLocation = btns[n].Location
                            };
                        }
                    }

                    break;

                case MessageKeyboardType.Inline:
                    break;
                }
            }
        }
Beispiel #13
0
        IMenuAudioReplyMarkup IKeyboardBuilder <IMenuAudioReplyMarkup> .Remove(bool selective)
        {
            var keyboard = new ReplyKeyboardRemove
            {
                Selective = selective
            };

            ReplyMarkup = keyboard;
            return(this);
        }
Beispiel #14
0
        public async override Task ExecuteAsync(CommandContext context)
        {
            EnterMessage    = Localizer["AddBookEnter"];
            NoExitstMessage = Localizer["AddBookSuccess"];
            ExistMessage    = Localizer["AddBookError"];

            IReplyMarkup keyboard = new ReplyKeyboardRemove();

            if (InputData(context, out Book book))
            {
                if (book == null)
                {
                    string title = context.Parameters ?? context.Data;

                    var bookAccessor = new BookDAO();

                    if (context.PreviousCommand == Alias[0])
                    {
                        book = await bookAccessor.GetBookAsync(title);
                    }

                    if (book == null)
                    {
                        book = new Book {
                            Title = title
                        };
                        if (context.PreviousCommand == Alias[0])
                        {
                            await BotClient.SendTextMessageAsync(context.Message.Chat, Localizer["AddBookSearchError"]);
                        }
                    }
                    else if (context.PreviousCommand == Alias[0])
                    {
                        await BotClient.SendTextMessageAsync(context.Message.Chat, Localizer["AddBookSearchSuccess"]);
                    }

                    book.Bookshelf = context.SelectedBookshelf;

                    context.AddBook(book);
                    context.CommandName = null;

                    keyboard = CommandKeyboards.GetBookMenu(Localizer);

                    context.RedirectToCommand("/select", book.Title);
                }
                else
                {
                    context.CommandName = Name;
                }
            }
            await BotClient.SendTextMessageAsync(context.Message.Chat, Message, replyMarkup : keyboard);
        }
Beispiel #15
0
        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }

            IReplyMarkup keyboard = new ReplyKeyboardRemove();

            switch (message.Text.Split(' ').First())
            {
            case "/XYIsize":
                Random rnd  = new Random();
                int    size = rnd.Next(5, 15);
                int    ret  = 0;
                string msg  = "Размер вашего дружка: ";

                if (dickSizes.TryGetValue(message.From.Id, out ret))
                {
                    size = ret;
                    msg  = "А больше-то не вырастет :(\nРазмер вашего дружка: ";
                }
                else
                {
                    dickSizes.Add(message.From.Id, size);
                }

                await Bot.SendTextMessageAsync(
                    message.Chat.Id,
                    msg + size + " см",
                    replyMarkup : keyboard);

                break;

            default:
                const string usage = @"Usage:
/XYIsize  - узнать размер болта
";

                await Bot.SendTextMessageAsync(
                    message.Chat.Id,
                    usage,
                    replyMarkup : new ReplyKeyboardRemove());

                break;
            }
        }
Beispiel #16
0
        public void SendReplyKeyboardRemoveToGroupTest()
        {
            ReplyKeyboardRemove hideMarkup = new ReplyKeyboardRemove
            {
                Selective = false
            };

            SendMessageResult sendMessageToGroup      = mTelegramBot.SendMessage(mChatGroupId, "Goodbay", replyMarkup: hideMarkup);
            SendMessageResult sendMessageToSuperGroup = mTelegramBot.SendMessage(mChatSuperGroupId, "Goodbay", replyMarkup: hideMarkup);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessageToGroup.Ok);
                Assert.True(sendMessageToSuperGroup.Ok);
            });
        }
Beispiel #17
0
        static void MessageWithoutKeyboard(Message msg) //
        {
            var    keys = new ReplyKeyboardRemove();    // набор кнопок
            string res  = "Ответ";

            if (msg.Text == "Время")
            {
                res = DateTime.Now.ToString();
            }
            bot.SendTextMessageAsync(
                chatId: msg.Chat.Id, // пользователь которому отправляем сообщение
                text: $"{res}",      // выборка
                                     //text: $"Выбрано: {msg.Text}", // выборка
                replyMarkup: keys
                );
        }
Beispiel #18
0
        public override async Task Execute(AppUser user, EventArgs args, TelegramBotClient client)
        {
            MessageEventArgs telegramArgs = (MessageEventArgs)args;
            Message          message      = telegramArgs.Message;

            // Меняем стейт беседы у пользователя
            ChangeUserState(user, "transaction category");

            // Данный объект нужен для удаления текущих кнопок из чата с пользоателем
            var removeMarkup = new ReplyKeyboardRemove()
            {
            };

            // Отправляем ответное сообщение
            await client.SendTextMessageAsync(message.Chat.Id, $"Введите доход: ", replyMarkup : removeMarkup);
        }
Beispiel #19
0
        public override async Task <UpdateHandlingResult> HandleCommand(IBot bot, Update update, AuthCommandArgs args)
        {
            if (args.ArgsInput.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length != 1)
            {
                await bot.Client.SendTextMessageAsync(update.Message.Chat.Id,
                                                      $"`Формат команды: {Constants.CommandFormat}`", ParseMode.Markdown);

                return(UpdateHandlingResult.Handled);
            }

            var acessToken = args.ArgsInput;

            var botUser = _botUserRepository.GetByTelegramId(update.Message.Chat.Id);

            if (botUser == null)
            {
                botUser = new BotUser
                {
                    TelegramChatId = update.Message.Chat.Id,
                    TelegramUserId = update.Message.Chat.Id
                };
            }

            IReplyMarkup replyMarkup = new ReplyKeyboardRemove();

            try
            {
                var userInfo = botUser.AuthorizeVk(acessToken);
                await _notificationsService.EnableNotifications(botUser);

                _botUserRepository.Add(botUser);
                await bot.Client.SendTextMessageAsync(
                    update.Message.Chat.Id,
                    $"`Вы авторизованы как: {userInfo.FirstName} {userInfo.LastName}`",
                    ParseMode.Markdown,
                    replyMarkup : replyMarkup);
            }
            catch (Exception e)
            {
                await bot.Client.SendTextMessageAsync(update.Message.Chat.Id, e.Message);
            }

            return(UpdateHandlingResult.Handled);
        }
        public IActionResult GetMessage(MessageModel model)
        {
            var cid  = model.Id;
            var name = model.Username;
            var txt  = model.Text;

            if (txt == "/start" || txt == "Cancel")
            {
                SetUpStartKeyboard();

                var time = CheckTimeOfTheDay();

                var message = String.Format("Good {0} {1}, how can I help you today?", time, name);

                return(new JsonResult(message));
            }
            else if (txt == "General Reminder")
            {
                type            = "General Reminder";
                markup.Keyboard = new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("Cancel")
                    }
                };

                return(new JsonResult("ok"));
            }

            if (IsValidTime(model.Text))
            {
                ReplyKeyboardRemove remove = new ReplyKeyboardRemove()
                {
                    RemoveKeyboard = true
                };

                string message = String.Format("You are all set! \nReminding for: {0} \nTime: {1}:00", description, time);
                Console.WriteLine(message);
                return(new JsonResult("ok"));
            }

            return(new JsonResult("ok"));
        }
Beispiel #21
0
 internal static async Task <Message> SendAsync(string message, long id, bool clearKeyboard = false, InlineKeyboardMarkup customMenu = null, Game game = null)
 {
     if (clearKeyboard)
     {
         var menu = new ReplyKeyboardRemove()
         {
             RemoveKeyboard = true
         };
         return(await Api.SendTextMessageAsync(id, message, replyMarkup : menu, disableWebPagePreview : true, parseMode : ParseMode.Html));
     }
     else if (customMenu != null)
     {
         return(await Api.SendTextMessageAsync(id, message, replyMarkup : customMenu, disableWebPagePreview : true, parseMode : ParseMode.Html));
     }
     else
     {
         return(await Api.SendTextMessageAsync(id, message, disableWebPagePreview : true, parseMode : ParseMode.Html));
     }
 }
Beispiel #22
0
 internal static Task <Message> Send(string message, long id, bool clearKeyboard = false, InlineKeyboardMarkup customMenu = null, ParseMode parseMode = ParseMode.Html)
 {
     MessagesSent++;
     //message = message.Replace("`",@"\`");
     if (clearKeyboard)
     {
         var menu = new ReplyKeyboardRemove()
         {
             RemoveKeyboard = true
         };
         return(Api.SendTextMessageAsync(id, message, replyMarkup: menu, disableWebPagePreview: true, parseMode: parseMode));
     }
     else if (customMenu != null)
     {
         return(Api.SendTextMessageAsync(id, message, replyMarkup: customMenu, disableWebPagePreview: true, parseMode: parseMode));
     }
     else
     {
         return(Api.SendTextMessageAsync(id, message, disableWebPagePreview: true, parseMode: parseMode));
     }
 }
Beispiel #23
0
 IMenuAudioReplyMarkup IReplyMarkupable <IMenuAudioReplyMarkup> .ReplyMarkup(ReplyKeyboardRemove markup, bool selective)
 {
     ReplyMarkup = markup; return(this);
 }
Beispiel #24
0
        private async static void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            try
            {
                var text = e?.Message?.Text;
                if (text == null)
                {
                    return;
                }
                if (text.Contains("/start") || text.Contains("Отмена"))
                {
                    var keyboard = GetKeyboard(new List <string> {
                        "Подобрать"
                    });
                    await BotClient.SendTextMessageAsync(e.Message.Chat, "Здравстуйте, подберите авто", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);

                    var user = new User {
                        Id = e.Message.From.Id, Username = e.Message.From.Username, Status = Status.Started
                    };
                    lock (locker)
                    {
                        var baseuser = Users.FirstOrDefault(x => x.Id == user.Id);
                        if (baseuser != null)
                        {
                            Users.Remove(baseuser);
                        }
                        Users.Add(user);
                    }
                }
                else
                {
                    if (Users.Any(x => x.Id == e.Message.From.Id))
                    {
                        var user = Users.First(x => x.Id == e.Message.From.Id);
                        if (user.Status == Status.Started)
                        {
                            var keyboard = GetKeyboard(new List <string> {
                                "7000 - 10 000$", "10 000 - 15000$", "15 000 - 20 000$", "20 000$+"
                            });
                            await BotClient.SendTextMessageAsync(e.Message.Chat, "Пожалуйста, выберите пункт из меню ниже", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);

                            lock (locker)
                                Users.FirstOrDefault(x => x.Id == user.Id).Status = Status.WaitMoney;
                            return;
                        }
                        if (user.Status == Status.WaitMoney)
                        {
                            var RemoveKeyboard = new ReplyKeyboardRemove();
                            var msg            = await BotClient.SendTextMessageAsync(e.Message.Chat, "Отлично! Теперь напишите модель автомобиля🚘", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, RemoveKeyboard);

                            lock (locker)
                            {
                                user.Money  = text;
                                user.Status = Status.WaitForCarModel;
                            }
                            return;
                        }
                        if (user.Status == Status.WaitForCarModel)
                        {
                            lock (locker)
                            {
                                user.Car    = text;
                                user.Status = Status.WaitMethod;
                            }
                            var keyboard = GetKeyboard(new List <string> {
                                "Напишите мне", "Позвоните мне"
                            });
                            await BotClient.SendTextMessageAsync(e.Message.Chat, "Очень хороший выбор, у вас есть вкус👍 Как бы вы хотели получить ответ?", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);

                            return;
                        }
                        if (user.Status == Status.WaitMethod)
                        {
                            if (text == "Напишите мне")
                            {
                                lock (locker)
                                {
                                    user.Status        = Status.WaitForPhoneNumber;
                                    user.ConnectMethod = "Написать";
                                }
                                await BotClient.SendTextMessageAsync(e.Message.Chat, "Тогда оставьте свои контакты и наши эксперты свяжуться с вами в  ближайшее время😊");
                            }
                            if (text == "Позвоните мне")
                            {
                                lock (locker)
                                {
                                    user.Status        = Status.WaitForPhoneNumber;
                                    user.ConnectMethod = "Позвонить";
                                }
                                await BotClient.SendTextMessageAsync(e.Message.Chat, "Тогда оставьте свои контакты и наши эксперты свяжуться с вами в  ближайшее время😊");
                            }
                            return;
                        }
                        if (user.Status == Status.WaitForPhoneNumber)
                        {
                            //Users.Find(x => x.Id == user.Id).Phone = text;
                            lock (locker)
                            {
                                user        = Users.FirstOrDefault(x => x.Id == user.Id);
                                user.Phone  = text;
                                user.Status = Status.ready;
                            }
                            if (user != null)
                            {
                                Mail.send("Клиент из бота", user.GetString());
                            }
                            //TODO отправляем письмо
                            var RemoveKeyboard = new ReplyKeyboardRemove();
                            await BotClient.SendTextMessageAsync(e.Message.Chat, "Спасибо, с Вами свяжутся в ближайшие время. Хорошего Вам дня👍", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, RemoveKeyboard);

                            return;
                        }
                    }
                }
            }
            catch (Exception)
            {
                Reboot();
            }
        }
        public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
        {
            var userchat = context.Update.ToUserchat();

            var cachedCtx = await GetCachedContextsAsync(context, userchat, cancellationToken)
                            .ConfigureAwait(false);

            if (cachedCtx.Bus != null && cachedCtx.Location != null)
            {
                _logger.LogTrace("Bus route and location is provided. Sending bus predictions.");

                var busStop = await _predictionsService.FindClosestBusStopAsync(
                    cachedCtx.Profile.DefaultAgencyTag,
                    cachedCtx.Bus.RouteTag,
                    cachedCtx.Bus.DirectionTag,
                    cachedCtx.Location.Longitude,
                    cachedCtx.Location.Latitude,
                    cancellationToken
                    ).ConfigureAwait(false);

                var predictions = await _predictionsService.GetPredictionsAsync(
                    cachedCtx.Profile.DefaultAgencyTag,
                    cachedCtx.Bus.RouteTag,
                    busStop.Tag,
                    cancellationToken
                    ).ConfigureAwait(false);

                IReplyMarkup locationReplyMarkup;
                if (string.IsNullOrWhiteSpace(cachedCtx.Bus.Origin))
                {
                    locationReplyMarkup = new ReplyKeyboardRemove();
                }
                else
                {
                    locationReplyMarkup = new InlineKeyboardMarkup(
                        InlineKeyboardButton.WithCallbackData("🚩 Remember this location", "loc/save")
                        );
                }

                await context.Bot.Client.MakeRequestWithRetryAsync(
                    new SendLocationRequest(userchat.ChatId, busStop.Latitude, busStop.Longitude)
                {
                    ReplyToMessageId = cachedCtx.Location.LocationMessageId,
                    ReplyMarkup      = locationReplyMarkup,
                },
                    cancellationToken
                    ).ConfigureAwait(false);

                string text = "👆 That's the nearest bus stop";
                if (!string.IsNullOrWhiteSpace(busStop.Title))
                {
                    text += $", *{busStop.Title}*";
                }
                text += " 🚏.";

                string message = RouteMessageFormatter.FormatBusPredictionsReplyText(predictions.Predictions);
                text += "\n\n" + message;

                var predictionsMessage = await context.Bot.Client.MakeRequestWithRetryAsync(
                    new SendMessageRequest(userchat.ChatId, text)
                {
                    ParseMode   = ParseMode.Markdown,
                    ReplyMarkup = (InlineKeyboardMarkup)InlineKeyboardButton.WithCallbackData("Update", "pred/"),
                },
                    cancellationToken
                    ).ConfigureAwait(false);

                var prediction = new BusPrediction
                {
                    AgencyTag    = cachedCtx.Profile.DefaultAgencyTag,
                    RouteTag     = cachedCtx.Bus.RouteTag,
                    DirectionTag = cachedCtx.Bus.DirectionTag,
                    BusStopTag   = busStop.Tag,
                    Origin       = cachedCtx.Bus.Origin,
                    UserLocation = new GeoJsonPoint <GeoJson2DCoordinates>(
                        new GeoJson2DCoordinates(cachedCtx.Location.Longitude, cachedCtx.Location.Latitude)),
                };

                await _predictionRepo.AddAsync(cachedCtx.Profile.Id, prediction, cancellationToken)
                .ConfigureAwait(false);

                await context.Bot.Client.MakeRequestWithRetryAsync(
                    new EditMessageReplyMarkupRequest(
                        predictionsMessage.Chat,
                        predictionsMessage.MessageId,
                        InlineKeyboardButton.WithCallbackData("Update", $"pred/id:{prediction.Id}")
                        ), cancellationToken
                    ).ConfigureAwait(false);
            }
            else if (cachedCtx.Bus != null)
            {
                _logger.LogTrace("Location is missing. Asking user to send his location.");

                var route = await _routeRepo.GetByTagAsync(
                    cachedCtx.Profile.DefaultAgencyTag,
                    cachedCtx.Bus.RouteTag,
                    cancellationToken
                    ).ConfigureAwait(false);

                var direction = route.Directions.Single(d => d.Tag == cachedCtx.Bus.DirectionTag);

                string text = _routeMessageFormatter.GetMessageTextForRouteDirection(route, direction);

                text += "\n\n*Send your current location* so I can find you the nearest bus stop 🚏 " +
                        "and get the bus predictions for it.";
                int replyToMessage = context.Update.Message?.MessageId
                                     ?? context.Update.CallbackQuery?.Message?.MessageId
                                     ?? 0;
                await context.Bot.Client.MakeRequestWithRetryAsync(
                    new SendMessageRequest(userchat.ChatId, text)
                {
                    ParseMode        = ParseMode.Markdown,
                    ReplyToMessageId = replyToMessage,
                    ReplyMarkup      = new ReplyKeyboardMarkup(new[]
                    {
                        KeyboardButton.WithRequestLocation("Share my location")
                    }, true, true)
                },
                    cancellationToken
                    ).ConfigureAwait(false);
            }
            else if (cachedCtx.Location != null)
            {
                _logger.LogTrace("Bus route and direction are missing. Asking user to provide them.");

                await context.Bot.Client.MakeRequestWithRetryAsync(
                    new SendMessageRequest(
                        userchat.ChatId,
                        "There you are! What's the bus you want to catch?\n" +
                        "Send me using 👉 /bus command."
                        )
                {
                    ReplyToMessageId = context.Update.Message.MessageId,
                    ReplyMarkup      = new ReplyKeyboardRemove()
                },
                    cancellationToken
                    ).ConfigureAwait(false);
            }

            // ToDo: Remove keyboard if that was set in /bus command
//
//            var userchat = context.Update.ToUserchat();
//
//            if (context.Update.Message?.Location != null)
//            {
//                await HandleLocationUpdateAsync(
//                    context.Bot,
//                    userchat,
//                    context.Update.Message.Location,
//                    context.Update.Message.MessageId,
//                    cancellationToken
//                ).ConfigureAwait(false);
//            }
//            else if (context.Update.Message?.Text != null)
//            {
//                _logger.LogTrace("Checking if this text message has location coordinates.");
//
//                var result = _locationService.TryParseLocation(context.Update.Message.Text);
//                if (result.Successful)
//                {
//                    _logger.LogTrace("Location is shared from text");
//                    await HandleLocationUpdateAsync(
//                        context.Bot,
//                        userchat,
//                        new Location { Latitude = result.Lat, Longitude = result.Lon },
//                        context.Update.Message.MessageId,
//                        cancellationToken
//                    ).ConfigureAwait(false);
//                }
//                else
//                {
//                    _logger.LogTrace("Message text does not have a location. Ignoring the update.");
//                }
//            }
//
//            var locationTuple = _locationsManager.TryParseLocation(context.Update);
//
//            if (locationTuple.Successful)
//            {
//                _locationsManager.AddLocationToCache(userchat, locationTuple.Location);
//
//                await _predictionsManager
//                    .TryReplyWithPredictionsAsync(context.Bot, userchat, context.Update.Message.MessageId)
//                    .ConfigureAwait(false);
//            }
//            else
//            {
//                // todo : if saved location available, offer it as keyboard
//                await context.Bot.Client.SendTextMessageAsync(
//                    context.Update.Message.Chat.Id,
//                    "_Invalid location!_",
//                    ParseMode.Markdown,
//                    replyToMessageId: context.Update.Message.MessageId
//                ).ConfigureAwait(false);
//            }
        }
Beispiel #26
0
        public static async Task Bot_Messages(Telegram.Bot.Types.Update e, object sender, Post el)
        {
            const string Init = "Привет!\nЭтот бот обрабатывает анкеты для HR агенства\n" +
                                "Horizon Recruiting.\n Если вы хотите оставить анкету введите \"Да\"  ";

            string Instructions = "Введите  свою  информацию согласно форме:"
                                  + el.Resume.Make_Resume();
            const string I2_1         = "ФИО Кандидата: ";
            const string I2_2         = "Номер телефона: ";
            const string I2_3         = "Возраст: ";
            const string I2_4         = "Город проживания: ";
            const string I2_5         = "Стаж по правам: ";
            const string I2_6         = "Стаж в такси: ";
            const string I2_7         = "Есть ли аккаунт UBER: ";
            const string I2_8         = "Судимости: ";
            const string I2_9         = "ДТП: ";
            const string I2_11        = "Ваш агент: ";
            const string I2_12        = "Время и дата собеседования: ";
            const string I2_13        = "Ваше имя и фамилия: ";
            const string I2_14        = "Партнер, к которому записан кандидат: ";
            const string Confirmation = "Подтверждаете заполнение?";  // Не участвует  в  логе
            const string Code_Bye     = "Спасибо, Ваша анкета принята";
            const string Instruction  = "Как пользоваться ботом?\n1.Нажмите кнопку 'Заполнить анкету'\n2.Ознакомтесь со списком формы и нажмите кнопку 'Подтверждение'\n3.По порядку заполните анкету(Напишите в ответ нужную информацию)\n4.Проверьте правильность заполнения, если всё соответсвует, нажмите 'Отправить анкету', если в какой то строке есть неточности, нажмите 'Откорректировать', и откорректируйте тот пункт, где вы допустили ошибку\n5.Если вы передумали отправлять анкету, нажмите 'Не оставлять анкету'\n6.Если хотите ввести заново, нажмите 'Перезапустить заполнение'  ";


            if (el.Codes.Count > 1)
            {
                bool Txt_Chk = el.Codes.Peek() == 11 || el.Codes.Peek() == 100 || el.Codes.Peek() == 10;
                bool edit    = (el.Codes.ElementAt(1) == 31 || el.Codes.ElementAt(1) == 32 || el.Codes.ElementAt(1) == 33 || el.Codes.ElementAt(1) == 34 || el.Codes.ElementAt(1) == 35 || el.Codes.ElementAt(1) == 36 || el.Codes.ElementAt(1) == 37 || el.Codes.ElementAt(1) == 38 || el.Codes.ElementAt(1) == 39 || el.Codes.ElementAt(1) == 40 || el.Codes.ElementAt(1) == 41 || el.Codes.ElementAt(1) == 42 || el.Codes.ElementAt(1) == 43);

                if (el.Codes.Peek() == 11 && (el.Codes.ElementAt(1) == 0))
                {
                    var kbq = new ReplyKeyboardMarkup

                    {
                        Keyboard = new[]  {
                            new[] {
                                new KeyboardButton("Заполнить анкету"),
                                new KeyboardButton("Инструкции")
                            }
                        },
                        ResizeKeyboard = true
                    };

                    el.Codes.Push(1);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Init, ParseMode.Html, false, false, 0, kbq);
                }
                else if (el.Codes.Peek() == 13)
                {
                    var kbd = new ReplyKeyboardMarkup

                    {
                        Keyboard = new[]  {
                            new[] {
                                new KeyboardButton("Заполнить анкету"),
                                new KeyboardButton("Вернуться назад")
                            }
                        },
                        ResizeKeyboard = true
                    };

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Instruction, ParseMode.Html, false, false, 0, kbd);
                }

                else if (el.Codes.Peek() == 11 && (el.Codes.ElementAt(1) == 1) || (el.Codes.Peek() == 11 && (el.Codes.ElementAt(1) == 13)))
                {
                    el.Codes.Push(2);
                    var kbd = new ReplyKeyboardMarkup
                    {
                        Keyboard = new[] {
                            new[] {
                                new KeyboardButton("Подтверждение")
                            },
                            new[] {
                                new KeyboardButton("Не оставлять анкету")
                            }
                        },
                        ResizeKeyboard = true
                    };
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Instructions);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Confirmation, ParseMode.Html, false, false, 0, kbd);
                }

                else if (el.Codes.Peek() == 11 && (el.Codes.ElementAt(1) == 2))
                {
                    el.Codes.Push(2.1);
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_1, ParseMode.Default, false, false, 0, keyboardRemove);
                }

                else if (el.Codes.Peek() == 100 && (el.Codes.ElementAt(1) == 2.1))
                {
                    el.Resume.F2_1 += e.Message.Text;
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_2);

                    el.Codes.Push(2.2);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.2))
                {
                    el.Resume.F2_2 += e.Message.Text;

                    el.Codes.Push(2.3);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_3);
                }
                else if (el.Codes.Peek() == 100 && (el.Codes.ElementAt(1) == 2.3))
                {
                    el.Resume.F2_3 += e.Message.Text;

                    el.Codes.Push(2.4);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_4);
                }
                else if (el.Codes.Peek() == 100 && (el.Codes.ElementAt(1) == 2.4))
                {
                    el.Resume.F2_4 += e.Message.Text;

                    el.Codes.Push(2.5);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_5);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.5))
                {
                    el.Resume.F2_5 += e.Message.Text;

                    el.Codes.Push(2.6);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_6);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.6))
                {
                    el.Resume.F2_6 += e.Message.Text;

                    el.Codes.Push(2.7);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_7);
                }

                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.7))
                {
                    el.Resume.F2_7 += e.Message.Text;

                    el.Codes.Push(2.8);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_8);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.8))
                {
                    el.Resume.F2_8 += e.Message.Text;

                    el.Codes.Push(2.9);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_9);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.9))
                {
                    el.Resume.F2_9 += e.Message.Text;

                    el.Codes.Push(2.11);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_11);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.11))
                {
                    el.Resume.F2_11 += e.Message.Text;

                    el.Codes.Push(2.12);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_12);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.12))
                {
                    el.Resume.F2_12 += e.Message.Text;
                    el.Codes.Push(2.13);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_13);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.13))
                {
                    el.Resume.F2_13 += e.Message.Text;
                    el.Codes.Push(2.14);
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, I2_14);
                }
                else if (Txt_Chk && (el.Codes.ElementAt(1) == 2.14))
                {
                    el.Resume.F2_14 += e.Message.Text;

                    el.Codes.Push(3);
                    el.Codes.Push(3);

                    await Bot_Messages(e, sender, el);
                }
                else if ((el.Codes.Peek() == 3 && (el.Codes.ElementAt(1) == 3)) || (Txt_Chk && edit))
                {
                    if (Txt_Chk && edit)
                    {
                        switch (el.Codes.ElementAt(1))
                        {
                        case 31:
                            el.Resume.F2_1 = el.Resume.F3_1 + e.Message.Text;
                            break;

                        case 32:
                            el.Resume.F2_2 = el.Resume.F3_2 + e.Message.Text;
                            break;

                        case 33:
                            el.Resume.F2_3 = el.Resume.F3_3 + e.Message.Text;
                            break;

                        case 34:
                            el.Resume.F2_4 = el.Resume.F3_4 + e.Message.Text;
                            break;

                        case 35:
                            el.Resume.F2_5 = el.Resume.F3_5 + e.Message.Text;
                            break;

                        case 36:
                            el.Resume.F2_6 = el.Resume.F3_6 + e.Message.Text;
                            break;

                        case 37:
                            el.Resume.F2_7 = el.Resume.F3_7 + e.Message.Text;
                            break;

                        case 38:
                            el.Resume.F2_8 = el.Resume.F3_8 + e.Message.Text;
                            break;

                        case 39:
                            el.Resume.F2_9 = el.Resume.F3_9 + e.Message.Text;
                            break;

                        case 40:
                            el.Resume.F2_11 = el.Resume.F3_11 + e.Message.Text;
                            break;

                        case 41:
                            el.Resume.F2_12 = el.Resume.F3_12 + e.Message.Text;
                            break;

                        case 42:
                            el.Resume.F2_13 = el.Resume.F3_13 + e.Message.Text;
                            break;

                        case 43:
                            el.Resume.F2_14 = el.Resume.F3_14 + e.Message.Text;
                            break;
                        }
                    }

                    var kbd = new ReplyKeyboardMarkup
                    {
                        Keyboard = new[] {
                            new[] {
                                new KeyboardButton("Отправить анкету"),
                                new KeyboardButton("Откорректировать")
                            },
                            new[] {
                                new KeyboardButton("Не оставлять анкету"),
                                new KeyboardButton("Перезапустить заполнение")
                            }
                        },
                        ResizeKeyboard = true
                    };
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, el.Resume.Make_Resume());

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Confirmation, ParseMode.Html, false, false, 0, kbd);
                }

                else if (el.Codes.Peek() == 200 && (el.Codes.ElementAt(1) == 200))
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, Code_Bye, ParseMode.Html, false, false, 0, keyboardRemove);

                    Console.WriteLine("Sended Resume!");

                    string CV = el.Resume.Make_Resume();

                    Console.WriteLine("\nRESUME:\n" + CV);
                    await Bot.SendTextMessageAsync(Channel_ID, CV);

                    el.Codes.Clear();
                    el.Resume = new Resume();

                    el.Codes.Push(99);
                    await Bot_Messages(e, sender, el);
                }

                else if (el.Codes.Peek() == 21) // 300 is edited  markup
                {
                    var kbd = new ReplyKeyboardMarkup
                    {
                        Keyboard = new[] {
                            new[] {
                                new KeyboardButton("1)ФИО Кандидата"),
                                new KeyboardButton("2)Номер телефона"),
                                new KeyboardButton("3)Возраст")
                            },
                            new[] {
                                new KeyboardButton("4)Город проживания"),
                                new KeyboardButton("5)Стаж по правам"),
                                new KeyboardButton("6)Стаж в такси")
                            },
                            new[] {
                                new KeyboardButton("7)Есть ли аккаунт UBER"),
                                new KeyboardButton("8)Судимости"),
                                new KeyboardButton("9)ДТП")
                            },
                            new[] {
                                new KeyboardButton("10)Ваш агент"),
                                new KeyboardButton("11)Время и дата собеседования"),
                                new KeyboardButton("12)Ваше Имя и Фамилия"),
                            },
                            new[] {
                                new KeyboardButton("13)Партнер")
                            }
                        },
                        ResizeKeyboard = true
                    };

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Выберите что отредактировать", ParseMode.Html, false, false, 0, kbd);
                }

                else if (el.Codes.Peek() == 31)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старое " + el.Resume.F2_1, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новое ФИО:");
                }
                else if (el.Codes.Peek() == 32)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_2, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый номер телефона:");
                }
                else if (el.Codes.Peek() == 33)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_3, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый Возраст:");
                }
                else if (el.Codes.Peek() == 34)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_4, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый Город проживания:");
                }
                else if (el.Codes.Peek() == 35)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_5, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый Стаж по правам:");
                }
                else if (el.Codes.Peek() == 36)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_6, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый Стаж в такси:");
                }
                else if (el.Codes.Peek() == 37)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, el.Resume.F2_7, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый статус: ");
                }
                else if (el.Codes.Peek() == 38)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, el.Resume.F2_8, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый статус: ");
                }
                else if (el.Codes.Peek() == 39)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, el.Resume.F2_9, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новый статус: ");
                }
                else if (el.Codes.Peek() == 40)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старая информация: " + el.Resume.F2_11, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите Вашего агента: ");
                }
                else if (el.Codes.Peek() == 41)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старая: " + el.Resume.F2_12, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новую дату:");
                }
                else if (el.Codes.Peek() == 42)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старая информация: " + el.Resume.F2_13, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите новую: ");
                }
                else if (el.Codes.Peek() == 43)
                {
                    ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Старый " + el.Resume.F2_14, ParseMode.Html, false, false, 0, keyboardRemove);

                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введите нового партнера:");
                }

                else if (el.Codes.Peek() == 20)
                {
                    el.Codes.Push(1);
                    el.Codes.Push(11);
                    el.Resume = new Resume();
                    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Перезапуск...");
                    await Bot_Messages(e, sender, el);
                }

                else if (el.Codes.Peek() == 99)
                {
                    el.Codes.Clear();
                    el.Resume = new Resume();
                    await Bot_Messages(e, sender, el);
                }
                else if (el.Codes.Peek() == 13)
                {
                }
                else
                {
                    el.Codes.Pop();
                    el.Codes.Pop();
                    await Bot_Messages(e, sender, el);
                }
            }

            else if (el.Codes.Count() == 0)
            {
                el.Codes.Push(0);
                el.Codes.Push(11);
                await Bot_Messages(e, sender, el);
            }
            else if (el.Codes.Peek() != 0)
            {
                el.Codes.Pop();
                el.Codes.Push(0);
                el.Codes.Push(11);
                await Bot_Messages(e, sender, el);
            }
            else
            {
                await Bot.SendTextMessageAsync(e.Message.Chat.Id, Init);

                await Bot.SendTextMessageAsync(e.Message.Chat.Id, Confirmation);
            }
        }
 public TelegramReplyMessage(Message message)
 {
     Id       = message.From.Id;
     Text     = message.Text;
     Keyboard = new ReplyKeyboardRemove();
 }
        private static async void OnMessage(object sender, MessageEventArgs e)
        {
            var mensagem = e.Message;

            //verifica se a mensagem é texto
            if (mensagem == null || mensagem.Type != MessageType.TextMessage)
            {
                return;
            }

            Usuario Usuario;

            if (Usuarios.FirstOrDefault(u => u.Chat == mensagem.Chat.Id) == null)
            {
                Usuarios.Add(new Usuario(mensagem.Chat.FirstName, mensagem.Chat.Id, new Fluxo()));
                Usuario = Usuarios.FirstOrDefault(u => u.Chat == mensagem.Chat.Id);
            }
            else
            {
                Usuario = Usuarios.FirstOrDefault(u => u.Chat == mensagem.Chat.Id);
                Usuario.Fluxo.MudarPasso(Usuario.Fluxo.Atual, mensagem.Text.Split(' ').First());
            }

            var fluxoAux = Usuario.Fluxo.Atual;

            if (fluxoAux.Nome == "Fim")
            {
                Usuarios.Remove(Usuario);
            }

            dynamic rkm = new ReplyKeyboardMarkup();


            if (fluxoAux.Opcoes.Count > 0)
            {
                rkm = new ReplyKeyboardMarkup();

                var rows = new List <KeyboardButton[]>();
                var cols = new List <KeyboardButton>();
                for (var Index = 0; Index < fluxoAux.Opcoes.Count; Index++)
                {
                    cols.Add(new KeyboardButton("" + fluxoAux.Opcoes[Index].Nome));
                    //if (Index % 4 != 0) continue;
                    rows.Add(cols.ToArray());
                    cols = new List <KeyboardButton>();
                }
                rkm.Keyboard = rows.ToArray();
            }
            else
            {
                rkm = new ReplyKeyboardRemove();
            }

            var aux = fluxoAux.Pergunta.Split('|');

            if (aux.Count() > 1)
            {
                OpcoesAtividade = fluxoAux.Opcoes;
                TimerIDs.Remove(e.Message.Chat.Id);
                TimerIDs.Add(e.Message.Chat.Id, DateTime.Now);
                var imagem  = aux[1];
                var FileUrl = Directory.GetCurrentDirectory() + @"\..\..\imagens\" + imagem.Replace("\r\n", "");
                using (var stream = System.IO.File.Open(FileUrl, FileMode.Open))
                {
                    FileToSend fts = new FileToSend();
                    fts.Content  = stream;
                    fts.Filename = FileUrl.Split('\\').Last();
                    var test = await Bot.SendPhotoAsync(mensagem.Chat.Id, fts, fluxoAux.Pergunta.Split('|')[0],
                                                        replyMarkup : rkm);
                }
            }
            else
            {
                TimerIDs.Remove(e.Message.Chat.Id);
                string msg = fluxoAux.Pergunta;

                msg = msg.Replace("{{usuario}}", Usuario.Nome);


                await Bot.SendTextMessageAsync(
                    mensagem.Chat.Id,
                    msg,
                    replyMarkup : rkm);
            }
        }
        private static async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            var txt  = e.Message.Text;
            var cid  = e.Message.Chat.Id;
            var name = e.Message.From.FirstName + " " + e.Message.From.LastName;
            var uid  = e.Message.From.Id;

            if (txt == "/start" || txt == "Cancel")
            {
                SetUpStartKeyboard();

                var time = CheckTimeOfTheDay();

                var message = String.Format("Good {0} {1}, how can I help you today?", time, name);

                await Bot.SendTextMessageAsync(cid, message, ParseMode.Default, false, false, 0, markup);
            }
            else if (txt == "General Reminder")
            {
                type            = "General Reminder";
                markup.Keyboard = new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("Cancel")
                    }
                };

                await Bot.SendTextMessageAsync(cid, "Please enter the description for your reminder.", ParseMode.Default, false, false, 0, markup);
            }
            else if (e.Message.Type == MessageType.TextMessage && !IsValidTime(e.Message.Text))
            {
                long hour = GetCurrentDatetime();
                description     = e.Message.Text;
                time            = hour;
                markup.Keyboard = new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton(String.Format("{0}:00", hour)),
                        new KeyboardButton(String.Format("{0}:00", hour + 1))
                    },
                    new KeyboardButton[]
                    {
                        new KeyboardButton(String.Format("{0}:00", hour + 2)),
                        new KeyboardButton(String.Format("{0}:00", hour + 3))
                    }
                };

                await Bot.SendTextMessageAsync(cid, "Please choose a time for your reminder.", ParseMode.Default, false, false, 0, markup);
            }

            if (IsValidTime(e.Message.Text))
            {
                ReplyKeyboardRemove remove = new ReplyKeyboardRemove()
                {
                    RemoveKeyboard = true
                };

                string message = String.Format("You are all set! \nReminding for: {0} \nTime: {1}:00", description, time);
                Console.WriteLine(message);
                await Bot.SendTextMessageAsync(cid, message, ParseMode.Default, false, false, 0, remove);
            }

            if (e.Message.Type == MessageType.TextMessage)
            {
                Console.WriteLine(e.Message.Text);
            }
        }
        internal void Processar(int id, User from, Chat chat, string text)
        {
            Usuario Usuario;

            if (Usuarios.FirstOrDefault(u => u.Chat == id) == null)
            {
                Usuarios.Add(new Usuario(from.FirstName, id, _fluxoAppService.NovoFlux()));
                Usuario = Usuarios.FirstOrDefault(u => u.Chat == id);
            }
            else
            {
                Usuario = Usuarios.FirstOrDefault(u => u.Chat == id);
                // FluxoAppService FServ = new FluxoAppService(_atividadeAppService, _aparelhoAppService);
                Usuario.Fluxo.Atual = _fluxoAppService.MudarPasso(Usuario.Fluxo.Atual, text.Split(' ').First());
            }

            var fluxoAux = Usuario.Fluxo.Atual;

            if (fluxoAux.Nome == "Fim")
            {
                Usuarios.Remove(Usuario);
            }

            dynamic rkm = new ReplyKeyboardMarkup();

            if (fluxoAux.Opcoes.Count > 0)
            {
                rkm = new ReplyKeyboardMarkup();

                var rows = new List <KeyboardButton[]>();
                var cols = new List <KeyboardButton>();
                for (var Index = 0; Index < fluxoAux.Opcoes.Count; Index++)
                {
                    cols.Add(new KeyboardButton("" + fluxoAux.Opcoes[Index].Nome));
                    //if (Index % 4 != 0) continue;
                    rows.Add(cols.ToArray());
                    cols = new List <KeyboardButton>();
                }
                rkm.Keyboard = rows.ToArray();
            }
            else
            {
                rkm = new ReplyKeyboardRemove();
            }

            var aux = fluxoAux.Pergunta.Split('|');

            if (aux.Count() > 1)
            {
                OpcoesAtividade = fluxoAux.Opcoes;
                TimerIDs.Remove(id);
                TimerIDs.Add(id, DateTime.Now);
                var imagem  = aux[1];
                var FileUrl = Directory.GetCurrentDirectory() + @"\..\..\imagens\" + imagem.Replace("\r\n", "");

                using (var stream = System.IO.File.Open(FileUrl, FileMode.Open))
                {
                    FileToSend fts = new FileToSend();
                    fts.Content  = stream;
                    fts.Filename = FileUrl.Split('\\').Last();
                    var test = Bot.Api.SendPhotoAsync(id, fts, fluxoAux.Pergunta.Split('|')[0],
                                                      replyMarkup: rkm).GetAwaiter().GetResult();
                }
            }
            else
            {
                TimerIDs.Remove(id);
                string msg = fluxoAux.Pergunta;

                msg = msg.Replace("{{usuario}}", Usuario.Nome);

                Bot.Api.SendTextMessageAsync(
                    id,
                    msg,
                    replyMarkup: rkm);
            }
        }