server.get_channel()返回None引发AttributeError的Discord Bot问题排查
问题描述
我在制作带按钮的Embed,点击按钮后会创建频道,同时Bot会给我发送Embed私信,但调用server.get_channel(channel_id)时触发错误:'NoneType' object has no attribute 'send'。
我的代码:
try: server = await bot.fetch_guild(server_id) channel = server.get_channel(channel_id) view = View() except Exception as e: print(f"Error: {e}") else: embed.set_author(name=server.name, icon_url=server.icon.url) await interaction.response.defer() await channel.send(embed=embed, view=view)
调试代码:
print(channel) print(channel.id)
调试输出:
None129 129xxxxxxxxxxxx6
备注:我使用interaction.response.defer()处理命令,因为该命令存在发送延迟。
解决方案
问题根源
从调试输出能看到channel是None,说明server.get_channel(channel_id)未找到对应频道,常见原因有:
- Bot没有目标服务器的查看频道权限,无法获取频道对象
channel_id对应的频道已被删除或不存在于目标服务器fetch_guild返回的公会对象是"部分对象",未缓存频道数据,get_channel无法从本地缓存中读取频道信息
修复步骤
检查Bot权限
确保Bot在目标服务器中拥有查看频道权限,且该权限覆盖了目标频道。替换频道获取方式
将server.get_channel(channel_id)替换为await server.fetch_channel(channel_id),fetch_channel会直接向Discord API请求频道数据,不受本地缓存限制,能更可靠地获取频道对象:
try: server = await bot.fetch_guild(server_id) # 改用fetch_channel主动请求频道数据 channel = await server.fetch_channel(channel_id) view = View() except Exception as e: print(f"Error: {e}") else: embed.set_author(name=server.name, icon_url=server.icon.url) await interaction.response.defer() await channel.send(embed=embed, view=view)
- 验证channel_id正确性
确认channel_id无拼写错误,且对应的频道确实存在于目标服务器内。
内容的提问来源于stack exchange,提问作者deverphz
相关产品推荐
相关产品推荐

