discord.js V14.15.3中interaction.createdTimestamp未定义报错问题
Discord.js v14.15.3 TypeError: Cannot read properties of undefined (reading 'createdTimestamp') in Ping Slash Command
问题根源
报错的核心是两个问题:execute函数参数顺序写反,导致interaction变量未拿到正确的交互对象;同时代码里用了未定义的wait函数。
1. 参数顺序不匹配
在Discord.js v14的命令体系中,interactionCreate事件触发调用命令execute方法时,默认传参顺序是交互对象(Interaction)在前,客户端实例(Client)在后。但你的代码里把参数顺序写反了:
async execute(client, interaction){ ... }
这会导致interaction变量实际接收到的是客户端实例(甚至可能是undefined),而客户端实例没有createdTimestamp属性,直接触发报错。
2. wait函数未定义
代码里用了await wait(2_000),但没有定义这个函数,就算前面的问题修复,这里也会触发新的报错。
解决方案
1. 修正参数顺序
把execute函数的参数顺序改成(interaction, client),确保拿到正确的交互对象:
async execute(interaction, client){ ... }
2. 替换未定义的wait函数
用Promise封装setTimeout实现等待功能,替换掉await wait(2_000):
await new Promise(resolve => setTimeout(resolve, 2000));
3. 修正Ping计算逻辑
interaction.createdTimestamp - Date.now()会得到负数(因为交互创建时间早于当前时间),改成Date.now() - interaction.createdTimestamp才能得到正确的延迟值。
修复后的完整代码
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('Responds with bot and your ping'), async execute(interaction, client) { const thinking = new EmbedBuilder() .setColor('Red') .setAuthor({ name: 'I am thinking', iconURL: 'https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExcmEydTFmcTAzMGR4dmYzc2pvdnpwdmlpb3FseHpnaDlkbHBybnAxNyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9cw/TNRDoCRLlOqgbtqQh0/giphy.gif' }); const thinked = new EmbedBuilder() .addFields( { name: 'Ping', value: `${Date.now() - interaction.createdTimestamp}ms` }, { name: 'API latency', value: `${Math.round(client.ws.ping)}ms` } ); await interaction.reply({ embeds: [thinking], ephemeral: true }); await new Promise(resolve => setTimeout(resolve, 2000)); await interaction.editReply({ embeds: [thinked], ephemeral: true }); } };
额外检查
确保你的interactionCreate事件处理代码传参正确,示例如下:
// events/interactionCreate.js module.exports = { name: 'interactionCreate', async execute(interaction, client) { if (!interaction.isChatInputCommand()) return; const command = client.commands.get(interaction.commandName); if (!command) return; try { await command.execute(interaction, client); // 保持interaction在前,client在后的顺序 } catch (error) { console.error(error); await interaction.reply({ content: '执行命令时出错了!', ephemeral: true }); } }, };
内容的提问来源于stack exchange,提问作者cotu
相关产品推荐
相关产品推荐

