K
K
knyaz_ostrov2019-11-24 05:16:14
Bots
knyaz_ostrov, 2019-11-24 05:16:14

How to get bot message ID in python TelegramBotApi or aiogram?

I need the bot to determine the ID of its last message so that it can be deleted later.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StickySkull, 2021-01-16
@StickySkull

The only option that comes to mind is the user's last message + 1.
That is:

@dp.message_handler()
async def other_command(message: types.Message):
    next_id = message.message_id + 1

next_id - id of any next message, no matter from whom.

V
Van0ne, 2022-01-28
@Van0ne

For a bot that will be used by more than 1 person, it is better not to resort to the method:

@dp.message_handler()
async def other_command(message: types.Message):
    next_id = message.message_id + 1

In this case, we write down the id of the message, which does not yet exist, if another user sends a message before the bot, then message.message_id + 1 will be assigned to the message of another user.
The bot will not be able to delete the message with next_id = message.message_id + 1, and the error "Message can't be edited" will occur.
For a multi-user bot, in order to avoid such a situation, it would be better to write:
@dp.message_handler()
async def bot_answer(message: types.Message):
    msg = await message.answer('Последнее сообщение бота')
    next_id = msg.message_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question