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

如何通过disnake实现Discord消息删除:含反应消息及特定角色触发

1. 如何通过disnake库删除带有反应的Discord消息?

删除带反应的消息核心是调用message.delete()方法,前提是机器人拥有对应频道的Manage Messages权限,反应本身不影响删除操作,分两种场景处理:

  • 单条目标消息删除:
    如果你已经获取到目标Message对象,直接执行删除即可:
# msg为目标消息对象
await msg.delete()
  • 批量删除带特定反应的消息:
    遍历频道消息,检查消息是否包含指定反应,符合条件则删除:
# 遍历指定频道最近100条消息
async for msg in channel.history(limit=100):
    # 检查是否有😀表情的反应
    for reaction in msg.reactions:
        if reaction.emoji == "😀":
            await msg.delete()
            break
2. 如何实现管理员反应后自动删除消息?

需要监听消息反应添加事件,校验用户角色后执行删除,步骤如下:

前置准备

  1. 确保机器人拥有频道的Manage Messages权限;
  2. 在Discord开发者后台的Bot页面开启Message Content Intent和Guild Message Reactions Intent。

核心代码实现

import disnake
from disnake.ext import commands

# 配置必要的意图
intents = disnake.Intents.default()
intents.message_content = True
intents.guild_reactions = True

bot = commands.Bot(command_prefix="!", intents=intents)

# 替换为你的管理员角色ID
ADMIN_ROLE_ID = 123456789012345678

@bot.event
async def on_reaction_add(reaction, user):
    # 忽略机器人自身的反应
    if user.bot:
        return
    
    # 获取用户的服务器成员对象
    member = reaction.message.guild.get_member(user.id)
    if not member:
        return
    
    # 检查用户是否拥有管理员角色
    if any(role.id == ADMIN_ROLE_ID for role in member.roles):
        await reaction.message.delete()
        return
    
    # 可选:仅允许特定表情触发删除
    # if reaction.emoji == "🗑️" and any(role.id == ADMIN_ROLE_ID for role in member.roles):
    #     await reaction.message.delete()

# 运行机器人,替换为你的TOKEN
bot.run("YOUR_BOT_TOKEN")

补充说明

  • 角色ID可在Discord开启开发者模式后,右键角色复制;
  • 也可通过角色名称校验(注意大小写敏感),替换角色ID判断为:
if any(role.name == "admin" for role in member.roles):

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:22:54