0
votes

I am writing a discord bot in Python, which already has the two async overwritten methods on_ready and on_message to react to messages in a certain way.

Now I wanted to add a function, which should be called once in a week. I tried something with asyncio.sleep() but I don't want to start the bot at that specific time and then sleep 604.800 sec (1 week in seconds) to repeat that function every week.

Here's what I got so far:

class MyClient(discord.Client):

    async def on_ready(self):
        #some initial stuff
        self.loop.create_task(self.routine())

    async def on_message(self, message):
        #reply to chat messages
        await message.channel.send("Reply")

    async def routine(self):
        while True:
            print("I'm on that routine boi")
            await asyncio.sleep(3)

It works so far, that I can use the bot in discord and get the outputs every 3 seconds. But I'd prefer something like from the schedule module to use something like

scheduler.every().sunday.at("8:55").do(self.routine())

Any chance to do something similar in combination with asyncio?

1
Is there any reason why you can't do this using a cron job?nageeb
@nageeb Yes, I can't do it like that, because I start the script once and it should keep running 24/7 to work as a discord bot on a remote server. With that I could do my "weekly routine" perfectly, but the bot would only work on Sundays, which is not what I want / anyone would want.fusion

1 Answers

1
votes

The Event loop provides mechanisms to schedule callback functions to be called at some point in the future, as shown here in Python docs

class MyClient(discord.Client):

    async def on_ready(self):
        #some initial stuff
        self.loop.create_task(self.routine())

    async def on_message(self, message):
        #reply to chat messages
        await message.channel.send("Reply")

   async def execute():
         res = await loop.call_later(delay, callback, *args)
         delay += delay + 604800 
         return res



    async def routine(self):
        while True:
            print("I'm on that routine boi")
            res = await loop.run_until_complete(execute)