"Cannot read property 'user' of undefined"

Hi, I’m making a guilds command that lists all the guilds that the bot is in and I get the error “Cannot read property ‘user’ of undefined”. I want the bot to display the username and discriminator of the guild owner. Here is my code:

const Discord = require("discord.js");

exports.run = (bot, message) => {
  if(!message.author.id == "495953543543521280") return;
 
  const guilds = bot.guilds.map(g => g.name + " ( " + g.id + " )" + " ( " + g.owner.user  + " )").join("\n\n");
  message.channel.send(guilds);
};

Hey there!

You appear to be having a bit of toubble on this line:

const guilds = bot.guilds.map(g => g.name + " ( " + g.id + " )" + " ( " + g.owner.user + " )").join("\n\n");

For starters, I would loop through the array of Guilds with .forEach

const Discord = require("discord.js");

bot.guilds.array() // Convert the list of guilds from Collection<Snowflake, Guild> to Array[]
    .forEach((guild) => {
        // Do stuff with the guild object
    });

Now we have the guild object of the guild, we can retrieve the required information from it!

const Discord = require("discord.js");

bot.guilds.array() // Convert the list of guilds from Collection<Snowflake, Guild> to Array[]
    .forEach((guild) => {
        // Do stuff with the guild object
        let guildName = guild.name;
        let guildId = guild.id;
        // Get the guild owner's Username and Discriminator
        let owner = guild.owner.user;
        let ownerUsername = owner.username;
        let ownerDiscriminator = owner.discriminator; // The numbers after the #
        // Final message about guild
        let info = `${guildName} (${guildId}) (${ownerUsername}#${ownerDiscriminator})`
    });

Here’s your final code:

const Discord = require("discord.js"); // Currently not in use. However, useful for typedefs.

exports.run = (bot, message) => {
    if (!message.author.id == "495953543543521280") return;
    
    var messageToPost = "Guilds:\n\n";

    bot.guilds.array() // Convert the list of guilds from Collection<Snowflake, Guild> to Array[]
    .forEach((guild) => {
        // Do stuff with the guild object
        let guildName = guild.name;
        let guildId = guild.id;
        // Get the guild owner's Username and Discriminator
        let owner = guild.owner.user;
        let ownerUsername = owner.username;
        let ownerDiscriminator = owner.discriminator; // The numbers after the #
        // Final message about guild
        let info = `${guildName} (${guildId}) (${ownerUsername}#${ownerDiscriminator})\n\n`
        messageToPost.concat(info); // 'Insert'/'Add' string to the messageToPost string/varible.
    });
    
    message.channel.send(messageToPost); // Send Message!
}

(I’m trying not to spoonfeed it to you but it’s hard not to).

Thank you so much!!!

1 Like