'TypeError: Cannot read properties of undefined (reading 'toJSON')
My code was going great and everything was working fine. Then I thought I would add a user info command to my bot. So I followed a tutorial about it and finished the .js file. This is what I wrote:
const { ContextMenuInteraction, MessageEmbed } = require("discord.js");
module.exports = {
name: "userinfo",
type: "USER",
permission: "ADMINISTRATOR",
/**
*
* @param {ContextMenuInteraction} interaction
*/
async execute(interaction) {
const target = await interaction.guild.members.fetch(interaction.targetId);
const Response = new MessageEmbed()
.setColor("AQUA")
.setAuthor(target.user.tag, target.user.avatarURL({dynamic: true, size: 512}))
.setThumbnail(target.user.avatarURL({dynamic: true, size: 512}))
.addField("ID", `${target.user.id}`)
.addField("Roles", `${target.roles.cache.map(r => r).join(" ").replace("@everyone", " ") || "None"}`)
.addField("Member Since", `<t:${parseInt(target.joinedTimestamp / 1000)}:R>`, true)
.addField("Discord User Since", `<t:${parseInt(target.user.createdTimestamp / 1000)}:R>`, true)
interaction.reply({embeds: [Response], ephemeral: true})
}
}
Now in my index.js file (which i've named bot.js), I've written this code:
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
}
To of course read the commands from my commands file. When I run the terminal it had this error in it: Cannot read properties of undefined (reading 'toJSON')
When I deleted the userinfo.js file, everything worked fine again. What did I do wrong please help.
Solution 1:[1]
From your current code it looks like you followed a tutorial for reading the commands from the commands folder. You get your error because in your exported command, there is no data property. However, when following the official discord.js guide to register slash commands, there is a property like this:
const data = new SlashCommandBuilder()
.setName('echo')
.setDescription('Replies with your input!')
However, your command file will not work properly unless there is a command handler because normal discord.js slash commands does not have any property like name or permissions. These properties are all declared in the .data property which is where your error is originating because your exported command does not have it. So to solve the problem, either create a command handler which would work with your current code or format your current code to this:
module.exports = {
data: new SlashCommandBuilder()
.setName('userinfo')
.setDescription('user info'),
async execute(interaction) {
/* Execute your code */
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Caladan |
