How to randomize tasks.loop timer in discord.py

Viewed 21

i tried this:

timer = 15
random_timer = timer
channel = 108728307283
@tasks.loop(seconds = random_timer)
async def hello():
    await channel.send("Hello!")
    random_timer = timer + random.randint(1, 20)
hello.start()

My guess is that while a loop is running, it only looks at the value when it is run for the first time, so how do I set this random_timer value back to seconds without stopping the loop? In short, what should I do to send a message to a channel in a random time between 15-35 times?

1 Answers

To specify the total amount of iterations before exiting the loop, we can pass count to @tasks.loop()

@tasks.loop(seconds = random_timer, count=random.randint(15,35))

To change the interval timing of our loop during iteration, You can use function.change_interval()

@tasks.loop(seconds = random_timer, count=random.randint(15,35))
async def hello():
    await channel.send("Hello!")
    hello.change_interval(seconds=timer + random.randint(1, 20))
Related