我正在使用discord.py rewrite 编写一个discord 机器人,并且我想每天在特定时间运行一个函数。我对异步函数完全没有经验,而且我无法弄清楚如何在不使用“await”的情况下运行异步函数。这只是我的一段代码,这就是为什么有些东西可能没有定义的原因。
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)
类型错误:第一个参数必须是可调用的
但是当我不使用等待时,我只是send_channel()
作为参数,我收到此错误:
RuntimeWarning:从未等待协程“send_channel”
我不太擅长编程,所以如果有人可以尝试为我简化它,那就太棒了。
Thanks
对此的内置解决方案不和谐.py /questions/tagged/discord.py是使用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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)