简体   繁体   中英

How to make the bot run a defined function at a specific time everyday 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?

You can easily set it up with asyncio

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

async def task():
    while True:
        schedule.run_pending()
        await asyncio.sleep(1)

and also you shouldn't forget to add client.loop.create_task(task()) on your on_ready event:

@client.event
async def on_ready():
    client.loop.create_task(task())

We can able to loop a function in discord.py with

client.loop.create_task(function())

So with this, we can able to check time every second or 10-15sec.

import datetime
async def function():

    schedule_time = datetime.datetime(2020, 10, 3, 11, 58, 00, 000000)#(year, month, day, hour, minute, second, microsecond)
    await client.wait_until_ready()

    while not client.is_closed():
       now = datetime.datetime.now()
       if schedule_time  <= now:
           #JOB
           #add one day to schedule_time to repeat on next day
           schedule_time+= datetime.timedelta(days=1)
       await asyncio.sleep(20)

client.loop.create_task(function())

first set the date and time in schedule_time variable and in the while statement, it checks for every 20 seconds if the schedule_time met or passed the current time! if it does then it will execute the #JOB segment and after completing the job segment we should update the schedule_time variable to the next day! else it will be looped forever So, with the help of the DateTime module we updated the schedule_time variable with this line at the end!

schedule_time+= datetime.timedelta(days=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM