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

如何在Discord.js机器人中实现!前缀命令(默认已用SlashCommand)

在Discord.js中添加!前缀命令(兼容已有的Slash命令)

核心思路

前缀命令基于messageCreate事件监听用户消息,判断消息开头是否匹配指定前缀后,解析命令与参数执行对应逻辑,和已有的Slash命令完全独立,不会互相干扰。

具体实现步骤

1. 基础实现:直接在主文件添加事件监听

在机器人主文件(如index.js)中添加消息监听逻辑,快速实现前缀命令:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent // 必须开启此意图才能读取消息内容
  ]
});

// 监听用户消息
client.on('messageCreate', async (message) => {
  // 跳过机器人自身发送的消息,避免循环触发
  if (message.author.bot) return;
  
  // 定义你的命令前缀
  const prefix = '!';
  
  // 判断消息是否以指定前缀开头
  if (!message.content.startsWith(prefix)) return;
  
  // 拆分命令名称和参数
  const commandBody = message.content.slice(prefix.length);
  const args = commandBody.split(/ +/);
  const commandName = args.shift().toLowerCase();
  
  // 处理具体命令
  switch (commandName) {
    case 'ping':
      await message.reply(`Pong! 延迟:${client.ws.ping}ms`);
      break;
    case 'say':
      if (!args.length) return message.reply('请输入要重复的内容!');
      await message.reply(args.join(' '));
      break;
    // 在这里添加更多命令
    default:
      await message.reply('未知命令,请检查输入!');
  }
});

// 登录机器人
client.login('你的机器人Token');

2. 进阶优化:用集合管理命令(适合多场景)

如果命令数量较多,建议将命令拆分到独立文件,用集合统一管理,提升可维护性:

第一步:初始化命令集合

在主文件中创建集合并加载所有前缀命令:

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

// 创建命令集合
client.prefixCommands = new Collection();

// 加载prefix目录下的所有命令文件
const prefixCommandFiles = fs.readdirSync('./commands/prefix').filter(file => file.endsWith('.js'));
for (const file of prefixCommandFiles) {
  const command = require(`./commands/prefix/${file}`);
  client.prefixCommands.set(command.name, command);
}

第二步:创建单个命令文件

在./commands/prefix目录下创建命令文件,比如ping.js:

module.exports = {
  name: 'ping',
  description: '返回机器人延迟',
  async execute(message, args) {
    await message.reply(`Pong! 延迟:${message.client.ws.ping}ms`);
  }
};

第三步:修改消息监听逻辑

client.on('messageCreate', async (message) => {
  if (message.author.bot) return;
  const prefix = '!';
  if (!message.content.startsWith(prefix)) return;
  
  const commandBody = message.content.slice(prefix.length);
  const args = commandBody.split(/ +/);
  const commandName = args.shift().toLowerCase();
  
  const command = client.prefixCommands.get(commandName);
  if (!command) return message.reply('未知命令!');
  
  // 捕获命令执行错误
  try {
    await command.execute(message, args);
  } catch (error) {
    console.error(error);
    await message.reply('执行命令时出现错误,请稍后再试!');
  }
});

3. 关键注意事项

  • 开启MessageContent意图:在Discord开发者门户的机器人设置中,找到「Privileged Gateway Intents」,开启「Message Content Intent」,同时在代码的intents数组中添加对应配置,否则机器人无法读取消息内容。
  • 权限配置:确保机器人在目标服务器拥有「发送消息」「读取消息历史」等必要权限。
  • 前缀冲突:尽量选择独特的前缀,避免与服务器内其他机器人的前缀重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:54:26