在使用 discord.py
库时,如果你发现始终获取到成员数为1,这通常意味着你的代码只获取了当前命令执行者(即调用命令的用户)而不是整个服务器的成员列表。以下是一些基础概念和相关解决方案:
如果你使用的是 ctx.guild.members
,默认情况下可能只获取了部分成员(例如,由于权限限制或缓存问题)。
确保你的Bot有足够的权限来读取服务器的所有成员信息,并且尝试刷新成员缓存。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Bot is ready. Connected to {len(bot.guilds)} guilds.')
@bot.command()
async def membercount(ctx):
guild = ctx.guild
member_count = guild.member_count
await ctx.send(f'The server has {member_count} members.')
bot.run('YOUR_BOT_TOKEN')
Discord API v13及以上版本要求明确启用所需的Intents。
确保在创建Bot实例时启用了 members
Intent。
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
有时Bot可能因为缓存问题而没有获取到最新的成员列表。
尝试手动刷新缓存或等待Discord自动更新缓存。
@bot.command()
async def refresh_members(ctx):
guild = ctx.guild
await guild.chunk() # 强制刷新成员列表
member_count = guild.member_count
await ctx.send(f'Refreshed members. The server has {member_count} members.')
确保你的Bot具有足够的权限,并且正确启用了所需的Intents。通过上述方法,你应该能够正确获取并显示服务器的成员数。如果问题仍然存在,可能需要检查Discord服务器的设置或联系Discord支持以获取进一步的帮助。
没有搜到相关的沙龙