python - 命令引发异常:AttributeError: 'Context' object has no attribute 'id' discord.py
问题描述
我想使用命令删除 JSON 文件中的公会 ID。
这是我的代码:
@welcome.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def reset(guild):
with open('welcome.json', 'r') as f:
welcome = json.load(f)
welcome.pop(str(guild.id))
with open('welcome.json', 'w',) as f:
json.dump(welcomereset, f, indent=4)
这是错误消息:discord.ext.commands.errors.CommandInvokeError:命令引发异常:AttributeError:'Context'对象没有属性'id'
我怎样才能解决这个问题?
解决方案
@welcome.command() #pass_context is deprecated, every command will always get passes Context as first param.
@commands.has_permissions(administrator=True)
async def reset(ctx: commands.Context): #Just normal typehint for you to easily understand.
with open('welcome.json', 'r') as f:
welcome = json.load(f)
welcome.pop(str(ctx.guild.id)) #ctx.guild -> discord.Guild and than .id for it's id. I would put an if statement to check if the command was even in a guild, so NoneType attribute error won't raise.
with open('welcome.json', 'w',) as f:
json.dump(welcomereset, f, indent=4)
每个命令中的第一个参数是 ctx 或 context 代表 discord.ext.commands.Context 对象,如您所见,它没有 id。如果您试图获取调用命令的公会 ID,则执行 ctx.guild 将返回 Optional[discord.Guild](如果命令是在私人频道中调用的)。如果它不是 None,你可以做 ctx.guild.id,这可能是你想要的。而且您不再需要 pass_context(用于传递 discord.ext.commands.Context btw)。这意味着现在,guild 是您的 Context 对象。
推荐阅读
- python - 如何切换窗口保持在顶部提示
- bash - 多个配对文件的 for 循环
- android - 使用列表适配器向回收站视图提交一个全新的列表会导致闪烁/滞后的动画
- django - 表单中的 CreateWithInlinesView 验证
- javascript - 为什么我收到错误 data.findIndex is not a function in React with Redux 项目?
- python - Blit 功能不起作用,循环会很快吗?
- reactjs - 组件隐藏时的响应式网格布局空块
- php - 更改 HTML GET 属性格式
- javascript - 通过键合并对象并创建新的键名
- string - 如何用大写字母分隔字符串?