How to restart a loop in discord.py?

Viewed 921

I am making a discord bot using discord.py. I want to make a command to purge all messages inside a channel every 100 seconds. Here is my code:

autodeletetime = -100
autodeletelasttime = 1



@client.command()
@commands.has_permissions(manage_messages=True)
async def autodelete(ctx):
        global autodeleterunning
        if autodeleterunning == False:
            autodeleterunning = True
            asgas = True
            while asgas:
                message = await ctx.send(f'All messages gonna be deleted in 100 seconds')
                await message.pin()
                for c in range(autodeletetime,autodeletelasttime):
                    okfe = abs(c)
                    await message.edit(content=f"All messages gonna be deleted in {okfe} seconds" )
                    await asyncio.sleep(1)
                    if c == 0:
                    
                        await ctx.channel.purge(limit=9999999999999999999999999999999999999999999999999999999999999999999)


                        await time.sleep(1)
            autodeleterunning = False
        else:
            await ctx.send(f'The autodelete command is already running in this server')
                    

I want the loop to restart every 100 seconds after the purge is complete.

1 Answers

You should use tasks instead of commands for these kind of commands.

import discord
from discord.ext import commands, tasks
import asyncio


@tasks.loop(seconds=100)
async def autopurge(channel):
    message = await channel.send(f'All messages gonna be deleted in 100 seconds')
    await message.pin()
    try:
        await channel.purge(limit=1000)
    except:
        await channel.send("I could not purge messages!")


@client.group(invoke_without_command=True)
@commands.has_permissions(manage_messages=True)
async def autopurge(ctx):
    await ctx.send("Please use `autopurge start` to start the loop.")


# Start the loop
@autopurge.command()
async def start(ctx):
    task = autopurge.get_task()
    if task and not task.done():
        await ctx.send("Already running")
        return
    autopurge.start(ctx.channel)


# Stop the loop
@autopurge.command()
async def stop(ctx):
    task = autopurge.get_task()
    if task and not task.done():
        autopurge.stop()
        return
    await ctx.send("Loop was not running")
Related