Discord.js, message.guild.owner returns null - discord

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.

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
After that, you could access your user owner tag.

Related

How to get bot to reply to user with a (#)ping

I am trying to get a bot to respond to people with a ping in the message, for example: "#user", but everything I've tried have given me not a function error or undefined error. All the stuff I can find about it is either outdated for discord.js v14 or it is for discord.py
Here is my code:
client.on("messageCreate", (message) => {
if (message.content.startsWith("test")) {
const user = message.author.userId();
message.channel.reply(`Hello <#${user}>`)
}
});
I've also attempted variations of the .userId() part - such as .tag, .user.id, and .username but all of them have come back with some sort of undefined error. I know it says userId is a snowflake on discord.js but I am unsure on how to use that for I am fairly new to javascript and discord.js. Also, please know that I am using Replit to host the bot and have discord.js#14.5.0 installed.
So, there are a couple issues here.
Issue 1
message.author.userId() is not a function. When trying to get a user's ID, you want to know what each property is returning.
message -> returns the Message object, which contains the data for the message.
message.author -> returns the User object, which contains the data for the user profile.
message.member -> returns the Member object, which contains the data for the guild member profile.
And so on.
In this case, you're going to want to get the User object: being message.author. You've already figured this out.
Now, the User Object has it's own set of properties (which you can find in the documentation at https://discord.js.org/).
The property that you are looking for is: .id, or in your use-case, message.author.id.
Your other attempts, message.author.tag returns the tag, message.author.user.id will throw an error, and message.author.username returns the user's username.
Issue 2
Your second issue is the .reply() method that you're using. The Channel Object doesn't have a .reply() method, but the message does.
So, how you would write this code:
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase().startsWith("test")) {
// Note that I added the .toLowerCase() method to ensure you can do tEST and it still works!
message.reply({ content: `Hello, ${message.author}!` });
}
});
Also, a cool feature that discord.js has is that you can supply the User or Member Object to the content of a message, and it will automatically mention the desired person.
Hope this helps!

How to get permissions in discord js when we do direct message

I am trying to get a list of the permission that the user has in Discord. If it sends the message in the channel, it’s fine as we can use message.member.hasPermission, etc.
But what if the message is DM? I want my users to send a DM to the bot and the bot be able to check and see if the user has certain permissions.
I cannot find anything anywhere. I keep getting redirected to message.member, or message.guild which both are null when it’s in DM.
In DM no one has permissions. All you have is the permission to see messages and send messages which aren’t shown visually, or to bots. To make sure that it isn’t DM, just return if the channel type is dm, or guild is null.
if(!message.guild) return;
//before checking "perms"
If you want the permissions for a certain guild if the message is from DM, use this code
if(message.channel.type === 'dm') {
let guild = await client.guilds.fetch('THE ID OF THE GUILD YOU WANT TO SEE THE USER’S PERMS IN')
let member = await guild.members.fetch(message.author.id);
//you can now access member.permissions
}
Keep in mind await must be in an async callback.
You did not provide any code so I cannot give any more code than this.
You can fetch the member with the guild's context.
Fetching is recommended, as Guild#member() relies on cache and is also deprecated.
Member#hasPermission() will be deprecated as well, using MemberRoleManager#has() is recommended
The following example uses async/await, ensure you're inside an async function
// Inside async function
const guild = await client.guilds.fetch('guild-id');
const member = await guild.members.fetch(message.author.id);
const hasThisPermission = member.roles.cache.has('permission');

Discord JS v12: How do you get a message's content by it's ID?

