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

Discord.py实现双参数DM斜杠命令报错求助

解决discord.py斜杠命令的类型注解错误

错误原因

你把参数user的类型注解语法用错了:Python中类型注解是用参数名: 类型的格式,而你写成了user = discord.Member——这是给参数设置默认值的语法,不是类型注解,导致discord.py无法识别user的参数类型,因此抛出了missing a type annotation错误。

修复后的完整代码

@tree.command(guild=discord.Object(id=guild_id), name='userping', description='DM the user to come back to the ticket')
@app_commands.describe(user="The user you want the DM to be sent to", reason="The reason to ping this user")
@app_commands.default_permissions(manage_channels=True)
@app_commands.checks.cooldown(3, 20, key=lambda i: (i.guild_id, i.user.id))
@app_commands.checks.bot_has_permissions(manage_channels=True)
async def userping(interaction: discord.Interaction, user: discord.Member, reason: str):
    # 检查是否在ticket频道
    if "ticket-for-" not in interaction.channel.name:
        await interaction.response.send_message("This isn't a ticket!", ephemeral=True)
        return
    
    # 尝试发送DM并处理异常
    try:
        await user.send(f"You've been pinged regarding your ticket: {reason}")
        await interaction.response.send_message(f"Successfully sent DM to {user.mention}!", ephemeral=True)
    except discord.Forbidden:
        await interaction.response.send_message(f"Failed to send DM to {user.mention} (user has DMs disabled or blocked the bot)", ephemeral=True)

关键修改点

  1. 修正类型注解:将user = discord.Member改为user: discord.Member,明确参数类型为discord.Member
  2. 优化参数顺序:把user参数移到reason前,贴合/dm @user 内容的使用逻辑,让用户先选择成员再输入理由
  3. 补充核心功能:添加了DM发送逻辑,同时处理发送失败的情况(比如用户关闭DM或屏蔽机器人)
  4. 简化判断逻辑:用not in直接返回提示,减少冗余代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:55:10