为什么@tasks.loop不像我想的那样工作?(discord.py)



嘿,伙计们,我想写一个dc bot:3

我想用cog设置一个后台任务,它将每5秒发送一些消息。我的Cog_Extension将由self.bot = bot初始化。

我的问题如下:

  1. 为什么注释部分不起作用?
discord.ext.commands.errors.ExtensionFailed: Extension 'cmds.task' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
  1. 为什么await self.bot.wait_until_ready()必须放在@tasks.loop?如果我不把它放在那里,变量channel将是None。

这是我的代码

class Task(Cog_Extension):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.channel_id = xxx
self.livingloop.start()
@tasks.loop(seconds = 5)
async def livingloop(self):
await self.bot.wait_until_ready()
channel = self.bot.get_channel(self.channel_id)
print(channel)
await channel.send("blabla")
# async def interval():
#     await self.bot.wait_until_ready()
#     self.channel = self.bot.get_channel(xxx)
#     while not self.bot.is_closed():
#         await self.channel.send("blabla")
#         await asyncio.sleep(5)
# self.bg_task = self.bot.loop.create_task(interval())

看来你需要让你的__init__()函数async。

class Task(Cog_Extension):
async def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.channel_id = xxx
self.livingloop.start()

最新更新