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

Discord.js机器人如何实现仅指定身份组成员可触发指令功能

Discord.js 机器人功能实现方案

版本兼容说明

  • 以下代码适配 Discord.js v14+ 版本,旧版本需调整对应API调用
  • 操作前请先复制3个备用参数:request role身份组ID、接收身份组申请的频道ID、机器人Token

完整可运行代码

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

// 替换为你自己的request role身份组ID
const REQUEST_ROLE_ID = '替换为你的request role身份组ID';
// 替换为接收身份组申请的频道ID
const APPLY_CHANNEL_ID = '替换为接收申请的频道ID';
// 存储申请记录的数组,重启机器人会清空,可自行扩展对接数据库
const roleApplications = [];

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("messageCreate", async msg => {
  // 跳过机器人自己发的消息、私聊消息
  if (msg.author.bot || !msg.guild || !msg.member) return;

  // 身份组校验:无request role直接终止逻辑,不返回任何消息
  if (!msg.member.roles.cache.has(REQUEST_ROLE_ID)) return;

  // 原有ping指令
  if (msg.content === "ping") {
    msg.reply("pong");
  }

  // 新增身份组申请指令,触发格式:!申请 <要申请的身份组名称> <申请理由>
  if (msg.content.startsWith("!申请")) {
    const args = msg.content.split(' ').slice(1);
    if (args.length < 2) {
      return msg.reply('申请格式错误,请按照:!申请 <身份组名称> <申请理由> 提交');
    }
    const applyRoleName = args[0];
    const applyReason = args.slice(1).join(' ');

    // 存储申请记录
    const application = {
      userId: msg.author.id,
      userName: msg.author.tag,
      applyRole: applyRoleName,
      reason: applyReason,
      time: new Date().toLocaleString()
    }
    roleApplications.push(application);

    // 转发申请到指定审核频道
    const applyChannel = await client.channels.fetch(APPLY_CHANNEL_ID);
    if (applyChannel) {
      applyChannel.send(`新身份组申请:
申请人:${msg.author.tag}(ID:${msg.author.id})
申请身份组:${applyRoleName}
申请理由:${applyReason}
申请时间:${application.time}`);
    }

    msg.reply('你的身份组申请已提交,等待管理员审核即可');
  }
})

client.login(process.env.TOKEN)

逻辑说明

  • 无request role的成员发送任何指令时,代码会直接终止运行,不会返回任何响应,符合需求
  • 身份组申请记录默认存在内存数组中,机器人重启后数据会清空,你可以后续学习数据库相关知识后,将存储逻辑替换为MongoDB、MySQL等持久化存储方案
  • 无法提供私人Discord联系方式,相关开发问题可在技术社区搜索或提问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:57:00