Discord.JS function error, "welcome message"
Solution 1
I believe the proper way to do this, is to get the channel by ID or by name since #general can be undefined, as Andre pointed out.
An easy way to do this is for members joining & leaving:
bot.on('guildMemberAdd', member => {
member.guild.channels.get('channelID').send('**' + member.user.username + '**, has joined the server!');
});
bot.on('guildMemberRemove', member => {
member.guild.channels.get('channelID').send('**' + member.user.username + '**, has left the server');
//
});
Turn developer mode on by going to user settings > Appearance > developer mode, then right clicking on the channel and clicking "copy ID"
Solution 2
Reading about how Discord.js works, defaultChannel
seems to be a misnomer since no such concept in Discord or its API exists:
The
#general
TextChannel of the guild
In reality, the #general
channel can be renamed and deleted, therefore defaultChannel
can be undefined
. You need to guard your call to sendMessage
:
var bot = new Discord.Client();
bot.on("guildMemberAdd", member => {
let mem = member.guild;
if (mem.defaultChannel) {
mem.defaultChannel.sendMessage(member.user + " welcome to the server!");
} else {
// do something if the #general channel isn't available
}
});
Solution 3
If I remember correctly guild#defaultChannel
and channel#sendMessage
are deprecated.
( Same as client#setGame ) but, this can be bypassed through easily finding a channel!
var defaultChannel = member.guild.channels.find( "name", "CHANNEL_NAME" );
Which then your code will end up something like this:
const discord = require('discord.js');
var bot = new discord.Client();
bot.on(`guildMemberAdd`, member => {
var dC= member.guild.channels.find("name", "CHANNEL_NAME");
/* Using dC for short. */
if (dC) {
dC.send(`${member.username}, welcome to the server!`);
} else {
member.guild.defaultChannel.send(`${member.username}, welcome to the server!`);
}
});
NulledRetry
Updated on June 14, 2022Comments
-
NulledRetry almost 2 years
I'm making a bot for Discord using "Discord.JS" I'm trying to make an intro message but I get the error "Cannot read property 'sendMessage' of undefined"
My Code for Welcome Message:
var bot = new Discord.Client(); bot.on("guildMemberAdd", member => { let mem = member.guild mem.defaultChannel.sendMessage(member.user + " welcome to the server!"); });
Any help?
-
André Dion over 6 yearsSeems pretty obvious...
mem.defaultChannel
isundefined
. -
JLRishe over 6 years@AndréDion That is obvious, but why would it be undefined here?
-