discord.js V14 报错:Cannot read properties of undefined (reading 'send')
解决discord.js v14中
TypeError: Cannot read properties of undefined (reading 'send')错误 错误原因
- 参数顺序不匹配:命令文件中
execute函数定义的参数顺序为(client, message, args, interaction),但interactions.js调用时传入的是(interaction, client),导致message变量为undefined,进而message.author也为undefined,调用send时触发错误。 - Slash命令无Message对象:Slash命令的上下文是
Interaction对象,而非普通Message对象,不能用message.author获取用户,需改用interaction.user。 - 过时API使用:v14中
MessageEmbed已被EmbedBuilder替代,原代码的message.delete()也不适用于Slash命令场景。
修复步骤及修改后的代码
1. 修改命令文件(test命令)
const { Client, EmbedBuilder } = require("discord.js"); const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('test') .setDescription('this is a test thing'), /** * @param {Client} client * @param {import('discord.js').ChatInputCommandInteraction} interaction */ async execute(interaction, client) { // 先回复交互,避免超时 await interaction.reply({ content: '已开始向你发送问卷,请查看私信', ephemeral: true }); const questions = [ "test", "test1?" ]; let collectCounter = 0; let endCounter = 0; const author = interaction.user; // 向用户发送第一条问题 const appStart = await author.send(questions[collectCounter++]); const channel = appStart.channel; // 过滤器:只收集发起命令的用户的消息 const filter = (m) => m.author.id === author.id; // 创建消息收集器,设置超时(可选,避免无限等待) const collector = channel.createMessageCollector({ filter, time: 600000 }); collector.on("collect", () => { if (collectCounter < questions.length) { channel.send(questions[collectCounter++]); } else { channel.send("提交完成!"); collector.stop("fulfilled"); } }); // 获取目标频道,推荐用fetch避免cache不存在的情况 const appsChannel = await client.channels.fetch("976110575547482152"); collector.on("end", async (collected, reason) =>{ if (reason === "fulfilled") { let index = 1; const mappedResponses = collected .map((msg) => { return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`; }) .join("\n\n"); await appsChannel.send({ embeds: [ new EmbedBuilder() .setAuthor({ name: author.tag, iconURL: author.displayAvatarURL({ dynamic: true}) }) .setTitle("!新报告!") .setDescription(mappedResponses) .setColor(`Random`) .setTimestamp() ] }); await appsChannel.send(`<@1057374161846145076>`); } else if (reason === 'time') { // 超时提示 await channel.send("问卷超时未完成,已取消"); } }); }, };
2. 关键修改点说明
- 参数顺序修正:将
execute函数的参数改为(interaction, client),与interactions.js的调用保持一致。 - 替换用户获取方式:用
interaction.user替代message.author,获取发起Slash命令的用户。 - 交互回复处理:添加
interaction.reply(),避免Slash命令因超时被Discord判定为失败。 - Embed替换:将
MessageEmbed改为v14推荐的EmbedBuilder,并调整setAuthor的参数格式(v14中该方法接收对象参数)。 - 频道获取优化:使用
client.channels.fetch()替代cache.get(),确保能获取到频道(即使不在缓存中)。 - 收集器超时设置:为消息收集器添加
time参数,避免无限等待用户回复。
3. 验证interactions.js的调用逻辑
你的interactions.js中的调用逻辑是正确的,无需修改,确保它始终以(interaction, client)的顺序传入参数即可。
内容的提问来源于stack exchange,提问作者Icebreaker
相关产品推荐
相关产品推荐

