如何让我的 Discord 机器人 运行 成为每个星期日 0:00 的一个功能?
How do I make my Discord bot run a function every sunday at 0:00?
我有一个使用 discord.py 广告的 Python discord 机器人,我想每周日在 0:00 做点什么。
我怎样才能做到这一点?
我使用 Python 3.7 和 discord.py 1.3.2
对于提供的时间间隔,这不是更有效的方法,而是一种方法
您可以使用 python 的 schedule 模块。
import schedule
def job():
"Write your job here "
if __name__=="__main__":
schedule.every().sunday.at("00:00").do(job)
while True:
schedule.run_pending()
更新:上面的程序被阻塞了。
对于非阻塞,您可以按以下方式使用线程和调度的组合。
import threading
import schedule
def job():
"""Your job here"""
def threaded(func):
job_thread = threading.Thread(target=func)
job_thread.start()
if __name__=="__main__":
schedule.every().sunday.at("00:00").do(threaded,job)
while True:
schedule.run_pending()
"""you can write your other tasks here"""
此程序为您的预定作业创建另一个线程。
您可以使用 aiocron。
pip 安装 aiocron
https://github.com/gawel/aiocron
在 bot.run(TOKEN)
之前将以下内容添加到您的机器人代码中
import aiocron
CHANNEL_ID=1234
@aiocron.crontab('0 * * * *')
async def cornjob1():
channel = bot.get_channel(CHANNEL_ID)
await channel.send('Hour Cron Test')
我有一个使用 discord.py 广告的 Python discord 机器人,我想每周日在 0:00 做点什么。 我怎样才能做到这一点? 我使用 Python 3.7 和 discord.py 1.3.2
对于提供的时间间隔,这不是更有效的方法,而是一种方法
您可以使用 python 的 schedule 模块。
import schedule
def job():
"Write your job here "
if __name__=="__main__":
schedule.every().sunday.at("00:00").do(job)
while True:
schedule.run_pending()
更新:上面的程序被阻塞了。
对于非阻塞,您可以按以下方式使用线程和调度的组合。
import threading
import schedule
def job():
"""Your job here"""
def threaded(func):
job_thread = threading.Thread(target=func)
job_thread.start()
if __name__=="__main__":
schedule.every().sunday.at("00:00").do(threaded,job)
while True:
schedule.run_pending()
"""you can write your other tasks here"""
此程序为您的预定作业创建另一个线程。
您可以使用 aiocron。
pip 安装 aiocron
https://github.com/gawel/aiocron
在 bot.run(TOKEN)
之前将以下内容添加到您的机器人代码中
import aiocron
CHANNEL_ID=1234
@aiocron.crontab('0 * * * *')
async def cornjob1():
channel = bot.get_channel(CHANNEL_ID)
await channel.send('Hour Cron Test')