You need to enable JavaScript to run this app. Discord.py实现Embed指令执行后自动删除用户触发指令消息
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py实现Embed指令执行后自动删除用户触发指令消息

自动删除指令触发消息的实现方案

要实现「用户发送?ra1触发指令后,自动清理这条触发消息」的需求,直接依托discord.py的内置上下文对象就能完成,无需额外引入组件。

实现逻辑

  • 指令对象ctx关联了完整的触发场景数据,其中ctx.message就是用户发送的?ra1原始消息,直接调用该消息的异步删除方法即可完成自动清理。
  • 前置要求:机器人需要在对应频道拥有管理消息权限,否则删除操作会触发权限报错。

基础版本修改代码

在原有指令函数最开头插入删除触发消息的代码即可:

@client.command()
async def ra1(ctx):
    # 自动删除用户发送的触发指令消息
    await ctx.message.delete()

    embed = discord.Embed(
        colour=discord.Colour.blue(),
        title="RIDEALONG 1 REQUEST",
        description=str(ctx.author.mention) + " IS REQUESTING THEIR FIRST RIDEALONG IN SERVER !"
    )
    embed.add_field(name="For CDTOs", value="Please message the user to accept their RA request. Please delete their message once the ridealong has been completed.", inline=False)
    embed.timestamp = datetime.utcnow()
    await ctx.send(embed=embed, delete_after=7200)

容错优化版本

为了避免权限不足导致整条指令流程中断,可以给删除操作加上异常捕获,保证后续Embed消息可以正常发送:

@client.command()
async def ra1(ctx):
    # 尝试删除触发消息,遇到权限不足时静默跳过,不影响后续逻辑
    try:
        await ctx.message.delete()
    except discord.Forbidden:
        pass

    embed = discord.Embed(
        colour=discord.Colour.blue(),
        title="RIDEALONG 1 REQUEST",
        description=str(ctx.author.mention) + " IS REQUESTING THEIR FIRST RIDEALONG IN SERVER !"
    )
    embed.add_field(name="For CDTOs", value="Please message the user to accept their RA request. Please delete their message once the ridealong has been completed.", inline=False)
    embed.timestamp = datetime.utcnow()
    await ctx.send(embed=embed, delete_after=7200)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 20:54:04