我希望机器人每天运行一个定义的函数。我做了一些研究然后我能够写这个:
def job():
print("task")
schedule.every().day.at("11:58").do(job)
while True:
schedule.run_pending()
time.sleep(1)
但是这段代码阻塞了所有其他函数,所以我从其他堆栈溢出答案中做了更多研究,然后我能够写出这个:
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()
不幸的是,这也阻止了我的整个代码。我需要一些不会阻塞我代码其他部分的东西。如何做到这一点?
最佳答案
您可以使用Tasks .
假设你想每天(24 小时)将一个 JSON 文件上传到一个特定的 channel ,你会做这样的事情
@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}")
然后您需要使用 loop_func_name.start()
开始循环
所以在这种情况下:
upload_json_to_discord.start()
因此这将使该函数每 24 小时运行一次
如果你在一个 cog 中,你必须在 Cog 类的 __init__
函数中使用它
您可以在文档中找到这方面的详细信息:https://discordpy.readthedocs.io/en/latest/ext/tasks/
关于python - 如何在 discord.py 中安排一个函数在每天的特定时间运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64167141/