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

Discord.js V14调用client.ws.ping报TypeError错误求助

Discord.js V14 Ping命令报错:TypeError: Cannot read properties of undefined (reading 'ws')

问题原因

你遇到的错误有两个核心原因:

  1. client参数未正确传递:execute函数中的client为undefined,导致无法读取client.ws.ping
  2. 未定义的message变量:代码中使用了未声明的message对象,会引发额外错误

修复步骤

1. 确保主文件正确传递client参数

在你的main.js处理交互事件的代码中,调用命令的execute方法时,必须将client作为第二个参数传入:

// main.js 中的交互处理逻辑
client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  const command = client.commands.get(interaction.commandName);
  if (!command) return;

  try {
    // 关键:传递client参数
    await command.execute(interaction, client);
  } catch (error) {
    console.error(error);
    await interaction.reply({ content: '执行命令时发生错误!', ephemeral: true });
  }
});

2. 修复Ping命令中的变量错误

Slash命令没有message对象,改用Date.now()计算Bot的响应延迟,同时优化模块引入路径:

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('返回机器人的延迟信息!'),
    async execute(interaction, client) {
        const botPing = Date.now() - interaction.createdTimestamp;
        await interaction.reply({ 
          content: `Pong! API延迟: ${client.ws.ping}ms,Bot响应延迟: ${botPing}ms。`,
          ephemeral: false
        });
    },
};

说明

  • client.ws.ping:获取Discord API的WebSocket连接延迟
  • Date.now() - interaction.createdTimestamp:计算从用户发起交互到机器人回复的时间差,即Bot的响应延迟

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:00:57