Home > Software engineering >  At a certain time the Bot writes something in Discord chat with background task
At a certain time the Bot writes something in Discord chat with background task

Time:06-24

I wanted to make the Bot greet in the chat at a certain time (like 10:00). The problem is that the "while" is not an asynchronous process (like "asyncio.sleep"). Could somebody tell me how I could do it?

I tried this (writed after "on_ready"):

while cyclebb == 1: #"cyclebb" is an always active variable
    blt = f"{datetime.now().hour} : {datetime.now().minute} : {datetime.now().second}"
    if blt == '10 : 42 : 15':
        chn = client.get_channel(964837651108732979)
        await chn.send('Hi guys!!')
        await asyncio.sleep(2) #I put it to prevent spamming

CodePudding user response:

You can use tasks loops. https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html?highlight=tasks loop#discord.ext.tasks.loop

it would look something like so.

from discord.ext import tasks

async def on_ready():
     greet_task.start()
     

@tasks.loop(hours=24)
async def greet_task():
     ...stuff here


  • Related