public static InlineKeyboardMarkup GetReplyMarkup(this Poll poll) { if (poll.Cancelled) { return(null); } var pollId = poll.GetId(); var buttons = new List <InlineKeyboardButton>(VoteEnumEx.GetFlags(poll.AllowedVotes ?? VoteEnum.Standard) .Select(vote => { var display = vote.AsString(EnumFormat.DisplayName); switch (vote) { case VoteEnum.Share: return(InlineKeyboardButton.WithSwitchInlineQuery(display, $"{ShareInlineQueryHandler.ID}:{pollId}")); default: return(InlineKeyboardButton.WithCallbackData(display, $"{VoteCallbackQueryHandler.ID}:{pollId}:{vote}")); } })); return(new InlineKeyboardMarkup(buttons.ToArray())); }
public static InlineKeyboardMarkup GetStartKeyboardMarkup() { return(new(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Поиск аниме"), InlineKeyboardButton.WithSwitchInlineQuery("🔗 Найти и поделиться аниме") })); }
public static InlineKeyboardMarkup GetStartInlineKeyboardMarkup() { return(new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Search books"), InlineKeyboardButton.WithSwitchInlineQuery("🔗 Find & share book") })); }
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"), }, } ) ) ) ); }
internal static void FriendNotFound(int userId) { string msg = "Номер телефона Вашего друга не найден, поделитесь ссылкой на бота, чтобы поскорее узнать желаемые подарки друга"; string sharingText = "Привет! Отправляй боту то, что хочешь получить в подарок, и заодно посмотри, что хочу получить в подарок я"; var inlineKeyBoard = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithSwitchInlineQuery("Поделиться с друзьями", sharingText) } }); Program.Bot.SendTextMessageAsync(userId, msg, replyMarkup: inlineKeyBoard); }
async Task PrintMenu() { var text = "Добро пожаловать в Бумеранг Бот, главное меню:"; var keyboard = new[] { new [] { InlineKeyboardButton.WithCallbackData($"📝 Поставить оценку", AddReviewAction) }, new [] { InlineKeyboardButton.WithSwitchInlineQuery($"📢 Поделиться ботом", "Привет, поставь мне оценку 😀") }, new [] { InlineKeyboardButton.WithCallbackData($"🎁 Посмотреть действующие акции", PromotionsAction) }, new [] { InlineKeyboardButton.WithCallbackData($"📈 Мой рейтинг и оценки", ProfileAction) }, new [] { InlineKeyboardButton.WithCallbackData($"💌 Связаться с разработчиками", FeedbackAction) }, new [] { InlineKeyboardButton.WithCallbackData($"❓ Что я умею", HelpAction) } }; var markup = new InlineKeyboardMarkup(keyboard); await Trail.SendTextMessageAsync(text, replyMarkup : markup); }
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"), }, }) ); }
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); } }
public async Task <bool?> Handle(InlineQuery data, object context = default, CancellationToken cancellationToken = default) { var location = data.Location; var queryParts = data.Query.Split(' ', StringSplitOptions.RemoveEmptyEntries); var poll = default(Poll); var pollQuery = new List <string>(queryParts.Length); var searchQuery = new List <string>(queryParts.Length); var query = pollQuery; foreach (var queryPart in queryParts) { switch (queryPart) { case string locationPart when OpenLocationCode.IsValid(locationPart): location = OpenLocationCode.Decode(locationPart) is var code ? new Location { Longitude = (float)code.CenterLongitude, Latitude = (float)code.CenterLatitude } : location; break; case string part when Regex.Match(part, PATTERN) is Match match && match.Success: if (int.TryParse(match.Groups["pollId"].Value, out var pollId)) { poll = myRaidService.GetTemporaryPoll(pollId); } query = searchQuery; break; default: query.Add(queryPart); break; } } Portal[] portals; if (searchQuery.Count == 0) { portals = await myIngressClient.GetPortals(0.200, location, cancellationToken); } else { portals = await myIngressClient.Search(searchQuery, location, cancellationToken); } var results = new List <InlineQueryResultBase>(Math.Min(portals.Length, MAX_PORTALS_PER_RESPONSE) + 2); if ((poll == null) && (pollQuery.Count != 0)) { var voteFormat = await myDb.Set <Settings>().GetFormat(data.From.Id, cancellationToken); for (var i = 0; i < portals.Length && i < MAX_PORTALS_PER_RESPONSE; i++) { poll = new Poll(data) { Title = string.Join(" ", pollQuery), AllowedVotes = voteFormat, Portal = portals[i], ExRaidGym = false }; await myRaidService.GetPollId(poll, cancellationToken); results.Add(new InlineQueryResultArticle(poll.GetInlineId(), poll.GetTitle(myUrlHelper), poll.GetMessageText(myUrlHelper, disableWebPreview: poll.DisableWebPreview())) { Description = poll.AllowedVotes?.Format(new StringBuilder("Create a poll ")).ToString(), HideUrl = true, ThumbUrl = poll.GetThumbUrl(myUrlHelper).ToString(), ReplyMarkup = poll.GetReplyMarkup() }); if (i == 0) { poll.Id = -poll.Id; poll.ExRaidGym = true; results.Add(new InlineQueryResultArticle(poll.GetInlineId(), poll.GetTitle(myUrlHelper) + " (EX Raid Gym)", poll.GetMessageText(myUrlHelper, disableWebPreview: poll.DisableWebPreview())) { Description = poll.AllowedVotes?.Format(new StringBuilder("Create a poll ")).ToString(), HideUrl = true, ThumbUrl = poll.GetThumbUrl(myUrlHelper).ToString(), ReplyMarkup = poll.GetReplyMarkup() }); } } } else { for (var i = 0; i < portals.Length && i < MAX_PORTALS_PER_RESPONSE; i++) { var portal = portals[i]; var title = portal.Name is string name && !string.IsNullOrWhiteSpace(name) ? name : portal.Guid; if (portal.EncodeGuid() is string portalGuid) { InlineQueryResultArticle Init(InlineQueryResultArticle article, InlineKeyboardButton createButton) { const int thumbnailSize = 64; article.Description = portal.Address; article.ReplyMarkup = new InlineKeyboardMarkup(createButton); article.ThumbUrl = portal.GetImage(myUrlHelper, thumbnailSize)?.AbsoluteUri; article.ThumbHeight = thumbnailSize; article.ThumbWidth = thumbnailSize; return(article); } var portalContent = new StringBuilder() .Bold((builder, mode) => builder.Sanitize(portal.Name)).NewLine() .Sanitize(portal.Address) .Link("\u200B", portal.Image) .ToTextMessageContent(); results.Add(Init( new InlineQueryResultArticle($"portal:{portal.Guid}", title, portalContent), InlineKeyboardButton.WithSwitchInlineQuery("Create a poll", $"{PREFIX}{portalGuid} {poll?.Title}"))); if (i == 0) { var exRaidPortalContent = new StringBuilder() .Sanitize("☆ ") .Bold((builder, mode) => builder.Sanitize(portal.Name)) .Sanitize(" (EX Raid Gym)").NewLine() .Sanitize(portal.Address) .Link("\u200B", portal.Image) .ToTextMessageContent(); results.Add(Init( new InlineQueryResultArticle($"portal:{portal.Guid}+", $"☆ {title} (EX Raid Gym)", exRaidPortalContent), InlineKeyboardButton.WithSwitchInlineQuery("Create a poll ☆ (EX Raid Gym)", $"{PREFIX}{portalGuid}+ {poll?.Title}"))); } } } } if (searchQuery.Count == 0) { results.Add( new InlineQueryResultArticle("EnterGymName", "Enter a Gym's Title", new InputTextMessageContent("Enter a Gym's Title to search")) { Description = "to search", ThumbUrl = default(Portal).GetImage(myUrlHelper)?.AbsoluteUri }); } if (results.Count == 0) { var search = string.Join(" ", searchQuery); results.Add(new InlineQueryResultArticle("NothingFound", "Nothing found", new StringBuilder($"Nothing found by request ").Code((builder, mode) => builder.Sanitize(search, mode)).ToTextMessageContent()) { Description = $"Request {search}", ThumbUrl = myUrlHelper.AssetsContent(@"static_assets/png/btn_close_normal.png").AbsoluteUri }); } await myBot.AnswerInlineQueryWithValidationAsync(data.Id, results, cacheTime : 0, isPersonal : true, cancellationToken : cancellationToken); await myDb.SaveChangesAsync(cancellationToken); return(true); }
public static KeyboardRow <InlineKeyboardButton> AddSwitchInlineQueryButton( this KeyboardRow <InlineKeyboardButton> rowBuilder, string text, string query = "") => rowBuilder.AddButton(InlineKeyboardButton.WithSwitchInlineQuery(text, query));
private static void PollAnswerCallback(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e) { if (bShouldIgnore) { bShouldIgnore = false; return; } var query = e.CallbackQuery; var data = query.Data.Split(new[] { '|' }); if (!string.IsNullOrEmpty(query.InlineMessageId)) { pollManager.SetUser(query.From.Id, UserToString(query.From)); if (data.Length == 2 && long.TryParse(data[0], out var pId)) { if (pollManager.GetPoll(pId) is PollData.Poll poll) { poll.AddQuery(query.InlineMessageId); pollManager.Update(poll); if (data[1] == "custom") { bot.AnswerCallbackQueryAsync(query.Id, url: $"t.me/{BotUsername}?start={pId}"); } else if (int.TryParse(data[1], out var oId)) { poll.AddVote(query.From.Id, oId); pollManager.Update(poll); bot.EditMessageTextAsync(query.InlineMessageId, BuildPoolMessage(pId, poll.Name), replyMarkup: new InlineKeyboardMarkup(GetPollButtons(poll))); bot.AnswerCallbackQueryAsync(query.Id); } } } } else { var msg = query.Message; if (query.Data == "pollList") { var buttons = pollManager.GetPollsByUser(query.From.Id) .Select(p => InlineKeyboardButton.WithCallbackData(p.Name, p.Id.ToString())) .Partition(BOT_MaxButtonLen) .ToArray(); bot.EditMessageTextAsync(msg.Chat.Id, msg.MessageId, BOT_PollList, replyMarkup: new InlineKeyboardMarkup(buttons)); } else { if (data.Length > 1) { if (long.TryParse(data[1], out var result)) { if (data[0] == "pollDelete") { pollManager.DeletePoll(result, query.From.Id); bot.DeleteMessageAsync(msg.Chat.Id, msg.MessageId); } else if (data[0] == "pollCustom" && pollManager.GetPoll(result) is PollData.Poll poll) { poll.CanAddOptions = !poll.CanAddOptions; pollManager.Update(poll); } } } else { if (long.TryParse(data[1], out var result)) { var test = new[] { new [] { InlineKeyboardButton.WithCallbackData("Toggle Custom Options", "pollCustom|" + data[0]) }, new [] { InlineKeyboardButton.WithSwitchInlineQuery("Share link", pollManager.GetPoll(result)?.Name) }, new [] { InlineKeyboardButton.WithCallbackData("Delete", "pollDelete|" + data[0]), InlineKeyboardButton.WithCallbackData("Go Back", "pollList") } }; bot.EditMessageTextAsync(msg.Chat.Id, msg.MessageId, BOT_Placeholder, replyMarkup: new InlineKeyboardMarkup(test)); } } } bot.AnswerCallbackQueryAsync(query.Id); } }
private static void PollMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { if (bShouldIgnore) { bShouldIgnore = false; return; } var msg = e.Message; if (msg.Chat.Type == ChatType.Private) { if (msg.EntityValues != null && msg.Entities != null) { var entVals = msg.EntityValues.ToList(); foreach (var i in Enumerable.Range(0, msg.Entities.Count())) { var ent = entVals[i]; var entity = msg.Entities[i]; if (msg.Entities[i].Type == MessageEntityType.BotCommand) { switch (ent) { case "/new": case "/start": // check if payload != string.Empty, if true then user tries to add option to the poll with Id == long.Parse(Payload) var payload = msg.Text.Replace(ent, null).Trim(); if (payload == string.Empty) { // Get current pool, if not exists then var poll = pollManager.GetCurrentSetupPoll(msg.From.Id); if (poll == null) { bot.SendTextMessageAsync(msg.Chat.Id, BOT_PollName, replyMarkup: new ForceReplyMarkup()); } else { bot.SendTextMessageAsync(msg.Chat.Id, BOT_FinishLast); } } else { if (long.TryParse(payload, out var pId) && pollManager.GetPoll(pId) is PollData.Poll poll && poll.CanAddOptions) { bot.SendTextMessageAsync(msg.Chat.Id, string.Format(BOT_CustomOption, poll.Id), replyMarkup: new ForceReplyMarkup()); } } break; case "/list": var buttons = pollManager.GetPollsByUser(msg.From.Id).Select(p => new[] { InlineKeyboardButton.WithCallbackData(p.Name, p.Id.ToString()) }); bot.SendTextMessageAsync(msg.Chat.Id, BOT_PollList, replyMarkup: new InlineKeyboardMarkup(buttons.ToArray())); break; case "/hcf": // halt & catch fire if (msg.From.Id == PrivateChatID) { ShouldQuit.Set(); return; } break; default: bot.SendTextMessageAsync(msg.Chat.Id, "Unknown entity: " + ent, replyToMessageId: msg.MessageId); break; } } } } var reply = msg.ReplyToMessage; if (reply != null) { if (pollManager.GetCurrentSetupPoll(msg.From.Id) is PollData.Poll poll) { if (reply.Text == BOT_GetOption2 && msg.Text == "Finish") { var name = poll.Name; poll.IsSetUp = true; // send share links var share = new[] { new[] { InlineKeyboardButton.WithCallbackData("Toggle custom options", $"pollCustom|{poll.Id}") }, new[] { InlineKeyboardButton.WithSwitchInlineQuery("Share poll", name) } }; bot.SendTextMessageAsync(msg.Chat.Id, BOT_ShareLink, replyMarkup: new InlineKeyboardMarkup(share)); } else { poll.AddOption(msg.From.Id, msg.Text); bot.SendTextMessageAsync(msg.Chat.Id, BOT_GetOption2.Replace("Finish", "`Finish`"), ParseMode.Markdown, replyMarkup: new ForceReplyMarkup()); } pollManager.Update(poll); } else if (reply.Text == BOT_PollName) { pollManager.AddPoll(msg.From.Id, msg.Text); bot.SendTextMessageAsync(msg.Chat.Id, BOT_GetOption, replyMarkup: new ForceReplyMarkup()); } else if (reply.Text.Split(new[] { '\'' }, StringSplitOptions.RemoveEmptyEntries) is string[] parts && parts.Length > 1) { if (long.TryParse(parts[1], out var pId) && pollManager.GetPoll(pId) is PollData.Poll custom) { if (custom.AddOption(msg.From.Id, msg.Text)) { custom.AddVote(msg.From.Id, custom.Options.Count - 1); } pollManager.Update(custom); custom.InlineQueries.ForEach(id => bot.EditMessageTextAsync(id, BuildPoolMessage(pId, custom.Name), replyMarkup: new InlineKeyboardMarkup(GetPollButtons(custom)))); } } } } }
public HurtomBot(string TelegramApiToken) { bot = new TelegramBotClient(TelegramApiToken); bot.SetWebhookAsync(""); bot.OnInlineQuery += async(object updobj, InlineQueryEventArgs iqea) => { if (string.IsNullOrEmpty(iqea.InlineQuery.Query) || string.IsNullOrWhiteSpace(iqea.InlineQuery.Query)) { return; } var toloka = new TolokaHurtom.Toloka(iqea.InlineQuery.Query).ToArray(); if (toloka.Length > 0) { var inline = new InlineQueryResultArticle[toloka.Length]; for (int i = 0; i < toloka.Length; i++) { var content = new InputTextMessageContent($"<b>{toloka[i].title}</b>\n\n{toloka[i].size} | Роздають: {toloka[i].seeders} | Завантажують: {toloka[i].leechers}\n\n<i>{toloka[i].forum_parent} / {toloka[i].forum_name}</i>\n\n{toloka[i].link}"); content.ParseMode = ParseMode.Html; inline[i] = new InlineQueryResultArticle( i.ToString(), toloka[i].title, content); inline[i].Description = toloka[i].size + " | Роздають: " + toloka[i].seeders + " | Завантажують: " + toloka[i].leechers; inline[i].ThumbUrl = toloka[i].link; } await bot.AnswerInlineQueryAsync(iqea.InlineQuery.Id, inline); } }; bot.OnMessage += async(object updobj, MessageEventArgs mea) => { var message = mea.Message; if (mea.Message.Type == MessageType.Text) { if (message.Text == null) { return; } var ChatId = message.Chat.Id; string command = message.Text.ToLower().Replace("@hurtombot", "").Replace("/", ""); switch (command) { case "start": await bot.SendTextMessageAsync(ChatId, "Вітаю! Я @HurtomBot!\nНапишіть, що ви хочете знайти на Гуртом, і я знайду для вас українські торренти.\nНатисніть '/', щоби обрати команду."); break; case "sendtorrent": await bot.SendTextMessageAsync(ChatId, "Оберіть чат, до якого хочете надіслати торрент.", replyMarkup : new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQuery("Надіслати") })); break; default: foreach (var torrent in new TolokaHurtom.Toloka(command).ToArray()) { bot.SendTextMessageAsync(ChatId, $"<b>{torrent.title}</b>\n\n{torrent.size} | Роздають: {torrent.seeders} | Завантажують: {torrent.leechers}\n\n<i>{torrent.forum_parent} / {torrent.forum_name}</i>\n\n{torrent.link}", ParseMode.Html); } break; } } }; }
async void textMessage(TelegramBotClient Bot, MessageEventArgs mea) { var message = mea.Message; if (message.Text == null) { return; } var ChatId = message.Chat.Id; string command = message.Text.ToLower().Replace("@stalkerukrbot", "").Replace("/", ""); switch (command) { case "start": await Bot.SendTextMessageAsync(ChatId, "Вітаю! Я @StalkerUkrBot!\nНатисніть '/', щоби обрати команду.\n"); // Також ви можете зіграти у гру: cheekibreekisnake.apphb.com"); break; case "stalker": await Bot.SendTextMessageAsync(ChatId, "Чого сталкерського бажаєте?", replyMarkup : new ReplyKeyboardMarkup(new[] { new KeyboardButton("Анекдот"), new KeyboardButton("Гітарна композиція"), new KeyboardButton("Роздуми") }, true)); break; case "анекдот": stalker_joke(Bot, ChatId); break; case "гітарна композиція": stalker_guitar(Bot, ChatId); break; case "роздуми": stalker_phrase(Bot, ChatId); break; case "quest": await Bot.SendPhotoAsync(ChatId, new Telegram.Bot.Types.InputFiles.InputFileStream(File.OpenRead(Path.Combine(path, "res", "stalker.jpg"))).Content, replyMarkup : new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithCallbackData("Нова гра", "shocnew") })); break; case "sendvoice": await Bot.SendTextMessageAsync(ChatId, "Оберіть чат до якого хочете надіслати фразу.", replyMarkup : new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQuery("Надіслати") })); break; case "cheekibreeki": //await Bot.SendTextMessageAsync(ChatId, "Гра тут: cheekibreekisnake.apphb.com"); break; } }
public GoogleSpeechUkrBot(string TelegramApiToken, string ConnectionString) { var userSettings = new UserSettings(ConnectionString); bot = new TelegramBotClient(TelegramApiToken); bot.SetWebhookAsync(""); bot.OnInlineQuery += async(object updobj, InlineQueryEventArgs iqea) => { try { if (string.IsNullOrEmpty(iqea.InlineQuery.Query) || string.IsNullOrWhiteSpace(iqea.InlineQuery.Query)) { return; } var url = new GoogleTTS.gTTS(iqea.InlineQuery.Query, URLonly: true).URL; if (!string.IsNullOrEmpty(url)) { var inline = new InlineQueryResultVoice[] { new InlineQueryResultVoice("0", url, iqea.InlineQuery.Query) }; await bot.AnswerInlineQueryAsync(iqea.InlineQuery.Id, inline); } } catch (Exception ex) { return; } }; bot.OnMessage += async(object updobj, MessageEventArgs mea) => { var message = mea.Message; if (message.Type == MessageType.Voice && userSettings.GetVoice(message.Chat.Id)) { try { var gSTT = new GoogleSTT.gSTT($"https://api.telegram.org/file/bot{TelegramApiToken}/{bot.GetFileAsync(message.Voice.FileId).Result.FilePath}"); await bot.SendTextMessageAsync(message.Chat.Id, gSTT.Result, replyToMessageId : message.MessageId); } catch (Exception ex) { await bot.SendTextMessageAsync(message.Chat.Id, $"Не вдалося розпізнати повідомлення. Помилка: {ex.Message}", replyToMessageId : message.MessageId); } } else if (mea.Message.Type == MessageType.Text) { if (message.Text == null) { return; } var ChatId = message.Chat.Id; var command = message.Text.ToLower().Replace("@googlespeechukrbot", "").Replace("/", ""); switch (command) { case "start": await bot.SendTextMessageAsync(ChatId, "Вітаю! Я @GoogleSpeechUkrBot!\nНадішліть мені текстове повідомлення, щоб синтезувати голосове повідомлення, або надішліть голосове повідомлення, щоб розпізнати мовлення.\nНатисніть '/', щоби обрати команду."); break; case "sendvoice": await bot.SendTextMessageAsync(ChatId, "Оберіть чат, до якого хочете надіслати голосове повідомлення.", replyMarkup : new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithSwitchInlineQuery("Надіслати") })); break; case "voiceon": userSettings.ManageVoice(ChatId, true); await bot.SendTextMessageAsync(message.Chat.Id, "Увімкнено розпізнавання мовлення у цьому чаті.", replyToMessageId : message.MessageId); break; case "voiceoff": userSettings.ManageVoice(ChatId, false); await bot.SendTextMessageAsync(message.Chat.Id, "Вимкнено розпізнавання мовлення у цьому чаті.", replyToMessageId : message.MessageId); break; case "texton": userSettings.ManageText(ChatId, true); await bot.SendTextMessageAsync(message.Chat.Id, "Увімкнено синтез мовлення у цьому чаті.", replyToMessageId : message.MessageId); break; case "textoff": userSettings.ManageText(ChatId, false); await bot.SendTextMessageAsync(message.Chat.Id, "Вимкнено синтез мовлення у цьому чаті.", replyToMessageId : message.MessageId); break; default: if (userSettings.GetText(message.Chat.Id)) { try { await bot.SendVoiceAsync(ChatId, new InputFileStream(new MemoryStream(new GoogleTTS.gTTS(command).ToByteArray())).Content, replyToMessageId : message.MessageId); } catch { await bot.SendTextMessageAsync(message.Chat.Id, "Під час синтезу мовлення виникла помилка.", replyToMessageId : message.MessageId); } } break; } } }; }
public async Task <bool?> Handle(InlineQuery data, object context = default, CancellationToken cancellationToken = default) { var location = await myDb.Set <UserSettings>().GetLocation(data, cancellationToken); var queryParts = data.Query.Split(' ', StringSplitOptions.RemoveEmptyEntries); var poll = default(Poll); List <VoteLimit> limits = default; var pollQuery = new List <string>(queryParts.Length); var searchQuery = new List <string>(queryParts.Length); var query = pollQuery; foreach (var queryPart in queryParts) { switch (queryPart) { case { } locationPart when OpenLocationCode.IsValid(locationPart): location = OpenLocationCode.Decode(locationPart) is var code ? new Location { Longitude = (float)code.CenterLongitude, Latitude = (float)code.CenterLatitude } : location; break; case { } part when Regex.Match(part, PATTERN) is { Success: true } match: if (int.TryParse(match.Groups["pollId"].ValueSpan, out var pollId)) { poll = myRaidService .GetTemporaryPoll(pollId) .InitImplicitVotes(data.From, myBot.BotId); } query = searchQuery; break; case { } part when myGeneralInlineQueryHandler.ProcessLimitQueryString(ref limits, part): break; default: query.Add(queryPart); break; } } Portal[] portals; if (searchQuery.Count == 0) { portals = await myIngressClient.GetPortals(0.200, location, cancellationToken); } else { portals = await myIngressClient.Search(searchQuery, location, near : true, cancellationToken); } var results = new List <InlineQueryResult>(Math.Min(portals.Length, MAX_PORTALS_PER_RESPONSE) + 2); if (poll == null && pollQuery.Count != 0) { var voteFormat = await myDb.Set <Settings>().GetFormat(data.From.Id, cancellationToken); poll = await new Poll(data) { Title = string.Join(" ", pollQuery), AllowedVotes = voteFormat, ExRaidGym = false, Limits = limits }.DetectRaidTime(myTimeZoneService, () => Task.FromResult(location), async ct => myClock.GetCurrentInstant().InZone(await myGeoCoder.GetTimeZone(data, ct)), cancellationToken); for (var i = 0; i < portals.Length && i < MAX_PORTALS_PER_RESPONSE; i++) { var portalPoll = new Poll(poll) { Portal = portals[i], Limits = poll.Limits ?? limits }.InitImplicitVotes(data.From, myBot.BotId); await myRaidService.GetPollId(portalPoll, data.From, cancellationToken); results.Add(myGeneralInlineQueryHandler.GetInlineResult(portalPoll)); if (i == 0) { portalPoll.Id = -portalPoll.Id; portalPoll.ExRaidGym = true; results.Add(myGeneralInlineQueryHandler.GetInlineResult(portalPoll)); } } } else { for (var i = 0; i < portals.Length && i < MAX_PORTALS_PER_RESPONSE; i++) { var portal = portals[i]; var title = portal.Name is { } name&& !string.IsNullOrWhiteSpace(name) ? name : portal.Guid; if (portal.EncodeGuid() is { } portalGuid) { InlineQueryResultArticle Init(InlineQueryResultArticle article, InlineKeyboardButton createButton) { const int thumbnailSize = 64; article.Description = portal.Address; article.ReplyMarkup = new InlineKeyboardMarkup(createButton); article.ThumbUrl = portal.GetImage(myUrlHelper, thumbnailSize)?.AbsoluteUri; article.ThumbHeight = thumbnailSize; article.ThumbWidth = thumbnailSize; return(article); } var portalContent = new TextBuilder() .Bold(builder => builder.Sanitize(portal.Name)).NewLine() .Sanitize(portal.Address) .Link("\u200B", portal.Image) .ToTextMessageContent(); results.Add(Init( new InlineQueryResultArticle($"portal:{portal.Guid}", title, portalContent), InlineKeyboardButton.WithSwitchInlineQuery("Create a poll", $"{PREFIX}{portalGuid} {poll?.Title}"))); if (i == 0) { var exRaidPortalContent = new TextBuilder() .Sanitize("☆ ") .Bold(builder => builder.Sanitize(portal.Name)) .Sanitize(" (EX Raid Gym)").NewLine() .Sanitize(portal.Address) .Link("\u200B", portal.Image) .ToTextMessageContent(); results.Add(Init( new InlineQueryResultArticle($"portal:{portal.Guid}+", $"☆ {title} (EX Raid Gym)", exRaidPortalContent), InlineKeyboardButton.WithSwitchInlineQuery("Create a poll ☆ (EX Raid Gym)", $"{PREFIX}{portalGuid}+ {poll?.Title}"))); } } } } if (searchQuery.Count == 0) { results.Add( new InlineQueryResultArticle("EnterGymName", "Enter a Gym's Title", new InputTextMessageContent("Enter a Gym's Title to search")) { Description = "to search", ThumbUrl = default(Portal).GetImage(myUrlHelper)?.AbsoluteUri }); } if (results.Count == 0) { var search = string.Join(" ", searchQuery); results.Add(new InlineQueryResultArticle("NothingFound", "Nothing found", new TextBuilder($"Nothing found by request ").Code(builder => builder.Sanitize(search)).ToTextMessageContent()) { Description = $"Request {search}", ThumbUrl = myUrlHelper.AssetsContent(@"static_assets/png/btn_close_normal.png").AbsoluteUri }); } await myBot.AnswerInlineQueryWithValidationAsync(data.Id, results, cacheTime : 0, isPersonal : true, cancellationToken : cancellationToken); await myDb.SaveChangesAsync(cancellationToken); return(true); }