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

Discord.js开发机器人ping命令触发Cannot read properties报错求解

错误根因分析

  • 第一个报错TypeError: Cannot read properties of undefined (reading 'createdTimestamp'):你使用斜杠命令触发ping时,index.js中缺少interactionCreate事件的斜杠命令执行逻辑,即使你后续补充了调用逻辑,传参顺序和ping.js中execute的参数定义不匹配,导致msg参数接收到的值为undefined。
  • 第二个报错TypeError: Cannot read properties of undefined (reading 'reply'):你使用前缀消息触发ping时,messageCreate.js中调用命令execute仅传入了msg、args、client三个参数,ping.js的execute第四个参数interaction没有被传值,默认为undefined,调用reply方法自然报错。

修复方案

第一步:补全index.js的斜杠命令处理逻辑

替换原有空的interactionCreate监听逻辑:

client.on("interactionCreate", async (interaction) => {
  // 只处理斜杠命令
  if (!interaction.isChatInputCommand()) return;
  const command = client.commands.get(interaction.commandName);
  if (!command) return;
  try {
    // 斜杠命令没有msg和args参数,前两位传null,最后一位传入interaction
    await command.execute(null, null, client, interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "Error: Please check console for error(s)",
      ephemeral: true,
    });
  }
});

第二步:修改ping.js的执行逻辑,兼容两种触发方式

调整execute内的判断逻辑,根据触发来源取对应参数:

const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageEmbed } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Replies to ping with pong"),
  async execute(msg, args, client, interaction) {
    let latency, replyTarget;
    // 前缀消息触发场景
    if (msg) {
      latency = Date.now() - msg.createdTimestamp;
      replyTarget = msg;
    // 斜杠命令触发场景
    } else if (interaction) {
      latency = Date.now() - interaction.createdTimestamp;
      replyTarget = interaction;
    } else {
      return;
    }
    const embed = new MessageEmbed()
      .setColor("#0099ff")
      .setTitle("🏓 Pong!")
      .setDescription(
        `Latency is ${latency}ms. API Latency is ${Math.round(client.ws.ping)}ms`
      )
      .setTimestamp();
    await replyTarget.reply({
      embeds: [embed],
      ephemeral: true,
    });
  },
};

可选优化

如果你不需要同时支持前缀消息命令和斜杠命令,建议统一使用一种触发方式,直接调整参数顺序和调用逻辑即可,代码会更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:15:05