Exemplo n.º 1
0
        private async Task ServeInlineQuery(Update update)
        {
            var inlineQuery    = update.InlineQuery;
            var audioRequested = inlineQuery.Query;

            if (!int.TryParse(inlineQuery.Offset, out var offset))
            {
                offset = 0;
            }

            var queryResults = await _memeDbContext.Audios
                               .OrderBy(audio => audio.Name)
                               .Where(audio => audio.Name.Contains(audioRequested))
                               .Skip(offset)
                               .Take(MaxResults)
                               .Select(audio =>
                                       new InlineQueryResultVoice(audio.AudioId.ToString(), audio.Url,
                                                                  audio.Name))
                               .ToListAsync();

            var nextOffset = (offset + MaxResults).ToString();

            //todo: remove cacheTime, set to default
            await TelegramBotClient.AnswerInlineQueryAsync(inlineQuery.Id, queryResults, cacheTime : 0,
                                                           nextOffset : nextOffset);
        }
Exemplo n.º 2
0
        private static async void Bot_OnInlineQuery(object sender, Telegram.Bot.Args.InlineQueryEventArgs e)
        {
            string query = e.InlineQuery.Query;

            if (query.Length < 3)
            {
                return;
            }

            Database.discsArray[]   discs   = db.Search(query.ToLower());
            InlineQueryResultBase[] results = new InlineQueryResultArticle[discs.Length];
            for (int i = 0; i < results.Length; i++)
            {
                var temp = new InlineQueryResultArticle(Convert.ToString(discs[i].id),
                                                        title: discs[i].name,
                                                        new InputTextMessageContent($"Товар {discs[i].id}: {discs[i].name}"));
                temp.Description = discs[i].platform + " | " + discs[i].price + " BYN";
                results[i]       = temp;
            }
            if (results.Length == 0)
            {
                return;
            }
            Console.WriteLine(query);
            db.SetAwaitInfoType(e.InlineQuery.From.Id, (int)awaitInfoType.searchResult);
            try
            {
                await bot.AnswerInlineQueryAsync(e.InlineQuery.Id, results);
            }
            catch (Telegram.Bot.Exceptions.InvalidParameterException e5)
            {
                log.Error(e5.Message);
                return;
            }
        }
Exemplo n.º 3
0
        private async void BotOnInlineQueryReceived(object sender, InlineQueryEventArgs inlineQueryEventArgs)
        {
            Console.WriteLine($"Received inline query from: {inlineQueryEventArgs.InlineQuery.From.Id}");

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultLocation(
                    id: "1",
                    latitude: 40.7058316f,
                    longitude: -74.2581888f,
                    title: "New York")   // displayed result
                {
                    InputMessageContent = new InputLocationMessageContent(
                        latitude: 40.7058316f,
                        longitude: -74.2581888f)        // message if result is selected
                },

                new InlineQueryResultLocation(
                    id: "2",
                    latitude: 13.1449577f,
                    longitude: 52.507629f,
                    title: "Berlin") // displayed result
                {
                    InputMessageContent = new InputLocationMessageContent(
                        latitude: 13.1449577f,
                        longitude: 52.507629f)       // message if result is selected
                }
            };

            await _bot.AnswerInlineQueryAsync(
                inlineQueryEventArgs.InlineQuery.Id,
                results,
                isPersonal : true,
                cacheTime : 0);
        }
        private async Task InnerHandler(InlineQuery query, CancellationToken ct)
        {
            var stickers = await mediator.Send(new FindMatchingStickersQuery(query.Query), ct);

            var results = stickers.Select((s, i) => new InlineQueryResultCachedSticker(i.ToString(), s.FileId));

            await botClient.AnswerInlineQueryAsync(query.Id, results, cancellationToken : ct);
        }
Exemplo n.º 5
0
        private async void OnInlineQueryReceived(object sender, InlineQueryEventArgs inlineQueryEventArgs)
        {
            _logger.LogInformation($"Received inline query from: {inlineQueryEventArgs.InlineQuery.From.Id}");

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultArticle("3", "Tg_clients", new InputTextMessageContent("hello"))
            };
            await _client.AnswerInlineQueryAsync(inlineQueryEventArgs.InlineQuery.Id, results, isPersonal : true, cacheTime : 0);
        }
