You need to enable JavaScript to run this app. 如何优化MissingPermissions命令处理程序的输出格式
优惠活动
大模型
产品
解决方案
定价
更多

如何优化MissingPermissions命令处理程序的输出格式

解决方案

输出中的方括号和引号是error.missing_perms为列表类型导致的:直接将列表嵌入格式化字符串时,会调用列表默认的字符串转换方法,自动带上列表的方括号与元素两侧的单引号。

你可以使用join()方法将列表中的权限名拼接为普通字符串,同时可适配多权限同时缺失的场景。
如果需要使用中文提示,修改后的代码如下:

@commands.Cog.listener()
async def on_command_error(self, ctx, error):
  if isinstance(error, commands.MissingPermissions):
    # 用逗号加空格拼接所有缺失的权限
    missing_perms = ', '.join(error.missing_perms)
    await ctx.send(f"{ctx.author.mention},抱歉,你没有权限执行该操作!`所需权限:{missing_perms}`")

如果需要保留原英文提示,仅修改权限拼接逻辑即可:

@commands.Cog.listener()
async def on_command_error(self, ctx, error):
  if isinstance(error, commands.MissingPermissions):
    missing_perms = ', '.join(error.missing_perms)
    await ctx.send(f"{ctx.author.mention}, Sorry, you do not have permission to do this! `Required Permission: {missing_perms}`")

效果说明

  • 单权限缺失时英文版本输出为:@member, Sorry, you do not have permission to do this! Required Permission: manage_roles
  • 多权限缺失时会自动用逗号分隔,例如同时缺失角色管理和踢出成员权限时,输出为:@member, Sorry, you do not have permission to do this! Required Permission: manage_roles, kick_members

内容的提问来源于stack exchange,提问作者ColeTMK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 08:54:08