You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在f-string中引用函数参数?Discord.py MissingRole错误时获取指定角色

问题解答

1. 如何在f-string中引用函数的参数?

其实超简单的,你直接在f-string的{}里写函数参数的变量名就行,和你在函数里使用其他变量的方式完全一样。举个直观的例子:

def calculate_area(length, width):
    return f"这个矩形的长是{length},宽是{width},面积是{length * width}。"

print(calculate_area(5, 3))

要是参数是个对象,还能直接调用它的属性或者方法,比如:

def show_user_info(user):
    return f"用户昵称:{user.nickname},账号创建于{user.joined_at.date()}。"

2. Discord命令错误处理中获取缺失的角色名

你只需要写error.missing_role就能拿到has_role()里指定的角色名称啦!commands.MissingRole这个错误对象本身就带了这个属性,专门用来存储缺失的角色信息。

修改后的错误处理代码如下:

@clear.error
async def mr4c(ctx, error):
    if isinstance(error, commands.MissingRole):
        mr4cembed=discord.Embed(title='ERROR...', description=f"You do not have the required permission to execute this command!", color=discord.Colour.blue())
        # 这里替换成error.missing_role就可以获取角色名了
        mr4cembed.set_footer(text=f'You need the {error.missing_role} role to proceed.')
        await ctx.send(embed=mr4cembed)

这样当用户触发MissingRole错误时,消息的footer就会正确显示需要的角色名称了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:12:57