[英]Why @tasks.loop doesn't works as I think? (discord.py)
Hey guys I'm trying to write a dc bot:3嘿伙计们,我正在尝试编写一个 dc bot:3
I want to set a background task with cog, and it'll send some message every 5 seconds.我想用 cog 设置一个后台任务,它会每 5 秒发送一些消息。 My
Cog_Extension
will initialize by self.bot = bot
.我的
Cog_Extension
将由self.bot = bot
初始化。
My questions are as following:我的问题如下:
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
await self.bot.wait_until_ready()
has to put in @tasks.loop
?await self.bot.wait_until_ready()
必须放入@tasks.loop
? If I don't put it there, the variable channel
will be None.channel
将为 None。 Here is my code这是我的代码
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())
It appears you need to make your __init__()
function async.看来您需要使
__init__()
function 异步。
class Task(Cog_Extension):
async def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.channel_id = xxx
self.livingloop.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.