Discord机器人报错AttributeError: 'NoneType' object has no attribute 'members'寻求解决方法
AttributeError: 'NoneType' object has no attribute 'members' in Discord.py Bot
问题描述
我写了一个Discord机器人,想获取指定语音频道的成员ID列表,但运行时一直报错:AttributeError: 'NoneType' object has no attribute 'members'。我的代码如下:
import os import discord from discord.ext.commands import Bot bot = Bot(command_prefix='$') @bot.event async def on_ready(): print('Logged in as ' f'{bot.user}') @bot.command() async def vclist(ctx): channel = bot.get_channel('944509044599697458') userids = [] users = channel.members for member in users: userids.append(member.id) print(userids)
问题分析与解决方法
这个错误的核心原因是bot.get_channel('944509044599697458')返回了None——也就是说机器人找不到你指定的频道,这时候去访问channel.members自然会触发报错。下面是具体的排查和修复步骤:
1. 修正频道ID的类型
Discord.py的get_channel()方法需要接收整数类型的频道ID,但你传入的是带引号的字符串,这会导致机器人无法正确匹配频道,直接返回None。
修复方法:去掉ID的引号,改成整数:
channel = bot.get_channel(944509044599697458)
2. 检查机器人权限
如果机器人没有足够的权限访问目标频道,get_channel()也会返回None。确保你的机器人在目标服务器中拥有以下权限:
- View Channel:允许机器人看到这个频道
- 查看语音状态:允许机器人获取语音频道的成员信息(在服务器设置的机器人权限面板中勾选对应选项)
3. 验证频道ID的正确性
可能你输入的频道ID有误,或者该频道已经被删除。你可以通过开启Discord的开发者模式来获取正确的频道ID:
- 打开Discord设置 → 高级 → 开启“开发者模式”
- 右键目标语音频道 → 选择“复制ID”,把复制到的数字作为参数传入
get_channel()
4. 添加错误处理优化代码
为了避免机器人崩溃,建议在代码中添加判断逻辑,提前处理channel为None的情况,同时验证频道类型是否为语音频道:
@bot.command() async def vclist(ctx): channel_id = 944509044599697458 channel = bot.get_channel(channel_id) # 检查是否找到频道 if not channel: await ctx.send(f"无法找到ID为{channel_id}的频道,请确认ID是否正确!") return # 检查是否是语音频道 if not isinstance(channel, discord.VoiceChannel): await ctx.send("该ID对应的频道不是语音频道,请重新确认!") return # 用列表推导式简化成员ID提取 userids = [member.id for member in channel.members] print(userids) # 可选:把结果发送到Discord频道 await ctx.send(f"当前语音频道的成员ID列表:{userids}")
内容的提问来源于stack exchange,提问作者salami55
相关产品推荐
相关产品推荐

