← 返回首页
inlinekeyboard.py - python-telegram-bot v22.8 Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Back to top

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