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

如何让discord.py开发的Discord机器人自动删除发送的@角色消息?

解决discord.py机器人删除自身提醒消息的问题

问题出在你调用的message.delete()操作的是触发事件的用户消息对象,而非机器人自己发送的提醒消息。要删除机器人发出的那条@消息,你需要保存机器人发送消息时返回的消息对象,再对这个对象执行删除操作。

具体实现步骤

  • 发送提醒消息时,将返回的消息实例保存到变量中
  • 对这个保存的消息实例调用delete()方法(可按需添加延迟,让用户短暂看到提醒)

完整代码示例

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True  # 需开启message_content权限
client = commands.Bot(command_prefix="!", intents=intents)

TARGET_CHANNEL_ID = 1234567890  # 替换为你的目标频道ID
TARGET_ROLE_ID = 9876543210     # 替换为你的目标角色ID

@client.event
async def on_message(message):
    # 忽略机器人自身的消息,避免触发循环
    if message.author.bot:
        return
    
    # 判断消息是否来自目标频道
    if message.channel.id == TARGET_CHANNEL_ID:
        target_role = message.guild.get_role(TARGET_ROLE_ID)
        # 发送提醒消息并保存消息对象
        reminder_msg = await message.channel.send(f"{target_role.mention} 频道有新消息!")
        # 删除机器人发送的提醒消息,这里设置1秒延迟(可根据需求调整)
        await reminder_msg.delete(delay=1)
    
    # 必须调用此方法,否则机器人的其他命令会失效
    await client.process_commands(message)

client.run("YOUR_BOT_TOKEN")  # 替换为你的机器人Token

注意事项

  • 确保机器人拥有管理消息的频道权限,否则无法执行删除操作
  • 如果不需要延迟,直接使用await reminder_msg.delete()即可,但可能导致用户完全看不到提醒
  • 务必添加if message.author.bot: return,防止机器人处理自身发送的消息引发无限循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:14:54