Discord.py:如何实现>delembeds命令以删除机器人自身发送的嵌入消息?
How to Make a Discord.py Bot Delete Its Own Embed Messages with a
>delembeds Command Absolutely! You can totally implement this functionality in Discord.py. Creating a >delembeds command to find and delete all embed messages your bot sent is straightforward—here's how to do it step by step:
Prerequisites
First, make sure your bot has the following permissions in the target server/channel:
Manage Messages: Required to delete messagesRead Message History: Required to fetch older messages sent by the bot
Full Command Implementation
Here's a complete, ready-to-use code example for the >delembeds command:
import discord from discord.ext import commands # Initialize the bot with necessary intents bot = commands.Bot(command_prefix=">", intents=discord.Intents.all()) @bot.command() @commands.has_permissions(manage_messages=True) # Restrict command to trusted users async def delembeds(ctx): # Check bot permissions (skip for DMs since guild doesn't exist there) if ctx.guild is not None: if not ctx.guild.me.guild_permissions.manage_messages: await ctx.send("I need the `Manage Messages` permission to delete messages!") return if not ctx.guild.me.guild_permissions.read_message_history: await ctx.send("I need the `Read Message History` permission to find my old embeds!") return # Bulk delete all embed messages sent by the bot deleted_messages = await ctx.channel.purge( limit=None, # Use a number like 100 if you want to limit deletion scope check=lambda msg: msg.author == bot.user and len(msg.embeds) > 0 ) # Send a temporary confirmation (auto-deletes after 5 seconds) confirmation = await ctx.send(f"Deleted {len(deleted_messages)} of my embed messages!") await confirmation.delete(delay=5) # Replace with your bot token bot.run("YOUR_BOT_TOKEN")
Key Notes & Customizations
- Rate Limits: Using
limit=Nonewill delete all matching messages, but Discord's API has rate limits for bulk actions. If you're dealing with a channel with thousands of messages, add a loop to delete in batches (e.g., 100 messages at a time) to avoid being throttled. - Selective Deletion: If you only want to delete embeds with specific content (like a certain title or description), modify the
checkfunction. For example:check=lambda msg: msg.author == bot.user and len(msg.embeds) > 0 and msg.embeds[0].title == "Target Title" - DM Support: The code works in both server channels and direct messages—we added a check to skip guild permission validation for DMs.
If you run into issues with rate limits, permissions, or want to tweak the functionality further, feel free to ask for more help!
内容的提问来源于stack exchange,提问作者cap




