Discord.js执行/ping命令时出现TypeError错误,请求排查问题
问题排查:TypeError: Cannot read properties of undefined (reading 'username')
错误原因
你代码里的核心问题是获取用户的方式错误:Discord.js的斜杠命令交互对象(ChatInputCommandInteraction)没有author属性,你用interaction.author获取用户时,得到的是undefined,自然无法读取username字段,进而抛出错误。
斜杠命令场景下,要获取发起命令的用户,必须使用interaction.user属性,这是交互对象对应的用户入口。
修复后的代码
把const user = interaction.author;替换为const user = interaction.user;即可,修复后的完整代码如下:
const TOKEN = "mybotstoken"; const CLIENT_ID = "mybotsclientid"; const { REST, Routes } = require('discord.js'); const commands = [ { name: 'ping', description: 'Replies with Pong!', }, ]; const rest = new REST({ version: '10' }).setToken(TOKEN); (async () => { try { console.log('Started refreshing application (/) commands.'); await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands }); console.log('Successfully reloaded application (/) commands.'); } catch (error) { console.error(error); } })(); const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'ping') { const user = interaction.user; // 修复的核心位置 const username = user.username; console.log(`Got a ping execute request from: ${username}`); await interaction.reply('Pong!'); console.log(`Execute successful`); // 顺便修正拼写错误:succesful → successful } }); client.login(TOKEN);
额外说明
interaction.author仅存在于普通消息对象(Message)中,斜杠命令属于交互体系,必须用interaction.user获取发起用户。- 顺便修正了代码里的拼写错误,将
succesful改为successful,避免日志出现拼写问题。
内容的提问来源于stack exchange,提问作者Guli
相关产品推荐
相关产品推荐