I'm relatively new to discord.js, and I've started building a bot project that allows a user to create a message via command, have that message stored in a hidden channel on my private server, and then said message can be extracted through the message ID.
I have the write working and it returns the message ID of the message sent in the hidden channel, but I'm completely stumped on the get command. I've tried searching around online but every method I tried would return errors like "Cannot read property 'fetch' of undefined" or "'channel' is not defined". Here are some examples of what I tried, any help would be appreciated. Note that my args is already accurate, and "args[0]" is the first argument after the command. "COMMAND_CHANNEL" is the channel where the command is being executed while "MESSAGE_DATABASE" is the channel where the targeted message is stored.
let msgValue = channel.messages.cache.get(args[0])
client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content)
let msgValue = msg.channel.message.fetch(args[0])
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
I even tried using node-fetch to call the discord API itself
const api = require("node-fetch")
let msgValue = api(`https://discordapp.com/api/v8/channels/${MESSAGE_DATABASE}/messages/${args[0]}`)
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
Am I missing something or am I making some sort of mistake?
Edit: Thanks for the help! I finished my bot, it's just a little experimental bot that allows you to create secret messages that can only be viewed through their ID upon executing the command :get_secret_message <message_id>. I posted it on top.gg but it hasn't been approved yet, so in the meantime if anyone wants to mess around with it here is the link: https://discord.com/api/oauth2/authorize?client_id=800368784484466698&permissions=76800&scope=bot
List of commands:
:write_secret_message - Write a secret message, upon execution the bot will DM you the message ID.
:get_secret_message <message_id> - Get a secret message by its ID, upon execution the bot will DM you the message content.
:invite - Get the bot invite link.
NOTE: Your DMs must be turned on or the bot won't be able to DM any of the info.
My test message ID: 800372849155637290
fetch returns the result as promise so you need to use the then to access that value instead of assigning it to a variable (msgValue). Also you made a typo (channel.message -> channel.messages).
I would recommend using something like this:
msg.channel.messages
.fetch(args[0])
.then(message => {
client.channels
.fetch(COMMAND_CHANNEL)
.then(channel => channel.send(message.content))
.catch(console.error)
})
.catch(console.error)
I think you were quite close with the second attempt you posted, but you made one typo and the way you store the fetched message is off.
The typo is you wrote msg.channel.message.fetch(args[0]) but it should be msg.channel.messages.fetch(args[0]) (the typo being the missing s after message). See the messages property of a TextChannel.
Secondly, but this is only a guess really as I can't be sure since you didn't provide much of your code, when you try to fetch the message, you are doing so from the wrong channel. You are trying to fetch the message with a given ID from in the channel the command was executed from (the msg.channel). Unless this command was executed from the "MESSAGE_DATABASE" channel, you would need to fetch the message by ID from the "MESSAGE_DATABASE" channel instead of the msg.channel.
Thirdly, if you fetch a message, the response from the Promise can be used in the .then method. You tried to assign the response to a variable msgValue with let msgValue = msg.channel.message.fetch(args[0]) but that won't do what you'll expect it to do. This will actual assign the entire Promise to the variable. What I think you want to do is just use the respone from the Promise directly in the .then method.
So taking all that, please look at the snippet of code below, with inspiration taken from the MessageManager .fetch examples. Give it a try and see if it works.
// We no longer need to store the value of the fetch in a variable since that won't work as you expect it would.
// Also we're now fetching the message from the MESSAGE_DATABASE channel.
client.channels.cache.get(MESSAGE_DATABASE).fetch(args[0])
// The fetched message will be given as a parameter to the .then method.
.then(fetchedMessage => client.channels.cache.get(COMMAND_CHANNEL).send(fetchedMessage.content))
.catch(console.error);

Set Role Color for Discord.js bot

I am trying to make my bot's role a pink color for the current server using the Client.on("ready") However whenever I run the bot with what I currently have the console returns:
(node:6504) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
Here is my code I am currently using. I know I need to for loop on every guild but I'm not sure how I would do that, I could use a for or just a .forEach however I can't find the correct way to do such.
const role = client.guild.roles.cache.get('Aiz Basic+');
role.edit({ name: 'Aiz Basic+', color: '#FFC0CB' });
In advance thank you to anybody who replies and helps with my message.
Client#Guild Isn‘t existing. Only Client#Guilds. You can fix this problem by looping through the cache of all your guilds with:
client.guilds.cache.forEach((g) => { })
And inside the loop you can use your code after fixing the .get function, because the get function needs a role id not a role name. You could find the role via the name by writing:
const role = <Guild>.roles.cache.find((r) => r.name === /* The role name */);
Make sure you replaced <Guild> with your guild variable.
Try this code if client.guild is not defined, it could also be because you are using bot instead of client
let role = message.guild.roles.cache.find(role => role.name === "Aiz Basic+");

Is there a way to add a role to someone without mentioning/pinging them? [discord.js]

Pretty much the title. Every time I try adding a role to someone using this:
const member = message.author;
member.roles.add('732727208774205460');
I end up with this TypeError:
TypeError: Cannot read property 'add' of undefined
However, if I use it like this:
const member = message.mentions.members.first();
member.roles.add('732727208774205460');
It works completely fine. Problem is, that only works if the person I'm adding a role to was mentioned/pinged by the user. I'm trying to add a role to the user himself where the user doesn't ping anyone (for censorship, mainly). Is there a way I could do this without getting the TypeError?
You are receiving an error because message.author.roles is undefined, so trying to use .add() on it causes an error.
message.author is of type User, which represents a discord user, and is not associated with any particular server.
You're looking instead for message.member which has type GuildMember, which represents a particular user's profile inside of a guild (message.member is just message.author but as a GuildMember instead of a User). It is the GuildMember type that has roles.
Solution:
const member = message.member;
member.roles.add('732727208774205460');
Official Documentation:
User,
GuildMember

Resources