Search code examples
pythondiscorddiscord.py

Python Bot That Repeats Deleted Messages on Discord (Issue)


I wrote a Discord bot that is supposed to repeat messages that were deleted by users. It responds to a ping without issue, and it composes a message if someone deletes a message, but it does not retrieve the content of the message that was deleted. The only time it is able to retrieve the content of a deleted message is if it was pinged in the message. Ex: if a message "@bot, this is a deleted message" was deleted then the bot will be able to retrieve it, but if a message "this is a deleted message" was deleted, when trying to retrieve the message it will spit out a no content error.

I am a novice at Python and would love any pointers. I have included my code below, with comments. Thank you.

import discord
import os
from flask.app import cli
from keep_alive import keep_alive
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
client = discord.Client(intents=discord.Intents.default())
token = os.getenv('token.env')

# Event to detect and log deleted messages
@client.event
async def on_message_delete(message):
     
     # Response message
    response = (
        f"🔔 **Deleted Message Alert** 🔔\n"
        f"User: {message.author}\n"
        f"{message.content or 'No text content'}"
        )

    # Ignore messages sent by bots
    if message.author.bot:
        return

    # Send the response to the same channel
    await message.channel.send(response)
    
# Event to detect when the bot is pinged
@client.event
async def on_message(message):
    # Check if the bot is mentioned
    if client.user in message.mentions:
        await message.channel.send("Hello!")

    # Ensure other commands and events still work
    await client.process_commands(message)

# Log when the bot is ready
@client.event
async def on_ready():
    print(f"Logged in as {client.user.name} - {client.user.id}")

#server activation
keep_alive()

# Runs the bot
client.run(os.getenv("TOKEN"))

What I have tried:

  • I re-wrote and formatted the code differently with no impact/change
  • I took sections out to test if the "event to detect when the bot is pinged" is causing the issue, but there was no change other than the bot not responding to a ping
  • I removed the no text content section, which just produced a blank message

Solution

  • Looks to me as though you define your intents but then assign default intents. I might start there.

    intents = discord.Intents.default()
    intents.message_content = True
    intents.messages = True
    client = discord.Client(intents=discord.Intents.default())
    

    Might need to look something like this:

    deezIntents = discord.Intents.default()
    deezIntents.message_content = True
    deezIntents.messages = True
    client = discord.Client(intents=deezIntents)