pythontelegramaiogram

Telegram Bot, problems with data


I have a telegram channel. Through the bot, I make a post with four inline buttons (1, 2, 3, 4) and a certain explanation text for the buttons, when I click on the buttons in different posts, I get the same Callback to all posts:

How to make callback.answer output its own text to each post? For example:

With the help of the bot, it is planned to post a lot of posts. So.. maybe sqlite3..? But How? (python, aiogram3) I tried to make a sqlite3 database, but I never figured it out..


Solution

  • You can encode post ID and button ID in the callback_data:

    Define class:

    class PostButtonCallbackData(CallbackData, prefix="post_btn_"):
        post_id: int
        btn_id: int
    
    

    To create your buttons use code like this:

    post_id = 112233 # Generate and store this unique post ID
    
    kb_btns = []
    for i in range(1, 5):
        cb_data = PostButtonCallbackData(post_id=post_id, btn_id=i).pack()
        kb_btns.append(
            [InlineKeyboardButton(text=str(i), callback_data=cb_data)]
        )
    
    reply_markup=InlineKeyboardMarkup(inline_keyboard=kb_btns)
    
    # use this reply_markup when you send post
    

    To handle callbacks use filter:

    @router.callback_query(PostButtonCallbackData.filter())
    async def cb_post_btn_clicked(callback: CallbackQuery, callback_data: PostButtonCallbackData):
        post_id = callback_data.post_id
        btn_id = callback_data.btn_id
        # Do whatever you need
        pass
    

    I haven't run this code and it may contain errors, but I hope this will help you to find the direction.