Is there kind of a limit for asyncio in discord.py?

Viewed 195

So I‘ve got a python discord bot. The idea is, there is a channel for funny quotes. In order to keep the channel organized, people can as well discuss in it, but after 24h their message should be deleted, if there‘s no %q before it. I‘ve got the following code:

@bot.event
async def on_message(ctx):
    await bot.process_commands(ctx)
    channel = bot.get_channel(ID_OF_CHANNEL)
    if ctx.channel == channel:
        if not ctx.content.lower().startswith("%q"):
            await asyncio.sleep(86400)
            await ctx.delete()

The problem is, it just doesn‘t work. The bot responds to other commands, but doesn‘t delete every single message after 24h. In fact, it doesn‘t delete any messages. I‘ve tried it with only 3h as well, but it didn‘t work too. Passing in only 30 seconds works… I‘m sorry if my question may be stupid, but I‘m just clueless and I hope anybody can help me :) May there be a limit of messages the bot can view or a limit of time it can do so? Btw: I‘m pretty sure the bot was running all the time, so it was not interrupted.

EDIT: Just to make that clear: The idea is to start something like a timer on every single message, which works for 30 seconds, but strangely not for 3h.

2 Answers

Try using tasks instead of asyncio. It is made for such repetetive operations and it is easier and nicer because it is made by discord and is included in discord.ext. The way I would do it is something like this:

from discord.ext import tasks

@bot.command()
async def start(ctx):
    deletingLoop.start() #here you start the loop

@tasks.loop(hours=24)
async def deletingLoop():
    guild = self.bot.get_guild(guildID)    #get the guild
    channel = guild.get_channel(channelID) #and the channel
    channel.purge(limit=1000)              #clear the channel

and if you are afraid that this channel may have more than 1000 messages you can add on_message() event that would count the messages on this channel.

You have to take ctx.message as you want to delete the message of the context. This can take the parameter delay which deletes the selected message after that amount of time.

Code:

@bot.event
async def on_message(ctx):
    await bot.process_commands(ctx)
    channel = bot.get_channel(ID_OF_CHANNEL)
    if ctx.channel == channel:
        if not ctx.content.lower().startswith("%q"):
            await ctx.message.delete(delay=24h_in_seconds)
Related