Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I schedule a function to run everyday at a specific time in discord.py?

I want the bot to run a defined function everyday. I did some research and then I was able to write this:

def job():
    print("task")
    
schedule.every().day.at("11:58").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

but this code is blocking all other functions so I did some more research from other stack overflow answers and then I was able to write this:

def job():
    print('hi task')

def threaded(func):
    job_thread = threading.Thread(target=func)
    job_thread.start()

if __name__=="__main__":

    schedule.every().day.at("12:06").do(threaded,job)      
    while True:
        schedule.run_pending()

unfortunately this too , blocks my entire code. I need something that doesn't block other parts of my code. How to do that?


1 Answers

You can use Tasks.

So let's say you want to upload a JSON file to a specific channel every day (24 hours) you will do something like this

    @tasks.loop(hours=24)
    async def upload_json_to_discord():
        channel_to_upload_to = client.get_channel(JSON_UPLOAD_CHANNEL_ID)
        try:
            await channel_to_upload_to.send(file=discord.File("id-list.json"))
            print("JSON file upload success")
        except Exception as e:
            print(f"Upload JSON failed: {e}")

and then you need to start the loop by using loop_func_name.start() so in this case:

upload_json_to_discord.start()

and so this will make the function run once every 24 hours

In case you are in a cog, you will have to use this in the __init__ function of the Cog's class

You can find detailed information on this in the documentation: https://discordpy.readthedocs.io/en/latest/ext/tasks/

like image 97
Zacky Avatar answered Oct 17 '25 04:10

Zacky