internal void GetUpdates() { _client = new Telegram.Bot.TelegramBotClient(_token); var me = _client.GetMeAsync().Result; if (me != null && !string.IsNullOrEmpty(me.Username)) { int offset = 0; while (true) { try { var updates = _client.GetUpdatesAsync(offset).Result; if (updates != null && updates.Count() > 0) { foreach (var update in updates) { processUpdate(update); offset = update.Id + 1; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Thread.Sleep(1000); } } }
public async Task <bool> Execute() { string botToken = _configuration.GetValue <string>("Bot:Token"); Telegram.Bot.TelegramBotClient botClient = new Telegram.Bot.TelegramBotClient(botToken); BotSettingModel setting = LoadSetting(); Telegram.Bot.Types.Update[] updates = await botClient.GetUpdatesAsync(setting.LastChatID + 1); string RegisterKey = _configuration.GetValue <string>("Bot:RegisterKey"); string DeleteAccountKey = _configuration.GetValue <string>("Bot:DeleteAccountKey"); string GetResponseKey = _configuration.GetValue <string>("Bot:GetResponseKey"); foreach (Telegram.Bot.Types.Update update in updates) { string chatText = string.Empty; chatText = update?.Message?.Text ?? string.Empty; long chatId = update.Message.Chat.Id; if (chatText == RegisterKey) { if (!setting.Receivers.Any(x => x == chatId.ToString())) { setting.Receivers.Add(chatId.ToString()); await botClient.SendTextMessageAsync(chatId, "به دریافت کنندگان اضافه شدی", replyMarkup : getKeyboard()); } else { await botClient.SendTextMessageAsync(chatId, "قبلا اضافه شدی", replyMarkup : getKeyboard()); } } else if (chatText == DeleteAccountKey) { if (setting.Receivers.Any(x => x == chatId.ToString())) { setting.Receivers.Remove(chatId.ToString()); await botClient.SendTextMessageAsync(chatId, "از دریافت کنندگان حذف شدی", replyMarkup : getKeyboard()); } else { await botClient.SendTextMessageAsync(chatId, "توی لیست نیستی", replyMarkup : getKeyboard()); } } else if (chatText == "/start") { await botClient.SendTextMessageAsync(chatId, "سلام، چیکار کنم برات ؟!", replyMarkup : getKeyboard()); } else if (chatText == GetResponseKey) { await _restApi.GetResponse(chatId); } else { await botClient.SendTextMessageAsync(chatId, "نمیفهمم چی میگی", replyMarkup : getKeyboard()); } setting.LastChatID = update.Id; } SaveSetting(setting); return(true); }
private async Task BotProcessCycle(bool firstTime) { try { await this.LoadBotSettings(); TimeSpan interval = TimeSpan.FromMilliseconds(this._config.Interval); TimeSpan delay = (firstTime ? TimeSpan.Zero : interval); while (!_cts.IsCancellationRequested) { if (delay > TimeSpan.Zero) { _logger.LogTrace(delay.ToString()); await Task.Delay(delay, _cts.Token); if (_cts.IsCancellationRequested) { break; } } DateTime startTime = DateTime.UtcNow; Update[] updates = await _telegramClient.GetUpdatesAsync(_offset, 10, 0, null, _cts.Token); if (_cts.IsCancellationRequested) { break; } foreach (Update update in updates) { _offset = Math.Max(_offset, update.Id) + 1; if (_cts.IsCancellationRequested) { break; } await this.UpdateOffset(_offset); } if (_cts.IsCancellationRequested) { break; } await this.SendNotifications(); DateTime endTime = DateTime.UtcNow; TimeSpan timeElapsed = endTime - startTime; delay = (timeElapsed > interval ? TimeSpan.Zero : interval - timeElapsed); } } catch (Exception ex) { string exStr = ex.ToString(); _logger.LogError(exStr); Helper.SaveDiagMessage(_sqlServer, DiagOptions.Tech, "DiagHostedService.BotProcessCycle: " + exStr, _logger); } }
/// <summary> /// Main loop of processing messages /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void TgBotWorker_DoWork(object sender, DoWorkEventArgs e) { try { var bgWorker = sender as BackgroundWorker; var bot = new Telegram.Bot.TelegramBotClient(this.ApiKey); // clear webhook field await bot.SetWebhookAsync(""); int offset = 0; //TODO: need read from file or database while (true) { var updates = await bot.GetUpdatesAsync(offset, allowedUpdates : new UpdateType[] { UpdateType.MessageUpdate }); foreach (var update in updates) { var resProc = await ProcessTgUpdate(bot, update); offset = update.Id + 1; } System.Threading.Thread.Sleep(1000); if (bgWorker?.CancellationPending ?? false) { break; } } } catch (Exception ex) { Log($"Exeption = {ex.ToString()}"); } }
private async void BW_TelegramLoop(object sender, DoWorkEventArgs e) { BackgroundWorker tbw = sender as BackgroundWorker; var key = e.Argument as string; try { var bot = new Telegram.Bot.TelegramBotClient(key); await bot.SetWebhookAsync(""); int offset = 0; while (true) { var updates = await bot.GetUpdatesAsync(offset); foreach (var update in updates) { bool res = await ProcessTelegramUpdate(bot, update); offset = update.Id + 1; } System.Threading.Thread.Sleep(1000); // to avoid CPU load } } catch (Exception ex) { MessageBox.Show($"Error {ex.Message}"); SetStatus("Работа остановлена по ошибке"); } }
public async Task <IActionResult> GetUpdates() { var token = configuration.GetValue <string>("TelegramToken"); var client = new Telegram.Bot.TelegramBotClient(token, httpClient); var updates = await client.GetUpdatesAsync(); lastupdate.Add(JsonConvert.SerializeObject(updates)); return(RedirectToAction("Index")); }
private static async void GetMessage() { int lastMessageID = 0; while (true) { var message = await bot.GetUpdatesAsync(); if (message.Length > 0) { var last = message[message.Length - 1]; if (lastMessageID != last.Id) { Console.WriteLine(last.Message.Text); if (last.Message.Text == "Привет") { bot.SendTextMessageAsync(last.Message.Chat.Id, "Ну, здравствуй!").Wait(); } if (last.Message.Text == "Варя") { bot.SendTextMessageAsync(last.Message.Chat.Id, "Варя - самая красивая и умная на свете!").Wait(); } try { CultureInfo temp_culture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); double cash = double.Parse(last.Message.Text); Thread.CurrentThread.CurrentCulture = temp_culture; if (cash > 0) { bot.SendTextMessageAsync(last.Message.Chat.Id, "Введено число. Что мы с ним будем делать?").Wait(); } } catch { } } lastMessageID = last.Id; } Thread.Sleep(200); } }
internal void GetUpdates() { _client = new Telegram.Bot.TelegramBotClient(_token); var me = _client.GetMeAsync().Result; // информация о боте if (me != null && !string.IsNullOrEmpty(me.Username)) { Console.WriteLine("Бот запущен"); int offset = 0; while (true) { try { var updates = _client.GetUpdatesAsync(offset).Result; // получаем сам апдейт if (updates != null && updates.Count() > 0) { foreach (var update in updates) { if (update.Message != null) { Console.WriteLine(DateTime.Now + " От пользователя: " + update.Message.Chat.FirstName + " - " + update.Message.From + " Текст: " + update.Message.Text); } else if (update.CallbackQuery != null) { Console.WriteLine(DateTime.Now + " От пользователя: " + update.CallbackQuery.Message.Chat.FirstName + " - " + update.CallbackQuery.From + " CallbackQuery: " + update.CallbackQuery.Data); } processUpdate(update); // обработка сообщения offset = update.Id + 1; // переключение на след. сообщение } } } catch (Exception ex) { Console.WriteLine("Ошибка в работе бота"); Console.WriteLine(ex.Message); } Thread.Sleep(1000); } } }
async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var key = e.Argument as String; // получаем ключ аргументов try { var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API await Bot.SetWebhookAsync(""); //Bot.SetWebhook(""); // Обязательно! убираем старую привязку к вебхуку для бота int offset = 0; // отступ по сообщениям while (true) { var newUpdates = await Bot.GetUpdatesAsync(offset); // получаем массив обновлений var updates = newUpdates.Distinct().ToArray(); // убираем повторения из списка новых запросов foreach (var update in updates) // Перебираем все обновления { var message = update.Message; if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text) { if (message.Text == "/getimage" || message.Text == "/getimage@...") //После @ - пишем ссылку на вашего бота!!! Это нужно для исп бота в конфах!!! { ImgurPars imgurPars = new ImgurPars(); // в ответ на команду /getimage выводим картинку await Bot.SendPhotoAsync(message.Chat.Id, imgurPars.GeneratePictur()); } } offset = update.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки } }
private static async Task RunBot() { var botClient = new Telegram.Bot.TelegramBotClient(botId); var me = await botClient.GetMeAsync(); Console.WriteLine($"Hello! My name is {me.FirstName}"); var updates = await botClient.GetUpdatesAsync(offset : updateId); Console.WriteLine("Found some updates. " + updates.Length); foreach (var update in updates) { updateId = update.Id + 1; if (string.Equals(update.Message.From.Username, fromOnly, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Received a message from Andrey."); if (update.Message.Text == "Privet") { await botClient.SendTextMessageAsync(update.Message.Chat.Id, "Privet andrey"); Console.WriteLine("Message sent"); } } } }
static async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var key = e.Argument as String; // получаем ключ из аргументов var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API await Bot.SetWebhookAsync(""); var preUpdates = await Bot.GetUpdatesAsync(-1); offset = preUpdates.Select(s => s.Id).LastOrDefault(); offset += 1; try { bool repeat = true; while (repeat) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates) // Перебираем все обновления { offset += 1; switch (update.Type) { case UpdateType.Message: var message = update.Message; if (update.Message.Type == Telegram.Bot.Types.Enums.MessageType.Text && message.Text.Replace("@BeOpenChatBot", "").ToLower() == ("/restart")) { repeat = false; offset = 0; throw new Exception($"Бот был перезапущен при помощи команды /restart , данную команду запустил @{message.From.Username} - {message.From.FirstName}"); } else { if (update.Message.Type == Telegram.Bot.Types.Enums.MessageType.Text) { await MessageHandling.MessageProcessingAsync(update, Bot, key); Console.WriteLine($"[{DateTime.Now}] - From: @{message.From.Username} - Message: {message.Text}"); } } if (update.Message.Type == Telegram.Bot.Types.Enums.MessageType.Voice || update.Message.Type == Telegram.Bot.Types.Enums.MessageType.VideoNote) { await Bot.SendTextMessageAsync(message.Chat.Id, "Мне лень его слушать...", replyToMessageId : message.MessageId); } break; case UpdateType.CallbackQuery: break; case UpdateType.InlineQuery: break; case UpdateType.EditedMessage: break; case UpdateType.EditedChannelPost: break; case UpdateType.ChosenInlineResult: break; case UpdateType.ChannelPost: break; case UpdateType.Poll: break; case UpdateType.PollAnswer: break; case UpdateType.PreCheckoutQuery: break; case UpdateType.ShippingQuery: break; case UpdateType.Unknown: break; default: break; } } } } catch (Exception ex) { await Bot.SendTextMessageAsync("441224506", ex.Message + "-" + ex.StackTrace); bw.RunWorkerAsync(publicKey); } }
async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var key = e.Argument as String; try { var Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; while (true) { Update[] updates; decimal conAttempts = 1; decimal allwaitingseconds = 0; while (true) { try { updates = await Bot.GetUpdatesAsync(offset); } catch (Exception ex) { allwaitingseconds += (conAttempts / 10); SendLog("No connection for the last " + allwaitingseconds + " seconds, attempt = " + conAttempts++); Thread.Sleep((int)conAttempts * 100); continue; } conAttempts = 1; break; } foreach (var update in updates) { Person p = null; if (update.Message.From.Username != null) { p = new Person(update.Message.From.Id, update.Message.From.Username, constr); } else { p = new Person(update.Message.From.Id, update.Message.From.FirstName + " " + update.Message.From.LastName, constr); } var keyboardStandart = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton("Задание"), }, new[] { new Telegram.Bot.Types.KeyboardButton("Очки"), new Telegram.Bot.Types.KeyboardButton("ТОП-10"), new Telegram.Bot.Types.KeyboardButton("Помощь") }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; var keyboardStandartFail = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton("Задание") }, new[] { new Telegram.Bot.Types.KeyboardButton("Очки"), new Telegram.Bot.Types.KeyboardButton("ТОП-10"), new Telegram.Bot.Types.KeyboardButton("Помощь") }, new[] { new Telegram.Bot.Types.KeyboardButton("Ошибка в последнем вопросе?") }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; var keyboardSerial = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton(p.VSerial[0]), new Telegram.Bot.Types.KeyboardButton(p.VSerial[1]), new Telegram.Bot.Types.KeyboardButton(p.VSerial[2]), new Telegram.Bot.Types.KeyboardButton(p.VSerial[3]) }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; var keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(); if (p.C_serial == "SGU") { keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton("1"), new Telegram.Bot.Types.KeyboardButton("2") }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; } else { keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton(p.V_Season[0]), new Telegram.Bot.Types.KeyboardButton(p.V_Season[1]), new Telegram.Bot.Types.KeyboardButton(p.V_Season[2]), new Telegram.Bot.Types.KeyboardButton(p.V_Season[3]) }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; } var keyboardSeries = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton(p.V_Series[0]) }, new[] { new Telegram.Bot.Types.KeyboardButton(p.V_Series[1]) }, new[] { new Telegram.Bot.Types.KeyboardButton(p.V_Series[2]) }, new[] { new Telegram.Bot.Types.KeyboardButton(p.V_Series[3]) }, }, OneTimeKeyboard = false, ResizeKeyboard = true }; var message = update.Message; bool recognise = false; if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { #region stand_0 if (p.stand == 0) { if (message.Text == "/start") { p.Ask = false; recognise = true; if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), "Из какого сериала или фильмов эта картинка?", false, 0, keyboardSerial); } else { await Bot.SendTextMessageAsync(message.Chat.Id, "Из какого сериала или фильмов эта фраза? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSerial); } } if (message.Text == p.VSerial[0] || message.Text == p.VSerial[1] || message.Text == p.VSerial[2] || message.Text == p.VSerial[3]) { p.Ask = false; recognise = true; if (message.Text == p.C_serial) { if (p.C_serial == "Movies") { p.stand += 2; p.SaveToSQl(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId); if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой фильм?", false, 0, keyboardSeries); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой фильм? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries); } } else { p.stand++; p.SaveToSQl(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId); if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой сезон?", false, 0, keyboardSeason); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой сезон? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeason); } } } else { p.stand = 3; p.TaskWrong(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId); await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail); } } } #endregion #region stand_1 if (p.stand == 1) { if (message.Text == "/start") { p.Ask = false; recognise = true; if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой сезон?", false, 0, keyboardSeason); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой сезон?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeason); } } if (p.C_serial == "SGU") { if (message.Text == "1" || message.Text == "2") { p.Ask = false; recognise = true; if (message.Text == p.C_season) { p.stand++; p.SaveToSQl(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId); if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries); } } else { p.stand = 3; p.TaskWrong(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId); await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail); } } } else { if (message.Text == p.V_Season[0] || message.Text == p.V_Season[1] || message.Text == p.V_Season[2] || message.Text == p.V_Season[3]) { p.Ask = false; recognise = true; if (message.Text == p.C_season) { p.stand++; p.SaveToSQl(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId); if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries); } } else { p.stand = 3; p.TaskWrong(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId); await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail); } } } } #endregion #region stand_2 if (p.stand == 2) { if (message.Text == "/start") { p.Ask = false; recognise = true; if (p.C_serial == "Movies") { if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой фильм?", false, 0, keyboardSeries); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой фильм?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries); } } else { if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries); } else { await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries); } } } if (message.Text == p.V_Series[0] || message.Text == p.V_Series[1] || message.Text == p.V_Series[2] || message.Text == p.V_Series[3]) { p.Ask = false; recognise = true; if (message.Text == p.C_series) { p.stand++; p.TaskDone(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " SCORE " + p.Score + " TASK_ID " + p.taskId); await Bot.SendTextMessageAsync(message.Chat.Id, p.C_series + ", верно! Вы молодец! Запрашивайте новое задание :)", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } else { p.stand = 3; p.TaskWrong(); SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId); await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail); } } } #endregion #region stand_3 if (p.stand == 3) { if (message.Text == "Задание") { recognise = true; p.Ask = false; p.stand = 0; p.GetTask(); SendLog(message.Text + " TO " + p.UserName + " TASK_ID " + p.taskId); if (p.task.Contains("http")) { await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), "Из какого сериала или фильмов эта картинка?", false, 0, keyboardSerial); } else { await Bot.SendTextMessageAsync(message.Chat.Id, "Из какого сериала или фильмов эта фраза?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSerial); } } if (message.Text == "Ошибка в последнем вопросе?" && !p.done) { recognise = true; p.Ask = true; p.SaveToSQl(); SendLog("SEND_INSTRUCTION_TO_WRONG_MSG_TO " + p.UserName + " TASK_ID " + p.taskId + " ASK_UNIT " + p.Ask.ToString()); await Bot.SendTextMessageAsync(message.Chat.Id, "Отправьте сообщение с описанием проблемы на столько широко как сможете, так же тут можно оставить свой отзыв.", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } if (message.Text == "Помощь") { p.Ask = false; recognise = true; SendLog(message.Text + " TO " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, "Просто отвечайте на вопросы и зарабатывайте очки. Верный ответ +1, неверный -1 балл.\nДля управления чатом используй кнопки внизу.", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } if (message.Text == "ТОП-10") { p.Ask = false; recognise = true; SendLog(message.Text + " TO " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, getTopList(), Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } if (message.Text == "Очки") { p.Ask = false; recognise = true; SendLog(message.Text + " TO " + p.UserName + " SCORE " + p.Score); await Bot.SendTextMessageAsync(message.Chat.Id, "Кол-во очков: " + p.Score, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } if (message.Text == "/start") { p.Ask = false; recognise = true; if (!p.amnew) { SendLog("NEW_OLD_USER " + p.Id + " NAME " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, "С Возвращением!\nИспользуйте клавиатуру для работы с чатом", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } else { SendLog("NEW_USER " + p.Id + " NAME " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, "Добро пожаловать!\nИспользуйте клавиатуру для работы с чатом", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } } } #endregion if (message.Text != "" && !recognise && !p.Ask) { SendLog(message.Text + " SOME_TEXT_WRONG " + " FROM " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, "Я не могу ответить на это сообщение, не кликайте на кнопку по нескольку раз, не дождавшись ответа и не пишите с клавиатуры до требования бота!"); } else if (message.Text != "" && p.Ask && !recognise) { p.Ask = false; SendLog(message.Text + " RECEIVING_MSG_FROM_USER " + p.UserName); AskToSQL(message.Text, p); p.SaveToSQl(); await Bot.SendTextMessageAsync(message.Chat.Id, "Ваше сообщение принято для обработки, со временем изменения вступят в силу", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart); } } else { SendLog("SOME_NOT_TEXT_WRONG " + " FROM " + p.UserName); await Bot.SendTextMessageAsync(message.Chat.Id, "Я могу отвечать только на текстовые сообщения!"); } offset = update.Id + 1; } } } catch (Exception ex) { File.WriteAllText(DateTime.Now.ToString("dd.MM.yy hh.mm.ss") + " errorlog.txt", DateTime.Now + " -- " + ex.Message + "\n" + ex.TargetSite.Name + "\n" + ex.StackTrace + "\n" + ex.HelpLink); Application.Current.Shutdown(); } }
static async Task Runasync() { var bot = new Telegram.Bot.TelegramBotClient("225047213:AAHMueC2hE3k_VTUJJMe5jxdPt0KT3Xm6xc"); var me = await bot.GetMeAsync(); var offset = 0; while (true) { var updates = await bot.GetUpdatesAsync(offset); foreach (var update in updates) { if (update.Message.Type == MessageType.PhotoMessage) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "چه عکس زیبایی"; await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (update.Message.Type == MessageType.TextMessage) { string msg = update.Message.Text; if (msg.Contains("salam")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "سلام عزیزم حالت چطوره؟"; await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("سلام")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "سلام عزیزم حالت چطوره؟"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("چطور")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "منم خوبم بلطف شما"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("chetor")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "منم خوبم بلطف شما"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("khabar")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "سلامتی"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("خبر")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "سلامتی"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("کوس")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("کس")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("بگا")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("گایید")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("گائید")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("بخطا")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (msg.Contains("به خطا")) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "عیبه حرف بد نزن"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "از ارسال زیبای شما متشکرم"; var t = await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } } else if (update.Message.Type == MessageType.StickerMessage) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "این استیکرارو از کجا میاری میگی منم دانلود کنم؟"; await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } else if (update.Message.Type == MessageType.VoiceMessage) { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "گوش میکنم بعدا نظرمو میگم"; await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); await Task.Delay(6000); await bot.SendTextMessageAsync(update.Message.Chat.Id, "جالب بود"); } else { await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing); await Task.Delay(2000); string outputMsg = "من تازه به دنیا اومدم همه چی رو که متوجه نمی شم ببخشید"; await bot.SendTextMessageAsync(update.Message.Chat.Id, outputMsg); } offset = update.Id + 1; } } }
async void bw_DoWork(object sender, DoWorkEventArgs e) { /*Commands.Add("/start"); * Commands.Add("/balance"); * Commands.Add("/chatID"); * Commands.Add("/ОРЁЛ"); * Commands.Add("/РЕШКА"); * Commands.Add("/0,2"); * Commands.Add("/0,4"); * Commands.Add("/0,6"); * Commands.Add("/0,8");*/ var worker = sender as BackgroundWorker; var key = "400994008:AAF_AngoYyaakmuAhsv63kSR_fXkO6NA8ek"; // получаем ключ из аргументов bool rate = false; int rateCount; //ОРЁЛ - 1 :РЕШКА - 2. int randomizeCount; Random rand = new Random(); try { var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API await Bot.SetWebhookAsync(""); //Bot.SetWebhook(""); // Обязательно! убираем старую привязку к вебхуку для бота int offset = 0; // отступ по сообщениям while (true) { var updates = await Bot.GetUpdatesAsync(offset); // получаем массив обновлений foreach (var update in updates) // Перебираем все обновления { var message = update.Message; chatID = message.Chat.Id; const string connStr = "server=localhost;user=root;database=bot_1;password = 000000;"; MySqlConnection conn = new MySqlConnection(connStr); conn.Open(); string blnc = "SELECT balance FROM bot_1.user where id = " + chatID; MySqlCommand commandCheckBalance = new MySqlCommand(blnc, conn); balance = (float)Convert.ToDouble(commandCheckBalance.ExecuteScalar()); conn.Clone(); if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { /*for (int i = 0; i < 9;i++) * { * if (message.Text.Substring(0, 1) != Commands[i]) * { * await Bot.SendTextMessageAsync(message.Chat.Id, "Я тебя не понимаю.. Напиши /start !"); * } * }*/ if (message.Text == "/start") { await Bot.SendTextMessageAsync(message.Chat.Id, "Начнём💸 "+ "\r\n\r\nДля начала я даю тебе " + startBonus.ToString() + " рублей." + "\r\nА благодаря этому боту можно влёгкую поднять денег!👑 " + "\r\nВсеголишь угадывая монету. " + "\r\nПрямо сейчас можешь начать зарабатывать!"); // reply buttons var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] // row 1 { new Telegram.Bot.Types.KeyboardButton("/0,2"), new Telegram.Bot.Types.KeyboardButton("/0,4"), new Telegram.Bot.Types.KeyboardButton("/0,6"), new Telegram.Bot.Types.KeyboardButton("/0,8") }, }, ResizeKeyboard = true }; await Bot.SendTextMessageAsync(message.Chat.Id, "Сделай ставку:", false, false, 0, keyboard, Telegram.Bot.Types.Enums.ParseMode.Default); } if (message.Text == "/0,2" || message.Text == "/0,4" || message.Text == "/0,6" || message.Text == "/0,8") { await Bot.SendTextMessageAsync(message.Chat.Id, "Ставки приняты💰"); var keyboard2 = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] // row 1 { new Telegram.Bot.Types.KeyboardButton("/ОРЁЛ"), new Telegram.Bot.Types.KeyboardButton("/РЕШКА") }, }, ResizeKeyboard = true }; await Bot.SendTextMessageAsync(message.Chat.Id, "Испытай удачу!💸", false, false, 0, keyboard2, Telegram.Bot.Types.Enums.ParseMode.Default); } if (message.Text == "/balance") { await Bot.SendTextMessageAsync(message.Chat.Id, "Твой баланс💸:" + balance); } if (message.Text == "/chatID") { await Bot.SendTextMessageAsync(message.Chat.Id, "Твой chatID:" + chatID); } // обработка reply кнопок if (message.Text == "/ОРЁЛ") { rate = true; rateCount = 1; randomizeCount = rand.Next(0, 2); if (randomizeCount == 0) { await Bot.SendTextMessageAsync(message.Chat.Id, "Ии этооо... ОРЁЛ \r\nУгадал!😇"); await Bot.SendTextMessageAsync(message.Chat.Id, "Тебе зачислено💸:"); } if (randomizeCount == 1) { await Bot.SendTextMessageAsync(message.Chat.Id, "Ии этооо... РЕШКА \r\nНе угадал!😈"); await Bot.SendTextMessageAsync(message.Chat.Id, "С чёта списано💵:"); } } if (message.Text == "/РЕШКА") { rate = true; rateCount = 2; randomizeCount = rand.Next(0, 2); if (randomizeCount == 1) { await Bot.SendTextMessageAsync(message.Chat.Id, "Ии этооо... РЕШКА \r\nУгадал!😇"); await Bot.SendTextMessageAsync(message.Chat.Id, "Тебе зачислено💸:"); } if (randomizeCount == 0) { await Bot.SendTextMessageAsync(message.Chat.Id, "Ии этооо... ОРЁЛ \r\nНе угадал!😈"); await Bot.SendTextMessageAsync(message.Chat.Id, "С чёта списано💵:"); } } Bot.StartReceiving(); } offset = update.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки } }
async void bw_DoWork(object sender, DoWorkEventArgs e) { bool answer = false; var translate = new Translate(); var worker = sender as BackgroundWorker; Telegram.Bot.Types.User u = new Telegram.Bot.Types.User(); var key = e.Argument as String; try { var Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; while (true) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates) { var message = update.Message; if (message == null) { continue; }/* * if ((message.Type == Telegram.Bot.Types.Enums.MessageType.StickerMessage)&&(message.From.FirstName=="Infinity")) * await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);*/ if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { //music /*if(message.Text.Contains("/music")) * { * Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://www.dropbox.com/s/1nwbwwe8d4m58uk/Death%20Note%20-%20L%27s%20Theme%20%28full%29.mp3"); * await Bot.SendDocumentAsync(message.Chat.Id, f, "here it`s"); * }*/ //crypt DateTime d = DateTime.Now; if (d.Minute % 15 == 0) { await Bot.SendTextMessageAsync(message.Chat.Id, "vote for AA!"); } if (message.Text.Contains("/encrypt")) { EnCrypt crypt = new EnCrypt(); try { string[] s = message.Text.Split(' ').ToArray(); string res = crypt.EncryptOrDecrypt(message.Text.Substring(message.Text.IndexOf("t") + 2), "1234"); await Bot.SendTextMessageAsync(message.Chat.Id, res, replyToMessageId : message.MessageId); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error", replyToMessageId : message.MessageId); } try { await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId); } catch (Exception) { } } //rev if (message.Text.ToLower().Contains("/realrevolution")) { try { await Bot.SendTextMessageAsync(message.Chat.Id, "It`s a revolution.", replyToMessageId : message.MessageId); await Bot.SendTextMessageAsync(message.Chat.Id, "В основном(5 человек) поддержали идею свержения Дани за:"); await Bot.SendTextMessageAsync(message.Chat.Id, "• Смену названия группы"); await Bot.SendTextMessageAsync(message.Chat.Id, "• Ненависть к аниме"); await Bot.SendTextMessageAsync(message.Chat.Id, "• Нечестные глосования(накрутка)"); await Bot.SendTextMessageAsync(message.Chat.Id, "Итак, мы свергаем его, и всеми банами/нарушениями будет заниматся БОТ. Только система будет определять меру присечения человека."); await Bot.SendTextMessageAsync(message.Chat.Id, "Админами будут я Бот, и тот, кого выберут на новом голо-и."); await Bot.SetChatTitleAsync(message.Chat.Id, "AAA club oficial"); } catch (Exception) { } } //ban if (message.Text.ToLower().Contains("/ban")) { var ban = new Ban(); try { ban.GetMessage(message.Text); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, message.From.FirstName + " " + message.From.LastName + "(" + message.From.Username + " pidor ne lamay bota"); } if (ban.NeedToBan()) { await Bot.SendTextMessageAsync(message.Chat.Id, "Sviatoslav(@pauchok1love) ban please " + ban.Name(), replyToMessageId : message.MessageId); } else { await Bot.SendTextMessageAsync(message.Chat.Id, "system don`t need to ban " + ban.Name(), replyToMessageId : message.MessageId); } } //counter if (message.Text.ToLower().Contains("/counter")) { if (message.Text.Substring(message.Text.IndexOf("r") + 2).Length > 5) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); continue; } Mamkate mamkate = new Mamkate(); mamkate.GetTime(Convert.ToInt32(message.Text.Substring(message.Text.IndexOf("r") + 2))); try { await Bot.SendTextMessageAsync(message.Chat.Id, mamkate.Timer()); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); } } //trigger if (message.Text.Contains("/trigger")) { if (message.Text.ToLower().Contains("dania") || message.Text.ToLower().Contains("даня")) { Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/ee1rvx/image.png"); Telegram.Bot.Types.FileToSend f2 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/mR9Gfx/20180228_073506_1.jpg"); Telegram.Bot.Types.FileToSend f1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/janjhc/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, f, "trigger #1"); await Bot.SendPhotoAsync(message.Chat.Id, f1, "trigger #2"); await Bot.SendPhotoAsync(message.Chat.Id, f2, "trigger #3"); } if (message.Text.ToLower().Contains("mark") || message.Text.ToLower().Contains("марк")) { Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/nMRLOH/image.png"); Telegram.Bot.Types.FileToSend f1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/dOnMVx/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, f, "trigger #1"); await Bot.SendPhotoAsync(message.Chat.Id, f1, "trigger #2"); } if (message.Text.ToLower().Contains("slavka") || message.Text.ToLower().Contains("славка")) { Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/gjhzHc/image.png"); Telegram.Bot.Types.FileToSend f2 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/jsLiCn/image.png"); Telegram.Bot.Types.FileToSend f1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/cJvEiH/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, f, "trigger #1"); await Bot.SendPhotoAsync(message.Chat.Id, f1, "trigger #2"); await Bot.SendPhotoAsync(message.Chat.Id, f2, "trigger #3"); } if (message.Text.ToLower().Contains("artur") || message.Text.ToLower().Contains("arturik") || message.Text.ToLower().Contains("артур") || message.Text.ToLower().Contains("артурик")) { Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/cC4tAx/image.png"); Telegram.Bot.Types.FileToSend f1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/e3PRVx/image.png"); Telegram.Bot.Types.FileToSend f2 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/bMt8Sc/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, f, "trigger #1"); await Bot.SendPhotoAsync(message.Chat.Id, f1, "trigger #2"); await Bot.SendPhotoAsync(message.Chat.Id, f2, "trigger #3"); } if (message.Text.ToLower().Contains("paliy") || message.Text.ToLower().Contains("палий")) { Telegram.Bot.Types.FileToSend f = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/mYqBxc/image.png"); Telegram.Bot.Types.FileToSend f1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/ddXmfx/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, f, "trigger #1"); await Bot.SendPhotoAsync(message.Chat.Id, f1, "trigger #2"); } } //fox if (message.Text.ToLower().Contains("fox")) { Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/cfkqJS/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs, "here is a fox #1"); Telegram.Bot.Types.FileToSend fs1 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/h0hqk7/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs1, "here is a fox #2"); } //say(need to upgrate) if (message.Text == "/say" || message.Text == "/say@aaaclub_bot") { await Bot.SendTextMessageAsync(message.Chat.Id, "slavka", replyToMessageId : message.MessageId); } //anime need to upgrate if (message.Text == "/anime" || message.Text == "/anime@aaaclub_bot") { //await Bot.SendTextMessageAsync(message.Chat.Id, "Chose ganre", replyToMessageId: message.MessageId); var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton("for paliy"), new Telegram.Bot.Types.KeyboardButton("for normal people"), new Telegram.Bot.Types.KeyboardButton("for artuturik") }, }, ResizeKeyboard = true }; keyboard.OneTimeKeyboard = true; await Bot.SendTextMessageAsync(message.Chat.Id, "Chose ganre?", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard); } //monday if (message.Text == "/monday" || message.Text == "/monday@aaaclub_bot") { var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] { new Telegram.Bot.Types.KeyboardButton("yes, i`m ready"), new Telegram.Bot.Types.KeyboardButton("no, i`m not ready") }, }, ResizeKeyboard = true }; keyboard.OneTimeKeyboard = true; await Bot.SendTextMessageAsync(message.Chat.Id, "are u ready to zalupa?", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard); } //answer to sqr if (answer) { try { string s = message.Text.ToLower(); if (math_1.input_message(s) == "error") { await Bot.SendTextMessageAsync(message.Chat.Id, "error", replyToMessageId : message.MessageId); } else { double x1 = 0, x2 = 0; math_1.x1x2(ref x1, ref x2); if (x1 == 2.228 && x2 == 2.228) { await Bot.SendTextMessageAsync(message.Chat.Id, "there are no roots", replyToMessageId : message.MessageId); } if (x2 == 2.228 && x1 != 2.228) { await Bot.SendTextMessageAsync(message.Chat.Id, "there is one root: " + Convert.ToString(x1), replyToMessageId : message.MessageId); } if (x1 != 2.228 && x2 != 2.228) { await Bot.SendTextMessageAsync(message.Chat.Id, "thereare two roots: " + Convert.ToString(x1) + " " + Convert.ToString(x2), replyToMessageId : message.MessageId); } } answer = false; } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { await Bot.SendTextMessageAsync(message.Chat.Id, "error", replyToMessageId : message.MessageId); } } //sqr if (message.Text == "/sqr" || message.Text == "/sqr@aaaclub_bot") { await Bot.SendTextMessageAsync(message.Chat.Id, "send me numbers", replyToMessageId : message.MessageId); answer = true; } //zinia answer if ((message.Text.ToLower().Contains("zinia") || message.Text.ToLower().Contains("зиня")) && !message.Text.ToLower().Contains("/zinia")) { Zinia zinia = new Zinia(); await Bot.SendTextMessageAsync(message.Chat.Id, zinia.res(message), replyToMessageId : message.MessageId); } //photo #1 if (message.Text == "/mamka" || message.Text == "/mamka@aaaclub_bot") { Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/joBJ7c/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs, "mamka"); } //photo #2 if (message.Text == "/doge" || message.Text == "/doge@aaaclub_bot") { Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/dHKuxc/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs, "doge #1"); Telegram.Bot.Types.FileToSend fs2 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/eV56Ax/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs2, "doge #2"); Telegram.Bot.Types.FileToSend fs3 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/cQhQ3H/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs3, "doge #3"); Telegram.Bot.Types.FileToSend fs4 = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/cgajxc/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, fs4, "doge #4"); } //mark`s code if (message.Text == "/pron" || message.Text == "/pron@aaaclub_bot") { await Bot.SendTextMessageAsync(message.Chat.Id, "zaidi v kod marka: https://drive.google.com/open?id=1_MTeOLrL1KMg2bP7jCob7fRSeOL0-osg", replyToMessageId : message.MessageId); } //nakuzin if (message.Text == "/nakuzin") { await Bot.SendTextMessageAsync(message.Chat.Id, "hAAAAA NAEBAL!"); } //mining if (message.Text == "/mining" || message.Text == "/mining@aaaclub_bot") { Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend("https://media.giphy.com/media/cAy7aIZ4dv5KiOAjFs/giphy.gif"); await Bot.SendDocumentAsync(message.Chat.Id, fs, "mayni dogecoini: https://cryptocash.guru/coin/dogecoin/majning-kriptovalyuty-dogecoin/"); } //answers if (message.Text.ToLower() == "yes, i`m ready") { await Bot.SendTextMessageAsync(message.Chat.Id, "then u will die from biologi", replyToMessageId : message.MessageId); } if (message.Text.ToLower() == "no, i`m not ready") { await Bot.SendTextMessageAsync(message.Chat.Id, "you will die on zalupa", replyToMessageId : message.MessageId); } if (message.Text.ToLower() == "for normal people") { await Bot.SendTextMessageAsync(message.Chat.Id, "go to yummyanime.com/catalog/item/milyj-vo-frankce", replyToMessageId : message.MessageId); } if (message.Text.ToLower() == "for paliy") { await Bot.SendTextMessageAsync(message.Chat.Id, "https://yummyanime.com/catalog/item/lyubovnye-nepriyatnosti-tv1", replyToMessageId : message.MessageId); } if (message.Text.ToLower() == "for artuturik") { await Bot.SendTextMessageAsync(message.Chat.Id, "https://yummyanime.com/catalog/item/plastikovye-vospominaniya", replyToMessageId : message.MessageId); } //anime hater if ((message.Text.ToLower().Contains("anime") || message.Text.ToLower().Contains("аниме")) && !message.Text.ToLower().Contains("/")) { await Bot.SendTextMessageAsync(message.Chat.Id, "ANIME - tupoe govno tupogo govna", replyToMessageId : message.MessageId); } //translate if (message.Text.ToLower().Contains("/translate")) { int index = message.Text.ToLower().IndexOf("e"); string s_res = String.Empty; try { s_res = message.Text.ToLower().Substring(index + 2); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error", replyToMessageId : message.MessageId); } await Bot.SendTextMessageAsync(message.Chat.Id, translate.tr(s_res), replyToMessageId : message.MessageId); } //mamkate if (message.Text.ToLower().Contains("/mamkate")) { int index = message.Text.ToLower().IndexOf("e"); string s_res = String.Empty; try { s_res = message.Text.ToLower().Substring(index + 2); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error", replyToMessageId : message.MessageId); } Mamkate mamkate = new Mamkate(); await Bot.SendTextMessageAsync(message.Chat.Id, mamkate.tr(s_res), replyToMessageId : message.MessageId); } //analis rechi 2117 if (message.Text.ToLower().Contains("kofe") || message.Text.ToLower().Contains("кофе")) { Telegram.Bot.Types.FileToSend file = new Telegram.Bot.Types.FileToSend("https://image.ibb.co/jag72c/image.png"); await Bot.SendPhotoAsync(message.Chat.Id, file, "buy kofee for me, " + message.From.FirstName); } if (message.Text.ToLower().Contains("didur") || message.Text.ToLower().Contains("дидур")) { await Bot.SendTextMessageAsync(message.Chat.Id, "BLYAT DIDUR PIDOR", replyToMessageId : message.MessageId); } if (message.Text.ToLower().Contains("amd") || message.Text.ToLower().Contains("амд")) { await Bot.SendTextMessageAsync(message.Chat.Id, "AMD IS THE BEST KOMPANY", replyToMessageId : message.MessageId); } if (message.Text.ToLower().Contains("intel") || message.Text.ToLower().Contains("интел")) { await Bot.SendTextMessageAsync(message.Chat.Id, "INTEL HUINIA)", replyToMessageId : message.MessageId); } if (message.Text.ToLower().Contains("думал") || message.Text.ToLower().Contains("думать")) { await Bot.SendTextMessageAsync(message.Chat.Id, "Не надо думать, у вас такого органа нет", replyToMessageId : message.MessageId); } /* * if (message.Text.ToLower() .Contains("slavka daun")|| message.Text.ToLower().Contains("slavka eblan")|| message.Text.ToLower().Contains("славка даун") || message.Text.ToLower().Contains("славка еблан")) * { * //ban * * //u = message.From; * try * { * await Bot.SetChatDescriptionAsync(message.Chat.Id, message.Chat.Description + " " + message.From.FirstName + " " + message.From.LastName + " - pidrila"); * await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId); * } * catch(Exception) * { * * } * * }/* * if(u.FirstName!=null) * if(message.From.FirstName.ToLower()==u.FirstName.ToLower()) * { * await Bot.SendTextMessageAsync(message.Chat.Id, "SASAT, pidrila", replyToMessageId: message.MessageId); * } */ } offset = update.Id + 1; } } } catch (Exception) { Console.WriteLine(); } }
/// <summary> /// Получение сообщений и ответ на них /// </summary> public async Task BotWork() { var bot = new Telegram.Bot.TelegramBotClient(_key); await bot.SetWebhookAsync(""); int offset = 0; //инервал между ответами while (!_token.IsCancellationRequested) { var updates = await bot.GetUpdatesAsync(offset); Message message; string responseMessage; foreach (var update in updates) { try { switch (update.Type) { case UpdateType.UnkownUpdate: break; case UpdateType.EditedMessage: break; case UpdateType.MessageUpdate: message = update.Message; switch (message.Type) { case MessageType.TextMessage: responseMessage = _messageControl.MessageCommands(message); if (_isWaitAnswerForRememder.Any(x => x == message.Chat.Id) || _isWaitAnswerForWeather.Any(x => x == message.Chat.Id)) { await bot.SendTextMessageAsync(message.Chat.Id, responseMessage, false, false, 0, CreateInlineKeyboard()); } else { await bot.SendTextMessageAsync(message.Chat.Id, responseMessage, false, false, 0, await CreateKeyboard(message.Chat.Id)); } _logger.Info(message.Chat.FirstName + " " + message.Chat.Id + " - " + message.Text); break; case MessageType.VideoMessage: await bot.SendTextMessageAsync(message.Chat.Id, "Сейчас посмотрю."); break; case MessageType.StickerMessage: await bot.SendTextMessageAsync(message.Chat.Id, $"Очень смешно, {message.Chat.FirstName}."); break; case MessageType.LocationMessage: responseMessage = _messageControl.LocationCommands(message.Location.Latitude, message.Location.Longitude); await bot.SendTextMessageAsync(message.Chat.Id, responseMessage); break; default: await bot.SendTextMessageAsync(message.Chat.Id, "И что мне на это ответить?"); break; } break; case UpdateType.CallbackQueryUpdate: await bot.EditMessageTextAsync(update.CallbackQuery.From.Id, update.CallbackQuery.Message.MessageId, "Возврат обратно."); _isWaitAnswerForRememder.Remove(update.CallbackQuery.From.Id); _isWaitAnswerForWeather.Remove(update.CallbackQuery.From.Id); break; default: break; } offset = update.Id + 1; } catch (Exception ex) { _logger.Error(ex.Message); } } } }
private void runBot() { Bot = new Telegram.Bot.TelegramBotClient(Token); this.Invoke(new Action(() => { lblStatus.Text = "Online"; lblStatus.ForeColor = Color.Green; })); int offset = 0; while (true) { try { Telegram.Bot.Types.Update[] Update = Bot.GetUpdatesAsync(offset).Result; foreach (Telegram.Bot.Types.Update Up in Update) { offset = Up.Id + 1; while (Up.CallbackQuery != null) { //Contatct To Me Inline if (Up.CallbackQuery.Data.Contains("gmail")) { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Gmail address is : [email protected]"); Up.CallbackQuery = null; break; } else if (Up.CallbackQuery.Data.Contains("outlook")) { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Outlook address is : [email protected]"); Up.CallbackQuery = null; break; } //Poll Inline var user = db.PollManager.SingleOrDefault(u => u.UserID == Up.CallbackQuery.From.Id); if (user == null) { user = new PollManager() { UserID = Up.CallbackQuery.From.Id, VotedByUser = "" }; db.PollManager.Add(user); db.SaveChanges(); } var UserID = Up.CallbackQuery.From.Id; var pUserID = db.PollManager.Select(p => p.UserID).ToList(); var pVotedByUSer = db.PollManager.Select(p => p.VotedByUser).ToList(); var query = Up.CallbackQuery.Data; string VotedNow = Up.CallbackQuery.Data; if (db.PollManager.Any(p => (p.UserID == Up.CallbackQuery.From.Id) && (p.VotedByUser != VotedNow))) { Poll(Up, db.PollManager.SingleOrDefault(a => a.UserID == UserID).VotedByUser, VotedNow); InlineKeyboardMarkup PollButons = PollInline(); Bot.EditMessageReplyMarkupAsync(Up.CallbackQuery.Message.Chat.Id, Up.CallbackQuery.Message.MessageId, replyMarkup: PollButons); Up.CallbackQuery = null; } else { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "You have rated before"); } Up.CallbackQuery = null; } if (Up.Message == null) { continue; } string MessageFromUser = Up.Message.Text.ToLower(); Telegram.Bot.Types.User Upfrom = Up.Message.From; Telegram.Bot.Types.ChatId ChatID = Up.Message.Chat.Id; StringBuilder SB = new StringBuilder(); if (MessageFromUser.Contains("start")) { ReplyKeyboardMarkup MainKeyboardMarkup = StartKeyboards(); SB.AppendLine("Welcome To My Bot"); SB.AppendLine("Contact To Me : /ContactToMe"); SB.AppendLine("About Me : /AboutMe"); Bot.SendTextMessageAsync(ChatID, SB.ToString(), parseMode: default, false, true, 0, MainKeyboardMarkup);
async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; Telegram.Bot.Types.User u = new Telegram.Bot.Types.User(); var key = e.Argument as String; bool setwords = false; bool settranslate = false; string[] words = null; string[] wordstranslate; bool answer = false; bool second_c = false; string w = String.Empty; int n_of_tests = 0; bool test = false; Brake brake = new Brake(); try { var Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; while (true) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates) { var message = update.Message; if (message == null) { continue; } if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { /* * if (settranslate) * { * wordstranslate = message.Text.ToLower().Split(' '); * settranslate = false; * await Bot.SendTextMessageAsync(message.Chat.Id, "good, now you can practise!"); * try * { * brake.SetDic(wordstranslate, words); * } * catch(Exception) * { * await Bot.SendTextMessageAsync(message.Chat.Id, "error"); * * } * * * }*/ if (setwords) { words = message.Text.ToLower().Split(' '); brake.SetDic(words); await Bot.SendTextMessageAsync(message.Chat.Id, "now you can start test"); setwords = false; } if (message.Text.Contains("/starttest")) { test = true; } if (message.Text.Contains("/setwords")) { try { setwords = true; await Bot.SendTextMessageAsync(message.Chat.Id, "please insert words in one string"); test = false; n_of_tests = 0; answer = false; } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); } } if (answer) { if (brake.GetRes(message.Text.ToLower())) { await Bot.SendTextMessageAsync(message.Chat.Id, "yes, it`s true"); second_c = false; } else { await Bot.SendTextMessageAsync(message.Chat.Id, "NO, try once more"); second_c = true; w = brake.now_word; n_of_tests--; } n_of_tests++; } if (test) { try { if (n_of_tests < words.Length) { if (second_c) { try { char[] tmp = brake.brakingC(w); string r = String.Empty; for (int i = 0; i < tmp.Length; i++) { r += tmp[i] + " "; } await Bot.SendTextMessageAsync(message.Chat.Id, r); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); } finally { await Bot.SendTextMessageAsync(message.Chat.Id, "Now insert word from this letters"); answer = true; } } if (!second_c) { try { char[] tmp = brake.brakingC(); string r = String.Empty; for (int i = 0; i < tmp.Length; i++) { r += tmp[i] + " "; } await Bot.SendTextMessageAsync(message.Chat.Id, r); } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); test = false; } finally { await Bot.SendTextMessageAsync(message.Chat.Id, "Now insert word from this letters"); answer = true; } } } else { answer = false; n_of_tests = 0; test = false; } } catch (Exception) { await Bot.SendTextMessageAsync(message.Chat.Id, "error"); } } } offset = update.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException) { } }
void ChatBot() { bot = new Telegram.Bot.TelegramBotClient(token); //set offset for update message or ... bot int offset = 0; //start app by while #region Code My Bot -> while (true) { //get update var update = bot.GetUpdatesAsync(offset).Result; //foreach for chekc all message & ... foreach (var up in update) { offset = up.Id + 1; //inline btn callback #region inline button and check callback //check call back if (up.CallbackQuery != null) { //get call ack data var callback = up.CallbackQuery.Data; //get chat id - user var chatidcall = up.CallbackQuery.Message.Chat.Id; if (callback.Contains("startBot")) { //check exist user in data base var user = botdb.users.SingleOrDefault(u => u.chatid == up.CallbackQuery.From.Id); if (user == null) { //creat user user = new user() { chatid = up.CallbackQuery.Message.Chat.Id, username = up.CallbackQuery.Message.Chat.Username }; //add user in data base botdb.users.Add(user); botdb.SaveChanges(); } string message = @"✅ جنسیت خود را وارد کنید ✅"; bot.SendTextMessageAsync(chatidcall, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, getButtosInlineGener()); } //if gener user = boy else if (callback.Contains("boy")) { var user = botdb.users.SingleOrDefault(u => u.chatid == up.CallbackQuery.Message.Chat.Id); if (user != null) { //edit user section gener user.gener = "پسر"; botdb.SaveChanges(); string message = @"ذخیره شد 📬 شهر خود را وارد کنید 🔍 📌 توجه در صورتی که شهر خود را یافت نکردید به پشتیبانی جهت افزودن شهر در ربات اطلاع دهید! 👨🏻💻"; bot.SendTextMessageAsync(chatidcall, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, GetMenuState()); } } //if gener user = girl//if gener user = girl else if (callback.Contains("girl")) { //edit user section gener var user = botdb.users.SingleOrDefault(u => u.chatid == up.CallbackQuery.Message.Chat.Id); if (user != null) { //edit user section gener user.gener = "دختر"; botdb.SaveChanges(); string message = @"ذخیره شد 📬 شهر خود را وارد کنید 🔍 📌 توجه در صورتی که شهر خود را یافت نکردید به پشتیبانی جهت افزودن شهر در ربات اطلاع دهید! 👨🏻💻"; bot.SendTextMessageAsync(chatidcall, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, GetMenuState()); } } //edit user section city else if (botdb.States.SingleOrDefault(s => s.Name == callback) != null) { //edit user section gener var user = botdb.users.SingleOrDefault(u => u.chatid == up.CallbackQuery.Message.Chat.Id); if (user != null) { //edit user section city user.city = callback; botdb.SaveChanges(); string message = @"ذخیره شد 📬"; bot.SendTextMessageAsync(chatidcall, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0); } } } #endregion //if null message if (up.Message == null) { continue; } //answer btn keyboard var chatid = up.Message.Chat.Id; var txt = up.Message.Text; var from = up.Message.From; //if click btn /start #region check message request keyboard button if (txt.ToLower().Contains("/start")) { string message = @" 🍯 سلام به ربات چت ناشناس ما خوش آمدید 💋 -------------------------------------- 🍯 برای شروع کار خود و ثبت نام در این ربات دکمه ی شروع را کلیک کنید 🥂 --------------------------------------"; bot.SendTextMessageAsync(chatid, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, GetMenuStart()); } //if click btn ok name //else if (txt.Contains("بعد از وارد کردن اسم کلیک کنید")) //{ // string message = @""; // bot.SendTextMessageAsync(chatid, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, GetMenuStart()); //} //else if (txt.Contains("نامم را وارد کردم")) //{ // user.name = name; // string message = @""; // bot.SendTextMessageAsync(chatid, message, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0); //} #endregion } } #endregion }
public async void bw_DoWork(string key) { List <User> availablePlayers = new List <User>(); try { var Bot = new Telegram.Bot.TelegramBotClient(key); await users.Init(Bot); //IHero.bot = Bot; await Bot.SetWebhookAsync(""); //Bot.SetWebhook(""); int offset = 0; timer = new Timer(x => AddSecondToTime(null, null), null, 0, 1000); while (true) { availablePlayers.RemoveAll(x => x.status != User.Status.Searching); ActiveGames.RemoveAll(x => !x.isWorking); while (availablePlayers.Count >= 2) { var firstPlayer = availablePlayers[0]; var secondPlayer = availablePlayers[1]; ActiveGames.Add(new Game(firstPlayer, secondPlayer, Bot)); var keyboard1 = new ReplyKeyboardMarkup(); keyboard1.Keyboard = new Telegram.Bot.Types.KeyboardButton[][] { new Telegram.Bot.Types.KeyboardButton[] { new Telegram.Bot.Types.KeyboardButton(firstPlayer.lang.YesMessage), new Telegram.Bot.Types.KeyboardButton(firstPlayer.lang.NoMessage) } }; keyboard1.ResizeKeyboard = true; keyboard1.OneTimeKeyboard = true; var keyboard2 = new ReplyKeyboardMarkup(); keyboard2.Keyboard = new Telegram.Bot.Types.KeyboardButton[][] { new Telegram.Bot.Types.KeyboardButton[] { new Telegram.Bot.Types.KeyboardButton(secondPlayer.lang.YesMessage), new Telegram.Bot.Types.KeyboardButton(secondPlayer.lang.NoMessage) } }; keyboard2.ResizeKeyboard = true; keyboard2.OneTimeKeyboard = true; string user1_msg = firstPlayer.lang.GameFounded + "\n" + firstPlayer.lang.AcceptGameQuestion; string user2_msg = secondPlayer.lang.GameFounded + "\n" + secondPlayer.lang.AcceptGameQuestion; await firstPlayer.Sender.SendAsync(lang => user1_msg, keyboard1); await secondPlayer.Sender.SendAsync(lang => user2_msg, keyboard2); try { availablePlayers.RemoveRange(0, 2); } catch (System.ArgumentOutOfRangeException ex) { Console.WriteLine(ex); } } var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates.Where(x => x.Message != null && x.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)) { var message = update.Message; if (!users.Contains(message.Chat.Id)) { await users.AddUser(message.Chat.Id); } User _usr = users.getUserByID(message.Chat.Id); if (_usr.Sender == null) { _usr.InitSender(Bot); } if (_usr.status == User.Status.Default) { if (message.Text == "/start") { await _usr.Sender.SendAsync(lang => "Welcome to DotA Text!\n/language - Change language\n/instruction - Get instruction"); } else if (message.Text == "/language") { var keyboard = new ReplyKeyboardMarkup(); keyboard.Keyboard = new Telegram.Bot.Types.KeyboardButton[][] { new Telegram.Bot.Types.KeyboardButton[] { new Telegram.Bot.Types.KeyboardButton("English"), new Telegram.Bot.Types.KeyboardButton("Русский") } }; keyboard.ResizeKeyboard = true; keyboard.OneTimeKeyboard = true; _usr.status = User.Status.LanguageChanging; await _usr.Sender.SendAsync(lang => lang.ChangeLanguage, keyboard); } else if (message.Text == "/profile") { if (_usr.net_status == User.NetworkStatus.Online) { await _usr.Sender.SendAsync(lang => _usr.GetStatisctisMessage()); } else { await _usr.Sender.SendAsync(lang => lang.ErrorByStatusOffline); } } else if (message.Text == "/online") { if (_usr.Name != "") { _usr.net_status = User.NetworkStatus.Online; await _usr.Sender.SendAsync(lang => lang.SetOnlineStatus); } else { _usr.status = User.Status.SettingNickname; await _usr.Sender.SendAsync(lang => lang.NeedToHaveNickname); await _usr.Sender.SendAsync(lang => $"{lang.NeedToSetNickname}:"); } } else if (message.Text == "/offline") { _usr.net_status = User.NetworkStatus.Offline; await _usr.Sender.SendAsync(lang => lang.SetOfflineStatus); } else if (message.Text == "/netstatus") { string msg; if (_usr.net_status == User.NetworkStatus.Online) { msg = _usr.lang.GetOnlineStatus; } else { msg = _usr.lang.GetOfflineStatus; } await _usr.Sender.SendAsync(lang => msg); } else if (message.Text == "/instruction") { _usr.lang.instruction.SetLanguage(_usr.lang.lang); var text = _usr.lang.instruction; string message_one = text.step1_Describe + "\n\n" + text.step2_AboutNetMode + "\n\n" + text.step3_AboutLanguage + "\n\n"; message_one += text.step4_AboutBattle + "\n\n" + text.step5_AboutHeroes; string message_two = text.step6_AboutAbilities + "\n\n" + text.step7_AboutBuffstAndModifiers + "\n\n" + text.step8_AboutDonate + "\n\n" + text.step9_AboutDeveloper + "\n\n" + text.step10_TheEnd; await _usr.Sender.SendAsync(lang => message_one); await _usr.Sender.SendAsync(lang => message_two); } else if (message.Text == "/donate") { await _usr.Sender.SendAsync(lang => lang.Donate); } else if (message.Text == "/startgame") { if (_usr.net_status == User.NetworkStatus.Online) { _usr.status = User.Status.Searching; availablePlayers.Add(_usr); await _usr.Sender.SendAsync(lang => lang.SearchingModeNotify); } else { await _usr.Sender.SendAsync(lang => lang.ErrorByStatusOffline); } } else if (message.Text == "/stopsearching") { await _usr.Sender.SendAsync(lang => lang.SeachingModeErrorNotStarted); } else if (message.Text == "/delete") { _usr.status = User.Status.DeletingAccount; var kb = new ReplyKeyboardMarkup(new[] { new[] { new Telegram.Bot.Types.KeyboardButton(_usr.lang.YesMessage), new Telegram.Bot.Types.KeyboardButton(_usr.lang.NoMessage) } }, true, true); await _usr.Sender.SendAsync(lang => lang.ConfirmQuestion, kb); } else if (message.IsCommand("[ADMIN] Set rating:") && message.Chat.Id == Users.AdminID) { int rating = 0; string res = System.Text.RegularExpressions.Regex.Match(message.Text, @"\d+").Value; if (int.TryParse(res, out rating)) { rating = int.Parse(res); } Console.WriteLine($"Parse {rating}"); User find_user = null; string name = System.Text.RegularExpressions.Regex.Match( message.Text, @"\{(.*)\}").Groups[1].ToString(); if (name != "") { find_user = users.GetUserByName(name); if (find_user != null && rating > 0) { find_user.rate = rating; await find_user.SaveToFile(); await _usr.Sender.SendAsync(lang => lang.GetMessageAdminCommandSuccesful( $"{message.Text} : {find_user.ID}")); } } } else if (message.IsCommand("[ADMIN] Send to all:") && message.Chat.Id == Users.AdminID) { string res = System.Text.RegularExpressions.Regex.Match(message.Text, "\"(.*)\"") .Groups[1].ToString(); if (res != "") { var list = users.GetUserList(); for (int i = 0; i < list.Count; i++) { User user = list.Values.ElementAt(i); try { await user.Sender.SendAsync(lang => res); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); list.Remove(user.ID); } } await _usr.Sender.SendAsync(lang => lang.GetMessageAdminCommandSuccesful(message.Text)); } } else if (message.IsCommand("[ADMIN] Get list of names") && message.Chat.Id == Users.AdminID) { string msg = $"{_usr.lang.List}:\n{string.Join("\n", users.GetNames())}\n"; await _usr.Sender.SendAsync(lang => msg); } else if (message.IsCommand("[ADMIN] Send to one:") && message.Chat.Id == Users.AdminID) { string name = Regex.Match(message.Text, @"\{(.*)\}").Groups[1].ToString(); string text = Regex.Match(message.Text, "\"(.*)\"").Groups[1].ToString(); long id = 0; id = users.GetIdByName(name); if (id != -1) { if (text != "") { try { await users.getUserByID(id)?.Sender.SendAsync(lang => text); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); users.GetUserList().Remove(id); } await _usr.Sender.SendAsync(lang => lang.GetMessageAdminCommandSuccesful(message.Text)); } } } else if (message.IsCommand("[ADMIN] Get profile of user:"******"\{(.*)\}").Groups[1].ToString(); if (name != "") { if (users.GetUserByName(name) != null) { await _usr.Sender.SendAsync(lang => users.GetUserByName(name) ?.GetStatisctisMessage()); await _usr.Sender.SendAsync(lang => lang.GetMessageAdminCommandSuccesful(message.Text)); } } } else if (message.IsCommand("[ADMIN] Delete user:"******"\{(.*)\}").Groups[1].ToString(); if (name != "") { if (users.GetUserByName(name) != null) { await users.DeleteUser(users.GetUserByName(name).ID); await _usr.Sender.SendAsync(lang => lang.GetMessageAdminCommandSuccesful(message.Text)); } } } else { if (await CheckHeroView(_usr, message.Text)) { } else { await _usr.Sender.SendAsync(lang => lang.HelloMessage); } } } else if (_usr.status == User.Status.LanguageChanging) { if (message.IsCommand("english") || message.IsCommand("русский")) { _usr.status = User.Status.Default; if (message.IsCommand("english")) { _usr.LanguageSet(User.Text.Language.English); } else if (message.IsCommand("русский")) { _usr.LanguageSet(User.Text.Language.Russian); } var hide_keyboard = new ReplyKeyboardHide(); await _usr.SaveToFile(); await _usr.Sender.SendAsync(lang => lang.ChangedLanguage, hide_keyboard); } } else if (_usr.status == User.Status.Picking) { await CheckHeroView(_usr, message.Text); if (message.Text == "/stopsearching") { GetActiveGame(_usr.ActiveGameID).GetController(message.Chat.Id)?.LeaveConfirming(); } else if (message.IsCommand(">")) { var kb = GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id)?.GetKeyboardNextPage(); await _usr.Sender.SendAsync(lang => ".", kb); Console.WriteLine(">"); } else if (message.IsCommand("<")) { var kb = GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id).GetKeyboardPrevPage(); await _usr.Sender.SendAsync(lang => ".", kb); Console.WriteLine("<"); } else { var hero = Game.hero_list.SingleOrDefault(x => message.IsCommand(x.Name)); if (hero != null) { GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id)?.PickHero(hero); } } } else if (_usr.status == User.Status.Picked) { await CheckHeroView(_usr, message.Text); if (message.Text == "/stopsearching") { GetActiveGame(_usr.ActiveGameID).GetController(message.Chat.Id)?.LeaveConfirming(); } else { await _usr.Sender.SendAsync(lang => lang.ErrorPickingIncorrectCommand); } } else if (_usr.status == User.Status.Attacking) { await CheckHeroView(_usr, message.Text); await CheckLeave(_usr, GetActiveGame(_usr.ActiveGameID), message.Text); if (message.IsDigits(message.Text)) { await GetActiveGame(_usr.ActiveGameID)?.GetController(_usr.ID)?.UseAbility( Convert.ToInt32(message.Text)); } else { await _usr.Sender.SendAsync(lang => lang.IncorrectSelection); } } else if (_usr.status == User.Status.Excepting) { await CheckLeave(_usr, GetActiveGame(_usr.ActiveGameID), message.Text); await CheckHeroView(_usr, message.Text); if (message.Text == "/report") { GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id)?.CheckInactive(); } } else if (_usr.status == User.Status.Searching) { await CheckHeroView(_usr, message.Text); if (message.Text == "/stopsearching") { availablePlayers.Remove(availablePlayers.Find(x => x.ID == _usr.ID)); _usr.status = User.Status.Default; await _usr.Sender.SendAsync(lang => lang.SearchingModeStopped); } else { await _usr.Sender.SendAsync(lang => lang.ErrorSearchingIncorrectCommand); } } else if (_usr.status == User.Status.GameConfirming) { if (message.IsCommand(_usr.lang.YesMessage) || message.IsCommand(_usr.lang.NoMessage)) { bool isConfirm = message.IsCommand(_usr.lang.YesMessage); GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id)?.ConfirmGame(isConfirm); } } else if (_usr.status == User.Status.WaitingForRespond) { if (message.Text == "/stopsearching") { await GetActiveGame(_usr.ActiveGameID)?.GetController(message.Chat.Id)?.LeaveConfirming(); } else { await _usr.Sender.SendAsync(lang => lang.ErrorPickingIncorrectCommand); } } else if (_usr.status == User.Status.DeletingAccount) { if (message.IsCommand(_usr.lang.YesMessage) || message.IsCommand(_usr.lang.NoMessage)) { var h_kb = new ReplyKeyboardHide(); if (message.IsCommand(_usr.lang.YesMessage)) { await _usr.Sender.SendAsync(lang => lang.AccountWasDeletedString, h_kb); await users.DeleteUser(message.Chat.Id); } else { _usr.status = User.Status.Default; await _usr.Sender.SendAsync(lang => lang.YouCanceledTheActionString, h_kb); } } } else if (_usr.status == User.Status.SettingNickname) { if (users.NicknameExists(message.Text)) { await _usr.Sender.SendAsync(lang => lang.NickNameIsAlreadyExists); } else if (message.Text.Length > 10) { await _usr.Sender.SendAsync(lang => lang.LengthOfNicknameError); } else { _usr.Name = message.Text; _usr.status = User.Status.Default; await _usr.SaveToFile(); await _usr.Sender.SendAsync(lang => lang.NickNameSet); } } else { var hide_keyboard = new ReplyKeyboardHide(); _usr.status = User.Status.Default; await _usr.Sender.SendAsync(lang => lang.StatusUndefinedError, hide_keyboard); } offset = update.Id + 1; } //return; } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); } }
async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var key = e.Argument as String; try { var Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; while (true) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates) { var message = update.Message; const string req = @"^((8|\+7)[\- ]?)?(\(?9\d{2}\)?[\- ]?)?([\d][\- ]?){7}$"; Console.WriteLine(Regex.Replace(message.Text, @"\D+", "")); String num = Regex.Replace(message.Text, @"\D+", ""); var regex = new Regex(req); Console.WriteLine(regex.IsMatch(num)); if (regex.IsMatch(num)) { String lastnum = Regex.Replace(num, @"^(8|\+7)?[\- ]?\(?(9\d{2})\)?[\- ]?([\d])[\- ]?([\d])[\- ]?([\d])[\- ]?([\d])[\- ]?([\d])[\- ]?([\d])[\- ]?([\d])$", "+7($2)$3$4$5-$6$7-$8$9"); Console.WriteLine(lastnum); } else { Console.WriteLine("Неверный номер"); } if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { if (dict.ContainsKey(message.Chat.Id)) { if (message.Date > dict[message.Chat.Id].AddSeconds(10)) { String phone = ""; for (int i = 0; i < message.Text.Length; i++) { if (message.Text[i] >= '0' && message.Text[i] <= '9') { phone += message.Text[i]; } } if (phone.Length == 10) { if (phone[0] == '9') { await Bot.SendTextMessage(message.Chat.Id, getPhone(phone), replyToMessageId : message.MessageId); } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } } else if (phone.Length == 11) { if ((phone[0] == '8' || phone[0] == '7') && phone[1] == '9') { await Bot.SendTextMessage(message.Chat.Id, getPhone(phone), replyToMessageId : message.MessageId); } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } dict[message.Chat.Id] = message.Date; } else { await Bot.SendTextMessage(message.Chat.Id, "Превышено количество обращений к боту", replyToMessageId : message.MessageId); } } else { String phone = ""; for (int i = 0; i < message.Text.Length; i++) { if (message.Text[i] >= '0' && message.Text[i] <= '9') { phone += message.Text[i]; } } if (phone.Length == 10) { if (phone[0] == '9') { await Bot.SendTextMessage(message.Chat.Id, getPhone(phone), replyToMessageId : message.MessageId); } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } } else if (phone.Length == 11) { if ((phone[0] == '8' || phone[0] == '7') && phone[1] == '9') { await Bot.SendTextMessage(message.Chat.Id, getPhone(phone), replyToMessageId : message.MessageId); } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } } else { await Bot.SendTextMessage(message.Chat.Id, "Неверный номер", replyToMessageId : message.MessageId); } dict.Add(message.Chat.Id, message.Date); } } offset = update.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); } }
async static void TelegramMetod() { string key = "417836710:AAHaiu8stm_QKQBiZX11MJqIcDCrOrTLyMk"; //telegram: @RandomPhoto_bot var bot = new Telegram.Bot.TelegramBotClient(key); await bot.SetWebhookAsync(""); int offset = 0; while (true) { var updates = await bot.GetUpdatesAsync(offset); // получаем массив обновлений foreach (var update in updates) // Перебираем все обновления { var message = update.Message; if (message?.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage) { string rain = ""; if (message.Text == "/start") { await bot.SendTextMessageAsync(message.Chat.Id, "Привет " + message.Chat.FirstName); var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup { Keyboard = new[] { new[] // row 1 { new Telegram.Bot.Types.KeyboardButton("Пришли картинку"), new Telegram.Bot.Types.KeyboardButton("Пришли музыку") }, new[] // row 1 { new Telegram.Bot.Types.KeyboardButton("Какая погода?"), new Telegram.Bot.Types.KeyboardButton("Какая погода завтра?") }, }, ResizeKeyboard = true }; await bot.SendTextMessageAsync(message.Chat.Id, "Выбери что хочешь получить", ParseMode.Default, false, false, 0, keyboard, CancellationToken.None); } if (message.Text == "/getimage" || message.Text == "Пришли картинку") { string[] dirs = Directory.GetFiles( @"C:\Users\workstation1\Documents\Visual Studio 2015\Projects\TelegramBotGetImage\TelegramBotGetImage\Images"); Random rnd = new Random(); int i = rnd.Next(0, dirs.Length); string FileUrl = dirs[i]; using (var stream = System.IO.File.Open(FileUrl, FileMode.Open)) { FileToSend fts = new FileToSend(); fts.Content = stream; fts.Filename = FileUrl.Split('\\').Last(); await bot.SendPhotoAsync(message.Chat.Id, fts, "New IMG"); } } if (message.Text == "/getmusic" || message.Text == "Пришли музыку") { string[] dirs = Directory.GetFiles( @"C:\Users\workstation1\Documents\Visual Studio 2015\Projects\TelegramBotGetImage\TelegramBotGetImage\Music"); Random rnd = new Random(); int w = rnd.Next(0, dirs.Length); string FileUrl = dirs[w]; using (var stream = System.IO.File.Open(FileUrl, FileMode.Open)) { FileToSend fts = new FileToSend(); fts.Content = stream; fts.Filename = FileUrl.Split('\\').Last(); string[] eq = fts.Filename.Split('-'); string songName = eq.Last(); string athor = ""; for (int i = 0; i < eq.Length - 1; i++) { athor += eq[i]; } await bot.SendTextMessageAsync(message.Chat.Id, "Отправляю песню: " + athor + " - " + songName + " подождите"); await bot.SendAudioAsync(message.Chat.Id, fts, "Файл получен", 0, athor, songName); } } if (message.Text == "/about") { await bot.SendTextMessageAsync(message.Chat.Id, "Бот написан 22.09.2017\nАвтор: Тимофей Забалуев\nКонтактные данные: [email protected]"); } if (message.Text == "/weathernow" || message.Text == "Какая погода?") { var q = GetSimpleWeather.WeatherGetNow(); //if (q.rain != null) rain = " дождь"; await bot.SendTextMessageAsync(message.Chat.Id, "В городе: " + q.Name + " сейчас " + q.Main.temp + " градусов"); } if (message.Text == "/weathertomorrow" || message.Text == "Какая погода завтра?") { var w = GetSimpleWeather.WeatherGetFor5Days(); await bot.SendTextMessageAsync(message.Chat.Id, "В городе: " + w.city.name); string str = " "; for (int i = 1; i < 9; i++) { if (w.list[i].rain != null) { rain = " дождь"; } string[] split = w.list[i].dt_txt.Split(' ', ':', '-'); if (split[3] == "00") { str += split[2] + "/" + split[1] + " "; //Выводим дополнительно число и месяц если следующий день } else { str += "---------"; } str += split[3] + ":00 = " + w.list[i].main.temp + "° " + rain + "\n"; } await bot.SendTextMessageAsync(message.Chat.Id, str); } } offset = update.Id + 1; } } }
async void launchWorkerAsync(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; string key = e.Argument as String; try { Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; while (true) { var messages = await Bot.GetUpdatesAsync(offset); foreach (var message in messages) { var msgText = message.Message; User currentUser; if (users.ContainsKey(msgText.Chat.Id)) { currentUser = users[msgText.Chat.Id]; } else { currentUser = new User("Уважаемый", bot); currentUser.Predicates.addSetting("favouriteanimal", "default"); currentUser.Predicates.addSetting("name", "default"); users[msgText.Chat.Id] = currentUser; } if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Text && msgText.Text.Contains("/game")) { string text = msgText.Text; text = text.Replace("/game ", ""); string[] clues = text.Split(','); clues = clues.Select(x => x.Trim().ToLower()).ToArray(); List <string> games = Program.SetupFacts(clues.ToList(), ""); if (games.Count == 0) { await Bot.SendTextMessageAsync(msgText.Chat.Id, "Не знаю таких игра :("); } else { string res = games.Aggregate((i, j) => i + '?' + j); res += '?'; await Bot.SendTextMessageAsync(msgText.Chat.Id, "Я что-то такое знаю. " + res); } } else if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Text) { Console.WriteLine(msgText.Text.ToUpper()); Request r = new Request(msgText.Text, currentUser, bot); Result res = bot.Chat(r); if (res.Output != "") { if (res.Output.EndsWith(".jpg.")) { await Bot.SendPhotoAsync(msgText.Chat.Id, res.Output.Remove(res.Output.Count() - 1, 1)); } else if (res.Output == "time.") { var time = "У меня " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ", сколько у вас - не знаю"; await Bot.SendTextMessageAsync(msgText.Chat.Id, time); } else if (res.Output == "foot.") { string table = football.getTable(); await Bot.SendTextMessageAsync(msgText.Chat.Id, table); } else if (res.Output == "anec.") { string anec = Anecdot.anec(); await Bot.SendTextMessageAsync(msgText.Chat.Id, anec); } else if (res.Output == "voice.") { string anec = Anecdot.anec(); SpeechSynthesizer speaker = new SpeechSynthesizer(); speaker.Rate = 2; speaker.Volume = 100; speaker.Speak(anec); speaker.SetOutputToWaveFile("soundfile.wav"); speaker.Speak(anec + "\n АХАХАХАХАХАХ"); speaker.SetOutputToDefaultAudioDevice(); var fStream = new FileStream("soundfile.wav", FileMode.OpenOrCreate); await Bot.SendVoiceAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream)); fStream.Dispose(); } else if (res.Output == "beauty.") { var fStream = new FileStream("..\\..\\1beauty.jpg", FileMode.OpenOrCreate); await Bot.SendPhotoAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream), "Красивее не сыскать"); } else if (res.Output.Contains("poetryFlag")) { var poem = res.Output.Replace("poetryFlag", ""); SpeechSynthesizer speaker = new SpeechSynthesizer(); speaker.Rate = 2; speaker.Volume = 100; speaker.SetOutputToWaveFile("soundfile.wav"); speaker.Speak(poem); speaker.SetOutputToDefaultAudioDevice(); var fStream = new FileStream("soundfile.wav", FileMode.OpenOrCreate); await Bot.SendVoiceAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream)); fStream.Dispose(); } else { await Bot.SendTextMessageAsync(msgText.Chat.Id, res.Output); } } } else if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Photo) { ProcessImage(msgText.Photo[msgText.Photo.Length - 1].FileId, "", msgText.Chat.Id); } offset = message.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException exception) { Console.WriteLine(exception.Message); asyncWorker.RunWorkerAsync("999037946:AAHbd0xIjp5l6iS0aGuVB-jIP2R4a99EUFo"); } }
public override async void bw_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var key = e.Argument as string; try { var Bot = new Telegram.Bot.TelegramBotClient(key); await Bot.SetWebhookAsync(""); int offset = 0; var ud = await Bot.GetUpdatesAsync(offset); //foreach (var v in ud) //{ // //var mes = v.Message; // //var keyBoard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Раз")); // //await Bot.SendTextMessageAsync(mes.Chat.Id, "Reply кнопка работает", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyBoard); //} while (true) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var v in updates) { var message = v.Message; if (message == null) { return; } if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text) { if (message.Text == "/saysomething") //answer { // в ответ на команду /saysomething выводим сообщение await Bot.SendTextMessageAsync(message.Chat.Id, "тест", replyToMessageId : message.MessageId); } if (message.Text == "/ibuttons") //inline buttons { var keyBoard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup ( new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { new [] { Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("Встряхнуть", "callBack1"), Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("Положить", "callBack2"), }, } ); await Bot.SendTextMessageAsync(message.Chat.Id, "Инлайн кнопка работает", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyBoard); } if (message.Text == "/rbuttons" || message.Text == "/to_shake" || message.Text == "Встряхнуть!") { var keyBoard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(new[] { new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Встряхнуть!") }, true, false); await Bot.SendTextMessageAsync(message.Chat.Id, processingAndReturnReply(), Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyBoard); } } //callBacks offset = v.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); } }