discord.py中如何将guild_subscriptions设为true以解决ctx.guild.owner返回None问题
针对
ctx.guild.owner返回None的修复方案 第一步:定位Bot初始化配置
*guild_subscriptions*是discord.Client/commands.Bot初始化时的构造参数,不属于命令逻辑里的运行时参数,因此你在命令代码块里找不到修改入口,需要回到Bot实例创建的代码段调整。
第二步:显式开启guild_subscriptions参数
- 找到项目中创建Bot实例的代码,通常形式为
bot = commands.Bot(...) - 在构造参数中添加
guild_subscriptions=True,参考示例:
import discord from discord.ext import commands intents = discord.Intents.default() # 确保开启匹配命令逻辑的意图配置 intents.message_content = True bot = commands.Bot( command_prefix="!", # 替换为你自己的实际命令前缀 intents=intents, guild_subscriptions=True # 显式开启公会订阅,解决owner取值返回None的问题 )
注意:
- 该参数默认值为True,如果之前的配置中显式把它设为了False,就会关闭公会成员数据的实时拉取权限,客户端仅会缓存公会ID、名称、图标这类基础元数据,不会拉取owner这类和成员身份绑定的信息,最终导致取值返回None。
- 这是Client基类的配置项,在commands扩展的专属文档中没有单独列出,因此很多开发者翻找Bot类的参数时会遗漏这一项,找不到调整入口。
第三步:增加缓存兜底逻辑
如果刚启动Bot、或刚加入新服务器时遇到临时缓存未同步的None问题,可以在原有serverstats命令中增加主动拉取逻辑兜底:
@commands.command(name="serverstats", aliases = ["serverinfo", "si", "ss", "check-stats", 'cs']) async def serverstats(self, ctx: commands.Context): guild = ctx.guild # 检测到owner缓存为空时主动发起网络请求拉取 if guild.owner is None: guild.owner = await guild.fetch_owner() embed = discord.Embed( color = discord.Colour.orange(), title = f"{guild.name}") embed.set_thumbnail(url = f"{guild.icon_url}") embed.add_field(name = "ID", value = f"{guild.id}") embed.add_field(name = "👑Owner", value = f"{guild.owner}") embed.add_field(name = "🌍Region", value = f"{guild.region}") embed.add_field(name = "👥Member Count", value = f"{guild.member_count}") embed.add_field(name = "📆Created at", value = f"{guild.created_at}") embed.set_footer(icon_url = f"{ctx.author.avatar_url}", text = f"Requested by {ctx.author.name}") await ctx.send(embed=embed)
内容的提问来源于stack exchange,提问作者Laurian Hurduza
相关产品推荐
相关产品推荐

