public async Task Should_Answer_Inline_Query_With_Cached_Video() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedVideo); // Video from https://pixabay.com/en/videos/fireworks-rocket-new-year-s-eve-7122/ Message videoMessage = await BotClient.SendVideoAsync( chatId : _fixture.SupergroupChat, video : "https://pixabay.com/en/videos/download/video-7122_medium.mp4", replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResultBase[] results = { new InlineQueryResultCachedVideo( id: "fireworks_video", videoFileId: videoMessage.Video.FileId, title: "New Year's Eve Fireworks" ) { Description = "2017 Fireworks in Germany" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); }
public async Task Should_Answer_Inline_Query_With_Cached_Mpeg4Gif() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedMpeg4Gif); Message gifMessage = await BotClient.SendDocumentAsync( chatId : _fixture.SupergroupChat, document : "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResultBase[] results = { new InlineQueryResultCachedMpeg4Gif( id: "mpeg4_gif_result", mpeg4FileId: gifMessage.Document.FileId ) { Caption = "A beautiful scene", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); }
public async Task Should_Answer_Inline_Query_With_Cached_Photo() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedPhoto); Message photoMessage; using (var stream = System.IO.File.OpenRead(Constants.FileNames.Photos.Apes)) { photoMessage = await BotClient.SendPhotoAsync( chatId : _fixture.SupergroupChat, photo : stream, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResultBase[] results = { new InlineQueryResultCachedPhoto( id: "photo1", photoFileId: photoMessage.Photo.First().FileId ) { Caption = "Apes smoking shisha" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); }
private InlineKeyboardMarkup GetChoices() { var choices = new List <InlineKeyboardButton>(); if (CurrentPlayer.Bet == CurrentBet) { choices.Add(InlineKeyboardButton.WithCallbackData("Parler", "check " + ChatId)); } else if (CurrentPlayer.CanBet(CurrentBet)) { choices.Add(InlineKeyboardButton.WithCallbackData($"Suivre +{BB(CurrentBet - CurrentPlayer.Bet)}", "call " + ChatId)); } if (!CurrentPlayer.CanBet(CurrentBet + BigBet + 1)) { choices.Add(InlineKeyboardButton.WithCallbackData("All in", "allin " + ChatId)); } else if (MaxBet == -1 || CurrentBet + BigBet < MaxBet) { choices.Add(InlineKeyboardButton.WithCallbackData($"Relance +{BB(CurrentBet + BigBet - CurrentPlayer.Bet)}", "raise " + ChatId)); } if (CurrentPlayer.Bet < CurrentBet) { choices.Add(InlineKeyboardButton.WithCallbackData("Passer", "fold " + ChatId)); } return(new InlineKeyboardMarkup(new IEnumerable <InlineKeyboardButton>[] { choices, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Voir mes cartes et jetons", "") }, })); }
public override BotMessage BuildMsg() { EditProductBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Редактор" + base.PenEmodji, InlineFind.EditProduct + "|"); HelpDesktBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Тех. поддержка" + base.PenEmodji, InlineFind.HelpdDesk + "|"); EditCategoryBtn = new InlineKeyboardCallbackButton("Изм. категорию" + " \ud83d\udd8a", BuildCallData(CategoryEditBot.CategoryEditorCmd, CategoryEditBot.ModuleName)); StockViewBtn = BuildInlineBtn("Остатки", BuildCallData("ViewStock", AdminBot.ModuleName), base.Depth2Emodji); ViewFollowerBtn = BuildInlineBtn("Пользователи", BuildCallData(AdminBot.ViewFollowerListCmd, AdminBot.ModuleName), base.ManEmodji2); ViewOrdersBtn = BuildInlineBtn("Заказы", BuildCallData(AdminBot.ViewOrdersListCmd, AdminBot.ModuleName), base.PackageEmodji); ViewPaymentsBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Платежи" + base.CreditCardEmodji, InlineFind.Payment + "|"); MoreSettingsBtn = BuildInlineBtn("Доп. настройки", BuildCallData(MoreSettingsBot.MoreSettingsCmd, MoreSettingsBot.ModuleName), base.CogwheelEmodji); ControlPanelPage2Btn = BuildInlineBtn(base.Next2Emodji, BuildCallData(AdminBot.AdminPage2Cmd, AdminBot.ModuleName)); ExportBtn = BuildInlineBtn("Экспорт данных в .xlsx", BuildCallData(AdminBot.ExportViewerCmd, AdminBot.ModuleName), base.NoteBookEmodji); base.TextMessage = Bold("Панель администратора") + NewLine() + "1) Добавить новый товар /addprod" + NewLine() + "2) Создать новую категорию /newcategory" + NewLine() + "3) Бот рассылает уведомления в ЛС. Что бы выключить нажмите /off , что бы включить нажмите /on" + NewLine() + "4) Документация /doc "; SetInlineKeyBoard(); return(this); }
private Task <Message> SendNotificationToChatAsync(bool isForCollection, string name, string instructions = default, ChatId chatid = default, bool switchInlineQuery = default) { var textFormat = isForCollection ? Constants.StartCollectionMessageFormat : Constants.StartTestCaseMessageFormat; string text = string.Format(textFormat, name); chatid = chatid ?? SupergroupChat.Id; if (instructions != default) { text += "\n\n" + string.Format(Constants.InstructionsMessageFormat, instructions); } IReplyMarkup replyMarkup = switchInlineQuery ? new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Start inline query") }) : default; var task = BotClient.SendTextMessageAsync(chatid, text, ParseMode.Markdown, replyMarkup: replyMarkup, cancellationToken: CancellationToken); return(task); }
public async Task Should_Answer_Inline_Query_With_Cached_Mpeg4Gif() { Message gifMessage = await BotClient.SendDocumentAsync( chatId : _fixture.SupergroupChat, document : "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "mpeg4_gif_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedMpeg4Gif(id: resultId, mpeg4FileId: gifMessage.Document.FileId) { Caption = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); }
public InlineKeyboardMarkup MoreBtn() { ViewAdditionalPhotosBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Доп. фото" + base.PictureEmodji, InlineFind.AdditionalProduct + "|" + ProductId); ProductEditUrlBtn = BuildInlineBtn("Заметка", BuildCallData(ProductEditBot.ProductEditUrlCmd, ProductEditBot.ModuleName, ProductId), base.PenEmodji); AdminPanelBtn = BackToAdminPanelBtn(); UnitBtn = BuildInlineBtn("Ед.изм.", BuildCallData(ProductEditBot.ProudctUnitCmd, ProductEditBot.ModuleName, ProductId), base.WeigherEmodji); BackBtn = BuildInlineBtn("Назад", BuildCallData(ProductEditBot.BackToProductEditorCmd, ProductEditBot.ModuleName, ProductId), base.Previuos2Emodji, false); InsertAdditionalPhotosBtn = BuildInlineBtn("Добавить доп. фото", BuildCallData(ProductEditBot.InsertAdditionalPhotosCmd, ProductEditBot.ModuleName, ProductId), base.PictureEmodji); return(new InlineKeyboardMarkup( new[] { new[] { ProductEditUrlBtn, UnitBtn }, new[] { ViewAdditionalPhotosBtn, InsertAdditionalPhotosBtn }, new[] { BackBtn, AdminPanelBtn } , })); }
public async Task Should_Answer_Inline_Query_With_Cached_Voice() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedAudio); Message voiceMessage; using (var stream = System.IO.File.OpenRead(Constants.FileNames.Audio.TestOgg)) { voiceMessage = await BotClient.SendVoiceAsync( chatId : _fixture.SupergroupChat, voice : stream, duration : 24, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResultBase[] results = { new InlineQueryResultCachedVoice( id: "voice_result", fileId: voiceMessage.Voice.FileId, title: "Test Voice" ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); }
public static InlineKeyboardMarkup GetStartInlineKeyboardMarkup() { return(new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Search books"), InlineKeyboardButton.WithSwitchInlineQuery("🔗 Find & share book") })); }
public static InlineKeyboardMarkup GetStartKeyboardMarkup() { return(new(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Поиск аниме"), InlineKeyboardButton.WithSwitchInlineQuery("🔗 Найти и поделиться аниме") })); }
public async Task Should_Send_Inline_Keyboard() { Message sentMessage = await BotClient.SendTextMessageAsync( chatId : _fixture.SupergroupChat, text : "Message with inline keyboard markup", replyMarkup : new InlineKeyboardMarkup(new[] { new [] { InlineKeyboardButton.WithUrl( "Link to Repository", "https://github.com/TelegramBots/Telegram.Bot" ), }, new [] { InlineKeyboardButton.WithCallbackData("callback_data1"), InlineKeyboardButton.WithCallbackData("callback_data2", "data"), }, new [] { InlineKeyboardButton.WithSwitchInlineQuery("switch_inline_query"), }, new [] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch_inline_query_current_chat"), }, }) ); Assert.True( JToken.DeepEquals( JToken.FromObject(sentMessage.ReplyMarkup), JToken.FromObject( new InlineKeyboardMarkup( new[] { new[] { InlineKeyboardButton.WithUrl( "Link to Repository", "https://github.com/TelegramBots/Telegram.Bot" ), }, new[] { InlineKeyboardButton.WithCallbackData("callback_data1"), InlineKeyboardButton.WithCallbackData("callback_data2", "data"), }, new[] { InlineKeyboardButton.WithSwitchInlineQuery("switch_inline_query"), }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch_inline_query_current_chat"), }, } ) ) ) ); }
public async Task ShouldEditInlineMessageDocumentWithFileId() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldEditInlineMessageDocumentWithFileId); // Upload a GIF file to Telegram servers and obtain its file_id. This file_id will be used later in test. string animationFileId; using (Stream stream = System.IO.File.OpenRead(Constants.FileNames.Animation.Earth)) { Message gifMessage = await BotClient.SendDocumentAsync( chatId : _fixture.SupergroupChat, document : new InputOnlineFile(stream, "Earth.gif"), caption : "`file_id` of this GIF will be used", parseMode : ParseMode.Markdown, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start Inline Query") ); animationFileId = gifMessage.Document.FileId; } #region Answer Inline Query with a media message Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResultBase[] inlineQueryResults = { new InlineQueryResultDocument( id: "document:acrobat", documentUrl: "http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf", title: "Parameters for Opening PDF Files", mimeType: "application/pdf" ) { ReplyMarkup = InlineKeyboardButton.WithCallbackData("Click here to edit"), } }; await BotClient.AnswerInlineQueryAsync(iqUpdate.InlineQuery.Id, inlineQueryResults, 0); #endregion // Bot waits for user to click on inline button under the media Update cqUpdate = await _fixture.UpdateReceiver.GetCallbackQueryUpdateAsync(data : "Click here to edit"); // Change the YouTube video for an animation. Note that, in the case of an inline message, the new media // should be either an URL or the file_id of a previously uploaded media. // Also, animation thumbnail cannot be uploaded for an inline message. await BotClient.EditMessageMediaAsync( inlineMessageId : cqUpdate.CallbackQuery.InlineMessageId, media : new InputMediaAnimation(animationFileId) ); }
public override BotMessage BuildMsg() { MenuBtn = new InlineKeyboardCallbackButton("Каталог (текстовая версия)" + " \ud83d\udcc3", BuildCallData("Menu", Bot.CategoryBot.ModuleName)); ContactBtn = new InlineKeyboardCallbackButton("О нас" + " \u260e\ufe0f", BuildCallData("Contact", Bot.MainMenuBot.ModuleName)); ViewBasketBtn = new InlineKeyboardCallbackButton("Корзина" + " \ud83d\uded2", BuildCallData(Bot.BasketBot.ViewBasketCmd, Bot.BasketBot.ModuleName)); MyOrdersBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Мои заказы", InlineFind.MyOrders + "|"); HelpBtn = new InlineKeyboardCallbackButton("Служба поддержки", BuildCallData("Help", Bot.HelpDeskBot.ModuleName)); OpenSourceBtn = InlineKeyboardButton.WithUrl("Чат бот для магазина", "https://t.me/ecommercechatbot"); PhotoCatalogBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Фотокаталог" + base.PictureEmodji, InlineFind.PhotoCatalog + "|"); SearchProductBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Поиск" + base.SearchEmodji, InlineFind.SearchProduct + "|"); SetInlineKeyBoard(); base.TextMessage = "Выберите действие"; return(this); }
public async Task Should_Answer_Inline_Query_With_Cached_Audio() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedAudio); Message audioMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Audio.CantinaRagMp3)) { audioMessage = await BotClient.SendAudioAsync( chatId : _fixture.SupergroupChat, audio : stream, performer : "Jackson F. Smith", duration : 201, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "audio_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedAudio( id: resultId, audioFileId: audioMessage.Audio.FileId ) { Caption = "Jackson F. Smith - Cantina Rag" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Audio); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Audio, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); }
public async Task Should_Answer_Inline_Query_With_Cached_Document() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedDocument); Message documentMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Documents.Hamlet)) { documentMessage = await BotClient.SendDocumentAsync( chatId : _fixture.SupergroupChat, document : stream, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "document_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedDocument( id: resultId, documentFileId: documentMessage.Document.FileId, title: "Test Document" ) { Caption = "The Tragedy of Hamlet, Prince of Denmark", Description = "Sample PDF Document", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); }
public async Task Should_Answer_Inline_Query_With_Cached_Photo() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedPhoto); Message photoMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Photos.Apes)) { photoMessage = await BotClient.SendPhotoAsync( chatId : _fixture.SupergroupChat, photo : stream, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:apes"; const string caption = "Apes smoking shisha"; InlineQueryResultBase[] results = { new InlineQueryResultCachedPhoto( id: resultId, photoFileId: photoMessage.Photo.First().FileId ) { Caption = caption } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Photo); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Photo, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); Assert.Equal(caption, messageUpdate.Message.Caption); }
private async Task PlaceOrderAsync(string callbackQueryId) { if (string.IsNullOrEmpty(RecipientFullName) || string.IsNullOrEmpty(StreetAddress) || string.IsNullOrEmpty(TownCity) || string.IsNullOrEmpty(Postcode) || string.IsNullOrEmpty(Country.Value)) { await _bot.AnswerCallbackQueryAsync(callbackQueryId, "Please fill all the required fields."); return; } using var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.shitexpress.com/btc/create.php") { // We sadly can't use FormUrlEncodedContent because spaces are escaped as '+': https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs#L52-L53 Content = new StringContent( $"btc={Uri.EscapeDataString("1")}" + $"&name={Uri.EscapeDataString(RecipientFullName)}" + $"&street={Uri.EscapeDataString(StreetAddress)}" + $"&city={Uri.EscapeDataString(TownCity)}" + $"&zip={Uri.EscapeDataString(Postcode)}" + $"&state={Uri.EscapeDataString(StateCounty ?? string.Empty)}" + $"&country={Uri.EscapeDataString(Country.Value)}" + $"¬es={Uri.EscapeDataString(Message ?? string.Empty)}" + $"&animal={Uri.EscapeDataString(Animal.Value)}" + $"&packaging={Uri.EscapeDataString(Sticker.Value)}" + $"&email={Uri.EscapeDataString(Email ?? string.Empty)}" + $"&referer={Uri.EscapeDataString("https://github.com/Laiteux/ShitexpressBot")}" + $"&ref={Uri.EscapeDataString("https://github.com/Laiteux/ShitexpressBot")}", Encoding.UTF8, "application/x-www-form-urlencoded") }; using var responseMessage = await Program.HttpClient.SendAsync(requestMessage); var contentString = await responseMessage.Content.ReadAsStringAsync(); string[] split = contentString.Split('|'); var text = new StringBuilder() .AppendLine("*Order ID:* " + split[0]) .AppendLine("*Address:* " + split[2]) .AppendLine("*Amount:* " + split[3]) .AppendLine() .AppendLine("Please send the exact provided amount to the Bitcoin address."); await _bot.SendTextMessageAsync(_orderMessage.Chat, text.ToString(), ParseMode.Markdown, replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Check order status", split[0]))); }
public async Task Should_Answer_Inline_Query_With_Cached_Voice() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedAudio); Message voiceMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Audio.TestOgg)) { voiceMessage = await BotClient.SendVoiceAsync( chatId : _fixture.SupergroupChat, voice : stream, duration : 24, replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "voice_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedVoice( id: resultId, fileId: voiceMessage.Voice.FileId, title: "Test Voice" ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Voice); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Voice, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); }
public InlineKeyboardMarkup SetInline() { if (Follower != null && Follower.Blocked) { return(new InlineKeyboardMarkup(new[] { new[] { BuildInlineBtn("Разблокировать:", BuildCallData(AdminBot.UnBlockFollowerCmd, AdminBot.ModuleName, Follower.Id)) }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Адреса", InlineFind.FollowerAddress + "|" + Follower.Id.ToString()), InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Заказы", InlineFind.FolowerOrder + "|" + Follower.Id.ToString()) }, new[] { BackToAdminPanelBtn() } })); } else { return(new InlineKeyboardMarkup(new[] { new[] { BuildInlineBtn("Заблокировать:", BuildCallData(AdminBot.BlockFollowerCmd, AdminBot.ModuleName, Follower.Id)) , BuildInlineBtn("Дать права оператора", BuildCallData(OperatorBot.AddOperatorRulesCmd, OperatorBot.ModuleName, Follower.Id)) }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Адреса", InlineFind.FollowerAddress + "|" + Follower.Id.ToString()), InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Заказы", InlineFind.FolowerOrder + "|" + Follower.Id.ToString()) }, new[] { BackToAdminPanelBtn() } })); } }
public override InlineQueryResult[] GetResult() { BotId = GeneralFunction.GetBotInfo().Id; AdditionalPhotos = ProductFunction.GetAdditionalPhoto(ProductId, BotId).Take(MaxResult).ToList(); InlineQueryResult [] result = new InlineQueryResult[AdditionalPhotos.Count]; InlineQueryResultCachedPhoto[] cachedPhoto = new InlineQueryResultCachedPhoto[AdditionalPhotos.Count]; int i = 0; foreach (var photo in AdditionalPhotos) { RemoveAdditionalPhotoBtn = BuildInlineBtn("Удалить", BuildCallData(ProductEditBot.RemoveAdditionalPhotoCmd, ProductEditBot.ModuleName, photo.ProductId, photo.AttachFsId)); BackToProductEditorBtn = BuildInlineBtn("Вернуться к товару", BuildCallData(ProductEditBot.ProductEditorCmd, ProductEditBot.ModuleName, photo.ProductId)); ViewAdditionalPhotoBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Другие фотографии", InlineFind.AdditionalProduct + "|" + ProductId); cachedPhoto[i] = new InlineQueryResultCachedPhoto(); cachedPhoto[i].FileId = photo.FileId; cachedPhoto[i].Caption = photo.Caption; cachedPhoto[i].Id = photo.AttachFsId.ToString(); cachedPhoto[i].ReplyMarkup = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup( new[] { new[] { RemoveAdditionalPhotoBtn }, new[] { BackToProductEditorBtn }, new[] { ViewAdditionalPhotoBtn } }); result[i] = cachedPhoto[i]; i++; } return(result); }
public async Task Should_Do() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSendInlineKeyboardMarkup); await BotClient.SendTextMessageAsync( chatId : _fixture.SupergroupChat, text : "Message with inline keyboard markup", replyMarkup : new InlineKeyboardMarkup(new[] { new [] { InlineKeyboardButton.WithUrl("Link to Repository", "https://github.com/TelegramBots/Telegram.Bot"), }, new [] { InlineKeyboardButton.WithCallbackData("callback_data1"), InlineKeyboardButton.WithCallbackData("callback_data2", "data"), }, new [] { InlineKeyboardButton.WithSwitchInlineQuery("switch_inline_query"), }, new [] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch_inline_query_current_chat"), }, }) ); }
public async Task Should_Answer_Inline_Query_With_Cached_Video() { // Video from https://pixabay.com/en/videos/fireworks-rocket-new-year-s-eve-7122/ Message videoMessage = await BotClient.SendVideoAsync( chatId : _fixture.SupergroupChat, video : "https://pixabay.com/en/videos/download/video-7122_medium.mp4", replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "fireworks_video"; InlineQueryResultBase[] results = { new InlineQueryResultCachedVideo( id: resultId, videoFileId: videoMessage.Video.FileId, title: "New Year's Eve Fireworks" ) { Description = "2017 Fireworks in Germany" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId : iqUpdate.InlineQuery.Id, results : results, cacheTime : 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Video); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); }
public override BotMessage BuildMsg() { base.TextMessage = Bold("Список операторов системы:"); string OperatorsList = ""; SearchOperatorBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Поиск" + base.SearchEmodji, InlineFind.FindOperators + "|"); using (MarketBotDbContext db = new MarketBotDbContext()) { var operators = db.Admin.Where(a => a.Enable).Include(a => a.Follower).ToList(); if (operators != null) { int counter = 1; foreach (var op in operators) { OperatorsList += NewLine() + counter.ToString() + ") " + base.ManAndComputerEmodji + " " + op.Follower.FirstName + " | телефон: " + op.Follower.Telephone + NewLine() + "забрать права оператора: /removeoperator" + op.Id.ToString() + NewLine(); counter++; } } } base.TextMessage += OperatorsList + NewLine() + Italic("Оператор системы имеет следующие права доступа: Обрабатывать заказы, Обрабатывать заявки технической поддержки."); base.MessageReplyMarkup = new InlineKeyboardMarkup( new[] { new[] { SearchOperatorBtn }, new[] { BackToAdminPanelBtn() }, }); return(this); }
public Task <Message> SendTestInstructionsAsync( string instructions, ChatId chatid = default, bool startInlineQuery = default ) { string text = string.Format(Constants.InstructionsMessageFormat, instructions); chatid = chatid ?? SupergroupChat.Id; IReplyMarkup replyMarkup = startInlineQuery ? (InlineKeyboardMarkup)InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Start inline query") : default; return(BotClient.SendTextMessageAsync( chatid, text, ParseMode.Markdown, replyMarkup: replyMarkup, cancellationToken: CancellationToken )); }
public override BotMessage BuildMsg() { if (Payment == null) { Payment = PaymentsFunction.GetPayment(PaymentId); } if (Payment != null && Payment.Invoice != null && Payment.Invoice.Orders.Count > 0) { ViewOrderBtn = BuildInlineBtn("Детали заказа", BuildCallData(OrderProccesingBot.CmdGetOrderAdmin, OrderProccesingBot.ModuleName, Payment.Invoice.Orders.FirstOrDefault().Id), base.PackageEmodji); ViewInvoiceBtn = BuildInlineBtn("Счет", BuildCallData(OrderProccesingBot.ViewInvoiceCmd, OrderProccesingBot.ModuleName, Payment.Invoice.Orders.FirstOrDefault().Id), base.PaperEmodji); SearchPaymentBtn = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Платежи" + base.CreditCardEmodji, InlineFind.Payment + "|"); base.TextMessage = "Платеж №" + Payment.Id.ToString() + " для Заказа №" + Payment.Invoice.Orders.FirstOrDefault().Number.ToString() + NewLine() + Bold("Дата добавления платежа:") + Payment.TimestampDataAdd.ToString() + NewLine() + Bold("Сумма:") + Payment.Summ.ToString() + NewLine() + Bold("ID Транзакции:") + Payment.TxId.ToString(); base.MessageReplyMarkup = new InlineKeyboardMarkup(new[] { new[] { ViewInvoiceBtn }, new[] { ViewOrderBtn }, new[] { SearchPaymentBtn } }); } return(this); }
private static async void OnOnMessageAsync(object sender, MessageEventArgs messageEventArgs) { try { var message = messageEventArgs.Message; if (message.Text.StartsWith("/start")) { await _bot.SendTextMessageAsync(new ChatId(message.From.Id), "This bot can help you find and share books. It is works in any chat, just write @GBooksBot " + "in the text field. Let's try!", replyMarkup : new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Search books"), InlineKeyboardButton.WithSwitchInlineQuery("🔗 Find and share book with friends") })); } } catch (Exception e) { Console.WriteLine(e); } }
private static async Task <InlineQueryExecutionResult> OnInlineQuerySearchUupAsync(this TelegramService telegramService) { var inlineQueryExecution = new InlineQueryExecutionResult(); var uupService = telegramService.GetRequiredService <UupDumpService>(); var query1 = telegramService.GetInlineQueryAt <string>(1); var query2 = telegramService.GetInlineQueryAt <string>(2); var queryValue = telegramService.InlineQueryValue; var builds = await uupService.GetUpdatesAsync(queryValue); var inlineQueryResults = builds.Response.Builds.Select( build => { var title = build.BuildNumber + " - " + build.Arch.ToString().ToUpper(); var downloadLink = build.Arch == Arch.Arm64 ? $"https://uupdump.net/download.php?id={build.Uuid}&pack=en-us&edition=core;professional" : $"https://uupdump.net/download.php?id={build.Uuid}&pack=en-us&edition=core;coren;professional;professionaln"; var htmlDescription = HtmlMessage.Empty .TextBr(build.Created.ToString("yyyy-MM-dd HH:mm:ss tt zz")) .TextBr(build.Title); var htmlContent = HtmlMessage.Empty .Bold("Title: ").CodeBr(build.Title) .Bold("Version: ").CodeBr(build.BuildNumber) .Bold("Date: ").CodeBr(build.Created.ToString("yyyy-MM-dd HH:mm:ss tt zz")) .Bold("Arch: ").CodeBr(build.Arch.ToString().ToUpper()); var result = new InlineQueryResultArticle( id: build.Uuid, title: title, inputMessageContent: new InputTextMessageContent(htmlContent.ToString()) { ParseMode = ParseMode.Html, DisableWebPagePreview = true } ) { Description = htmlDescription.ToString(), ReplyMarkup = new InlineKeyboardMarkup( new[] { new[] { InlineKeyboardButton.WithUrl("Unduh", downloadLink) }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Pencarian lanjut", $"uup {queryValue} "), InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Ulang pencarian", $"uup "), } } ) }; return(result); } ); await telegramService.AnswerInlineQueryAsync(inlineQueryResults); return(inlineQueryExecution); }
private static async Task <InlineQueryExecutionResult> OnInlineQueryGuideAsync(this TelegramService telegramService) { var learnMore = "https://docs.zizibot.winten.my.id/features/inline-query"; var inlineResult = new InlineQueryExecutionResult(); var learnMoreContent = $"Silakan pelajari selengkapnya" + $"\n{learnMore}" + $"\n\nAtau tekan salah satu tombol dibawah ini"; var replyMarkup = new InlineKeyboardMarkup( new[] { new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Ping", $"ping") }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Buat pesan dengan tombol", $"message") }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Cari subtitle", "subscene ") }, new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Cari UUP dump", "uup ") }, } ); await telegramService.AnswerInlineQueryAsync( new List <InlineQueryResult>() { new InlineQueryResultArticle( id: "guide-1", title: "Bagaimana cara menggunakannya?", inputMessageContent: new InputTextMessageContent(learnMoreContent) { DisableWebPagePreview = true } ) { ReplyMarkup = replyMarkup }, new InlineQueryResultArticle( id: "guide-2", title: "Cobalah ketikkan 'ping'", inputMessageContent: new InputTextMessageContent(learnMoreContent) { DisableWebPagePreview = true } ) { ReplyMarkup = replyMarkup } } ); inlineResult.IsSuccess = true; return(inlineResult); }
private async void OnMessageRecieved(object sender, MessageEventArgs e) { var message = e.Message; if (message == null || message.Type == MessageType.Document) { var res = await Bot.GetFileAsync(e.Message.Document.FileId); } if (message == null || message.Type == MessageType.Video) { var res = await Bot.GetFileAsync(e.Message.Video.FileId); } if (message == null || message.Type == MessageType.Photo) { } if (message == null || message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/start": await Bot.SendTextMessageAsync(message.Chat.Id, "Hello. Please use 'subscribe' command with enter your email for get notifications"); break; case "/subscribe": var splitted = message.Text.Split(' '); if (splitted.Length == 1) { await Bot.SendTextMessageAsync(message.Chat.Id, "You are not subscribed enter command with email"); return; } var email = splitted[1]; Subscribers.Add(email, message.Chat.Id); //SaveSubscribers(); await Bot.SendTextMessageAsync(message.Chat.Id, "You are subscribed to notification for " + email); break; case "/mainmenu": await Bot.SendMainMenu(message.Chat.Id); break; case "/notifications_on": await Bot.SendTextMessageAsync(message.Chat.Id, "вы подписались на уведомления о загрузке файлов"); break; case "/lastfiles": ///var request = "<a href=\"https://t.me/MasevaDriveBot?filestoday=image1234_56789">image name</a>"; await Bot.SendTextMessageAsync(message.Chat.Id, "сформировать запрос", ParseMode.Default, false, false, 0, new InlineKeyboardMarkup(InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("сформировать запрос", DateTime.Now.TimeOfDay.ToString().Substring(8))), default);; lastFilesQuery = StorageItemsProvider.Instance.Items.Values.OrderByDescending(file => new DateTime(Math.Max(file.DateTimeOriginal.Ticks, file.DateTimeCreation.Ticks))); break; case "/filestoday1": var splitteds = message.Text.Split('_'); var url = string.Format(urlFormat, splitteds[1]); try { await Bot.SendPhotoAsync(message.Chat.Id, new InputOnlineFile(url)); } catch { } break; case "/wh": break; #region // send custom keyboard /*case "/keyboard": * ReplyKeyboardMarkup ReplyKeyboard = new[] * { * new[] { "1.1", "1.2" }, * new[] { "2.1", "2.2" }, * }; * * await Bot.SendTextMessageAsync( * message.Chat.Id, * "Choose", * replyMarkup: ReplyKeyboard); * break; * case "/rootfolderlist": * var subFolders = Directory.GetDirectories(selectedFolder); * var items = subFolders.Count() != 0 ? subFolders.Select(folder => folder.Split(Path.DirectorySeparatorChar).Last()) : Directory.GetFiles(selectedFolder).Select(f => Path.GetFileName(f)); * * ReplyKeyboardMarkup keyboardWithFolders = new ReplyKeyboardMarkup( * items.Select(folder => new[] { new KeyboardButton(folder) }).Take(20)); * await Bot.SendTextMessageAsync( * message.Chat.Id, * "Choose", * replyMarkup: keyboardWithFolders); * ; * break; * // send a photo * case "/photo": * await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); * * const string file = @"d:\Temp\1.jpg"; * * var fileName = file.Split(Path.DirectorySeparatorChar).Last(); * * using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) * { * await Bot.SendPhotoAsync( * message.Chat.Id, * fileStream, * "Nice Picture"); * } * break; * * // request location or contact * case "/request": * var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] * { * KeyboardButton.WithRequestLocation("Location"), * KeyboardButton.WithRequestContact("Contact"), * }); * * await Bot.SendTextMessageAsync( * message.Chat.Id, * "Who or Where are you?", * replyMarkup: RequestReplyKeyboard); * break; * * default: * if (message.Text.ToLower().EndsWith(".jpg")) * { * var pathToFile = Path.Combine(selectedFolder, message.Text); * Image image = Image.FromFile(pathToFile); * var aspect = (double)image.Size.Width / (double)image.Size.Height; * Image thumb = image.GetThumbnailImage((int)(480 * aspect), 480, () => false, IntPtr.Zero); * using (MemoryStream imageStream = new MemoryStream()) * { * thumb.Save(imageStream, ImageFormat.Jpeg); * imageStream.Position = 0; * await Bot.SendPhotoAsync( * message.Chat.Id, * imageStream, * null); * } * return; * // put the image into the memory stream * } * * selectedFolder = Path.Combine(selectedFolder, message.Text); * try * { * var sFolders = Directory.GetDirectories(selectedFolder); * var itms = sFolders.Count() != 0 ? sFolders.Select(folder => folder.Split(Path.DirectorySeparatorChar).Last()) : Directory.GetFiles(selectedFolder).Select(f => Path.GetFileName(f)); * var buttons = itms.Select(folder => new[] { new KeyboardButton(folder) }).Take(20).ToArray(); * ReplyKeyboardMarkup _keyboardWithFolders = new ReplyKeyboardMarkup(buttons); * await Bot.SendTextMessageAsync( * message.Chat.Id, * null, * replyMarkup: _keyboardWithFolders); * ; * } * catch (Exception ex) * { * await Bot.SendTextMessageAsync( * message.Chat.Id, * "Wrong command", * replyMarkup: new ReplyKeyboardRemove()); * } * * break;*/ #endregion } }