Search code examples
pythondiscorddiscord.pypycord

How to get all the servers and channels the bot is in


I want to know how to access all servers and channels the bot is in for a /info page.

The following is an example:

Example of info command

What I've tried:

  • Something somebody gave me on a coding discord server that didn't work.

Solution

  • Code

    @commands.slash_command(name="botinfo", description="Get bot info!")
    async def botinfo(self, ctx):
        amount = 0
        bot_channels = 0
        members = 0
        for i in self.bot.guilds:
            amount += 1
            bot_channels += len(i.channels)
            members += i.member_count
        embed = discord.Embed(
            title="Bot Info",
            description=f"I'm in {amount} servers! \n I'm in {bot_channels} channels! \n There are {members} members that can use my commands!",
            color=discord.Color.random()
        )
        await ctx.respond(embed=embed)
    

    How this works:

    bot is the bot instanced at the beginning of most pycord files with bot = discord.Bot()

    To get the amount of guilds:

    1. bot has the built-in attribute guilds that has a list of guilds.
    2. By looping through the list (or using len(bot.guilds) both work)

    To get all channels:

    1. You can use i.channels (i is the iterator for iterating over the guilds). (Docs)
    2. Use len() to get the length of that attribute.

    To get the member count:

    DANGER DO NOT ITERATE OVER ALL guild.members (It's just slow)

    1. Just use guild.member_count. (Docs)