Discord.js v14中TypeError: Cannot read properties of undefined(reading 'reply')求助
解决Discord机器人Ping命令的两个TypeError错误
错误现象
开发Discord机器人时,编写ping命令遇到两个连续错误:
- 调用
client.ws.ping时出现:TypeError: Cannot read properties of undefined (reading 'ws') - 修正后又出现:
TypeError: Cannot read properties of undefined (reading 'reply')
核心原因
命令执行函数的参数不匹配:
ping.js的execute函数定义为async execute(client, interaction),但主文件mortis.js调用时只传入了interaction(await command.execute(interaction);)。- 这导致函数内的
client变量实际是传入的interaction对象,而interaction变量变成undefined:- 调用
interaction.reply()时,因interaction为undefined触发第二个错误; - 调用
client.ws.ping时,实际是访问interaction.ws(Interaction对象无ws属性),触发第一个错误。
- 调用
- 额外问题:主文件同时绑定了两次
InteractionCreate事件(直接编写的逻辑 + events文件夹加载的interactionCreate.js),导致事件触发两次,加重错误。
解决方法
方案1:修正ping.js的参数与client获取方式(推荐)
无需单独传递client,直接通过interaction.client获取客户端实例,符合discord.js最佳实践:
const { SlashCommandBuilder } = require('@discordjs/builders'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('Display the latency'), async execute(interaction) { const apiLatency = interaction.client.ws.ping; await interaction.reply(`Latency is ${Date.now() - interaction.createdTimestamp}ms. API Latency is ${apiLatency}ms`); }, };
方案2:修改主文件的调用逻辑
如果要保留ping.js的参数定义,需在mortis.js的事件处理中同时传入client和interaction:
// 替换mortis.js中InteractionCreate事件内的调用代码 try { await command.execute(client, interaction); } catch (error) { console.error(error); await interaction.reply({ content: '执行命令时出错!', ephemeral: true }); }
额外修复:移除重复的事件绑定
删除mortis.js中直接编写的InteractionCreate事件处理逻辑,只保留events文件夹中的事件文件,避免事件重复触发。
内容的提问来源于stack exchange,提问作者Androser
相关产品推荐
相关产品推荐