Exemplo n.º 6
0
        static async void Bot_OnInlineQuery(object sender, InlineQueryEventArgs e)
        {
            Console.WriteLine($"Received inline query from: {e.InlineQuery.From.Id}: {e.InlineQuery.Query}");
            var results = await SearchByQuery(e.InlineQuery.Query);

            await botClient.AnswerInlineQueryAsync(
                inlineQueryId : e.InlineQuery.Id,
                results : results,
                isPersonal : true,
                cacheTime : 0
                );
        }
Exemplo n.º 7
0
        private async void TelegramBotClientOnOnInlineQuery(object sender, InlineQueryEventArgs e)
        {
            string url = "https://images.ctfassets.net/9n3x4rtjlya6/2JnpX9q4fypdaeNjdhhbzz/dc2d2542b6fd121ed7a1e71d557802b6/prosin.jpg";
            var    l   = new List <InlineQueryResultPhoto>();

            l.Add(new InlineQueryResultPhoto("1", url + "?w=200", url + "?w=150")
            {
                Caption     = "Рома Просин",
                Description = "Спикер из Райфа",
                Title       = "Code Review",
            });

            await _telegramBotClient.AnswerInlineQueryAsync(e.InlineQuery.Id, l, isPersonal : true, cacheTime : 0);
        }
Exemplo n.º 8
0
        private static async void OnInlineQueryAsync(object sender, InlineQueryEventArgs e)
        {
            try
            {
                var inlineQuery = e.InlineQuery;

                if (string.IsNullOrEmpty(inlineQuery.Query))
                {
                    return;
                }

                using var responseMessage = await HttpClient.PostAsync("https://www.shitexpress.com/status.php", new FormUrlEncodedContent (new Dictionary <string, string>()
                {
                    { "id", inlineQuery.Query }
                }));

                var contentString = await responseMessage.Content.ReadAsStringAsync();

                var text = new StringBuilder();

                if (contentString == string.Empty)
                {
                    text.AppendLine("Order not found - wrong ID. Try again, please.");
                }
                else
                {
                    string[] split = contentString.Split('|');

                    string status = int.Parse(split[1]) switch
                    {
                        0 => "Order received. Your package will be processed in 48 hours.",
                        1 => "Processing the order. Your package will be shipped in 48 hours.",
                        2 => "Your package has been shipped."
                    };

                    text.AppendLine("*Status:* " + status)
                    .AppendLine("*Last update:* " + split[2]);
                }

                await _bot.AnswerInlineQueryAsync(inlineQuery.Id, new[]
                {
                    new InlineQueryResultArticle(inlineQuery.Query, inlineQuery.Query, new InputTextMessageContent(text.ToString())
                    {
                        ParseMode = ParseMode.Markdown
                    })
                });
            }
            catch { }
        }
Exemplo n.º 9
0
        public async Task AnswerInlineQuery(string inlineQueryId, IEnumerable <InlineQueryResultBase> results, string switchPmText = null, string switchPmParameter = null)
        {
            try
            {
                await _telegramBotClient.AnswerInlineQueryAsync(inlineQueryId, results, cacheTime : 10, switchPmText : switchPmText, switchPmParameter : switchPmParameter);
            }
            catch (InvalidParameterException exception)
            {
                // This may crash when the inline query is too old, just ignore it.
                if (exception?.Message == "query is too old and response timeout expired or query ID is invalid")
                {
                    return;
                }

                throw;
            }
        }
Exemplo n.º 10
0
        private static async void BotOnOnInlineQuery(object sender, InlineQueryEventArgs inlineQueryEventArgs)
        {
            Console.WriteLine($"{DateTime.Now} | {inlineQueryEventArgs.InlineQuery.From.Username}: {inlineQueryEventArgs.InlineQuery.Query}");
            var queryString = inlineQueryEventArgs.InlineQuery.Query;
            var result      = await _webSearchAggregator.Search(queryString);

            if (result == null)
            {
                return;
            }
            try
            {
                await _bot.AnswerInlineQueryAsync(inlineQueryEventArgs.InlineQuery.Id, result.ToArray(), isPersonal : true, cacheTime : 300);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now}: {ex}");
            }
        }
Exemplo n.º 11
0
        private async Task BotOnInlineQueryReceived(InlineQuery inlineQuery)
        {
            _logger.Info($"Received inline query from: {inlineQuery.From.Id}");
            InlineQueryResultBase[] results =
            {
                // displayed result
                new InlineQueryResultArticle(
                    id: "3",
                    title: "TgBots",
                    inputMessageContent: new InputTextMessageContent(
                        "hello"
                        )
                    )
            };

            await _botClient.AnswerInlineQueryAsync(
                inlineQuery.Id,
                results,
                isPersonal : true,
                cacheTime : 0, cancellationToken : Token);
        }
        protected override async Task Handle(InlineUsersSearchCommand request, CancellationToken cancellationToken)
        {
            var searchUserText = request.SearchUserText.ToLower();
            var channels       = await twitchApiService.SearchChannels(searchUserText);

            var results = new List <InlineQueryResultArticle>();

            foreach (var user in channels.Channels)
            {
                var article = new InlineQueryResultArticle(
                    id: user.Id,
                    title: user.DisplayName,
                    inputMessageContent: new InputTextMessageContent(user.DisplayName))
                {
                    ReplyMarkup = new InlineKeyboardMarkup(new[]
                    {
                        new[] {
                            InlineKeyboardButton.WithCallbackData(
                                "Show messages",
                                $"{BotCommands.UserMessages} {user.BroadcasterLogin}")
                        },
                        new[] {
                            InlineKeyboardButton.WithCallbackData(
                                "Show subs count",
                                $"{BotCommands.SubscribersCount} {user.BroadcasterLogin}")
                        }
                    }),
                    ThumbUrl    = user.ThumbnailUrl,
                    Description = $"IsLive: {user.IsLive}"
                };
                results.Add(article);
            }

            await telegramBotClient.AnswerInlineQueryAsync(
                request.InlineQueryId,
                results,
                cacheTime : 0,
                cancellationToken : cancellationToken);
        }
        public async Task HandleAsync(InlineQuery inlineQuery)
        {
            if (!string.IsNullOrEmpty(inlineQuery.Query))
            {
                var animes = await _api.Anime.SearchAsync(new SearchParams
                {
                    Search = inlineQuery.Query,
                    Limit  = 10
                });

                var response = animes.Select(InlineQueryResultArticleHelpers.GetInlineQueryResultArticleForAnime);

                try
                {
                    await _bot.AnswerInlineQueryAsync(inlineQuery.Id, response);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Error during AnswerInlineQueryAsync");
                }
            }
        }
Exemplo n.º 14
0
        private async Task <Func <Task> > GetInlineQueryAnswer(InlineQuery inlineQuery)
        {
            var query         = inlineQuery.Query;
            var inlineQueryId = inlineQuery.Id;

            var result = await _chordsService.FindChords(query);

            var inlineQueryResults = result.Results.Take(MaxResultsForInlineSearch)
                                     .Select((x, index) => new InlineQueryResultContact
            {
                Id                  = index.ToString(),
                Title               = x.SongName,
                PhoneNumber         = x.SongAuthor,
                FirstName           = x.SongName,
                ThumbUrl            = x.Thumbnail.ToString(),
                InputMessageContent = new InputTextMessageContent
                {
                    MessageText = $"/{SelectCommandName} '{query}' {index}"
                }
            });

            return(() => _botClient.AnswerInlineQueryAsync(
                       inlineQueryId, inlineQueryResults.ToArray <InlineQueryResult>()));
        }
