Haider
Haider

Reputation: 71

randomize time for looping task in discord

I have this code:

import discord
from discord.ext import tasks    
client = discord.Client()
@tasks.loop(minutes=1)
    async def test():
        channel = client.get_channel(MY_CHANNEL)
        await channel.send("hello")

    @client.event
    async def on_ready():
        test.start()

Which basically sends every minute a hello message in my channel. But is it also possible to randomize the time between the message sent. Like for one loop it is 3 and in the other 5...

Upvotes: 0

Views: 457

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15728

One way of doing so would be using the current_loop attribute and the change_interval method:

@tasks.loop(minutes=1)
async def test():
    channel = client.get_channel(MY_CHANNEL)
    await channel.send("hello")

    if test.current_loop % 2 == 0:
        test.change_interval(minutes=3)
    else:
        test.change_interval(minutes=1)

It simply changes the interval to 3 minutes every two iterations, then resets it back to the original 1 minute

Reference:

Upvotes: 2

Related Questions