Implementing Inline Mode in Telegram Bots
Inline mode is a feature of sending messages "via bots". When a bot supports the inline mode, users can access it from any chat and send messages generated by the bot. The inline mode works even in chats where the bot does not participate.
This allows bot users, for example, to quickly search for videos or music and instantly send them.
A user starts the inline mode by entering bot username and a space. They may add a text query afterwards if needed; the query can contain up to 256 characters. Then, the menu of results appears. The user clicks on a result to send the message.
Here is a simple example with text results:
@dp.inline_query()
async def handle_inline(query: InlineQuery):
input_text = query.query
result1 = InlineQueryResultArticle(
id='1',
title='Option 1',
description='This is the first option',
input_message_content=InputTextMessageContent(
message_text='If chosen, this text will be sent'
)
)
result2 = InlineQueryResultArticle(
id='2',
title='Option 2',
description='This is the second option',
input_message_content=InputTextMessageContent(
message_text='If the second option is chosen, this text will be sent'
)
)
await query.answer(results=[result1, result2], cache_time=1)
A developer can enable inline mode in BotFather, as well as select a placeholder (the default is "Search...")
Group admins may forbid everyone or selected users sending inline messages. In the official Telegram apps, this group member restriction is united with the restriction to send stickers and GIFs.
Result layout
The results may form a vertical list (which looks good in case of text) or a grid (which looks good in case of pictures).
Two layouts may be combined, but apparently this works correctly only in Telegram Desktop (while other official apps show such results in a list.)
Combination screenshot
Inline feedback
Inline feedback is updates arriving when a user chooses an inline result and sends a message. You will not receive them unless you explicitly turn on this setting in BotFather.
Although the purpose of the inline feedback feature is collecting statistics, bot developers sometimes use it to edit messages after they are sent. This comes handy when the bot should load only the selected result rather then all of them. For example, a music search bot may add a song to a sent message and not load all songs during the search.
Here is a trick: a bot may edit a sent inline message only if it contains inline buttons. (Otherwise, the inline feedback update does not include the message ID.)