Exemplo n.º 15
0
        private static void BotClient_OnInlineQuery(object sender, InlineQueryEventArgs e)
        {
            var results = new List <InlineQueryResultBase>();

            try
            {
                var q = QueryParser.Parse(e.InlineQuery.Query);
                if (q.Type == QueryType.Exception)
                {
                    throw q.Exception;
                }
                else if (q.Type == QueryType.Repository)
                {
                    var repo = github.Repository.Get(q.Owner, q.Repository).GetAwaiter().GetResult();
                    results.Add(InlineFromRepo(repo));
                }
                else if (q.Type == QueryType.SearchOrOwner)
                {
                    try
                    {
                        var owner = github.User.Get(q.Owner).GetAwaiter().GetResult();
                        results.Add(InlineFromUser(owner));
                    }
                    catch (NotFoundException)
                    {
                        var repos = github.Search.SearchRepo(new SearchRepositoriesRequest(q.Owner)).GetAwaiter().GetResult();
                        for (int i = 0; i < repos.Items.Count && i < Limits.HybridSearchLimit; i++)
                        {
                            results.Add(InlineFromRepo(github.Repository.Get(repos.Items[i].Id).GetAwaiter().GetResult()));
                        }

                        var users = github.Search.SearchUsers(new SearchUsersRequest(q.Owner)).GetAwaiter().GetResult();
                        for (int i = 0; i < users.Items.Count && i < Limits.HybridSearchLimit; i++)
                        {
                            results.Add(InlineFromUser(github.User.Get(users.Items[i].Login).GetAwaiter().GetResult()));
                        }
                    }

                    if (results.Count <= 0)
                    {
                        throw new Exception("Nothing found.");
                    }
                }
                else if (q.Type == QueryType.SearchRepo)
                {
                    var repos = github.Search.SearchRepo(new SearchRepositoriesRequest(q.Repository)).GetAwaiter().GetResult();

                    if (repos.Items.Count <= 0)
                    {
                        throw new Exception("No repos found");
                    }

                    for (int i = 0; i < repos.Items.Count && i < Limits.CleanSearchLimit; i++)
                    {
                        results.Add(InlineFromRepo(github.Repository.Get(repos.Items[i].Id).GetAwaiter().GetResult()));
                    }
                }
                else if (q.Type == QueryType.SearchUser)
                {
                    var users = github.Search.SearchUsers(new SearchUsersRequest(q.Owner)).GetAwaiter().GetResult();

                    if (users.Items.Count <= 0)
                    {
                        throw new Exception("No users found");
                    }

                    for (int i = 0; i < users.Items.Count && i < Limits.CleanSearchLimit; i++)
                    {
                        results.Add(InlineFromUser(github.User.Get(users.Items[i].Login).GetAwaiter().GetResult()));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                var result = new InlineQueryResultArticle(
                    "0", "🔴 " + ex.Message, new InputTextMessageContent(ex.ToString()));

                results.Add(result);
            }

            botClient.AnswerInlineQueryAsync(e.InlineQuery.Id, results);
        }
Exemplo n.º 16
0
        public async Task HandleAsync(InlineQuery q)
        {
            if (IsNullOrEmpty(q.Query))
            {
                return;
            }

            var input = q.Query;

            var dataTask             = GetValCursAsync();
            var currenciesEmojisTask = repo.GetCurrencyEmojisAsync();

            var data             = dataTask.Result;
            var currenciesEmojis = currenciesEmojisTask.Result;

            string currency = null;

            foreach (var i in currenciesEmojis)
            {
                if (input.Contains(i.Currency))
                {
                    currency = i.Currency;
                    break;
                }
            }

            var space    = " "; // format: {decimal}{space}{currency} e.g "53.2 UAH" or just {decimal}
            var argsPart = currency == null ? "" : $"{space}{currency}";

            var pattern = $@"[0-9][0-9]*([\.,][0-9][0-9]*)?{argsPart}";

            if (!Regex.IsMatch(input, pattern))
            {
                var text = "format: {decimal}{space}{currency} e.g \"53.2 UAH\" or just {decimal} e.g \"53.2\"";

                await bot.AnswerInlineQueryAsync(
                    q.Id,
                    await InlineAnswerBuilder.ArticleToQueryResultAsync(
                        "Result", text, text)
                    );

                return;
            }

            var valueToParse = IsNullOrEmpty(argsPart) ? input : input.Replace(argsPart, "");
            var isValid      = decimal.TryParse(valueToParse, out var value);

            if (isValid)
            {
                if (currency == null)
                {
                    currency = DefaultValues.DefaultValueCurrency;
                }

                var currencyEmoji = currenciesEmojis.First(ce => ce.Currency == currency);

                var values =
                    await ValuesCalculator.GetCurrenciesValuesAsync(value, currencyEmoji, data, currenciesEmojis);

                var answer1 = await AnswerBuilder.BuildStringFromValuesAsync(values, currencyEmoji);

                await bot.AnswerInlineQueryAsync(
                    q.Id,
                    await InlineAnswerBuilder.ArticleToQueryResultAsync(
                        "Result", answer1, answer1)
                    );
            }
        }