3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger

3 horizontal lines, burger
Remove all
LOADING ...

Content



    How to implement an inline bot in telegram. Plus how to add translations and localizations

    Clock
    10.01.2025
    /
    Clock
    02.10.2025
    /
    Clock
    4 minutes
    An eye
    3830
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0

    Introduction

    In this article I will show how the inline telegram bot works, how to send responses, and how to set up these responses. You will also learn how to set up translations for your bot, and of course you will be able to test my bot, @joker_gut_bot
    What is the point of the inline mode of bots? The point is that the user can send bot responses on his behalf to any chats. Some bots are embedded in the telegram itself, for example:
    1. @like
    2. @poll
    3. @gif
    4. @vid
    5. @pic
    6. @bing
    7. @wiki
    8. @imdb
    9. @bold
    And of course you can make your own if needed.

    Preparing and installing the necessary packages

    We will need the following packages:
    1. aiogram library
    2. Babel library
    The first one is needed for communication and work with the Telegram API. The Babel library is required for translations.
    pip install Babel aiogram pandas
    I store the bot token in a separate file called .env, make it. It contains only one line: BOT_TOKEN=1111111111:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    Hopefully by now you have a bot token and a virtual environment for it. Never install python packages without a corresponding virtual environment.
    You can see the complete, basic setup of the telegram bot (and token too) in this article.

    Writing an inline bot

    Let's move on to writing the bot itself. In the main.py file, import the following modules:
    import asyncio import logging import sys import uuid from aiogram import F from aiogram.types import Message, InlineQuery, InlineQueryResultArticle, InputTextMessageContent, InlineQueryResultPhoto from aiogram.filters import Command from config import bot_dispatcher, bot
    After that, at the end, we add an entry point and standard handlers to launch the application and to help with its functionality:
    @bot_dispatcher.message(Command('help')) async def help(message: Message): await message.answer("Этот бот является примером того, как можно реализовать inline функционал для него.") await message.answer("/startapp - запустить приложение") await message.answer("@joker_gut_bot memes - запросить мемы для показа") await message.answer("@joker_gut_bot greeting - запросить ответы по умолчанию") @bot_dispatcher.message(Command("startapp")) async def start_app(message: Message): await message.answer("Этот бот является примером того, как можно реализовать inline функционал для него.") async def main() -> None: await bot_dispatcher.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main())
    Now in the config.py file we add the token importer and the default router, bot_dispatcher:
    from aiogram import Bot, Dispatcher # Read the file and send a token to dispatcher with open(".env", "r") as file: buffer = file.read() line_pos = buffer.find("BOT_TOKEN") TOKEN = buffer[buffer.find("=", line_pos) + 1:] bot = Bot(TOKEN) bot_dispatcher = Dispatcher(bot=bot)
    The bot skeleton is ready. And it can even be launched, but it does not provide any functionality yet. Now let's start adding inline bot functionality to it. Telegram supports 20 inline responses in total:
    1. InlineQueryResultCachedAudio
    2. InlineQueryResultCachedDocument
    3. InlineQueryResultCachedGif
    4. InlineQueryResultCachedMpeg4Gif
    5. InlineQueryResultCachedPhoto
    6. InlineQueryResultCachedSticker
    7. InlineQueryResultCachedVideo
    8. InlineQueryResultCachedVoice
    9. InlineQueryResultAudio
    10. InlineQueryResultDocument
    11. InlineQueryResultGif
    12. InlineQueryResultMpeg4Gif
    13. InlineQueryResultPhoto
    14. InlineQueryResultVideo
    15. InlineQueryResultVoice
    16. InlineQueryResultContact
    17. InlineQueryResultGame
    18. InlineQueryResultLocation
    19. InlineQueryResultArticle
    20. InlineQueryResultVenue
    As you can see, there are three groups of responses. The first with the Cached root, which means the bot will take data from the database. The second group without the Cached root. They use links as a data source. And the third group consists of those responses that have no analogue with Cached.
    I will show the work of inline bots using the example of InlineQueryResultArticle and InlineQueryResulltPhoto. Let's add the following functions to main.py:
    import asyncio import logging import sys import uuid from aiogram import F from aiogram.types import Message, InlineQuery, InlineQueryResultArticle, InputTextMessageContent, InlineQueryResultPhoto from aiogram.filters import Command from config import bot_dispatcher, bot @bot_dispatcher.inline_query(F.query == "greeting") async def send_greetings(inline_query: InlineQuery): results = [] results.append(InlineQueryResultArticle( id=str(uuid.uuid4()), title="Обычное приветствие", input_message_content=InputTextMessageContent( disable_web_page_preview=True, message_text="Приветствую я вас сегодня." ) )) results.append(InlineQueryResultArticle( id=str(uuid.uuid4()), title="Жёсткое приветствие", input_message_content=InputTextMessageContent( disable_web_page_preview=True, message_text="Ну чё, как дела" ) )) results.append(InlineQueryResultArticle( id=str(uuid.uuid4()), title="Спокойное приветствие", input_message_content=InputTextMessageContent( disable_web_page_preview=True, message_text="Привет" ) )) await inline_query.answer(results) @bot_dispatcher.inline_query(F.query == "memes") async def send_user_images(inline_query: InlineQuery): results = [] results.append(InlineQueryResultPhoto( id=str(uuid.uuid4()), photo_url="https://wisconsinskydivingcenter.com/wp-content/uploads/2024/05/you-dont-need-a-parachute-to-go-skydiving-meme.jpeg", thumbnail_url="https://wisconsinskydivingcenter.com/wp-content/uploads/2024/05/you-dont-need-a-parachute-to-go-skydiving-meme.jpeg" )) results.append(InlineQueryResultPhoto( id=str(uuid.uuid4()), photo_url="https://jungleroots.com/wp-content/uploads/2022/11/1_OkVxoXBTygSKB8K-zbB7uQ-300x176.jpeg", thumbnail_url="https://jungleroots.com/wp-content/uploads/2022/11/1_OkVxoXBTygSKB8K-zbB7uQ-300x176.jpeg" )) results.append(InlineQueryResultPhoto( id=str(uuid.uuid4()), photo_url="https://livestorm.imgix.net/1127/1651607695-obi-wan-alarm-work-meme.jpeg?h=auto&w=730&fm=jpeg&auto=format&q=90&dpr=1", thumbnail_url="https://livestorm.imgix.net/1127/1651607695-obi-wan-alarm-work-meme.jpeg?h=auto&w=730&fm=jpeg&auto=format&q=90&dpr=1" )) await inline_query.answer(results) @bot_dispatcher.message(Command('help')) async def help(message: Message): await message.answer("Этот бот является примером того, как можно реализовать inline функционал для него.") await message.answer("/startapp - запустить приложение") await message.answer("@joker_gut_bot memes - запросить мемы для показа") await message.answer("@joker_gut_bot greeting - запросить ответы по умолчанию") @bot_dispatcher.message(Command("startapp")) async def start_app(message: Message): await message.answer("Этот бот является примером того, как можно реализовать inline функционал для него.") async def main() -> None: await bot_dispatcher.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main())
    The send_greetings handler is called when the user writes greeting after the bot name. All it does is combine 3 InlineQueryResultArticles into the list and return the user's answer to choose from. Like this:
    The send_user_images handler does the same thing, only with images, InlineQueryResultArticle.
    The Telegram bot is ready. All that's left is to deploy it on the server, and voila, your new assistant is ready. I wrote about how to do this in a separate article, ooo, here it is. You can read more about it here.

    Translate (optional)

    Also, if you need to make your bot support multiple languages ​​of communication, then you should also read this article, where I show in detail how to do this.

    Conclusions

    I tried to make the article about inline bots as simple as possible and not overloaded with any databases or translations. But I eventually included translations ◑﹏◐. You can find all the bot files and resources on the corresponding tools page. Cheers.


    Do not forget to share, like and leave a comment :)

    Comments

    (0)

    captcha
    Send
    LOADING ...
    It's empty now. Be the first (o゚v゚)ノ

    Other

    Similar articles


    How I created a telegram bot with questions. Or a quiz bot | Tim the Webmaster

    Clock
    16.11.2023
    /
    Clock
    05.10.2025
    An eye
    14898
    Hearts
    4
    Connected dots
    0
    Connected dots
    2
    Connected dots
    0
    Ready-made telegram bot, on aiogram. With ready-made sources and bot scripts in Python. This tg bot is already running and ready, look for TimQuizzer

    Types and features of Telegram bots

    Clock
    22.12.2024
    /
    Clock
    02.10.2025
    An eye
    5904
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    Here you will learn the classification of telegram bots and the capabilities they have

    How to get a telegram bot token and initial setup for telegram bot

    Clock
    14.01.2025
    /
    Clock
    02.10.2025
    An eye
    4241
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article you will see how I get the telegram bot token (via bot father), where I store the token and how I set it up

    Used termins


    Related questions