如何重新启动discord.py中的循环?

时间:2020-07-24 20:59:40

标签: python python-3.x discord.py

我正在使用discord.py做一个不和谐的机器人。我想发出一个命令,每100秒清除一次通道内的所有消息。这是我的代码:

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')
                    

我希望清除后每100秒重新启动一次循环。

1 个答案:

答案 0 :(得分:2)

对于这类命令,您应该使用tasks而不是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")