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

Python 3 Discord机器人类型错误(缺少注解)修复咨询

解决Discord机器人kick命令的类型注解错误

问题根源

你遇到的TypeError: parameter 'reason' is missing a type annotation,是因为discord.py的app_commands要求所有命令参数必须显式添加类型注解——哪怕参数已经设置了默认值,也不能省略类型标注。你当前只给reason设了默认值'None',但没标注它的类型是str,导致库无法识别参数类型,触发错误。

修复步骤

1. 给reason参数添加类型注解

修改kick命令的参数定义,明确标注reason的类型为str:

@app_commands.command(name='kick', description='Kicks the member of your choice if you have kick permissions.')
@app_commands.has_permissions(kick_members=True)  # 注意:app_commands要用对应框架的权限装饰器,不要混用旧版commands的
async def kick(interaction: discord.Interaction, member: discord.Member, *, reason: str = 'None'):
    await interaction.response.send_message(f'User {member} has been kicked.')
    await member.kick(reason=reason)

2. 修正错误处理的异常类型

你当前用的commands.MissingPermissions是旧版commands框架的异常类,app_commands对应的权限缺失异常是app_commands.MissingPermissions,同步修改错误处理函数:

@kick.error
async def kick_error(interaction: discord.Interaction, error):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message('You don\'t have permission to kick people!')

额外提示

  • 你之前添加的-> str是函数返回值的类型注解,但这个异步命令没有返回值(实际返回None),所以这个注解完全多余,直接去掉就行。
  • 注意不要混用discord.ext.commands和discord.app_commands的API,两者的装饰器、异常类都不通用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:16:14