arbitrarycallbackdatabot.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"""This example showcases how PTBs "arbitrary callback data" feature can be used.
  6
  7For detailed info on arbitrary callback data, see the wiki page at
  8https://github.com/python-telegram-bot/python-telegram-bot/wiki/Arbitrary-callback_data
  9
 10Note:
 11To use arbitrary callback data, you must install PTB via
 12`pip install python-telegram-bot[callback-data]`
 13"""
 14import logging
 15from typing import List, Tuple, cast
 16
 17from telegram import __version__ as TG_VER
 18
 19try:
 20    from telegram import __version_info__
 21except ImportError:
 22    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
 23
 24if __version_info__ < (20, 0, 0, "alpha", 1):
 25    raise RuntimeError(
 26        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
 27        f"{TG_VER} version of this example, "
 28        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
 29    )
 30from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
 31from telegram.ext import (
 32    Application,
 33    CallbackQueryHandler,
 34    CommandHandler,
 35    ContextTypes,
 36    InvalidCallbackData,
 37    PicklePersistence,
 38)
 39
 40# Enable logging
 41logging.basicConfig(
 42    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 43)
 44logger = logging.getLogger(__name__)
 45
 46
 47async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 48    """Sends a message with 5 inline buttons attached."""
 49    number_list: List[int] = []
 50    await update.message.reply_text("Please choose:", reply_markup=build_keyboard(number_list))
 51
 52
 53async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 54    """Displays info on how to use the bot."""
 55    await update.message.reply_text(
 56        "Use /start to test this bot. Use /clear to clear the stored data so that you can see "
 57        "what happens, if the button data is not available. "
 58    )
 59
 60
 61async def clear(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 62    """Clears the callback data cache"""
 63    context.bot.callback_data_cache.clear_callback_data()
 64    context.bot.callback_data_cache.clear_callback_queries()
 65    await update.effective_message.reply_text("All clear!")
 66
 67
 68def build_keyboard(current_list: List[int]) -> InlineKeyboardMarkup:
 69    """Helper function to build the next inline keyboard."""
 70    return InlineKeyboardMarkup.from_column(
 71        [InlineKeyboardButton(str(i), callback_data=(i, current_list)) for i in range(1, 6)]
 72    )
 73
 74
 75async def list_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 76    """Parses the CallbackQuery and updates the message text."""
 77    query = update.callback_query
 78    await query.answer()
 79    # Get the data from the callback_data.
 80    # If you're using a type checker like MyPy, you'll have to use typing.cast
 81    # to make the checker get the expected type of the callback_data
 82    number, number_list = cast(Tuple[int, List[int]], query.data)
 83    # append the number to the list
 84    number_list.append(number)
 85
 86    await query.edit_message_text(
 87        text=f"So far you've selected {number_list}. Choose the next item:",
 88        reply_markup=build_keyboard(number_list),
 89    )
 90
 91    # we can delete the data stored for the query, because we've replaced the buttons
 92    context.drop_callback_data(query)
 93
 94
 95async def handle_invalid_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 96    """Informs the user that the button is no longer available."""
 97    await update.callback_query.answer()
 98    await update.effective_message.edit_text(
 99        "Sorry, I could not process this button click 😕 Please send /start to get a new keyboard."
100    )
101
102
103def main() -> None:
104    """Run the bot."""
105    # We use persistence to demonstrate how buttons can still work after the bot was restarted
106    persistence = PicklePersistence(filepath="arbitrarycallbackdatabot")
107    # Create the Application and pass it your bot's token.
108    application = (
109        Application.builder()
110        .token("TOKEN")
111        .persistence(persistence)
112        .arbitrary_callback_data(True)
113        .build()
114    )
115
116    application.add_handler(CommandHandler("start", start))
117    application.add_handler(CommandHandler("help", help_command))
118    application.add_handler(CommandHandler("clear", clear))
119    application.add_handler(
120        CallbackQueryHandler(handle_invalid_button, pattern=InvalidCallbackData)
121    )
122    application.add_handler(CallbackQueryHandler(list_button))
123
124    # Run the bot until the user presses Ctrl-C
125    application.run_polling()
126
127
128if __name__ == "__main__":
129    main()