如何用Python的Discord Bot获取语音频道用户数及用户名?
解决Discord Bot获取语音频道用户数量及用户名的问题
先拆解你遇到的两个代码问题:
- 第一段代码是属性名大小写错误:Discord.py中成员对象的语音频道属性是小写的
voice.channel,并非大写的VoiceChannel。 - 第二段代码缺少前置判断:如果调用命令的用户当前不在任何语音频道,
ctx.message.author.voice会返回None,此时访问.channel必然触发NoneType错误。
以下是可直接运行的完整实现方案,包含错误处理和功能逻辑:
from discord.ext import commands import discord bot = commands.Bot(intents=discord.Intents.all(), command_prefix="/") @bot.command() async def teamup(ctx): # 检查用户是否在语音频道内 if not ctx.author.voice: await ctx.send("你当前不在任何语音频道里!") return # 获取用户所在的语音频道 voice_channel = ctx.author.voice.channel # 获取频道内所有成员 channel_members = voice_channel.members # 统计用户数量 member_count = len(channel_members) # 提取所有成员的用户名 member_names = [member.name for member in channel_members] # 发送结果到文本频道 await ctx.send(f"当前语音频道共有 {member_count} 位用户:") await ctx.send("\n".join(member_names)) # 替换为你的Bot Token后运行 bot.run("YOUR_BOT_TOKEN_HERE")
关键细节说明:
voice_channel.members可直接获取该语音频道内的所有成员对象,无需遍历整个服务器成员。- 必须先判断
ctx.author.voice是否存在,避免用户未加入语音时抛出属性错误。 - 确保在Discord开发者后台的Bot设置中,已开启Server Members Intent和Voice States Intent(代码中
Intents.all()已包含,但后台权限需手动确认启用,否则无法正常获取成员数据)。
内容的提问来源于stack exchange,提问作者arthur moiret
相关产品推荐
相关产品推荐

