1#!/usr/bin/env python
2# pylint: disable=unused-argument, wrong-import-position
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"""
17import logging
18from html import escape
19from uuid import uuid4
20
21from telegram import __version__ as TG_VER
22
23try:
24 from telegram import __version_info__
25except ImportError:
26 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
27
28if __version_info__ < (20, 0, 0, "alpha", 1):
29 raise RuntimeError(
30 f"This example is not compatible with your current PTB version {TG_VER}. To view the "
31 f"{TG_VER} version of this example, "
32 f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
33 )
34from telegram import InlineQueryResultArticle, InputTextMessageContent, Update
35from telegram.constants import ParseMode
36from telegram.ext import Application, CommandHandler, ContextTypes, InlineQueryHandler
37
38# Enable logging
39logging.basicConfig(
40 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
41)
42# set higher logging level for httpx to avoid all GET and POST requests being logged
43logging.getLogger("httpx").setLevel(logging.WARNING)
44
45logger = logging.getLogger(__name__)
46
47
48# Define a few command handlers. These usually take the two arguments update and
49# context.
50async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
51 """Send a message when the command /start is issued."""
52 await update.message.reply_text("Hi!")
53
54
55async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
56 """Send a message when the command /help is issued."""
57 await update.message.reply_text("Help!")
58
59
60async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
61 """Handle the inline query. This is run when you type: @botusername <query>"""
62 query = update.inline_query.query
63
64 if not query: # empty query should not be handled
65 return
66
67 results = [
68 InlineQueryResultArticle(
69 id=str(uuid4()),
70 title="Caps",
71 input_message_content=InputTextMessageContent(query.upper()),
72 ),
73 InlineQueryResultArticle(
74 id=str(uuid4()),
75 title="Bold",
76 input_message_content=InputTextMessageContent(
77 f"<b>{escape(query)}</b>", parse_mode=ParseMode.HTML
78 ),
79 ),
80 InlineQueryResultArticle(
81 id=str(uuid4()),
82 title="Italic",
83 input_message_content=InputTextMessageContent(
84 f"<i>{escape(query)}</i>", parse_mode=ParseMode.HTML
85 ),
86 ),
87 ]
88
89 await update.inline_query.answer(results)
90
91
92def main() -> None:
93 """Run the bot."""
94 # Create the Application and pass it your bot's token.
95 application = Application.builder().token("TOKEN").build()
96
97 # on different commands - answer in Telegram
98 application.add_handler(CommandHandler("start", start))
99 application.add_handler(CommandHandler("help", help_command))
100
101 # on inline queries - show corresponding inline results
102 application.add_handler(InlineQueryHandler(inline_query))
103
104 # Run the bot until the user presses Ctrl-C
105 application.run_polling(allowed_updates=Update.ALL_TYPES)
106
107
108if __name__ == "__main__":
109 main()