I have a chat id and a message id. I want to find out whether this message exists or not. So far the only way I can figure out to do it is a nasty hack (try to delete or edit message and hope the bot has no rights to actually do so, theoretically it should throw and exception "message not found" and not "no rights").
Surely there is a better way?
3
Answers
As for now, (December 2022) Telegram Bot API doesn’t have a direct method to check whether a message exists or not.
Old workaround
This question has been asked and as a workaround, it was suggested to use the
forwardMessage
method. But since the question was asked several updates have been released and one of them brought a new feature – Protected Content in Groups and Channels, and if it is enabled thenforwardMessage
returns 400 Bad Request error on an attempt to forward any message.New workaround
As a new workaround
copyMessage
could be used, this method will succeed even in copying messages from groups with the enabled Protected Content feature. If the message was deleted, then 400 Bad Request error returns.Here is
aiogram
‘s documentation on this method.This workaround I found during reading documentation of another Python Telegram Bot library and here is an important note from there:
In the python aiogram library, you can try to use the
telegram.Bot.get_chat_member
method to check if a message with a given message ID exists in a chat. This method returns atelegram.ChatMember
object, which contains information about the user who sent the message.I tried to write something that could check if a message with a given message ID exists in a chat, let me know if I understood your question correctly:
If the message does not exist, it will raise an exception with the message "Message to delete not found". In this case, the function returns False. If the message does exist, the function returns True.
Note that this method requires the bot to be a member of the chat in which the message was sent. If the bot is not a member of the chat, it will not be able to access the message and will raise an exception.
Let me know if it helps!
In this example
from_user_id
means id of user which will get copied message.