Discord js TypeError: Cannot read property members - discord.js

Hello i have this code,
user = message.guild.members.fetch(id2).then((use,err)
And i have this error
TypeError: Cannot read property 'members' of null
Please can yuo help me ?
Thank you

message.guild is not initialized. You could check if it is null before use eg
if(message.guild){
user = message.guild.members.fetch(id2).then((use,err) ...
}else{
//do something when it is not initialized
}

Your error occurs because the message object refers to a message that was received as a DM. Because of how DMs work, there is no guild or member property for such message (they are left as nulls).
To avoid that, you should handle direct messages slightly differently. The easiest and most commonly used way is to completely stop direct messages from running your message event code. This can be done by adding
if (message.channel.type === 'dm') return;
at the very top of your event.
As that makes it impossible to initiate commands in DMs, even if they don't need to be executed in a guild to work (like ping command for example), this might be not what you want. In such case, you should implement a way to determine if command someone tried to run in DM is "allowed" to be executed there. Implementations for that vary depending on command handling implementation, but snippet below is basic princinple.
client.on('message', message => {
if (message.author.bot || !message.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/ /g);
const command = args.shift().toLowerCase();
if (command === 'memberinfo') {
if (message.channel.type === 'dm') return message.reply('this command cannot be run in DMs.');
// Actual command code
}
});

Related

Why isn't my code working? Discord.js index.js client.on

It's not sending a message, there are no errors I tried modifying the code nothing is working the bot welcome message still works I think that it's not updating with replit.
I tried modifying the code switching some stuff around basically doing stuff if I see any flaws I made.
client.on('message', message => {
// We'll want to check if the message is a command, and if it is, we'll want to handle it
if (!message.content.startsWith(prefix) || message.author.bot) return;
// Split the message into an array of arguments, with the command being the first element
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
// Check if the command is "privatevc"
if (command === 'Privatevc') {
// Check if the member is in a voice channel
if (!message.member.voice.channel) {
// If the member is not in a voice channel, send a message letting them know they need to be in one to use the command
return message.channel.send('You need to be in a voice channel to use this command.');
}
// If the member is in a voice channel, create a private voice channel for them
message.member.voice.createChannel({type: 'Voice'}).then(channel => {
// Send a message to the member letting them know the private voice channel has been created
message.channel.send(`Private voice channel created for you: ${channel}`);
}).catch(console.error); // If there was an error creating the private voice channel, log it to the console
}
});
This code is for Discord.js v12. If using the newest (v14) you need to use the messageCreate event instead of message. So the code would be:
client.on('messageCreate', message => {
You might also enable the MessageContent and GuildMessages intents.
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent
To make it all work you need to enable at least the third option, as you might see in the screenshot.

Error when console.log the displayname of the message owner

I get this Error:
TypeError: Cannot read property 'displayName' of null
This is the code that should console-log the command and the username of the user who used it:
client.on('message', (message) => {
const { content, member } = message
const autor = member.displayName || member.username
aliases.forEach((alias) => {
const command = `${prefix}${alias}`
if (content.startsWith(`${command}`) || content === command) {
console.log(`${autor} used: ${command}`)
callback(message)
}
})
})
In the console I get the username but it still gives an error. It only gives this error if I use a specific command. The command sends an embed of the message. Then it sends a copy of the message to the user who sent it.
if (message.content.includes('...'))
{message.delete({timeout: 800})
.then(message.member.send(message.content))
message.channel.send(embed)
Thank you for your help
If you want to use the nickname primarily, you can make your bot default to the username if the nickname is unavailable.
For your first section, you can use a ternary operator.
const autor = member ? member.displayName : message.author.username
If member returns null, it'll instead use the username property of the author which is never null.
For the second part of your code, you might as well replace message.member.send() with message.author.send() since then former provides no advantages over the latter and instead only leads to instances such as this one.
As from the documentation about message.member:
Represents the author of the message as a guild member. Only available if the message comes from a guild where the author is still a member
That means the error you are having may happen if the user is not a member of the server/guild anymore, or is a private message.
You can use message.author if you just want the username. Or you can return the function when message.member is null.

How to not send bots message edit discord.js

I have a message edit log but I want to stop sending the log if a mobs message was updated, I tried a few codes like
if(bot.oldMessage.content.edit()){
return;
}
It showed and error
cannot read property 'edit' of undefined
I then removed edit then content was undefined. The code for the message update is below.
The Code
module.exports = async (bot, oldMessage, newMessage) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[oldMessage.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
if (oldMessage.content === newMessage.content){
return;
}
let mEmbed = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL({dynamic: true}))
.setColor(cyan)
.setDescription(`**Message Editied in <#${oldMessage.channel.id}>**`)
.addField(`Before`, `${oldMessage.content}`)
.addField(`After`, `${newMessage.content}`)
.setFooter(`UserID: ${oldMessage.author.id}`)
.setTimestamp()
msgChannel.send(mEmbed)
}
How would I stop it from sending the embed if a bots message was updated.
Making a really simple check will resolve this issue. In Discord.js there is a user field that tells you if the user is a bot or not.
In fact, it is really recommended you add this in the "onMessage" part of your code as it stops other bots from using your bot, this is to make sure things are safe and no loopbacks/feedbacks happen, either way, you don't want a malicious bot taking advantage of your bot, which can get your bot in trouble too.
Here is what you want to do;
if (message.author.bot) return;
What this code specifically does is check if the message's author is a bot, if it returns true, it will break the code from running, if it returns a false, the code continues running.
You can do the same if you want to listen to bots ONLY by simply adding a exclamation mark before the message.author.bot like this;
if (!message.author.bot) return;
It is also possible to see what other kinds of information something holds, you can print anything to your console. For example, if you want to view what a message object contains, you can print it into your console with;
console.log(message) // This will show everything within that object.
console.log(message.author) // This will show everything within the author object (like ID's, name, discriminators, avatars, etc.)
Go ahead and explore what you can do!
Happy developing! ^ -^
That is really easy to do. All you need to do is check if the author of the message ist a bot and then return if true. You do that like this
if (oldMessage.author.bot) return;

How do I stop an infinite loop command on a Discord Bot?

Let's say I made an infinite command for my bot, Would there be any way to stop the loop at any time? I want to be able to stop it from the server, not in the actual code.
Example:
if(msg.content === "Just Monika"){
msg.channel.send('Just Monika')
}
})
Is there any way I can type something in chat, and it stops the command? thanks.
Making your bot respond to itself infinitely probably isn't a good idea. But just for learning, it's very possible to do what you wish.
You could make a different phrase (let's call it the stop command) set a boolean variable in your code to true. Then, whenever the looping command gets triggered by a user message or by one of its own, it should check if this boolean telling it to stop is true. If it is, it should set it to false and not send that message, else it should just send that message as per usual.
// The following should be defined in the outmost scope
let loopPhrase = "Just Monika";
let stopPhrase = "Stop Spamming The API";
let triggerStop = false;
// The following should be a part of the message event
if (msg.content === loopPhrase) {
if (!triggerStop) msg.channel.send(loopPhrase);
else triggerStop = false;
} else if (msg.content === stopPhrase) triggerStop = true;

"Announce" command giving errors in console

I'm trying to write an announce command which when used sends an announcement to the announcements channel, but only if you have a certain role, that works, but it shows an error in my console.
The error is TypeError: client.fetchGuild is not a function
if (await client.fetchGuild(message.guild.id).fetchMember(message.author.id).hasPermission("MENTION_EVERYONE") && message.content.startsWith(adminPrefix + 'announce')) {
const trueMessage = message.content.substr(10)
client.channels.get('545343689216491541').send('#everyone, ' + trueMessage)
}
How do I make it send no errors
P.s. I'm new to this, very new.
fetchGuild
is not a function. Use
client.guilds.get(id)
or
message.guild
as you already have the guild attached to the message object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=guilds
In order to verify if a member has a role, you'd better use this:
if(message.member.roles.cache.some(role => role.name === 'role name'))
then send the message inside the if statement

Resources