private async static void Bot_OnMessage(object sender, MessageEventArgs e) { var msg = e.Message; if (msg.Text == "/start") { string texto = $"🙋♂️ Olá *{msg.Chat.FirstName} {msg.Chat.LastName}*. O texto que você enviar será retornado pelo Bot. " + $"Você pode compartilhar a sua *localização* ou o seu *contato*, basta pressionar os botões abaixo."; var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("📍 Localização"), KeyboardButton.WithRequestContact("👤 Contato"), }); await bot.SendTextMessageAsync( chatId : msg.Chat.Id, text : texto, parseMode : ParseMode.Markdown, replyMarkup : RequestReplyKeyboard); } else if (msg.Type == MessageType.Text) { await bot.SendTextMessageAsync(msg.Chat.Id, $"Olá *{msg.Chat.FirstName}*. \nVocê escreveu: \n*{msg.Text}*", ParseMode.Markdown); } }
/// <summary> /// Requests the location from the user. /// </summary> /// <param name="buttonText"></param> /// <param name="requestMessage"></param> /// <param name="OneTimeOnly"></param> /// <returns></returns> public async Task <Message> RequestLocation(String buttonText = "Send your location", String requestMessage = "Give me your location!", bool OneTimeOnly = true) { var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)); rcl.OneTimeKeyboard = OneTimeOnly; return(await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rcl))); }
public void AddRequestLocation(string text) { KeyboardButton btn = KeyboardButton.WithRequestLocation(text); _buttons.Add(new List <KeyboardButton> { btn }); }
public static async Task AskLocationMessage(long chatId) { await botClient.SendTextMessageAsync(chatId : chatId, text : "Share your contact & location", replyMarkup : new ReplyKeyboardMarkup(new [] { new [] { KeyboardButton.WithRequestContact("Share Contact") }, new [] { KeyboardButton.WithRequestLocation("Share Location") } } )); }
private async Task StartActionAsync(Update update) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Get places"), new KeyboardButton("/add"), }); await Bot.SendTextMessageAsync( update.Message.Chat.Id, "Choose", replyMarkup : RequestReplyKeyboard); }
public async void request(TelegramBotClient Bot, Message message) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard); }
private async Task SendReplyKeyboard(Message message) { var replyKeyboardMarkup = new ReplyKeyboardMarkup( new[] { new[] { KeyboardButton.WithRequestLocation("Location"), "1" }, new[] { KeyboardButton.WithRequestContact("Contact"), "2" }, }, true ); await _client.SendTextMessageAsync(message.Chat.Id, Strings.Choose, replyMarkup : replyKeyboardMarkup); }
public async Task RequestLocation() { ReplyKeyboardMarkup RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), }); await TelegramBotClient.SendTextMessageAsync( chatId : Update.Message.Chat.Id, text : "Send your location please 😉", replyMarkup : RequestReplyKeyboard ); }
static async Task RequestContactAndLocation(Message message) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); }
static async Task <Message> RequestContactAndLocation(ITelegramBotClient botClient, Message message) { ReplyKeyboardMarkup RequestReplyKeyboard = new( new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); return(await botClient.SendTextMessageAsync(chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : RequestReplyKeyboard)); }
public async Task Should_Receive_Location() { await BotClient.SendTextMessageAsync( chatId : _classFixture.PrivateChat, text : "Share your location using the keyboard reply markup", replyMarkup : new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation("Share Location")) ); Message locationMessage = await GetMessageFromChat(MessageType.Location); Assert.NotNull(locationMessage.Location); await BotClient.SendTextMessageAsync( chatId : _classFixture.PrivateChat, text : "Got it. Removing reply keyboard markup...", replyMarkup : new ReplyKeyboardRemove() ); }
public async void UpdateAsync(Message msg, TelegramBotClient bot, long chatId, Context db) { switch (msg.Type) { case MessageType.Text when msg.Text.Equals("/order", StringComparison.OrdinalIgnoreCase): { await bot.SendTextMessageAsync( chatId : msg.Chat.Id, text : "`Здравствуйте, откуда вас забрать? \n" + "Для определения вашего местонахождения " + "в настройках телефона включите` *геолокацию* \n" + "и нажмите на кнопку Местоположение.", replyMarkup : new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Местоположение"), new KeyboardButton("Отмена"), }, true, true), parseMode : ParseMode.Markdown); var user = db.Users.FirstOrDefault(x => x.ChatId == msg.Chat.Id); if (user != null) { user.State = StateChatEnum.StartText; } db.SaveChanges(); break; } case MessageType.Text: { await bot.SendTextMessageAsync( chatId : msg.Chat.Id, text : "Для заказа такси введите команду \n /order"); break; } } }
public async Task EchoAsync(Update update) { if (update.Type != UpdateType.Message) { return; } Message message = update.Message; switch (message.Text.Split(' ').First()) { case "/menu": await TelegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] { InlineKeyboardButton.WithCallbackData("soon", "soon"), InlineKeyboardButton.WithCallbackData("soon", "soon"), }, new [] { InlineKeyboardButton.WithCallbackData("soon", "soon"), InlineKeyboardButton.WithCallbackData("soon", "soon"), } }); await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : inlineKeyboard ); break; case "/fun": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : ReplyKeyboard ); break; case "/request": ReplyKeyboardMarkup RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); break; case "/Sasha": await TelegramBotClient.SendTextMessageAsync(message.Chat.Id, $"I love you bab"); break; case "/Nikita": await TelegramBotClient.SendTextMessageAsync(message.Chat.Id, $"You are f*g!!! HA-ha"); break; default: const string usage = "Usage:\n" + "/menu - send inline keyboard\n" + "/request - Test request\n" + "/Nikita - That's for you Nikita"; const string usageForSandra = "Usage:\n" + "/Sasha - if you have bad mood enter this command"; await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : message.Chat.Username == "Sandra_Nikitina"?usageForSandra : usage, replyMarkup : new ReplyKeyboardRemove() ); break; } }
public async Task EchoAsync(Update update) { switch (update.Type) { case UpdateType.Message: var message = update.Message; if (message == null || message.Type != MessageType.Text) { return; } _logger.LogInformation("Received Message from {0}", message.Chat.Id); switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await _botService.Client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("1.1"), InlineKeyboardButton.WithCallbackData("1.2"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("2.1"), InlineKeyboardButton.WithCallbackData("2.2"), } }); await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : ReplyKeyboard); break; // send a photo case "/photo": try { await _botService.Client.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); var req = HttpWebRequest.Create("https://i.imgur.com/l8WqVDx.png"); using (var stream = req.GetResponse().GetResponseStream()) { await _botService.Client.SendPhotoAsync( message.Chat.Id, stream, "Nice Picture"); } } catch (System.Exception e) { _logger.LogInformation("Exception:{0}", e.Message); throw e; } break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard); break; default: const string usage = @" Usage: /inline - send inline keyboard /keyboard - send custom keyboard /photo - send a photo /request - request location or contact"; await _botService.Client.SendTextMessageAsync( message.Chat.Id, usage, replyMarkup : new ReplyKeyboardRemove()); break; } break; case UpdateType.CallbackQuery: var callbackQuery = update.CallbackQuery; await _botService.Client.AnswerCallbackQueryAsync( callbackQuery.Id, $"Received {callbackQuery.Data}"); await _botService.Client.SendTextMessageAsync( callbackQuery.Message.Chat.Id, $"Received {callbackQuery.Data}"); break; default: break; } }
public async Task DefineCommand() { Message message = Update.Message; switch (message.Text.Split(' ').First().Trim('/')) { case "Menu": await new MenuBotCommand().Menu(TelegramBotClient, Update); break; case "start": await new MenuBotCommand().Menu(TelegramBotClient, Update); break; case "Weather": ReplyKeyboardMarkup RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), }); await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : "Send your location please 😉", replyMarkup : RequestReplyKeyboard ); break; case "Sasha": await TelegramBotClient.SendTextMessageAsync(message.Chat.Id, $"I love you bab"); break; case "Nikita": await TelegramBotClient.SendTextMessageAsync(message.Chat.Id, $"You are f*g!!! HA-ha"); break; case "Emoji": await TelegramBotClient.SendTextMessageAsync(message.Chat.Id, $"😀"); break; default: const string usage = "Usage:\n" + "/menu - send inline keyboard\n" + "/request - Test request\n" + "/Nikita - That's for you Nikita"; const string usageForSandra = "Usage:\n" + "/Sasha - if you have bad mood enter this command"; await TelegramBotClient.SendTextMessageAsync( chatId : message.Chat.Id, text : message.Chat.Username == "Sandra_Nikitina"?usageForSandra : usage, replyMarkup : new ReplyKeyboardRemove() ); break; } }
private static async Task BotOnMessageReceived(Message message) { Console.WriteLine($"Recevie message type: {message.Type}"); if (message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); // simulate longer running task await Task.Delay(500); var inlineKeyboard = new InlineKeyboardMarkup(new[] { // first row new [] { InlineKeyboardButton.WithCallbackData("1.1", "11"), InlineKeyboardButton.WithCallbackData("1.2", "12"), }, // second row new [] { InlineKeyboardButton.WithCallbackData("2.1", "21"), InlineKeyboardButton.WithCallbackData("2.2", "22"), } }); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : inlineKeyboard ); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : ReplyKeyboard ); break; // send a photo case "/photo": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"Files/tux.png"; using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { var fileName = file.Split(Path.DirectorySeparatorChar).Last(); await Bot.SendPhotoAsync( chatId : message.Chat.Id, photo : new InputOnlineFile(fileStream, fileName), caption : "Nice Picture" ); } break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); break; default: const string usage = "Usage:\n" + "/inline - send inline keyboard\n" + "/keyboard - send custom keyboard\n" + "/photo - send a photo\n" + "/request - request location or contact"; await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : usage, replyMarkup : new ReplyKeyboardRemove() ); break; } }
public async Task NavigateTo(string messageBody, long chatId, int userId, TelegramBotClient _telegramBot) { await _telegramBot.SendChatActionAsync(chatId, ChatAction.Typing); if (messageBody == "🆘 SOS ДТП" || messageBody == "💲 Купить" || messageBody == "☎️ Связаться с оператором" || messageBody == "📝 Мои полисы") { messagePath = string.Empty; } else { messageBody = '\\' + messageBody; } var responseMessage = string.Empty; var splittedMessageBody = messagePath.Split('\\'); if (messageBody == "\\🔙 Назад..." || messageBody == "\\⏩ Продолжить...") { CutMessagePath(splittedMessageBody, 0); } else { if (splittedMessageBody[splittedMessageBody.Length - 1] != messageBody) { messagePath += messageBody; } } splittedMessageBody = messagePath.Split('\\'); if (splittedMessageBody.Length > 2 && (splittedMessageBody[splittedMessageBody.Length - 1] == splittedMessageBody[splittedMessageBody.Length - 2])) { CutMessagePath(splittedMessageBody); } switch (splittedMessageBody[0]) { case "💲 Купить": { if (splittedMessageBody.Length > 1) { switch (splittedMessageBody[1]) { case "Sam takoi": { await _telegramBot.SendTextMessageAsync( chatId, "Ty durak?"); break; } case "Izvinis": { await _telegramBot.SendTextMessageAsync( chatId, "izvini"); break; } } } inlineKeyboard = CreateInlineKeyboard("🔙 Назад...|"); await _telegramBot.SendTextMessageAsync( chatId, "otvet", replyMarkup : inlineKeyboard); break; } case "🆘 SOS ДТП": if (splittedMessageBody.Length > 1) { switch (splittedMessageBody[1]) { case "📞 Контакты при ДТП": { responseMessage = "Вызовите сотрудников административной полиции – 102\n" + "<b>1) В случае необходимости:</b>\n" + "\t- 101 – пожарная служба; 🚒\n" + "\t- 103 – скорая медицинская помощь; 🚑\n" + "\t- 104 – газовая служба; 👷\n" + "\t- 112 – служба спасения. ⛑️\n" + "<b>2) Сообщите другим участникам ДТП номер Вашего полиса ОГПО ВТС и телефон Jysan Garant</b>\n" + "\t- <b>Контакты для консультации:</b> \n" + "\tс <b>8:00 до 22:00</b> – call центр: 3264 с мобильных бесплатно, +7 (727) 357 25 25\n" + "\tс <b>22:00 до 8:00</b> – аварийный комиссар +7 701 529 80 48 🚔\n"; inlineKeyboard = CreateInlineKeyboard("🔙 Назад...|"); await _telegramBot.SendTextMessageAsync( chatId, responseMessage, replyMarkup : inlineKeyboard, parseMode : ParseMode.Html); break; } case "📝 Список документов": { inlineKeyboard = CreateInlineKeyboard("🔙 Назад...|"); await _telegramBot.SendTextMessageAsync( chatId, "1⃣ Включите аварийную световую сигнализацию.\n" + "2⃣ Выставьте знак аварийной остановки(не менее 15 м от авто в населенном пункте и не менее 30 м от - вне населенного пункта).\n" + "3⃣ Вызовите сотрудников административной полиции – 102 👮\n\n" + " В случае необходимости:\n" + "👨🚒 101 – пожарная служба;\n" + "👨⚕ 103 – скорая медицинская помощь;\n" + "👷 104 – газовая служба;\n" + "⛑ 112 – служба спасения.\n\n" + "4⃣ Сообщите другим участникам ДТП номер Вашего полиса ОГПО ВТС и телефон «Jýsan Garant»\n" + "Контакты для консультации:\n\n" + "с 8:00 до 22:00 – call центр: 3264 с мобильных бесплатно, +7(727) 357 25 25\n" + "с 22:00 до 8:00 – аварийный комиссар 8 701 529 80 48\n\n" + "5⃣ Оставайтесь на месте ДТП до приезда сотрудников Административной полиции.\n" + "Вниманию лиц, пострадавших в дорожно-транспортных происшествиях, в случаях, когда виновное лицо не установлено!\n" + "АО «Фонд гарантирования страховых выплат» сообщает, что при ДТП, произошедших с 1 октября 2008 года, предусмотрена выплата компенсаций пострадавшим, получившим тяжкие телесные повреждения и родственникам погибших.\n\n" + "Выплаты осуществляются только в случаях, когда виновник ДТП скрылся с места аварии.\n\n" + "Для получения компенсаций пострадавшим необходимо представить в Фонд полный пакет документов в соответствии с требованиями действующего законодательства:\n\n" + "⚫ заявление на выплату возмещения вреда в произвольной форме;\n\n" + "⚫ документ от органов Министерства внутренних дел Республики Казахстан, подтверждающий факт наступления случая, то есть случай не установления лица, скрывшегося с места транспортного происшествия и ответственного за причинение вреда потерпевшему;\n\n" + "⚫ копия заключения организации здравоохранения, в которой потерпевшему была оказана медицинская помощь в связи с причиненным тяжким вредом здоровью в результате транспортного происшествия, с указанием характера полученных потерпевшим травм и увечий, диагноза, периода временной нетрудоспособности;\n\n" + "⚫ копия заключения учреждений медико-социальной или судебно-медицинской экспертизы;\n\n" + "⚫ нотариально засвидетельствованная копия свидетельства о смерти потерпевшего(в случае смерти потерпевшего);\n\n" + "⚫ документ, подтверждающий право лица, имеющего согласно законодательным актам Республики Казахстан право на возмещение вреда(в случае смерти потерпевшего);\n\n" + "⚫ документы либо их копии, подтверждающие затраты на погребение(при отсутствии родственников);\n\n" + "⚫ копия удостоверения личности заявителя(получателя);\n\n" + "⚫ данные о банковских реквизитах для перечисления средств.\n\n" + "Обращаем внимание, что право на выплату компенсаций в случае смерти потерпевшего согласно статье 940 Гражданского кодекса РК имеют только \n" + "нетрудоспособные лица, состоявшие на иждивении умершего или имевшие ко дню его смерти право на получение от него содержания; ребенок умершего, \n" + "родившийся после его смерти, а также один из родителей, супруг либо другой член семьи, независимо от трудоспособности, который не работает и\n" + " занят уходом за находившимся на иждивении умершего его детьми, внуками, братьями и сестрами, не достигшими четырнадцати лет либо хотя и достигшими \n" + "указанного возраста, но по заключению медицинских органов, нуждающимися по состоянию здоровья в постороннем уходе.\n" + "Потерпевшие вправе обратиться в Фонд в течение одного года с момента наступления дорожно - транспортного происшествия.\n", replyMarkup : inlineKeyboard); break; } case "❓ Действия клиента": { if (splittedMessageBody.Length > 2) { switch (splittedMessageBody[2]) { case "❗ Виновник": { responseMessage = "1) заявление о страховом случае;\n" + "2) страховой полис(его дубликат) виновника ДТП;\n" + "3) документ компетентных органов, подтверждающий факт наступления страхового случая и размер вреда, причиненного потерпевшим;\n" + "4) копию удостоверения личности;\n" + "5) копия водительского удостоверения(временных прав);заключение медицинского освидетельствования.\n"; break; } case "❕ Потерпевший": { responseMessage = "1) (Прямое урегулирование)\n" + "2) К вышеперечисленному списку документов + полис виновника ДТП\n" + "3) Более полную информацию по перечню предоставляемых документов можно получить у специалиста\n" + "4) Отдела страховых выплат(список аварийных комиссаров)\n"; break; } } CutMessagePath(splittedMessageBody); await _telegramBot.SendTextMessageAsync(chatId, responseMessage, replyMarkup : inlineKeyboard); break; } inlineKeyboard = CreateInlineKeyboard("❗ Виновник|❕ Потерпевший|🔙 Назад...|"); await _telegramBot.SendTextMessageAsync( chatId, "izvini", replyMarkup : inlineKeyboard); break; } case string s when s == "🛂 Заявить о ДТП": var user = _insuranceService.GetUserInfo(userId); if (splittedMessageBody.Length > 2) { switch (splittedMessageBody[2]) { case string st when st == "❌ ФИО" || st == "✔️ ФИО": if (splittedMessageBody.Length == 3) { await _telegramBot.SendTextMessageAsync(chatId, "⌨️ Введите ФИО", replyMarkup : new ReplyKeyboardRemove()); } else if (splittedMessageBody[3].Split(' ').Length == 3) { user.FIO = st; _insuranceService.UserUpdate(user); CutMessagePath(splittedMessageBody, 0); } else { await _telegramBot.SendTextMessageAsync(chatId, "Неверное ФИО", replyMarkup : new ReplyKeyboardRemove()); CutMessagePath(splittedMessageBody); } break; case string st when st == "❌ ИИН" || st == "✔️ ИИН" || IsStringIIN(st): if (splittedMessageBody.Length == 3) { await _telegramBot.SendTextMessageAsync(chatId, "⌨️ Введите ИИН", replyMarkup : new ReplyKeyboardRemove(), parseMode : ParseMode.Html); } else if (IsStringIIN(splittedMessageBody[3])) { user.IIN = splittedMessageBody[3]; _insuranceService.UserUpdate(user); CutMessagePath(splittedMessageBody); } else { await _telegramBot.SendTextMessageAsync(chatId, "Неверный ИИН", replyMarkup : new ReplyKeyboardRemove()); CutMessagePath(splittedMessageBody); } break; case string st when st == "❌ Телефон" || st == "✔️ Телефон": if (splittedMessageBody.Length == 3) { replyKeyboardMarkup = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact("Отправить телефон")); replyKeyboardMarkup.ResizeKeyboard = true; await _telegramBot.SendTextMessageAsync(chatId, "📲 Поделитесь номером телефона", parseMode : ParseMode.Html, replyMarkup : replyKeyboardMarkup); } break; case string st when st == "❌ Местоположение" || st == "✔️ Местоположение": if (splittedMessageBody.Length == 3) { replyKeyboardMarkup = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation("🌏 Отправить местоположение")); replyKeyboardMarkup.ResizeKeyboard = true; await _telegramBot.SendTextMessageAsync(chatId, "🌏 Поделитесь местоположением", parseMode : ParseMode.Html, replyMarkup : replyKeyboardMarkup); } break; case string st when st == "❌ Фото" || st == "✔️ Фото": if (splittedMessageBody.Length == 3) { await _telegramBot.SendTextMessageAsync(chatId, "Отправьте фото <b>ДТП</b>", parseMode : ParseMode.Html); } break; case string st when st == "❓ Как сделать фото?": inlineKeyboard = CreateInlineKeyboard("🔙 Назад...|"); responseMessage = "<b>Какие снимки делаются при ДТП?</b>\n" + "<i>Фотоснимки, необходимые для документирования дорожно-транспортного происшествия:</i>\n" + "❕ Фотография, на которой запечатлено место аварии. На ней также должны быть видны машины, ставшие участниками ДТП;\n" + "❕ Снимки государственных номеров ТС. Если есть такая возможность – примените макросъемку;\n" + "❕ Фотоснимок общего вида автомобиля, участвовавшего в ДТП. Особенно важно снять место контакта двух машин. Повреждения фотографируйте детально. Неплохо запечатлеть малейшие следы соприкосновения, например, след краски;\n" + "❕ Фотография общего плана ДТП и его главного очевидца;\n" + "❕ Снимок, запечатлевший положение автомобилей относительно полос движения. При фотографировании в вечернее время или ночное, учтите особенности вспышки своего фотоаппарата, особенно ее дальность;\n" + "❕ Фото со следами торможения (если таковые есть);\n" + "❕ Снимки, запечатлевшие погодные условия на момент аварии (снег, лужи, прочее);\n" + "❕ Если в районе места аварии есть дорожные знаки, сделайте их фотографии в том виде, в котором они были на момент столкновения (например, знак “STOP”, закрытый деревьями, прочее);\n" + "❕ Фото приборной доски автомобиля, особенно часов, спидометра (если он сохранил показания скорости);\n" + "❕ Сделайте снимок водителя и пассажиров ТС, их состояние. Это необходимо для того случая, когда они потребуют возмещения ущерба. А если у вас есть возможность сделать видеосъемку – это будет еще лучше;\n" + "Фотографии, снятые крупным планом травм и ранений пострадавших в ДТП, вплоть до выбитых зубов.\n\n" + "<b>Иногда участники ДТП, которые все сфотографировали, говорят о том, что другие участники аварии даже не хотят писать заявление, стараются оправдаться. " + "А все это происходит по той причине, что по снимкам совершенно ясно, что это именно они виновны в данном происшествии. Позвольте дать вам несколько полезных советов:</b>" + "❕ Место, в котором произошло столкновение машин, снимайте крупным планом;\n" + "❕ Обязательно делайте фото таким образом, чтобы в объектив попадал и государственный номер машины. " + "Так специалисты точно поймут, какой именно автомобиль сфотографирован.\n"; await _telegramBot.SendTextMessageAsync(chatId, responseMessage, parseMode : ParseMode.Html, replyMarkup : inlineKeyboard);; break; } CutMessagePath(splittedMessageBody, 3); } if (splittedMessageBody.Length != 3) { string FIO = string.Empty, IIN = string.Empty, phoneNum = string.Empty, location = string.Empty, photos = string.Empty, fullKeyboardString = string.Empty; if (user.FIO == null) { FIO += "❌ ФИО"; } else { FIO += "✔️ ФИО"; } if (user.IIN == null) { IIN += "❌ ИИН"; } else { IIN += "✔️ ИИН"; } if (user.Contact == null) { phoneNum += "❌ Телефон"; } else { phoneNum += "✔️ Телефон"; } if (user.DTPs == null) { user.DTPs = new DTOs.DTP(); } if (user.DTPs.Location == null) { location += "❌ Местоположение"; } else { location += "✔️ Местоположение"; } if (user.DTPs.Photos == null) { photos += "❌ Фото"; } else { photos += "✔️ Фото"; } fullKeyboardString = $"{FIO}\\{IIN}\\{phoneNum}|{location}\\{photos}|❓ Как сделать фото?|"; if (fullKeyboardString.Contains("❌")) { inlineKeyboard = CreateInlineKeyboard(fullKeyboardString); } else { inlineKeyboard = CreateInlineKeyboard(fullKeyboardString + "🛂 Заявить о ДТП|"); } await _telegramBot.SendTextMessageAsync(chatId, "❕ Заполните все поля чтобы продолжить", replyMarkup : inlineKeyboard); } break; case "📖 Вернуться в меню": messagePath = string.Empty; break; } break; } else { inlineKeyboard = CreateInlineKeyboard("📞 Контакты при ДТП\\📝 Список документов|🛂 Заявить о ДТП|❓ Действия клиента\\🔙 Назад...|"); await _telegramBot.SendTextMessageAsync( chatId, "<b>🆘 SOS ДТП</b>\n\n" + "- для того, чтобы заявить о ДТП, нажмите на кнопку - <b>'🛂 Заявить о ДТП'</b>\n\n" + "- для того, чтобы узнать что делать при ДТП, нажмите на кнопку - <b>'❓ Действия клиента</b>\n\n" + "- для того, чтобы посмотреть необходимые контакты при ДТП, нажмите на кнопку - <b>'📞 Контакты при ДТП</b>\n\n" + "- для того, чтобы просмотреть необходимый перечень документов при ДТП, нажмите на кнопку - <b>'📝 Список документов'</b>\n\n", replyMarkup : inlineKeyboard, parseMode : ParseMode.Html);; break; } case "☎️ Связаться с оператором": if (splittedMessageBody.Length > 1) { switch (splittedMessageBody[1]) { case "🌎 Ближайшее отделение": var user = _insuranceService.GetUserInfo(userId); if (user.DTPs.IsLocationNeeded()) { replyKeyboardMarkup = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation("🌏 Отправить местоположение")); replyKeyboardMarkup.ResizeKeyboard = true; await _telegramBot.SendTextMessageAsync(chatId, "🌏 Поделитесь местоположением", parseMode : ParseMode.Html, replyMarkup : replyKeyboardMarkup); } else { List <Tuple <Location, string, float> > allDepartamentsAndPhones = new List <Tuple <Location, string, float> >(); string connetionString = System.Configuration.ConfigurationManager.ConnectionStrings["fstpString"].ConnectionString; try { using (SqlConnection cnn = new SqlConnection(connetionString)) { using (SqlCommand command = new SqlCommand("exec [Fstp]..Report_ogpo_dept", cnn)) { cnn.Open(); using (SqlDataReader dataReader = command.ExecuteReader()) { while (dataReader.Read()) { try { Location loc = GetLocationByAdress(dataReader.GetValue(4).ToString()); String phon = dataReader.GetValue(5).ToString(); float dist = GetDistanceBettweenLocations(user.DTPs.Location.Latitude, user.DTPs.Location.Longitude, float.Parse(loc.lat, CultureInfo.InvariantCulture), float.Parse(loc.lon, CultureInfo.InvariantCulture)); allDepartamentsAndPhones.Add(new Tuple <Location, string, float>(loc, phon, dist)); } catch { } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Tuple <Location, string, float> sortedDepts = allDepartamentsAndPhones.OrderBy(x => x.Item3).First(); await _telegramBot.SendTextMessageAsync(chatId, $"🌏 Ближайшее подразеделение\n" + $"🚶 Расстояние: {sortedDepts.Item3.ToString("0.##")}км", parseMode : ParseMode.Html); await _telegramBot.SendLocationAsync(chatId, float.Parse(sortedDepts.Item1.lat, CultureInfo.InvariantCulture), float.Parse(sortedDepts.Item1.lon, CultureInfo.InvariantCulture)); await _telegramBot.SendTextMessageAsync(chatId, $"☎️ Номер: {sortedDepts.Item2}\n", parseMode : ParseMode.Html, replyMarkup : CreateInlineKeyboard("🔙 Назад...|")); } break; } } else { responseMessage = "Вошел в \"☎️ Связаться с оператором\""; inlineKeyboard = CreateInlineKeyboard("🌎 Ближайшее отделение|"); await _telegramBot.SendTextMessageAsync(chatId, responseMessage, replyMarkup : inlineKeyboard); } break; default: inlineKeyboard = CreateInlineKeyboard("💲 Купить\\🆘 SOS ДТП|🌍 Подразделения|📝 Мои полисы|"); responseMessage = $"<b>'🕮 Главное меню'</b> \n\n" + $"- для того, чтобы приобрести полис, нажмите на кнопку - <b>'💲 Купить'</b>\n\n" + "- для того, чтобы заявить о ДТП и получить необходимую информацию, нажмите на кнопку - <b>'🆘 SOS ДТП'</b>\n\n" + "- для того, чтобы получить необходимые контакты, нажмите на кнопку - <b>'🌍 Подразделения'</b>\n\n" + "- для того, чтобы посмотреть свои полисы, нажмите на кнопку - <b>'📝 Мои полисы'</b>\n\n"; await _telegramBot.SendTextMessageAsync(chatId, responseMessage, parseMode : ParseMode.Html, replyMarkup : inlineKeyboard); break; } }
private async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ')[0]) { // Send inline keyboard case "/inline": await SendInlineKeyboard(message); break; // send custom keyboard case "/keyboard": await SendReplyKeyboard(message); break; // send a photo case "/photo": await SendDocument(message); break; // request location or contact case "/request": await RequestContactAndLocation(message); break; default: await Usage(message); break; } // Send inline keyboard // You can process responses in BotOnCallbackQueryReceived handler async Task SendInlineKeyboard(Message message) { await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); // Simulate longer running task await Task.Delay(500); var inlineKeyboard = new InlineKeyboardMarkup(new[] { // first row new [] { InlineKeyboardButton.WithCallbackData("1.1", "11"), InlineKeyboardButton.WithCallbackData("1.2", "12"), }, // second row new [] { InlineKeyboardButton.WithCallbackData("2.1", "21"), InlineKeyboardButton.WithCallbackData("2.2", "22"), } }); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : inlineKeyboard ); } async Task SendReplyKeyboard(Message message) { var replyKeyboardMarkup = new ReplyKeyboardMarkup( new KeyboardButton[][] { new KeyboardButton[] { "1.1", "1.2" }, new KeyboardButton[] { "2.1", "2.2" }, }, resizeKeyboard: true ); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : replyKeyboardMarkup ); } async Task SendDocument(Message message) { await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string filePath = @"Files/tux.png"; using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var fileName = filePath.Split(Path.DirectorySeparatorChar).Last(); await _bot.SendPhotoAsync( chatId : message.Chat.Id, photo : new InputOnlineFile(fileStream, fileName), caption : "Nice Picture" ); } async Task RequestContactAndLocation(Message message) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); } async Task Usage(Message message) { const string usage = "Usage:\n" + "/inline - send inline keyboard\n" + "/keyboard - send custom keyboard\n" + "/photo - send a photo\n" + "/request - request location or contact"; await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : usage, replyMarkup : new ReplyKeyboardRemove() ); } }
private async Task ProcessReport() { var user = cleanCityApi.GetUser(manager.UserId); if (user == null) { await manager.SendTextMessageAsync( "Пройдите процедуру регистрации (/register), чтобы иметь возможность оформлять обращения к городским квартальным"); return; } var attachments = new List <Attachment>(); var markup = new ReplyKeyboardMarkup(new[] { new[] { new KeyboardButton("Грязь на тротуаре") }, new[] { new KeyboardButton("Парковка в неположенном месте") }, new[] { new KeyboardButton("Реклама в неположенном месте") }, new[] { new KeyboardButton("Складированое в неположенном месте") }, }); var makeReport = new ReplyKeyboardMarkup(new[] { new[] { new KeyboardButton("Отправить обращение") }, }); var subject = string.Empty; while (string.IsNullOrWhiteSpace(subject)) { await manager.SendTextMessageAsync("Выберите одну из предложенных тем обращения или введите свою:", markup); subject = (await GetResponseAsync(attachments)).Text; } var reportText = string.Empty; while (string.IsNullOrWhiteSpace(reportText)) { await manager.SendTextMessageAsync("Подробно опишите детали проблемы:", resetMarkup); reportText = (await GetResponseAsync(attachments)).Text; } GeoLocation location = null; while (location == null) { await manager.SendTextMessageAsync( "Укажите своё местоположение", new ReplyKeyboardMarkup( KeyboardButton.WithRequestLocation("Отправить моё текущее местоположение"))); var locationMessage = await GetResponseAsync(attachments); if (locationMessage.Location != null) { location = new GeoLocation { Latitude = locationMessage.Location.Latitude, Longitude = locationMessage.Location.Longitude, }; } } while (true) { var(count, caption) = Pluralizator.Pluralize(attachments.Count, "фотографий", "фотографию", "фотографии"); await manager.SendTextMessageAsync( $"Добавьте к своему обращению фотографии, чтобы зафиксировать нарушение\n" + $"Мы уже прикрепили к вашему обращению {count} {caption}. Вы можете отправить ещё фотографии или отправить обращение", makeReport); var message = await GetResponseAsync(attachments); if (message.Text != null && message.Text.Contains("обращение")) { break; } } var initialReport = new InitialReport { UserId = manager.UserId, Subject = subject, ReportText = reportText, Location = location, Attachments = attachments.ToArray(), }; var reportId = cleanCityApi.SendReport(initialReport); var report = cleanCityApi.GetReport(reportId); var responsible = cleanCityApi.GetResponsible(report.ResponsibleId); await manager.SendTextMessageAsync( $"Обращение успешно сформировано и отправлено соответствующему квартальному: " + $"{responsible.Name}\n" + $"Вы можете оформить ещё одно обращение с помощью команды /report", resetMarkup); }
public static async Task CreateLocation(this ITelegramBotClient client, long chatId) { var requestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Сообщить мое местоположение") }); await client.SendTextMessageAsync(chatId, "Отметьте местоположение", replyMarkup : requestReplyKeyboard); }
private async Task ProcessMessageWithCommands(Message message) { switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await _botService.Client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("1.1"), InlineKeyboardButton.WithCallbackData("1.2"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("2.1"), InlineKeyboardButton.WithCallbackData("2.2"), } }); await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard ); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : ReplyKeyboard ); break; // send a photo case "/photo": await _botService.Client.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"Files/flat.jpg"; var fileName = file.Split(Path.DirectorySeparatorChar).Last(); using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { await _botService.Client.SendPhotoAsync( message.Chat.Id, fileStream, "Nice Picture" ); } break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await _botService.Client.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); break; default: const string usage = @" Usage: /inline - send inline keyboard /keyboard - send custom keyboard /photo - send a photo /request - request location or contact"; await _botService.Client.SendTextMessageAsync( message.Chat.Id, usage, replyMarkup : new ReplyKeyboardRemove()); break; } }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("1.1"), InlineKeyboardButton.WithCallbackData("1.2"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("2.1"), InlineKeyboardButton.WithCallbackData("2.2"), } }); await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : ReplyKeyboard); break; case "/rootfolderlist": var subFolders = Directory.GetDirectories(selectedFolder); var items = subFolders.Count() != 0 ? subFolders.Select(folder => folder.Split(Path.DirectorySeparatorChar).Last()) : Directory.GetFiles(selectedFolder).Select(f => Path.GetFileName(f)); ReplyKeyboardMarkup keyboardWithFolders = new ReplyKeyboardMarkup( items.Select(folder => new[] { new KeyboardButton(folder) }).Take(20)); await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : keyboardWithFolders); ; break; // send a photo case "/photo": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"d:\Temp\1.jpg"; var fileName = file.Split(Path.DirectorySeparatorChar).Last(); using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { await Bot.SendPhotoAsync( message.Chat.Id, fileStream, "Nice Picture"); } break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard); break; default: if (message.Text.ToLower().EndsWith(".jpg")) { var pathToFile = Path.Combine(selectedFolder, message.Text); Image image = Image.FromFile(pathToFile); var aspect = (double)image.Size.Width / (double)image.Size.Height; Image thumb = image.GetThumbnailImage((int)(480 * aspect), 480, () => false, IntPtr.Zero); using (MemoryStream imageStream = new MemoryStream()) { thumb.Save(imageStream, ImageFormat.Jpeg); imageStream.Position = 0; await Bot.SendPhotoAsync( message.Chat.Id, imageStream, null); } return; // put the image into the memory stream } selectedFolder = Path.Combine(selectedFolder, message.Text); try { var sFolders = Directory.GetDirectories(selectedFolder); var itms = sFolders.Count() != 0 ? sFolders.Select(folder => folder.Split(Path.DirectorySeparatorChar).Last()) : Directory.GetFiles(selectedFolder).Select(f => Path.GetFileName(f)); var buttons = itms.Select(folder => new[] { new KeyboardButton(folder) }).Take(20).ToArray(); ReplyKeyboardMarkup _keyboardWithFolders = new ReplyKeyboardMarkup(buttons); await Bot.SendTextMessageAsync( message.Chat.Id, null, replyMarkup : _keyboardWithFolders); ; } catch (Exception ex) { await Bot.SendTextMessageAsync( message.Chat.Id, "Wrong command", replyMarkup : new ReplyKeyboardRemove()); } /**/ break; } }
private async Task <int> SendMessage(BotClientWrapper botClient, long chatId, RequestLocationTelegramMessage message, bool notify) { return(await botClient.SendTextMessageAsync(chatId, message.Text, disableWebPagePreview : message.DisableWebPagePreview, disableNotification : !notify, replyMarkup : new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(message.RequestLocation)))); }
public async Task <bool?> Handle(MessageEntityEx entity, PollMessage context = default, CancellationToken cancellationToken = default) { if (!this.ShouldProcess(entity, context)) { return(null); } var author = entity.Message.From; var settings = await myContext.Set <UserSettings>().Get(author, cancellationToken); var content = await GetMessage(settings, cancellationToken); var sentMessage = await myBot.SendTextMessageAsync(entity.Message.Chat, content, cancellationToken : cancellationToken, replyMarkup : new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation("Send a location to set up your home place and timezone")) { ResizeKeyboard = true, OneTimeKeyboard = true }); myCache.GetOrCreate(this[sentMessage.MessageId], _ => true); return(false); // processed, but not pollMessage }
public static KeyboardRow <KeyboardButton> AddLocationButton( this KeyboardRow <KeyboardButton> rowBuilder, string text) => rowBuilder.AddButton(KeyboardButton.WithRequestLocation(text));
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); // } }
private static async Task BotOnMessageReceived(Message message) { Console.WriteLine($"Recevie message type: {message.Type}"); if (message.Type == MessageType.Location) { var userGeo = $"{message.Location.Latitude},{message.Location.Longitude}"; var closestFood = (await new FoodService().FindClosestFoodAsync(userGeo)) .OrderBy(f => f.DistanceInMeters) .ToList(); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, parseMode : ParseMode.Markdown, text : $"I found *{closestFood.Count}* meals 🍲 for you nearby..." //replyMarkup: new ReplyKeyboardRemove() ); foreach (var food in closestFood) { await Bot.SendPhotoAsync(chatId : message.Chat.Id, photo : food.Food.ImageUrl); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, parseMode : ParseMode.Markdown, text : $"*{food.Food.Name}* from *{food.Food.RestaurantName}* is in *{food.DistanceInMeters}* meters from you.\n" + $"It will take only {food.ArivalTime.Subtract(DateTime.Now).Minutes} minutes ⏱ for you to get there.\n" + $"Go grab your free food 🥙 😀", replyMarkup : new InlineKeyboardMarkup(new[] { new [] { InlineKeyboardButton.WithCallbackData("Grab this food", food.Food.Geo), }, }) ); } return; } if (message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/start": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); var startReplyKeyboard = new ReplyKeyboardMarkup( new[] { new[] { KeyboardButton.WithRequestLocation("Find some free food nearby !"), }, }); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Hi, I'm Greta Food Bot, and I will find some free food for you. Please, send me your location for next steps", replyMarkup : startReplyKeyboard ); break; default: const string usage = "Usage:\n" + "/start - start conversation with saint Greta\n" + "/search - find some food fo you\n"; await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : usage, replyMarkup : new ReplyKeyboardRemove() ); break; } }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("1.1"), InlineKeyboardButton.WithCallbackData("1.2"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("2.1"), InlineKeyboardButton.WithCallbackData("2.2"), } }); await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "1.1", "1.2" }, new[] { "2.1", "2.2" }, }; await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : ReplyKeyboard); break; // send a photo case "/photo": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"Files/tux.png"; var fileName = file.Split(Path.DirectorySeparatorChar).Last(); using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { await Bot.SendPhotoAsync( message.Chat.Id, fileStream, "Nice Picture"); } break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard); break; default: const string usage = @" Usage: /inline - send inline keyboard /keyboard - send custom keyboard /photo - send a photo /request - request location or contact"; await Bot.SendTextMessageAsync( message.Chat.Id, usage, replyMarkup : new ReplyKeyboardRemove()); break; } }
// LOGIC private static async void MenuLogic(Telegram.Bot.Types.Message message) { if (!dictionary.ContainsKey(message.Chat.Id)) { dictionary[message.Chat.Id] = 0; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "Меню": dictionary[message.Chat.Id] = 0; ShowMenuMain(message); break; case "/admin": if (message.Chat.Username == "PotatOS") { await Bot.SendTextMessageAsync(message.Chat.Id, "Hello, senpai ^_^"); dictionary[message.Chat.Id] = 80; } else { Console.WriteLine("baka"); } break; default: break; } if (dictionary[message.Chat.Id] >= 0 && dictionary[message.Chat.Id] < 3) { switch (message.Text) { case "Графити": dictionary[message.Chat.Id] = 1; ShowMenuBuy(message); break; case "Район 1": dictionary[message.Chat.Id] = 2; string[] graphits = new string[] { "1", "2", "3", "4", "5", "0" }; ShowMenugraphits(message, graphits); break; case "Обратная связь": ShowTBA(message); break; default: break; } } if (dictionary[message.Chat.Id] >= 80 && dictionary[message.Chat.Id] < 500) { switch (message.Text) { case "/admin": dictionary[message.Chat.Id] = 80; ShowMenuAdmin(message); break; case "Добавить графити": ShowAdminAddProd(message); dictionary[message.Chat.Id] = 81; adminprod = new GraphityClass(); break; case "Удалить графити": ShowAdminDelProd(message); dictionary[message.Chat.Id] = 91; break; case "Добавить район": ShowAdminAddRegion(message); dictionary[message.Chat.Id] = 101; break; case "Удалить район": ShowAdminDelRegion(message); dictionary[message.Chat.Id] = 111; break; case "Статистика": ShowTBA(message); break; case "Закрыть бота": ShowTBA(message); break; case "Открыть бота": ShowTBA(message); break; default: break; } if (dictionary[message.Chat.Id] > 80 && dictionary[message.Chat.Id] < 500) { string answer = ""; int localid = dictionary[message.Chat.Id]; switch (localid) { case 81: answer = "[Название]: "; dictionary[message.Chat.Id] += 1; break; case 82: adminprod.title = message.Text; adminlocation = new LocationClass(); answer = "[Размер]: "; dictionary[message.Chat.Id] += 1; break; case 83: adminprod.size = Convert.ToInt32(message.Text); answer = "[Широта]: "; dictionary[message.Chat.Id] += 1; break; case 84: adminlocation.latitude = float.Parse(message.Text, CultureInfo.InvariantCulture.NumberFormat); answer = "[Долгота]: "; dictionary[message.Chat.Id] += 1; break; case 85: adminlocation.longitude = float.Parse(message.Text, CultureInfo.InvariantCulture.NumberFormat); answer = "[Радиус]: "; dictionary[message.Chat.Id] += 1; break; case 86: adminlocation.radius = float.Parse(message.Text, CultureInfo.InvariantCulture.NumberFormat); answer = "[Район]: "; ShowTBA(message); dictionary[message.Chat.Id] += 1; break; case 87: adminprod.region = Convert.ToInt32(message.Text); adminlocation.author = 1; answer = JsonConvert.SerializeObject(adminlocation); answer += JsonConvert.SerializeObject(adminprod); answer += "Всё верно?"; ShowFinishDialog(message); dictionary[message.Chat.Id] += 1; break; case 88: if (message.Text == "Да") { // To-Do ShowMenuAdmin(message); } else if (message.Text == "Нет") { adminlocation = new LocationClass(); adminprod = new GraphityClass(); answer = "Отменено"; } else { answer = JsonConvert.SerializeObject(adminlocation); answer += JsonConvert.SerializeObject(adminprod); answer += "Всё верно?"; ShowFinishDialog(message); } break; default: break; } if (dictionary[message.Chat.Id] == 191) { } await Bot.SendTextMessageAsync(message.Chat.Id, answer); } } switch (message.Text.Split(' ').First()) { case "111": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("1.1"), InlineKeyboardButton.WithCallbackData("1.2"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("Купить"), } }); await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard); break; // send a photo case "/photo": //await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"Files/tux.jpg"; var fileName = file.Split(Path.DirectorySeparatorChar).Last(); using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { await Bot.SendPhotoAsync( message.Chat.Id, fileStream, "Nice Picture"); } break; // request location or contact case "/request": var RequestReplyKeyboard1 = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard1); break; default: break; } }