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

discord.py指定成员删除特定用户消息功能报错求助

解决Discord Bot中AttributeError: 'coroutine' object has no attribute 'author'错误

错误根源

你代码里的channel.fetch_message(message)是异步方法,调用时未添加await关键字,导致message2拿到的是协程对象(coroutine)而非真正的Discord Message实例,因此无法访问author属性。

修正后的代码

async def deletemessage(interaction: discord.Interaction, message_id: str):
    # 仅允许特定用户执行命令
    if interaction.user.id != userid1:
        await interaction.response.send_message("你没有权限执行这个命令", ephemeral=True)
        return
    
    try:
        # 将字符串类型的消息ID转为整数
        msg_id = int(message_id)
        # 异步获取目标消息
        target_msg = await interaction.channel.fetch_message(msg_id)
        
        # 检查消息是否属于指定用户
        if target_msg.author.id == userid2:
            await target_msg.delete()
            await interaction.response.send_message("已删除目标消息", ephemeral=True)
        else:
            await interaction.response.send_message("该消息不属于指定用户", ephemeral=True)
    except ValueError:
        await interaction.response.send_message("请输入有效的消息ID", ephemeral=True)
    except discord.NotFound:
        await interaction.response.send_message("未找到该消息", ephemeral=True)
    except discord.Forbidden:
        await interaction.response.send_message("我没有权限删除这条消息", ephemeral=True)
    except Exception as e:
        await interaction.response.send_message(f"执行出错: {str(e)}", ephemeral=True)

关键修改说明

  • 给fetch_message添加await,确保获取到真实的Message对象
  • 将命令参数重命名为message_id(语义更清晰),并转为整数类型(Discord消息ID为整数)
  • 提前校验命令执行者权限,不符合条件直接返回,避免无效操作
  • 增加异常捕获,处理消息ID无效、消息不存在、无权限删除等常见场景
  • 使用ephemeral=True让回复仅执行者可见,避免频道刷屏

额外注意事项

  • 替换代码中的userid1和userid2为实际的用户ID(整数类型,非字符串)
  • 确保Bot拥有管理消息或删除消息的频道权限
  • 消息ID可通过右键点击消息(需开启开发者模式)复制获取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:57:52