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