You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py如何获取机器人所在的成员数量最多的服务器

discord.py 实现获取机器人加入的成员数最多的服务器

前置要求

首先确保你已经在Discord开发者平台的机器人设置页,开启了Privileged Gateway Intents下的Server Members Intent权限,同时代码中初始化机器人时要开启对应的intent,否则无法正确获取服务器成员数。

核心逻辑

  • 通过bot.guilds获取机器人已加入的所有服务器(Guild)对象列表
  • 使用Python内置的max()函数,指定key为每个Guild对象的member_count属性,直接筛选出成员数最高的服务器

代码示例

基础实现

import discord
from discord.ext import commands

# 配置权限
intents = discord.Intents.default()
intents.guilds = True
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

# 示例命令:触发后返回最大服务器信息
@bot.command(name="查最大服务器")
async def show_largest_guild(ctx):
    # 筛选最大成员服务器
    largest_guild = max(bot.guilds, key=lambda guild: guild.member_count)
    # 格式化返回信息
    await ctx.send(
        f"成员最多的服务器:{largest_guild.name}\n"
        f"成员数量:{largest_guild.member_count}\n"
        f"服务器ID:{largest_guild.id}"
    )

bot.run("你的机器人Token")

异常兼容优化

针对机器人未加入任何服务器的场景做兼容,避免max()函数报错:

@bot.command(name="查最大服务器")
async def show_largest_guild(ctx):
    if len(bot.guilds) == 0:
        await ctx.send("当前机器人未加入任何服务器")
        return
    largest_guild = max(bot.guilds, key=lambda guild: guild.member_count)
    await ctx.send(
        f"成员最多的服务器:{largest_guild.name}\n"
        f"成员数量:{largest_guild.member_count}"
    )

内容的提问来源于stack exchange,提问作者Phoenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 17:15:02