inlinekeyboard.pyΒΆ

 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"""
 6Basic example for a bot that uses inline keyboards. For an in-depth explanation, check out
 7 https://github.com/python-telegram-bot/python-telegram-bot/wiki/InlineKeyboard-Example.
 8"""
 9import logging
10
11from telegram import __version__ as TG_VER
12
13try:
14    from telegram import __version_info__
15except ImportError:
16    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
17
18if __version_info__ < (20, 0, 0, "alpha", 1):
19    raise RuntimeError(
20        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
21        f"{TG_VER} version of this example, "
22        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
23    )
24from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
25from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes
26
27# Enable logging
28logging.basicConfig(
29    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
30)
31# set higher logging level for httpx to avoid all GET and POST requests being logged
32logging.getLogger("httpx").setLevel(logging.WARNING)
33
34logger = logging.getLogger(__name__)
35
36
37async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
38    """Sends a message with three inline buttons attached."""
39    keyboard = [
40        [
41            InlineKeyboardButton("Option 1", callback_data="1"),
42            InlineKeyboardButton("Option 2", callback_data="2"),
43        ],
44        [InlineKeyboardButton("Option 3", callback_data="3")],
45    ]
46
47    reply_markup = InlineKeyboardMarkup(keyboard)
48
49    await update.message.reply_text("Please choose:", reply_markup=reply_markup)
50
51
52async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
53    """Parses the CallbackQuery and updates the message text."""
54    query = update.callback_query
55
56    # CallbackQueries need to be answered, even if no notification to the user is needed
57    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
58    await query.answer()
59
60    await query.edit_message_text(text=f"Selected option: {query.data}")
61
62
63async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
64    """Displays info on how to use the bot."""
65    await update.message.reply_text("Use /start to test this bot.")
66
67
68def main() -> None:
69    """Run the bot."""
70    # Create the Application and pass it your bot's token.
71    application = Application.builder().token("TOKEN").build()
72
73    application.add_handler(CommandHandler("start", start))
74    application.add_handler(CallbackQueryHandler(button))
75    application.add_handler(CommandHandler("help", help_command))
76
77    # Run the bot until the user presses Ctrl-C
78    application.run_polling(allowed_updates=Update.ALL_TYPES)
79
80
81if __name__ == "__main__":
82    main()