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.
Related
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!
I'm trying to set up a server with a bunch of text channels named after users so that I can read their DMs to the bot. I can't figure out how to find if a text channel with that person's tag exists already, and I'm not sure if this is the correct code to do this.
Here is the code I'm trying to use:
try{
var txtChannel = client.guilds.cache.get(dmServerID).channels.find(channel => channel.name === (mesage.author.tag.replace('#','-')) && channel.type === "text");
}
catch(e){
client.guilds.cache.get(dmServerID).channels.create(message.author.tag.replace('#', '-'), 'text');
}
txtChannel.send(message.author.tag + ": " + message.content);
After running this code, it gives me an error that reads: Cannot read property 'send' of undefined.
I would also like to know if I am able to create the text channels inside of a category.
First of all, use let over var.
The error is caused by the fact that you declare txtChannel inside the try so it is not available outside that block of code.
Also, you forgot channels.cache (if you are using discord.js v12).
Here is what the code should look like:
let txtChannel = null;
// Already get the guild from the cache since we are gonna use it a bit
const guild = client.guilds.cache.get(guildID);
// Find a text channel that includes in the name the tag of the user
txtChannel = GUILD.channels.cache.find(c => c.type === "text" && c.name.includes(message.author.tag.replace('#','-'));
// If the channel doesn't exist we create the channel, using await to wait until the channel gets successfully created
if(!txtChannel) txtChannel = await GUILD.channels.create(message.author.tag);
// At the end we send the message in the gotten / created channel
txtChannels.send("the message to send");
Note that this code needs to be inside an async function, you can read more about that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
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.
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
}
});
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