Discord.py task.loop用于更改齿轮无法工作的状态

import discord
from discord.ext import commands,tasks

from itertools import cycle

status = cycle(['status 1','status 2','status 3'])

class Example(commands.Cog):


    def __init__(self,dBot):
        self.dBot = dBot
        self.dBot.change_stats.start()

    #EVENTS
    @commands.Cog.listener()
    async def on_member_join(self,context,member):
        await context.send(f'Member {member.mention} has joined!')

    #TASKS
    @tasks.loop(seconds=10.0)
    async def change_stats(self):
        await self.dBot.change_presence(activity=discord.Game(next(status)))

    #COMMANDS
    @commands.command()
    async def ping(self,context):
        await context.send("Pong!")

    @commands.command()
    async def clear(self,amount=5):
        await context.channel.purge(limit=amount)

def setup(dBot):
    dBot.add_cog(Example(dBot))

这是上面cog文件中的代码,其中任务无法正常运行,除此之外,其他所有工作都很好。

我一直收到的错误是“ AttributeError:'Bot'对象没有属性'change_stats'”

感谢您的帮助。

imcoolmint 回答:Discord.py task.loop用于更改齿轮无法工作的状态

change_stats将是Example对象的属性:

self.change_stats.start()

请查看Recipes部分中的示例,在该示例中您可以找到齿轮中更多任务的用法。

,

你必须在 start() 方法中加入“self”:change_status.start(self) 所以它会在 cog 中工作

,

你只需要制作

@client.event()
async def status_task():
   while True:
      await client.change_presence()
      await asyncio.sleep(4)
      await client...
      await asyncion.sleep(4)

@client.event
async def on_ready():
   print('ready')
   client.loop.create_task(status_task())
,

您只需将机器人保存在构造函数的一个属性中,以便能够在 on_ready 方法中调用 change_presence。非常适合我

class PresenceCog(commands.Cog):
    def __init__(self,bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.change_presence.start()

    @tasks.loop(seconds=10) 
    async def change_presence(self):
        status = random.choice(self.statuses)
        await self.bot.change_presence(activity=discord.Game(name=status))

def setup(bot):
    bot.add_cog(PresenceCog(bot))
本文链接:https://www.f2er.com/3107672.html

大家都在问