Discord.JS function error, "welcome message" - javascript

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

Related

Trying to make it so my command only works in one guild Discord.js

in discord.js i am trying to make it so that my code only executes if the user is in a specific guild, how would i go about doing this?
module.exports = client => {
const channelId = '798241375572328479'
const infoId = '<#798241375136776215>'
const serverId = '798241375098896414'
client.on('guildMemberAdd', (member) => {
console.log(member)
if (client.guild.id(serverId)) {
const message = `Welcome to **awbtawtnawtb** ${member.user}!\n Please take some time to read through ${infoId}. \nI have also Direct Messaged you some quick information`
const welcomeEmbed = new Discord.MessageEmbed()
.setDescription(message);
client.channels.cache.get(channelId).send(welcomeEmbed)
const welcomeDMEmbed = new Discord.MessageEmbed()
.setColor('#9000D2')
.setTitle(`Welcome To The awbeyvatw Discord ${member.user.tag}!`)
.setDescription(`\n\nBy joining this server you are abide by the #info-read rules. Breaking one of these rules will result in punishments accordingly.\nIf you require help create a ticket in #support\nIf you have any further concerns you may DM me #JohnDoe#5032 as a last resort!\n\nI Hope you enjoy your time!\n\n-JohnDoe`)
.setAuthor(``);
const welcomedmipEmbed = new Discord.MessageEmbed()
.setColor('#00F0FF')
.setTitle(`Server Address: wvawbattbvga`)
} else {
} console.log(`Didn't send message due to not being in the same guild!`)
You would use the comparison operator.
if (member.guild.id === serverId) {
// Your code
}

How do I get a specific channel in a server and send a message there?

I've been making a discord bot in Discord.js and I'm trying to make a welcome command. I'm trying to send a message to a specific channel in my server. I don't know how to do this since the update in discord.js because I've done this before. Can you help me?
Here is a chunk of my code:
bot.on('guildMemberAdd', (member) => {
let embed = new Discord.MessageEmbed()
.setColor(0xcccccc)
.setThumbnail(member.user.avatarURL)
.setTitle("Welcome " + member.user.tag + "!")
.setDescription("Hello, welcome to this server!")
.addField("Welcome", "imageurl")
.setFooter("Server Name")
bot.channels.find('XXXXX').send(embed)
})
The introduction of managers is likely the cause of confustion. Try something like this:
// assuming 'bot' is client object in this context
client.channels.fetch( CHANNEL_ID ).then(channel =>{
channel.send( YOUR_EMBED )
}).catch(err =>{
// do something with err
})
// if you need to fetch by channel name
let channelsCollection = client.channels.cache; // returns collection
let channel = channelsCollection.find(channel => channel.name === YOUR_CHANNEL_NAME );
channel.send( YOUR_EMBED );

How can I make my Discord bot give a user a role?

How can I make my Discord bot give a user a role? It has the "Administrator" permission, and I'm using the nodejs library. Here's my code so far (this initializes the bot):
var auth = require("./auth.json");
var fs = require("fs");
var bot = new discord.Client();
bot.login("TOKENTOKENTOKENTOKENTOKENTOKENTOKENTOKENTOKEN")
bot.on("ready", function(event) {
console.log("Initialized");
});
You must use the GuildMember.addRole() function. (to get a guild member, use Guild#members.get()). Read the Discord.js.org documentation for more informations.
You can use:
bot.on("message", (message) => {
if(!message.member) return
// Find the role by name
var role = message.guild.roles.find((r) => r.name === "Name of your role");
// Assign the role to the message author
message.member.roles.add(role);
});
You can try this
client.on('guildMemberAdd', member => {
//Search and add the role to the new user
member.addRole(member.guild.roles.find(nm => nm.name === "Your role name"));
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(ch => ch.name === 'general');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
});

Javascript Discord Bot giving code reference errors when ran

I've been working on a discord bot lately, this is my first time coding in general, and I thought Javascript would be easier than other options I might have had. Right now, I'm struggling through reading error after error.
Anyways, lets get to the question at hand. Currently, the code is as follows:
const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
let short = msg.content.toLowerCase()
let GeneralChannel = server.channels.find("General", "Bot")
if (msg.content.startsWith( prefix + "suggest")) {
var args = msg.content.substring(8)
msg.guild.channels.get(GeneralChannel).send("http\n SUGGESTION:" + msg.author.username + " suggested the following: " + args + "")
msg.delete();
msg.channel.send("Thank you for your submission!")
}
});
When I ran said code, it returned an error that (I think) basically told me that "server" in let GeneralChannel = server.channels.find("General", "Bot") was undefined. My problem is, I dont actually know how to define server. I'm assuming that when I define server to it, it will also tell me I need to define channel and find, though I'm not sure.
Thanks in advance :)
First of all, why are you using both let and var? Anyways, as the error says, server is not defined. The client doesn't know what server you're referring to. That's where your msg object comes in, it has a property guild which is the server.
msg.guild;
Secondly, what are you trying to achieve with let GeneralChannel = server.channels.find("General", "Bot")? the find method for arrays takes a function. Are you trying to look for the channel with the name "General" or something? If so, better to use the id of the channel that way, you can use a channel from any server the bot is in (in case you're trying to send all suggestions to a specific channel on a different server).
let generalChannel = client.channels.find(chan => {
return chan.id === "channel_id"
})
//generalChannel will be undefined if there is no channel with the id
If you're trying to send
Going by that assumption, your code can then be re-written to:
const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
let short = msg.content.toLowerCase();
if (msg.content.startsWith( prefix + "suggest")) {
let generalChannel = client.channels.find(chan => {
return chan.id === 'channel_id';
});
let args = msg.content.substring(8);
generalChannel.send("http\n SUGGESTION: " + msg.author.username + " suggested the following: " + args + "");
msg.delete();
msg.channel.send("Thank you for your submission!")
}
});
Not that scope is a concern in this instance but it's worth noting that 'let 'defines a local variable while 'var' defines a global variable. There is a difference.

