简体   繁体   English

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

[英]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:我的问题如下:

  1. Why the commented part doesn't work?为什么评论部分不起作用?
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. Why 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM