【问题标题】:Can you get the number of users in on_ready? In a cog你能得到on_ready中的用户数吗?在一个齿轮
【发布时间】:2021-05-12 10:09:43
【问题描述】:

我试图让机器人状态来说明它所在的所有服务器中的人数。示例:状态:正在观看 82 人 | $cmds

这是我尝试过的:

@commands.Cog.listener()
    async def on_ready(self):
        print('{0.user} has awoken!'.format(self.bot))
        await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name = f"{self.bot.users} people | $cmds"))

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    是的,你可以。请注意,您应该首先添加Bot.wait_until_ready,以便缓存加载完成。

    一种方法:

    @commands.Cog.listener()
    async def on_ready(self):
        await self.bot.wait_until_ready()
        
        total_members = 0
        for guild in self.bot.guilds:
            total_members += guild.member_count
    
        await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name = f"{total_members} people | $cmds"))
    

    另一种方式

    @commands.Cog.listener()
    async def on_ready(self):
        await self.bot.wait_until_ready()
    
        members = [x for x in self.bot.get_all_members()] # Doing this to "flatten" the generator
        total_members = len(members)
    
        await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name = f"{total_members} people | $cmds"))
    

    参考:

    【讨论】:

    • 我尝试了这两种解决方案,但都没有改变机器人的状态。这是因为在我的主 .py 文件中调用主 on_ready 函数之后加载了 cog?
    • 是的,确切地说,如果您在 on_ready 事件上加载扩展,则不会调用 cog 内的事件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2012-09-27
    • 2016-03-06
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多