inlinekeyboard.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"""
 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 InlineKeyboardButton, InlineKeyboardMarkup, Update
12from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes
13
14# Enable logging
15logging.basicConfig(
16    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
17)
18# set higher logging level for httpx to avoid all GET and POST requests being logged
19logging.getLogger("httpx").setLevel(logging.WARNING)
20
21logger = logging.getLogger(__name__)
22
23
24async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
25    """Sends a message with three inline buttons attached."""
26    keyboard = [
27        [
28            InlineKeyboardButton("Option 1", callback_data="1"),
29            InlineKeyboardButton("Option 2", callback_data="2"),
30        ],
31        [InlineKeyboardButton("Option 3", callback_data="3")],
32    ]
33
34    reply_markup = InlineKeyboardMarkup(keyboard)
35
36    await update.message.reply_text("Please choose:", reply_markup=reply_markup)
37
38
39async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
40    """Parses the CallbackQuery and updates the message text."""
41    query = update.callback_query
42
43    # CallbackQueries need to be answered, even if no notification to the user is needed
44    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
45    await query.answer()
46
47    await query.edit_message_text(text=f"Selected option: {query.data}")
48
49
50async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
51    """Displays info on how to use the bot."""
52    await update.message.reply_text("Use /start to test this bot.")
53
54
55def main() -> None:
56    """Run the bot."""
57    # Create the Application and pass it your bot's token.
58    application = Application.builder().token("TOKEN").build()
59
60    application.add_handler(CommandHandler("start", start))
61    application.add_handler(CallbackQueryHandler(button))
62    application.add_handler(CommandHandler("help", help_command))
63
64    # Run the bot until the user presses Ctrl-C
65    application.run_polling(allowed_updates=Update.ALL_TYPES)
66
67
68if __name__ == "__main__":
69    main()