Telegram机器人如何处理一对一及群组内用户删除的消息?
Great question—yes, there are absolutely workable solutions to handle deleted messages in Telegram private chats or groups where your bot is a member. Since you already have logic set up for message edits, these methods will fit right into your existing workflow. Here’s how to implement them:
Enable Deletion Update Notifications via the Bot API
The Telegram Bot API includes dedicated update types for deleted messages, which you might not have enabled yet. To receive these updates, you need to specifydeleted_messagesin theallowed_updatesparameter when initializing your bot (either via webhook or long polling).For example, if you’re using the
python-telegram-botlibrary, your initialization would look like this:from telegram.ext import Updater # Include "deleted_messages" alongside your existing enabled updates updater = Updater( token="YOUR_BOT_TOKEN", allowed_updates=["message", "edited_message", "deleted_messages"] )This tells Telegram to send your bot a notification whenever a message is deleted in any chat it has access to (private chats or groups it’s part of).
Track Messages Locally to Contextualize Deletions
Deletion updates only include the chat ID and the IDs of the deleted messages—they don’t include the original message content. To know what was deleted, you’ll need to maintain a local database or cache that stores every message your bot processes (including edits).Here’s a straightforward workflow:
- Every time your bot receives a new message or an edited message, save key details (message ID, chat ID, timestamp, original content, edited content if applicable) to your database.
- When a
deleted_messagesupdate arrives, loop through the deleted message IDs, look up their entries in your database, and execute your desired action (e.g., log the deletion, alert group admins, archive the deleted content).
Keep These Limitations in Mind
- Your bot can only receive deletion updates for messages sent after it joined the group or started the private chat. It won’t get notified about messages deleted that were sent before the bot was present.
- For supergroups, ensure your bot has the
read_message_historypermission enabled—without this, it won’t receive deletion updates for older messages.
内容的提问来源于stack exchange,提问作者alireza

