Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Discord.py) How to make bot delete his own message after some time?

I have this code in Python:

import discord
client = commands.Bot(command_prefix='!')

@client.event
async def on_voice_state_update(member):
    channel = client.get_channel(channels_id_where_i_want_to_send_message))
    response = f'Hello {member}!'
    await channel.send(response)

client.run('bots_token')

And I want the bot to delete its own message. For example, after one minute, how do I do it?

like image 383
Eron Avatar asked Dec 22 '20 23:12

Eron


2 Answers

There is a better way than what Dean Ambros and Dom suggested, you can simply add the kwarg delete_after in .send

await ctx.send('whatever', delete_after=60.0)

reference

like image 157
Łukasz Kwieciński Avatar answered Sep 30 '22 17:09

Łukasz Kwieciński


Before we do anything, we want to import asyncio. This can let us wait set amounts of time in the code.

import asyncio

Start by defining the message you send. That way we can come back to it for later.

msg = await channel.send(response)

Then, we can wait a set amount of time using asyncio. The time in the parentheses is counted in seconds, so one minute would be 60, two 120, and so on.

await asyncio.sleep(60)

Next, we actually delete the message that we originally sent.

await msg.delete()

So, altogether your code would end up looking something like this:

import discord
import asyncio

client = commands.Bot(command_prefix='!')

@client.event
async def on_voice_state_update(member, before, after):
    channel = client.get_channel(123...))
    response = f'Hello {member}!'
    msg = await channel.send(response) # defining msg
    await asyncio.sleep(60) # waiting 60 seconds
    await msg.delete() # Deleting msg

You can also read up more in this here. Hope this helped!

like image 23
Dom Avatar answered Sep 30 '22 17:09

Dom