/// <summary> /// Write a vote callback query to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="voteType">The type of the vote.</param> /// <param name="messageId">The id of the message that the callback was triggered by.</param> /// <param name="messageText">The text of the message that the callback was triggered by.</param> /// <param name="trackUrl">The url in de original message the bot replied to.</param> public Task WriteVoteCallbackQueryToStream(Stream stream, VoteType voteType, int messageId, string messageText, string trackUrl) { var update = new Telegram.Bot.Types.Update { CallbackQuery = new Telegram.Bot.Types.CallbackQuery { Id = "testId", Data = KeyboardService.GetVoteButtonText(voteType), From = GetTestUser(), Message = new Telegram.Bot.Types.Message() { Text = messageText, Date = DateTime.UtcNow, From = GetTestUser(isBot: true), Chat = GetTestChat(), Entities = new Telegram.Bot.Types.MessageEntity[0], ReplyMarkup = _keyboardService.CreatePostedTrackResponseKeyboard(), ReplyToMessage = new Telegram.Bot.Types.Message { From = GetTestUser(), Chat = GetTestChat(), Date = DateTime.UtcNow, Text = trackUrl }, MessageId = messageId, }, ChatInstance = "testChatInstance" } }; return(WriteUpdateToStream(stream, update)); }
private async static Task processUpdate(Telegram.Bot.Types.Update u) { switch (u.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: case Telegram.Bot.Types.Enums.UpdateType.EditedMessage: var msg = u.Type == Telegram.Bot.Types.Enums.UpdateType.Message ? u.Message : u.EditedMessage; if (!string.IsNullOrWhiteSpace(msg.Text)) { var words = msg.Text.Split(" \"';:.,?/\\!(){}[]|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var w in words) { if (WordsHelper.WordsList.Any(i => i.Equals(w, StringComparison.OrdinalIgnoreCase))) { await _client.DeleteMessageAsync(msg.Chat.Id, msg.MessageId); return; } } } break; default: Console.WriteLine($"Type {u.Type} is not implemnted"); break; } }
public Message(Telegram.Bot.Types.Update update) { Id = update.Message.MessageId; DTime = update.Message.Date; Text = update.Message.Text; User = new User(update.Message.From); Location = new Location(update.Message.Location); }
/// <summary> /// Serializes an update and writes it to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="update">The update to write.</param> private async Task WriteUpdateToStream(Stream stream, Telegram.Bot.Types.Update update) { var jsonString = JsonConvert.SerializeObject(update); await stream.WriteAsync(Encoding.UTF8.GetBytes(jsonString)); // Make sure the stream can be read from by resetting it's position. stream.Position = 0; }
public async Task Execude(Telegram.Bot.Types.Update update, TelegramBotClient bot) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, update.Message.Text); _log.Information(update.Message.Text); }
public async Task <bool> ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) { try { var latest = await CheckForUpdatesAsync().ConfigureAwait(false); var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); if (IsNewerVersionAvailable(latest)) { Vars.UpdatePending = true; Vars.UpdateVersion = new Version(latest.Latest); Vars.UpdateLevel = latest.UpdateLevel; var updateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", latest.Latest) .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) .Replace("$3", Methods.GetUpdateLevel(latest.UpdateLevel)); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, updateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); } else { Vars.UpdatePending = false; _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_AlreadyUpToDate .Replace("$1", latest.Latest) .Replace("$2", Vars.AppVer.ToString()) .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); } return(true); } catch (Exception ex) { var errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.Message); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, errorString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); return(true); } }
private void TClient_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e) { Telegram.Bot.Types.Update u = e.Update; if (!SupportedTypes.Contains(u.Message.Type)) { return; } string text = u.Message.Text; Console.WriteLine("Message received: " + text); this.OnMessageReceived(FromTelegramMessage(e.Update.Message)); }
private void processUpdate(Telegram.Bot.Types.Update update) { switch (update.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: var text = update.Message.Text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Recive text: " + text); break; default: Console.WriteLine(update.Type + "Not implemented"); break; } }
public Task WriteInlineQueryToStream(Stream stream, string query) { var update = new Telegram.Bot.Types.Update { InlineQuery = new Telegram.Bot.Types.InlineQuery { Id = "testId", From = GetTestUser(), Query = query, Offset = "" } }; return(WriteUpdateToStream(stream, update)); }
/// <summary> /// Write an update with a text message to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="text">The text to use in the text message.</param> /// <param name="isPrivateChat">Whether or not the chat the message is sent in should be regarded as a private chat.</param> public Task WriteTextMessageToStream(Stream stream, string text, bool isPrivateChat) { var update = new Telegram.Bot.Types.Update { Message = new Telegram.Bot.Types.Message() { Text = text, Date = DateTime.UtcNow, From = GetTestUser(), Chat = GetTestChat(isPrivateChat), Entities = new Telegram.Bot.Types.MessageEntity[0] } }; return(WriteUpdateToStream(stream, update)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); try { Telegram.Bot.Types.Update upd = JsonConvert.DeserializeObject <Telegram.Bot.Types.Update>(requestBody); TelegramBotClient cli = new TelegramBotClient("876359447:AAG66NQmwN0zsUwWH9wrRoTwpJtXo1WwElI"); if (upd.Message.Type == Telegram.Bot.Types.Enums.MessageType.Text) { log.LogInformation($"{upd.Message.From.FirstName} {upd.Message.From.LastName} [{upd.Message.From.Id}] ({upd.Message.From.Username}): {upd.Message.Text}"); QueryHistoryBase qhb = new QueryHistoryBase(); string res = await qhb.GetData(upd.Message.Text); var chatID = upd.Message.Chat.Id; var messageID = upd.Message.MessageId; await cli.SendTextMessageAsync(chatID, res); /* * List<BotCommand> cmds = new List<BotCommand>(); * cmds.Add(new HelloCommand()); * * foreach (BotCommand cmd in cmds) * { * if (cmd.Contains(upd.Message.Text)) * { * cmd.Execute(upd.Message, cli); * } * } */ } } catch (Exception ex) { log.LogInformation($"Caugth :{ex.Message}"); log.LogInformation($"Query for exception :{requestBody}"); } return(new OkResult()); }
static private async void recieveMessage() { writeMessage("Start recieving message"); string lastMessage = null; var lastMessageId = 0; int lastMessageLength = 0; Telegram.Bot.Types.Update last = null; while (true) { try { var message = await botClient.GetUpdatesAsync(); lastMessageLength = message.Length; if (message.Length > 0) { last = message[message.Length - 1]; if (lastMessage != last.Message.Text && DateTime.UtcNow < last.Message.Date.AddSeconds(10).ToUniversalTime()) { lastMessage = last.Message.Text; if (last.Message.Text.Contains("hello")) { botClient.SendTextMessageAsync(last.Message.From.Id, "hello"); } } } if (lastMessageLength < message.Length) { Console.WriteLine(last.Message.Text); lastMessageLength = message.Length; } Thread.Sleep(200); } catch (System.Net.Http.HttpRequestException e) //TODO current decision are not acceptable { Console.WriteLine("Error in recieve message"); Thread thread = new Thread(TelegramBotController.recieveMessage); thread.Start(); } } }
public static async Task Bot_OnMessage(object sender, Telegram.Bot.Types.Update e) { Post Code; if (Is_Init(Persons, e.Message.Chat.Id)) { Code = Return_Chat(Persons, e.Message.Chat.Id); } else { Code = new Post(); Code.Chat_ID = e.Message.Chat.Id; Persons.Add(Code); } Txt_check(e.Message.Text, Code); await Bot_Messages(e, sender, Code); }
public static async Task Edit_Resume(Telegram.Bot.Types.Update e, object sender, Post el) { }
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 async Task <bool> ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) { try { var latest = await CheckForUpdatesAsync().ConfigureAwait(false); var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); if (IsNewerVersionAvailable(latest)) { var updateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", latest.Latest) .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) .Replace("$3", GetUpdateLevel(latest.UpdateLevel)); // \ update available! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, updateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); // \ updating! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateProcessing, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); // download compiled package await DownloadUpdatesAsync(latest, currentLocalizedIndex).ConfigureAwait(false); // update languages if (Vars.CurrentConf.AutoLangUpdate) { await DownloadLangAsync().ConfigureAwait(false); } // \ see you! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateFinalizing, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); Log("Exiting program... (Let the daemon do the restart job)", "BOT"); await ExitApp(0); return(true); // end of difference } else { _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_AlreadyUpToDate .Replace("$1", latest.Latest) .Replace("$2", Vars.AppVer.ToString()) .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); return(true); } } catch (Exception ex) { string errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.ToString()); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, errorString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); return(true); } }
public bool IsApplicable(Telegram.Bot.Types.Update update) { return(true); }
private void processUpdate(Telegram.Bot.Types.Update update) { switch (update.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: var text = update.Message.Text; var msgid = update.Message.Chat.Username; var tlgusername = update.Message.Chat.Username; if (tlgusername != inst.TlgUserName) { inst.TlgUserName = tlgusername; _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons()); } else { // TODO: need to code refactoring in the feature and build this app in Asp.Net if (text == CANCEL) { _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons()); inst.Clear(); break; } if (inst.TicketType == MAIN_3 & string.IsNullOrEmpty(inst.TicketCategory) & string.IsNullOrEmpty(inst.UserName) & string.IsNullOrEmpty(inst.TicketDescription)) { inst.TicketDescription = text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите ваше имя", replyMarkup: CancelButton()); break; } if (inst.TicketType == MAIN_3 & string.IsNullOrEmpty(inst.TicketCategory) & !string.IsNullOrEmpty(inst.TicketDescription) & string.IsNullOrEmpty(inst.PhoneNumber) & string.IsNullOrEmpty(inst.UserName) | !string.IsNullOrEmpty(inst.TicketType) & !string.IsNullOrEmpty(inst.TicketCategory) & string.IsNullOrEmpty(inst.UserName)) { inst.UserName = text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите номер телефона \nПример: 89281234567", replyMarkup: CancelButton()); break; } if (!string.IsNullOrEmpty(inst.TicketType) & !string.IsNullOrEmpty(inst.UserName)) { //if (text.All(char.IsDigit) & text.Substring(0, 1) == "8" || text.Substring(0, 1) == "7" & text.Length == 11) if (text.All(char.IsDigit) & text.Substring(0, 1) == "8" & text.Length == 11) { inst.PhoneNumber = text; // create random no of ticket inst.TicketNumber = RandomNo(); // just for cw Console.WriteLine("ticket: " + inst.TicketNumber); Console.WriteLine("type: " + inst.TicketType); Console.WriteLine("category: " + inst.TicketCategory); Console.WriteLine("description: " + inst.TicketDescription); Console.WriteLine("username" + inst.UserName); Console.WriteLine("phone: " + inst.PhoneNumber); Console.WriteLine("tlg: " + inst.TlgUserName); Console.WriteLine("------------"); _client.SendTextMessageAsync(update.Message.Chat.Id, $"Спасибо, {inst.UserName}! Ваша заявка №{inst.TicketNumber} принята."); _client.SendTextMessageAsync(update.Message.Chat.Id, "Перенаправляю вас в Главное меню!", replyMarkup: GetButtons()); // run method for sendind tlgChannel SendTlgChannel(inst.TicketType, inst.TicketCategory, inst.TicketNumber, inst.TicketDescription, inst.UserName, inst.PhoneNumber, inst.TlgUserName); // run method for sendind Email //SendEmail(inst.TicketType, inst.TicketCategory, inst.TicketNumber, inst.UserName, inst.PhoneNumber); inst.Clear(); } else { _client.SendTextMessageAsync(update.Message.Chat.Id, "Некорректный номер, пожалуйста, введите правильный номер телефона \nПример: 89281234567", replyMarkup: CancelButton()); } break; } switch (text) { case MAIN_1: case MAIN_2: case MAIN_4: inst.TicketType = text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите категорию в меню", replyMarkup: GetCategory()); break; case MAIN_3: inst.TicketType = text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите описание проблемы", replyMarkup: CancelButton()); break; case CAT_1: case CAT_2: case CAT_3: case CAT_4: inst.TicketCategory = text; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите имя", replyMarkup: CancelButton()); break; default: _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons()); break; } } break; } }
private void processUpdate(Telegram.Bot.Types.Update update) { switch (update.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: var text = update.Message.Text; switch (text) { case "/Start": _client.SendTextMessageAsync(update.Message.Chat.Id, "Бот запушен\t\n Для получения новостей воспользуйтесь командой /News"); break; case "/start": _client.SendTextMessageAsync(update.Message.Chat.Id, "Бот запушен\t\n Для получения новостей воспользуйтесь командой /News"); break; case "/News": _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите интересующий вас новостной раздел", replyMarkup: GetInlineButtons()); break; case "/news": _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите интересующий вас новостной раздел", replyMarkup: GetInlineButtons()); break; default: _client.SendTextMessageAsync(update.Message.Chat.Id, "Неизвестная команда - " + text + "\t\n Для получения новостей воспользуйтесь командой /News"); break; } break; case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery: NewsAgregator NA = new NewsAgregator(); switch (update.CallbackQuery.Data) { case "1": var msg1 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, "\ud83d\udce2 ГЛАВНОЕ:\t\n" + NA.GetMain().Result, replyMarkup: GetInlineButtons()); break; case "2": var msg2 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, "\u2694\ufe0f ПОЛИТИКА:\t\n" + NA.GetPolitic().Result, replyMarkup: GetInlineButtons()); break; case "3": var msg3 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, "\ud83d\udcbc ЭКОНОМИКА:\t\n" + NA.GetEconomic().Result, replyMarkup: GetInlineButtons()); break; case "4": var msg4 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, "\ud83e\udd4a СПОРТ:\t\n" + NA.GetSport().Result, replyMarkup: GetInlineButtons()); break; case "5": var msg5 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, "\ud83d\udcb5 КУРС ВАЛЮТ:\t\n" + NA.GetRates().Result); break; } break; default: Console.WriteLine(update.Type + " Данный тип сообщения не обрабатывается"); break; } }
public UpdateAction(IBotContext botContext) : base(botContext) { Update = botContext.Update; }
private void processUpdate(Telegram.Bot.Types.Update update) { switch (update.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: var text = update.Message.Text; string imagePath = null; var state = _clientStates.ContainsKey(update.Message.Chat.Id) ? _clientStates[update.Message.Chat.Id] : null; if (state != null) { switch (state.State) { case State.SearchMusic: if (text.Equals(TEXT_BACK)) { _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите:", replyMarkup: GetButtons()); _clientStates[update.Message.Chat.Id] = null; } else { var songs = GetSongsByAuthor(author: text); if (songs?.Item2 != null && songs.Item2.Count > 0) { state.State = State.SearchSong; state.Author = text; imagePath = Path.Combine(Environment.CurrentDirectory, songs.Item1); using (var stream = File.OpenRead(imagePath)) { var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: state.Author).Result; } _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите название песни:", replyMarkup: getSongsButtons(songs.Item2)); } else { _client.SendTextMessageAsync(update.Message.Chat.Id, "Ничего не найдено\nВведите автора:", replyMarkup: getAuthors()); } } break; case State.SearchSong: if (text.Equals(TEXT_BACK)) { state.State = State.SearchMusic; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите автора:", replyMarkup: getAuthors()); } else { var songPath = getSongPath(text); var songs2 = GetSongsByAuthor(author: state.Author); if (!string.IsNullOrEmpty(songPath) && File.Exists(songPath)) { _client.SendTextMessageAsync(update.Message.Chat.Id, "Песня загружается..."); using (var stream = File.OpenRead(songPath)) { var r = _client.SendAudioAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), replyMarkup: getSongsButtons(songs2.Item2)).Result; } } else { _client.SendTextMessageAsync(update.Message.Chat.Id, "Ничего не найдено\nВведите название песни:", replyMarkup: getSongsButtons(songs2.Item2)); } } break; } } else { switch (text) { case TEXT_MUSIC: _clientStates[update.Message.Chat.Id] = new UserState { State = State.SearchMusic }; _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите автора:", replyMarkup: getAuthors()); break; case TEXT_1: imagePath = Path.Combine(Environment.CurrentDirectory, "1.png"); using (var stream = File.OpenRead(imagePath)) { var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "1", replyMarkup: GetInlineButton(1)).Result; } break; case TEXT_2: imagePath = Path.Combine(Environment.CurrentDirectory, "2.png"); using (var stream = File.OpenRead(imagePath)) { var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "2", replyMarkup: GetInlineButton(2)).Result; } break; case TEXT_3: imagePath = Path.Combine(Environment.CurrentDirectory, "3.png"); using (var stream = File.OpenRead(imagePath)) { var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "3", replyMarkup: GetInlineButton(3)).Result; } break; case TEXT_4: imagePath = Path.Combine(Environment.CurrentDirectory, "4.png"); using (var stream = File.OpenRead(imagePath)) { var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "4", replyMarkup: GetInlineButton(4)).Result; } break; default: _client.SendTextMessageAsync(update.Message.Chat.Id, "Receive text :" + text, replyMarkup: GetButtons()); break; } } break; case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery: switch (update.CallbackQuery.Data) { case "1": var msg1 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result; break; case "2": var msg2 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result; break; case "3": var msg3 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result; break; case "4": var msg4 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result; break; } break; default: Console.WriteLine(update.Type + " Not ipmlemented!"); break; } }
private static bool IsUpdate(TelegramUpdate update) { return(update.Message?.Type == MessageType.Text && update.Message?.Text == "/update"); }
public void Receive(Telegram.Bot.Types.Update update) { Incoming.Invoke(new Message(update)); }
public async Task Post([FromBody] Telegram.Bot.Types.Update update) { await _commandHandler.HandleCommand(update.Message); }