Jakob Møller
Jakob Møller

Reputation: 171

getting message content in on_raw_message_delete

I'm trying to make a bot that will detect when a message is deleted, and send a message to the same channel with the message content.

I want to be able to do this even if the message is not in the bot's cached_messages, so I'm using on_raw_message_delete(payload).

My problem is that when trying to get the message from the channel with await channel.fetch_message(payload.message_id), I get the following error:
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

I assume this is because the message is already gone from the channel, but I don't know how else I would get the content or anything else from the message.

Here is my code (note that I have a self parameter, as this snippet is part of a cog)

@commands.Cog.listener()
async def on_raw_message_delete(self, payload):
    channel = self.bot.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)

    channel.send(f'Message deleted with content: {message.content}')

I have also tried with channel = await self.bot.fetch_channel(payload.channel_id), but I get the same error

Upvotes: 1

Views: 1949

Answers (1)

Nurqm
Nurqm

Reputation: 4743

You can use payload.cached_message for this.

But the problem is, if the deleted message is sent when the bot is offline, then it returns None and I guess it's also the same if bot can't see a channel. If your bot will run uninterrupted, then there is no problem.

So you can simply do:

@commands.Cog.listener()
async def on_raw_message_delete(self, payload):
    message = payload.cached_message
    channel = message.channel
    await channel.send(f'Message deleted with content: {message.content}')

Upvotes: 3

Related Questions