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

Discord JS开发问题:为消息发送者添加角色并设置消息自动删除

实现Discord机器人的Ping-Pong功能(含角色添加与消息自动删除)

以下是修改后的完整代码,已实现你需要的所有功能:

const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({ 
    intents: [ 
        GatewayIntentBits.Guilds, 
        GatewayIntentBits.GuildMessages, 
        GatewayIntentBits.MessageContent, 
        GatewayIntentBits.GuildMembers 
    ] 
});

client.on("ready", () => { 
    console.log("I am ready!"); 
});

client.on("messageCreate", async (message) => { 
    if (message.author.bot) return;
    if (message.content === "ping") { 
        try {
            // 发送回复并保存回复消息对象
            const replyMsg = await message.reply("pong!");

            // 查找服务器内的"Pong"角色
            const pongRole = message.guild.roles.cache.find(role => role.name === "Pong");
            if (!pongRole) {
                console.error("服务器中未找到名为'Pong'的角色");
                return;
            }

            // 为消息发送者添加角色
            await message.member.roles.add(pongRole);
            console.log(`已为用户 ${message.author.tag} 添加Pong角色`);

            // 10秒后自动删除原消息和回复消息
            setTimeout(async () => {
                await message.delete().catch(err => console.error("删除原消息失败:", err));
                await replyMsg.delete().catch(err => console.error("删除回复消息失败:", err));
            }, 10000);
        } catch (err) {
            console.error("执行过程中出现错误:", err);
        }
    } 
});

client.login('MY TOKEN');

核心修改说明

  • 异步操作处理:将messageCreate回调改为async,使用await等待所有异步操作完成,避免因异步时序问题导致的错误。
  • 获取回复消息实例:通过await message.reply()获取回复的消息对象,后续才能对其执行删除操作。
  • 角色查找与校验:通过角色名称查找目标角色,若角色不存在则输出错误日志并终止流程,防止后续代码报错。
  • 角色添加逻辑:调用message.member.roles.add()为用户添加角色,需确保机器人拥有管理角色的服务器权限,否则会触发权限错误。
  • 定时删除消息:使用setTimeout设置10秒延迟,到期后删除原消息和回复消息,同时添加catch捕获删除失败的异常,避免程序崩溃。

注意事项

  1. 确保服务器内已创建名为Pong的角色,否则机器人会在控制台提示角色未找到。
  2. 给机器人分配管理角色权限,否则无法执行添加角色的操作。
  3. 若消息在10秒内被手动删除,删除操作会触发异常,但已被catch捕获,不会影响机器人正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:20:19