Discord js deafening an user

Hello I'm trying to deafen a particular person in discord but I keep getting the following error:
TypeError: message.setDeaf is not a function
The discord js docs state that you should deafen members like this.
.setDeaf(deaf)
Deafen/undeafen a user.
I'm unsure as to why I'm getting this error, below is my code;
var Discord = require("discord.js");
var client = new Discord.Client();
var user = "30898500862111287"
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', function(message) {
if (message.content === '$deafen') {
message.setDeaf(user);
}
});
setDeaf() is a function derived from GuildMember, not Message. Since Message does not contain a function called setDeaf(), it gave you that error.
In order to get GuildMember, which is the user you want to deafen/undeafen, you can first get the user from the Message, in your case, it will be message.author, which will return the user who sent that message.
Now, on Guild, there is a FetchMember() function that returns a GuildMember datatype. For that function's argument, all you have to do is just to put in your user that you want to target.
(Your Guild will of course be the guild where the message is in! Message.Guild should do the trick.)
Last step is just to deafen/undeafen the user.
You're using setDeaf() on a Message and not a GuildMember (SetDeaf() is a GuildMember method).
Additionally, you're passing an unexisting value user to setDeaf(). I'm guessing you were trying to pass the message.author, but setDeaf() takes a boolean and an optional reason string, not a User.
You can achieve what you're looking for with this:
if(message.content == "$deafen")
message.member.setDeaf(true);
Alternatively, add a reason:
if(message.content == "$deafen")
message.member.setDeaf(true, "reason");
References:
Message Object
GuildMember Object
you cannot invoke a Server Deaf on Message. You can do it on Guild_Member.
If you want to get the first mentioned member:
let mMember = message.mentions.members.first()
mMember.setDeaf(true)
You can also invoke it on the message_author with a member property.
message.member.setDeaf(true)
But you cannot set a Server Deaf on a Message.
It looks like they've changed the code for this a little bit, instead of:
member.setDeaf(true);
You now use:
member.voice.setDeaf(true);
The code below is solution:
const user = message.mentions.members.first()
if(!args[1]) {
message.channel.send('send me a user to mute in voice')
} else {
user.voice.setDeaf(true, `${args[2]}`)
}
Seeing as you may only deafen guild members a useful approach could be getting the guild member.
You pass the set deaf an id, this would in short throw a logic error because you passed an invalid argument type.
The following should achieve what you were going for.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
const guild = client.guilds.cache.get("YOUR GUILD ID");
const user = guild.members.cache.get("30898500862111287");
client.on('message', message => {
if (message.content === '$deafen') {
user.voice.setDeaf(true);
}
});
However, if you instead want to deafen a mentioned member you could take this approach.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
let mentioned = message.mentions.members.first();
if (message.content === '$deafen') {
mentioned.voice.setDeaf(true);
}
});
(On a side note I'd recommend the use of constants for your discord and client object so they may not be mutated)
const Discord = require("discord.js");

Categories