gpt4 book ai didi

python - 如何使用计划库运行异步函数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:58 27 4
gpt4 key购买 nike

我正在使用 discord.py 重写编写一个 discord 机器人,我想在每天的特定时间运行一个函数。我完全没有使用异步函数的经验,而且我不知道如何在不使用“等待”的情况下运行异步函数。这只是我的一段代码,这就是为什么有些东西可能没有定义的原因。

async def send_channel():
try:
await active_channel.send('daily text here')
except Exception:
active_channel_id = None
active_channel = None

async def timer():
while True:
schedule.run_pending()
await asyncio.sleep(3)
schedule.every().day.at("21:57").do(await send_channel())

@bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print(bot.user.id)
print("------")

bot.loop.create_task(timer())

使用 schedule.every().day.at("00:00").do()函数,当我输入 await send_channel() 时出现此错误在 .do() 的参数中:

self.job_func = functools.partial(job_func, *args, **kwargs) TypeError: the first argument must be callable

但是当我不使用 await 时,我只有 send_channel()作为参数,我得到这个错误:

RuntimeWarning: coroutine 'send_channel' was never awaited

我不是很擅长编程,所以如果有人能帮我把它简化一下那就太棒了。

谢谢

最佳答案

中的内置解决方案是使用 discord.ext.tasks 扩展。这使您可以注册一个以特定时间间隔重复调用的任务。当机器人开始时,我们将循环的开始延迟到目标时间,然后每 24 小时运行一次任务:

import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta

bot = commands.Bot("!")

@tasks.loop(hours=24)
async def my_task():
...

@my_task.before_loop
async def before_my_task():
hour = 21
minute = 57
await bot.wait_until_ready()
now = datetime.now()
future = datetime.datetime(now.year, now.month, now.day, hour, minute)
if now.hour >= hour and now.minute > minute:
future += timedelta(days=1)
await asyncio.sleep((future-now).seconds)

my_task.start()

关于python - 如何使用计划库运行异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51530012/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com