public async Task SendNewQuestion() { var randomNumber = new Random().Next(0, 5); var chatIdList = await _requestHistoryRepository.GetChatIdListAsync(); var words = await _wordRepository.GetAnyWordsAsync(count : 5); var questionWord = words.ToList()[randomNumber]; var question = $"Which translation is correct? 🤔 *{questionWord.En}*"; var options = words.Select(word => word.Tr); foreach (var chatId in chatIdList) { try { await _telegramBotClient.SendPollAsync(chatId, question, options, type : PollType.Quiz, isAnonymous : false, correctOptionId : randomNumber); } catch { System.Console.WriteLine($"{chatId} blocked me! :(("); } } }
private async void BotClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e) { if (e.CallbackQuery.Data == "quiz") { List <string> answers = new List <string>(); answers.Add("Nice"); answers.Add("Bad"); var id = await botClient.SendPollAsync(chatId : e.CallbackQuery.Message.Chat, question : "How are you ?", answers, isAnonymous : false); Polls.Add(new Poll { ChatId = e.CallbackQuery.Message.Chat, PollId = id.Poll.Id }); } }
public override async Task Execute(BunkerUser user, ITelegramBotClient client) { Room room = Program.rooms.GetRoomByPlayer(user); int size = room.Players.Count; if (size == 1) { Program.SendMessage(user, "You must have at least 2 players to start a poll!"); } else { string[] options = new string[size]; for (int i = 0; i < size; i++) { options[i] = $"{room.Players[i].NickName}"; } var pollInt = await client.SendPollAsync(room.Players[0].ChatID, "Whom to quit", options); for (int i = 1; i < size; i++) { await client.ForwardMessageAsync(room.Players[i].ChatID, pollInt.Chat.Id, pollInt.MessageId); } await Task.Delay(20000); var stoppedPoll = await client.StopPollAsync(pollInt.Chat.Id, pollInt.MessageId); int max = 0; string name = ""; foreach (PollOption option in stoppedPoll.Options) { if (option.VoterCount > max) { max = option.VoterCount; name = option.Text; } } BunkerUser player = room.GetPlayerByName(name); room.RemovePlayer(player); } }
public async Task ExecuteAsync(Message message) { await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); var randomNumber = new Random().Next(0, 5); var words = await _wordRepository.GetAnyWordsAsync(count : 5); var questionWord = words.ToList()[randomNumber]; var question = $"Which translation is correct? 🤔 *{questionWord.En}*"; var options = words.Select(word => word.Tr); try { await _telegramBotClient.SendPollAsync(message.Chat.Id, question, options, type : PollType.Quiz, isAnonymous : false, correctOptionId : randomNumber); } catch { System.Console.WriteLine($"{message.Chat.Id} blocked me! :(("); } }
static async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message.Text == "/hello") { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Hello, world!", parseMode : ParseMode.Default, disableNotification : false); } if (e.Message.Text == "/sendpic") { Message photoMessage = await botClient.SendPhotoAsync( chatId : e.Message.Chat, photo : "https://cdn5.zp.ru/job/attaches/2019/08/35/b8/35b8649f6773c52f3535793d96d84317.jpg", caption : "<b>Логотип ИнПАД</b>. <i>Источник</i>: <a href=\"https://www.inpad.ru\">ИнПАД</a>", parseMode : ParseMode.Html); } if (e.Message.Text == "/sendpoll") { Message pollMessage = await botClient.SendPollAsync( chatId : e.Message.Chat, isAnonymous : false, question : "Ты работаешь в ИнПАДе?", options : new[] { "Да", "Нет, в другом месте" }); } if (e.Message.Text == "/sendfile") { Message fileMessage = await botClient.SendDocumentAsync( chatId : e.Message.Chat, document : "https://media.tenor.com/images/e9cc959f643d3aac2322295eb95d19ce/tenor.gif" ); } if (e.Message.Text == "/sendsticker") { Message stickerMessage = await botClient.SendStickerAsync( chatId : e.Message.Chat, sticker : "https://raw.githubusercontent.com/zubanidze/telegramBot/master/TelegramTestBot/1146271698.webp"); } if (e.Message.Text == "/sendlocation") { Message locationMessage = await botClient.SendVenueAsync( chatId : e.Message.Chat.Id, latitude : 56.8393f, longitude : 60.5836f, title : "ИНСТИТУТ ПРОЕКТИРОВАНИЯ, архитектуры и дизайна", address : "ул. Шейнкмана, 10, Екатеринбург, Свердловская обл., 620014", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl( "Перейти на сайт организации", "https://www.inpad.ru/"))); } if (e.Message.Text == "/sendcontact") { Message contactMessage = await botClient.SendContactAsync( chatId : e.Message.Chat.Id, phoneNumber : "+73432875694", firstName : "Виктор", lastName : "Сальников"); } if ((!e.Message.Text.Contains("/") && (!e.Message.Text.All(char.IsDigit)))) { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Такой команды пока нет :(", parseMode : ParseMode.Default, replyMarkup : keyboard); } if (e.Message.Text == "custom") { var rkm = new ReplyKeyboardMarkup(); var rows = new List <KeyboardButton[]>(); var cols = new List <KeyboardButton>(); for (var Index = 1; Index < 17; Index++) { cols.Add(new KeyboardButton("" + Index)); if (Index % 4 != 0) { continue; } rows.Add(cols.ToArray()); cols = new List <KeyboardButton>(); } rkm.Keyboard = rows.ToArray(); await botClient.SendTextMessageAsync( e.Message.Chat, "Choose", replyMarkup : rkm); } if (e.Message.Text == "1") { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Hello, world!", parseMode : ParseMode.Default, disableNotification : false); } if (e.Message.Text == "2") { Message contactMessage = await botClient.SendContactAsync( chatId : e.Message.Chat.Id, phoneNumber : "+73432875694", firstName : "Виктор", lastName : "Сальников"); } if (e.Message.Text == "3") { Message pollMessage = await botClient.SendPollAsync( chatId : e.Message.Chat, isAnonymous : false, question : "Ты работаешь в ИнПАДе?", options : new[] { "Да", "Нет, в другом месте" }); } }
// async OnMessage event task for the bot // it has to be async so the bot can be always listening private async static void BotClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { // Normal text message. Checks wether the message does have text. // in case it does, the bot answers. #region Text Message if (e.Message.Text != null) { Console.WriteLine($"Received text message in chat {e.Message.Chat.Id}."); // the bot sends asynchronously a message to the chat await botClient.SendTextMessageAsync( chatId : e.Message.Chat.Id, text : "You said:\n" + e.Message.Text ); } #endregion // Normal text message, with all the properties // a text message can have. #region Text message with properties Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, // or a chat id: 123456789 text : "Trying *all the parameters* of `sendMessage` method", parseMode : ParseMode.Markdown, disableNotification : true, replyToMessageId : e.Message.MessageId, replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl( "Check sendMessage method", "https://core.telegram.org/bots/api#sendmessage" )) ); #endregion // Almost all of the methods for sending messages return you // the message you just sent. #region Messages return you the message you sent (as an object) Console.WriteLine( $"{textMessage.From.FirstName} sent message {textMessage.MessageId} " + $"to chat {textMessage.Chat.Id} at {textMessage.Date.ToLocalTime()}. " + // if you don't use ToLocalTime(), the bot will show the UTC time. $"It is a reply to message {textMessage.ReplyToMessage.MessageId} " + $"and has {textMessage.Entities.Length} message entities." ); #endregion // Photo message. It gets the image from a URL on the internet. // All images can have captions. You can use HTML or Markdown on them. #region Photo Message Message photoMessage = await botClient.SendPhotoAsync( chatId : e.Message.Chat, photo : "https://github.com/TelegramBots/book/raw/master/src/docs/photo-ara.jpg", caption : "<b>Ara bird</b>. <i>Source</i>: <a href=\"https://pixabay.com\">Pixabay</a>", parseMode : ParseMode.Html ); #endregion // Sticker message. Sticker files should be in WebP format. // Sends two messages. The first one gets the sticker by passing HTTP URL // to WebP sticker file, and the second by reusing the file_id of the // first sticker (kinda like a cache?) #region Sticker Messages Message stickerMessage1 = await botClient.SendStickerAsync( chatId : e.Message.Chat, sticker : "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-fred.webp" ); Message stickerMessage2 = await botClient.SendStickerAsync( chatId : e.Message.Chat, sticker : stickerMessage1.Sticker.FileId ); #endregion // Audio message. Opens it in Media Player. MP3 Format. // Telegram can read metadata from the MP3 file (that's why // there are commented properties; the bot gets the same // properties, but from the file metadata!) #region Audio Message Message audioMessage = await botClient.SendAudioAsync( e.Message.Chat, "https://github.com/TelegramBots/book/raw/master/src/docs/audio-guitar.mp3" /*, * performer: "Joel Thomas Hunger", * title: "Fun Guitar and Ukulele", * duration: 91 // in seconds */ ); #endregion // Voice message. Not opened in Media Player (played directly // on the chat). OGG Format. // In this case, the OGG file is on our disk! #region Voice Message Message voiceMessage; using (var stream = System.IO.File.OpenRead("C:/Users/Biel/source/repos/TelegramBot/voice-nfl_commentary.ogg")) { voiceMessage = await botClient.SendVoiceAsync( chatId : e.Message.Chat, voice : stream, duration : 36 ); } #endregion // You can send MP4 files as a regular video or as a video note. // Other video formats must be sent as a file. // Video message. They can have caption, reply, and reply markup // (like other multimedia messages) // You can optionally specify the duration and the resolution // of the video. In this case the video is streamed, // meaning the user can partly watch the video on stream, without // having to download it completely. #region Video Message Message videoMessage = await botClient.SendVideoAsync( chatId : e.Message.Chat, video : "https://raw.githubusercontent.com/TelegramBots/book/master/src/docs/video-countdown.mp4", thumb : "https://raw.githubusercontent.com/TelegramBots/book/master/src/2/docs/thumb-clock.jpg", supportsStreaming : true ); #endregion // Video note message. They are shown in circles to the user. // They are usually short (1 minute or less). // You can send a video note only by the video file or // reusing the file_id of another video note. // (sending it by its HTTP URL is not supported currently) #region Video Note Message Message videoNoteMessage; using (var stream = System.IO.File.OpenRead("C:/Users/step/Source/Repos/TelegramBotExamples/video-waves.mp4")) { videoNoteMessage = await botClient.SendVideoNoteAsync( chatId : e.Message.Chat, videoNote : stream, duration : 47, length : 360 // value of width/height ); } #endregion // Poll message. They can be sent only to groups and channels. // You can optionally send a keyboard with a poll, // both inline and a regular one. #region Poll Message Message pollMessage = await botClient.SendPollAsync( chatId : "@group_or_channel_username", question : "Did you ever hear the tragedy of Darth Plagueis The Wise?", options : new [] { "Yes for the hundredth time!", "No, who's that?" } ); #endregion // To stop the poll, you need to know original chat and message ids // (you get them from the Poll object you get on SendPollAsync, the pollMessage) #region Closing a Poll Poll poll = await botClient.StopPollAsync( chatId : pollMessage.Chat.Id, messageId : pollMessage.MessageId ); #endregion // Filtering messages for commands if (e.Message.Text == "/sayhello") { Message sayHello = await botClient.SendTextMessageAsync ( chatId : e.Message.Chat.Id, text : "Hello! Glad to see you!" ); } if (e.Message.Text == "/saygoodbye") { Message sayHello = await botClient.SendTextMessageAsync ( chatId : e.Message.Chat.Id, text : "Bye! Have a nice day!" ); } }