Inline Mode
Telegram bots can be queried directly in the chat or via inline queries.
To use inline queries in your bot, you need to set up inline mode by command:
Import Telegram.Bot.Types.InlineQueryResults
namespace for inline query types.
There are two types that allow you to work with inline queries - InlineQuery
and ChosenInlineResult
:
switch (update.Type)
{
case UpdateType.InlineQuery:
await OnInlineQueryReceived(bot, update.InlineQuery!);
break;
case UpdateType.ChosenInlineResult:
await OnChosenInlineResultReceived(bot, update.ChosenInlineResult!);
break;
};
InlineQuery
Suppose we have two arrays:
private readonly string[] sites = { "Google", "Github", "Telegram", "Wikipedia" };
private readonly string[] siteDescriptions =
{
"Google is a search engine",
"Github is a git repository hosting",
"Telegram is a messenger",
"Wikipedia is an open wiki"
};
So we can handle inline queries this way:
async Task OnInlineQueryReceived(ITelegramBotClient bot, InlineQuery inlineQuery)
{
var results = new List<InlineQueryResult>();
var counter = 0;
foreach (var site in sites)
{
results.Add(new InlineQueryResultArticle(
$"{counter}", // we use the counter as an id for inline query results
site, // inline query result title
new InputTextMessageContent(siteDescriptions[counter])) // content that is submitted when the inline query result title is clicked
);
counter++;
}
await bot.AnswerInlineQuery(inlineQuery.Id, results); // answer by sending the inline query result list
}
InlineQueryResult
is an abstract type used to create a response for inline queries. You can use these result types for inline queries: InlineQueryResultArticle
for articles, InlineQueryResultPhoto
for photos, etc.
ChosenInlineResult
This type helps to handle chosen inline result. For example, you may want to know which result users chose:
Task OnChosenInlineResultReceived(ITelegramBotClient bot, ChosenInlineResult chosenInlineResult)
{
if (uint.TryParse(chosenInlineResult.ResultId, out var resultId) // check if a result id is parsable and introduce variable
&& resultId < sites.Length)
{
Console.WriteLine($"User {chosenInlineResult.From} has selected site: {sites[resultId]}");
}
return Task.CompletedTask;
}
To use the feature you need to enable "inline feedback" in BotFather by /setinlinefeedback
command:
Final result: