Discord.js斜杠命令Embed遇interaction未定义错误,如何在标题和头像中使用?
问题原因
你在deploy-commands.js里直接引用interaction对象是错误的——这个脚本的作用是注册/更新Discord斜杠命令,此时并没有实际用户触发命令,自然不存在interaction实例。interaction对象只有在用户执行命令时,才会在命令的回调函数中生成。
正确实现方式
你需要把Embed的构建逻辑放在命令的执行处理代码里,而不是部署脚本中。
1. 部署脚本(deploy-commands.js)只负责注册命令结构
这个脚本只定义命令的基本信息(名称、描述等),不需要处理Embed:
const { SlashCommandBuilder, REST, Routes } = require('discord.js'); const { clientId, guildId, token } = require('./config.json'); const commands = [ new SlashCommandBuilder() .setName('profile') .setDescription('查看你的个人资料') ] .map(command => command.toJSON()); const rest = new REST({ version: '10' }).setToken(token); (async () => { try { console.log(`开始刷新 ${commands.length} 个应用命令`); const data = await rest.put( Routes.applicationGuildCommands(clientId, guildId), { body: commands }, ); console.log(`成功刷新 ${data.length} 个应用命令`); } catch (error) { console.error(error); } })();
2. 在命令处理逻辑中构建Embed并使用interaction
在你的主客户端脚本(比如index.js)里,监听interactionCreate事件,处理命令执行,此时就能拿到有效的interaction对象:
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on('ready', () => { console.log(`已登录为 ${client.user.tag}`); }); client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'profile') { // 在这里构建Embed,此时interaction是可用的 const profileEmbed = new EmbedBuilder() .setTitle(`${interaction.user.username}'s Profile`) .setThumbnail(interaction.user.displayAvatarURL()) // 设置用户头像作为缩略图 .addFields( { name: '用户ID', value: interaction.user.id, inline: true }, { name: '创建时间', value: interaction.user.createdAt.toLocaleString(), inline: true } ) .setColor('#0099ff'); await interaction.reply({ embeds: [profileEmbed] }); } }); client.login(token);
关键要点
- 部署脚本≠命令执行逻辑:deploy-commands.js只负责告诉Discord有哪些命令,不处理命令的实际功能。
- interaction的作用域:只有在用户触发命令时,
interactionCreate事件的回调里才会有可用的interaction对象,这里才能获取用户信息、回复消息等。
内容的提问来源于stack exchange,提问作者MrTacoCat
相关产品推荐
相关产品推荐

