python - 如何在 discord.py 中安排一个函数在每天的特定时间运行?

标签 python time discord discord.py schedule

我希望机器人每天运行一个定义的函数。我做了一些研究然后我能够写这个:

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/

相关文章:

python - Django Rest框架 View 集方法返回HTTP 405方法不允许

time - 为 Fortran 多线程程序计时

python - Discord 机器人帮助命令

discord - 嵌入消息 : DiscordAPIError: Cannot send an empty message v. 13 (discord.js)

audio - 音乐 discord.js 机器人 : The "url" argument must be of type string

python - 使用 pytesseract 从类型为 'PIL.PpmImagePlugin.PpmImageFile' 的图像中提取文本时出现错误

python - 如何为 Glass 设置目标位置?

python - 词典列表 - 如何格式化打印输出

PHP:如何检查日期是今天、昨天还是明天

r - 从 R 中的分钟数据创建 15 分钟的时间间隔?