Skip to content
Back to top
View this page

# `inlinebot.py`

     1#!/usr/bin/env python
     2# pylint: disable=unused-argument
     3# This program is dedicated to the public domain under the CC0 license.
     4
     5"""
     6Don't forget to enable inline mode with @BotFather
     7
     8First, a few handler functions are defined. Then, those functions are passed to
     9the Application and registered at their respective places.
    10Then, the bot is started and runs until we press Ctrl-C on the command line.
    11
    12Usage:
    13Basic inline bot example. Applies different text transformations.
    14Press Ctrl-C on the command line or send a signal to the process to stop the
    15bot.
    16"""
    17
    18import logging
    19from html import escape
    20from uuid import uuid4
    21
    22from telegram import InlineQueryResultArticle, InputTextMessageContent, Update
    23from telegram.constants import ParseMode
    24from telegram.ext import Application, CommandHandler, ContextTypes, InlineQueryHandler
    25
    26# Enable logging
    27logging.basicConfig(
    28    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
    29)
    30# set higher logging level for httpx to avoid all GET and POST requests being logged
    31logging.getLogger("httpx").setLevel(logging.WARNING)
    32
    33logger = logging.getLogger(__name__)
    34
    35
    36# Define a few command handlers. These usually take the two arguments update and
    37# context.
    38async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    39    """Send a message when the command /start is issued."""
    40    await update.message.reply_text("Hi!")
    41
    42
    43async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    44    """Send a message when the command /help is issued."""
    45    await update.message.reply_text("Help!")
    46
    47
    48async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    49    """Handle the inline query. This is run when you type: @botusername <query>"""
    50    query = update.inline_query.query
    51
    52    if not query:  # empty query should not be handled
    53        return
    54
    55    results = [
    56        InlineQueryResultArticle(
    57            id=str(uuid4()),
    58            title="Caps",
    59            input_message_content=InputTextMessageContent(query.upper()),
    60        ),
    61        InlineQueryResultArticle(
    62            id=str(uuid4()),
    63            title="Bold",
    64            input_message_content=InputTextMessageContent(
    65                f"<b>{escape(query)}</b>", parse_mode=ParseMode.HTML
    66            ),
    67        ),
    68        InlineQueryResultArticle(
    69            id=str(uuid4()),
    70            title="Italic",
    71            input_message_content=InputTextMessageContent(
    72                f"<i>{escape(query)}</i>", parse_mode=ParseMode.HTML
    73            ),
    74        ),
    75    ]
    76
    77    await update.inline_query.answer(results)
    78
    79
    80def main() -> None:
    81    """Run the bot."""
    82    # Create the Application and pass it your bot's token.
    83    application = Application.builder().token("TOKEN").build()
    84
    85    # on different commands - answer in Telegram
    86    application.add_handler(CommandHandler("start", start))
    87    application.add_handler(CommandHandler("help", help_command))
    88
    89    # on inline queries - show corresponding inline results
    90    application.add_handler(InlineQueryHandler(inline_query))
    91
    92    # Run the bot until the user presses Ctrl-C
    93    application.run_polling(allowed_updates=Update.ALL_TYPES)
    94
    95
    96if __name__ == "__main__":
    97    main()