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

Discord.js 命令加载异常与.sping无响应问题排查求助

解决Discord.js机器人命令无响应与启动日志顺序问题

嘿,我看到你在迁移Discord v11机器人到新版本时遇到了两个头疼的问题,咱们一步步来解决它们:

问题1:.sping命令无响应,仅输出"Prefix"和"Cmd"

这个问题的核心是你没有正确获取对应的命令对象,还有一处参数传递的小错误:

错误点分析

在message事件处理中,你写了:

var cmd = Bot.commands.get();

Collection.get()方法需要传入要获取的键名(也就是你的命令名称,比如ping),但你这里没有传任何参数,所以cmd永远是undefined,自然不会执行命令逻辑。

另外,你在调用命令的run方法时,参数顺序也错了:

cmd.run(Bot, msg, args);

你的ping.js里run方法的第二个参数是message(Discord的Message对象),但你传了msg(一个字符串数组),这会导致message.channel.send报错。

修复代码

修改message事件的处理逻辑:

Bot.on("message", message => {
  // 先忽略机器人自己发的消息和私聊(可选,根据需求调整)
  if (message.author.bot || !message.guild) return;
  
  const msgl = message.content.toLowerCase();
  if (!message.content.startsWith(prefix)) return;
  
  // 处理消息:去掉前缀,修剪空格,按任意数量空格分割
  const msgParts = message.content.slice(prefix.length).trim().split(/\s+/);
  const cmdName = msgParts[0];
  const args = msgParts.slice(1);

  console.log("Prefix detected");
  // 传入命令名称获取命令对象
  const cmd = Bot.commands.get(cmdName);
  console.log(`Attempting command: ${cmdName}`);
  
  if (cmd) {
    console.log("Running command");
    try {
      // 传递正确的参数:Bot实例、Message对象、参数数组
      cmd.run(Bot, message, args);
      console.log("Command executed");
    } catch (err) {
      console.error("Command error:", err);
      message.reply("Oops, something went wrong running that command!");
    }
  } else {
    console.log(`Command ${cmdName} not found`);
    // 可选:提示用户未知命令
    // message.reply(`Sorry, I don't recognize the command \`${cmdName}\``);
  }
});

问题2:"Ready!"日志在命令加载前输出

这是因为fs.readdir是异步函数,它不会等待命令加载完成就继续执行后面的代码,所以console.log("Ready!")会先被触发。

修复代码

把"Ready!"的输出移到fs.readdir的回调里,等所有命令加载完成后再打印:

Bot.on("ready", () => {
  fs.readdir("./commands/", (err, files) => {
    if (err) return console.error(err);
    
    const jsfiles = files.filter(f => f.split(".").pop() === "js");
    if (jsfiles.length <= 0) {
      console.log("No commands found..");
      console.log("Ready!");
      return;
    }

    console.log(`${jsfiles.length} commands found.`);
    jsfiles.forEach((f, i) => {
      const cmds = require(`./commands/${f}`);
      console.log(`Command ${f} loading..`);
      Bot.commands.set(cmds.config.command, cmds);
      
      // 当循环到最后一个命令时,输出Ready
      if (i === jsfiles.length - 1) {
        console.log("Ready!");
      }
    });
  });
});

完整验证后的代码

修正后的index.js

const Discord = require("discord.js");
const fs = require("fs");
const Bot = new Discord.Client();
const config = require("./config.json");
Bot.commands = new Discord.Collection();
const prefix = ".s"; // 用const更安全,因为前缀不会动态改变

console.log("Sentry's Token Is " + config.token);
Bot.login(config.token);

Bot.on("ready", () => {
  fs.readdir("./commands/", (err, files) => {
    if (err) return console.error(err);
    
    const jsfiles = files.filter(f => f.split(".").pop() === "js");
    if (jsfiles.length <= 0) {
      console.log("No commands found..");
      console.log("Ready!");
      return;
    }

    console.log(`${jsfiles.length} commands found.`);
    jsfiles.forEach((f, i) => {
      const cmds = require(`./commands/${f}`);
      console.log(`Command ${f} loading..`);
      Bot.commands.set(cmds.config.command, cmds);
      
      if (i === jsfiles.length - 1) {
        console.log("Ready!");
      }
    });
  });
});

Bot.on("message", message => {
  if (message.author.bot || !message.guild) return;
  
  if (!message.content.startsWith(prefix)) return;
  
  const msgParts = message.content.slice(prefix.length).trim().split(/\s+/);
  const cmdName = msgParts[0];
  const args = msgParts.slice(1);

  console.log("Prefix detected");
  const cmd = Bot.commands.get(cmdName);
  console.log(`Attempting command: ${cmdName}`);
  
  if (cmd) {
    console.log("Running command");
    try {
      cmd.run(Bot, message, args);
      console.log("Command executed successfully");
    } catch (error) {
      console.error("Error running command:", error);
      message.reply("There was an error executing that command!");
    }
  } else {
    console.log(`Command ${cmdName} not found`);
  }
});

ping.js(无需大改,确认参数顺序即可)

module.exports.run = async (Bot, message, args) => {
  console.log("Ping! Pong!");
  await message.channel.send({ 
    embed: { 
      title: "Ping!", 
      description: "Pong!", 
      color: 0x17a589 
    } 
  });
  console.log("Ping message sent");
};

module.exports.config = { 
  command: "ping" 
};

测试效果

  1. 启动机器人后,终端会先输出命令加载的日志,最后打印Ready!
  2. 在Discord发送.sping(前缀.s + 命令ping),机器人会回复嵌入的"Ping! Pong!"消息,终端也会输出对应的执行日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:22:32