Search code examples
telegramtelegram-botpython-telegram-bot

How to use 'sendDice' on 'InlineKeyboard' using 'Python-Telegram-bot'


I'm trying to do an InlineKeyboard which has multiple options that then send a dice depending on which button you pressed

As I'm using CallbackQuery the only methods available to send some sort of response are edit_text_ and there isn't any type of 'dice' or sticker to send. Is there any other way to handle the button so that I can send the dice back to the user?

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
keyboard = [
    [
        InlineKeyboardButton("Dice", callback_data="1"),
        InlineKeyboardButton("Basket", callback_data="2"),
    ],
    [InlineKeyboardButton("test", callback_data="3")],
]

reply_markup = InlineKeyboardMarkup(keyboard)

await update.message.reply_text("Please choose:", reply_markup=reply_markup)



async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query

    await query.answer()
    if query.data == '1':
        await update.callback_query.edit_message_text(query.data)
        #I want to do so that here it sends the dice back
    
    else:
        await query.edit_message_text(text=f"Selected option: {query.data}")

Solution

  • Note that inline buttons can be attached to messages sent by users - namely when these messages are generated via the inline mode. In those cases, the message can be sent in a chat where the bot isn't even a participant. Hence, the CallbackQuery class doesn't have any direct shortcuts to send messages as reply to it.

    However, if the callback query is originating from a button attached to a message sent by the bot itself, the attribute CallbackQuery.message is an instance of the Message and you can use the shortcuts methods like Message.reply_text.

    In addition to that, you can ofc course call any method of the Bot class. An instance of that class is always available via context.bot.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.