Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a specific message by ID using discord.py

I am trying to delete a message using it's ID. I am using discord.py.

Logic Flow

User sends command. example: !message hi
Bot deletes "!message hi" using User's message ID
Bot says "hi"

I have figured out how to get it to copy my messages, but I am having difficulty getting it to delete them. I didn't want to say that it deletes the message before it's one otherwise on busy servers it might not work. I wanted to get the command message's ID then delete it using it's ID.

like image 678
SoulFanatic Avatar asked Aug 09 '17 17:08

SoulFanatic


1 Answers


Updated for discord.py v1.2+

You should use the TextChannel.fetch_message function.

msg = await channel.fetch_message(message_id)
await msg.delete()

Original answer (no longer works):

To answer the question: To delete a message by ID, you must either fetch the message object (preferred) or go through client.http (not-preferred)

First option: Finding the message.

You can use the Client.get_message function

msg = await client.get_message(channel, message_id)

Alternately, your specific use case seems to just be deleting the message that was sent, so you could just use the message supplied by on_message(msg)
After you have the message, you can do:

await client.delete_message(msg)

Second option: Using client.http

Assuming you know the channel's ID, you can simply call

await client.http.delete_message(channel_id, message_id)

This method while useful for deleting arbitrary messages in arbitrary places shouldn't be used if getting the message is feasably an option.

like image 70
Sam Rockett Avatar answered Oct 07 '22 14:10

Sam Rockett