简体   繁体   中英

Discord.JS function error, “welcome message”

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?

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"

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
    }
});

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!`);
    }
});

In my bots, I make my Welcome messages more simples. Maybe this work:

 const Discord = require('discord.js');

 var bot = new Discord.Client();

 bot.on("guildMemberAdd", (member) => {

    let channel = bot.channels.get('*CHANNEL_ID*');

    channel.send(`Hey ${member.user}, welcome to the server!`); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM