Discord.js, message.guild.owner returns null

Viewed 7199

I'm coding a server-info command for my discord bot, and I want to get the owner username or tag from the actual guild. I found a way to do it in discord js 11, but it's not working anymore under 12th version :

const guild = client.guilds.get(message.guild.id);
message.channel.send(message.guild.member(guild.owner) ? guild.owner.toString() : guild.owner.user.tag);
// if the user is in that guild it will mention him, otherwise it will use .tag

So in discord js 12, client.guilds.get isn't a function, and guild.owner returns null. message.guild.owner.user.usernameis also returning Cannot read property 'user' of null. I took a look at the documentation, and message.guild.owner seems to be a real property (https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=owner). So I don't know why it's returning null.

3 Answers

I'd recommend that you first get the guild and make sure that it's available before trying to modify or access it. Therefore, your bot won't hit any errors. Additionally, as far as I know, guild.owner returns null but there is a way around this. You can get the guild owner ID through guild.ownerID and fetch the member as a guildMember. Here is the code:

const guild = message.guild; // Gets guild from the Message object
if(!guild.available) return; // Stops if unavailable
await message.guild.members.fetch(message.guild.ownerID) // Fetches owner
      .then(guildMember => sOwner = guildMember) // sOwner is the owner
message.channel.send(guild.member(sOwner) ? sOwner.toString() : guild.owner.user.tag);

This is how you would get the owner's tag when you have the guild. This also does not rely on the cache, so if your bot restarts or the cache is cleared, it will work regardless.

let ownerTag = undefined;
<client>.users.fetch(<guild>.ownerID).then(user => ownerTag = user.tag);

.fetch() returns a promise, which is why I declared a variable and then assigned the value to it.

Make sure you enable these intents in your discord developer portal so your bot could access your server

Example to enable intent

After that, you could access your user owner tag.

Related