Home > Net >  Multitasks in discord py bot
Multitasks in discord py bot

Time:09-17

I'm trying to multitask with discord py, but I have a problem

Code:

@tasks.loop(seconds=10)
async def taskLoop(ctx, something):

    await ctx.send(something)

@client.command()
async def startX(ctx, something):
    
    taskLoop.start(ctx, something)

@client.command()
async def endX(ctx):
    
    taskLoop.cancel()
    taskLoop.stop()

In discord I start the command like: -startX zzzzzzzzzz
So it works, every 10 seconds the bot sends "zzzzzzzzzz"

When I try to create a new task (while the previous one is still running), for example: -startX yyyyyyyy
I get the error:
Command raised an exception: RuntimeError: Task is already launched and is not completed.

Obviously I understand it's because the other task is still working, but I looked in the documentation and couldn't find a way to create multiple tasks.

Are there any solutions for this? Thread maybe?

CodePudding user response:

You can't really start the same task more than once. You can create a "task generator" which will generate and start the tasks

started_tasks = []

async def task_loop(ctx, something):  # the function that will "loop"
    await ctx.send(something)


def task_generator(ctx, something):
    t = tasks.loop(seconds=10)(task_loop)
    started_tasks.append(t)
    t.start(ctx, something)


@bot.command()
async def start(ctx, something):
    task_generator(ctx, something)


@bot.command()
async def stop(ctx):
    for t in started_tasks:
        t.cancel()
  • Related