Deleting User Messages in Discord.py

Deleting User Messages In Discord Py

Have you ever wanted to create a Discord bot that can delete inappropriate or unwanted messages sent by users? Deleting user messages is a common requirement for managing chat servers and keeping conversations civil.

In this comprehensive guide, you’ll learn how to delete user messages with a Discord.py bot using simple Python code. We’ll cover everything from setting permissions, detecting trigger words, targeting the message to delete, and handling errors.

Whether you’re a beginner or an experienced Python developer, you’ll be able to follow along with code examples and detailed explanations. By the end, you’ll know to delete messages from any user in a Discord server programmatically.

Also read: Making Your Discord Bot Play YouTube Audio: A Step-by-Step Guide

To enable a Discord.py bot to delete user messages, the bot account must have the “Manage Messages” permission enabled on the Discord server. This allows programmatic message deletion through Message.delete().

Setting Delete Permissions for Your Discord Bot

The first step to deleting user messages is ensuring your bot has the correct permissions.

Discord uses a permission system to control what bots can do in servers. To delete messages, your bot will need the Manage Messages permission enabled on the server it joins.

Here is how to set up the permission:

  1. Open the Discord server settings
  2. Navigate to Roles
  3. Create or edit the role for your bot
  4. Enable the “Manage Messages” permission
Manage Message Permission Discord
Manage Message Permission Discord

You can also set permissions directly when you add the bot using OAuth2 URL parameters. Append &permissions=8 to enable Manage Messages. Once enabled, your bot will have the ability to delete any user’s messages in text channels with that role.

Detecting Messages to Delete using Discord.py

Now that permissions are configured, the next step is detecting which messages your bot should delete.

There are a few common ways to target message deletion:

  • Delete all messages – Indiscriminately delete everything.
  • Listen for trigger words – Delete messages containing banned/blacklisted words.
  • Filter on message attributes – Delete based on message metadata like author, channel, etc.
  • Respond to user reports – Users can report bad messages to prompt deletion.
  • Integrate with external services – Use Zapier/IFTTT to watch external sources.

For most use cases, using trigger words and message attributes filters will be the best approach.

1. Listen for Trigger Words

Discord.py makes it easy to listen and respond to message content in real time. By listening to messages containing banned words, you can automatically delete toxic, inappropriate, or spammy messages.

Here is basic example code:

BAD_WORDS = ["slur1", "slur2", "swear1"]

@bot.event
async def on_message(message):
    content = message.content.lower()
    for word in BAD_WORDS:
        if word in content:
            await message.delete()

This listens to the on_message event, checks for bad words, and deletes matching messages immediately.

You can make this more sophisticated by ignoring word boundaries, handling leetspeak, checking attachments, etc. But this is enough to get started with basic automatic moderation.

2. Filter on Message Attributes

Instead of message content, you may want to target messages based on attributes like:

  • Author ID
  • Channel name
  • Message age
  • Attachment type

For example, you could delete messages from banned users, old messages to purge history, media attachments to disallow images, etc.

Here’s some sample code showcasing a few filters:

@bot.event  
async def on_message(message):
    # Delete media attachments
    if message.attachments:
       await message.delete() 

    # Delete messages from banned user
    banned_users = [123, 456]
    if message.author.id in banned_users:
        await message.delete()  

    # Delete messages older than 2 weeks 
    TWO_WEEKS = 1209600
    if discord.utils.utcnow() - message.created_at > TWO_WEEKS: 
        await message.delete()

The key is checking attributes on the Message object and acting on matches. Refer to the documentation for all available attributes.

Also read: Adding Buttons to Discord Messages Using Python Pycord

Targeting the Message

Now that you can detect messages for removal, the next step is targeting the message object to delete. This is done using the Message.delete() method.

Basic Message Deletion Using Discord.py

The simplest case is deleting the message that triggered your on_message event listener:

@bot.event
async def on_message(message):
    if should_delete(message):
        await message.delete()

The message object passed into the event handler maps to the message that triggered the event. Calling .delete() on that message removes it from the channel.

This works great for direct responses, but falls apart when you need asynchronous deletion on the same message.

Asynchronous Deletion Using Discord.py

Since on_message delete calls could fail or encounter errors, its safer to make a task to delete asynchronously:

async def delete_message(message):
    try:
        await message.delete()
    except discord.HTTPException:
        logging.error(f"Unable to delete message {message.id}")

@bot.event 
async def on_message(message):
    if should_delete(message):
        asyncio.create_task(delete_message(message))

This queues up the delete call in the background rather than blocking the bot’s event loop, preventing hangs.

Deleting Other Messages Using Discord.py

You can also delete messages other than the one triggering the event by targeting them through:

  • Message ID lookup
  • Channel history search

For example:

CHANNEL = "general"

@bot.event
async def on_message(message):
    if is_bad(message):
        channel = bot.get_channel(CHANNEL)
        async for history_msg in channel.history():
            if is_bad(history_msg):
                await history_msg.delete() 

This does a slow history scan of the #general channel and deletes any matching bad messages. Use judiciously to avoid rate limits!

For better lookup performance, use fetch_message() with a specific ID instead.

Handling Permission Errors Using Discord.py

Even if your bot has the Manage Messages permission, deletion could fail due to hierarchy rules. Bots cannot delete messages from server admins or mods ranked higher than their highest role.

Make sure to gracefully handle errors:

@bot.event
async def on_message(message):
    try:
        await message.delete()
    except discord.Forbidden:
        logging.warning(f"Couldn't delete message from {message.author}")

This logs the failure reason without interrupting bot operation.

Also read: Creating A Python Discord Bot – A Complete Step-by-Step Guide

Delayed Deletion Using Discord.py

Discord also supports queued delayed deletion using the delay parameter:

await message.delete(delay=60) # Deletes after 60 second delay

This is useful for temporary message moderation, e.g:

  • Delete messages after 24 hours to auto-archive conversations
  • Preview moderated messages then delete after approval
  • Delete messages reacting to bot commands after usage

The delete task runs in the background so errors are automatically suppressed.

Blacklists, Whitelists, and Filters with Discord.py

For automated moderation, you’ll typically want to tune control beyond a basic allowlist or blocklist. For example, you could build a robust moderation filter using:

  • Regex blacklist for slurs and hate speech
  • Filter whitelist to skip scanning allies and mods
  • Minimum vulnerability score threshold before deleting
  • Image attachments OCR’d to detect policy violations
  • Configure settings per server account

This would allow precisely targeting unwanted messaging while avoiding false positives.

Conclusion

And there you have it – a comprehensive guide to deleting user messages in Discord.py! You should now understand all the steps required to start automatically deleting targeted messages on Discord. The capabilities are extensive, but remember to use responsibility when deleting user messages! Having transparency, accountability and recourse processes is important as well.

Now start improving your Discord communities with automated moderation powered by Discord.py!

Reference: https://discordpy.readthedocs.io/en/stable/api.html