Welcome message in Discord.js - javascript

I'm programming a discord bot and I'm having a problem in one of the main functionalities - the welcome message.
I've tried several methods but none of them worked, except for one: the one that needs a channel ID.
I dont want to use that method because I want to use my bot on multiple servers, and that would mean that I have to change the code for each one of them - and I really dont want to.
client.on('guildMemberAdd', function(message) {
member.guild.channels.cache.get('MY CHANNEL ID').send('welcome dadadadada');
});
This code worked (actually, I just tried it and it doesn't - but it did. It was something like that). Now I'm trying more 'advanced' coding to tell the bot to automatically get the channel ID from #general (for this I did npm install long)
const getDefaultChannel = (guild) => {
if(guild.channel.has(guild.id))
return guild.channels.get(guild.id)
const generalChannel = guild.channels.find(channel => channel.name === 'general');
if (generalChannel)
return generalChannel;
return guild.channels
.filter(c => c.type === 'text' &&
c.permissionsFor(guild.client.user).has('SEND_MESSAGES'))
.sort((a, b) => a.position - b.position) ||
Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber()
.first();
}
client.on("guildMemberAdd", member => {
const channel = getDefaultChannel(member.guild);
channel.send(`Welcome ${member} to the server, wooh!`);
});
I didn't find anything useful and I don't know what to do. Also, english is not my first language.
What else could I try? Thank you.

I think this could help you!
The guildMemberAdd listener can send messages
client.on('guildMemberAdd', function(member, message) => {
let generalChannelName = message.guild.channels.find(channel => channel.name === 'general');
let generalChannel = generalChannel.id;
generalChannel.send(`Welcome ${member.tag} to the server!`);
});
It's hard to insert your filtering here, may this help you?

Related

Discord, Mention someone when gets a role

Is there a way to mention someone immediately after getting a specific role in a specific channel?
For example when I, or any other admin, give someone a specific role the bot mentions them in a specific channel.
Here is my code:
client.on("guildMemberUpdate", (oldMember, newMember) => {
const channel = client.channels.cache.get("channelid");
// If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)
const removedRoles = oldMember.roles.cache.filter((role) => !newMember.roles.cache.has("roleid"));
if (removedRoles.size > 0) console.log(`The roles ${removedRoles.map((r) => r.name)} were removed from ${oldMember.displayName}.`);
// If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)
const addedRoles = newMember.roles.cache.filter((role) => !oldMember.roles.cache.has("roleid"));
if (addedRoles.size > 0) {
if (newMember.roles.cache.some((role) => role.name === "testing")) {
let embed = new Discord.MessageEmbed().setTitle("♡﹕welcome!").setDescription("lalalala").setColor("#FFB6C1").setThumbnail("https://cdn.discordapp.com/attachments/806974794461216813/817737054745526304/giffy_2.gif");
channel.send(`Welcome ${oldMember.user}`, embed);
}
console.log(`The roles ${addedRoles.map((r) => r.name)} were added to ${oldMember.displayName}.`);
}
});
This is assuming your code is exactly as shown in the question, and not using placeholder strings.
Firstly, "roleid" should be role.id without the "" when you're filtering. This will filter it properly, as should channelId where channel is defined, which I'm guessing are placeholders, but just in case.
Secondly, you'll probably want to check using addedRoles.has("roleIdToSend") as opposed to newMember.roles.cache.some(). This will DM them every time they're updated if they have the role, not if they only just got the role on that update.
Lastly, assuming you're using discord.js v13, you'll need to correct your send() method. It should look something like
channel.send({
content: `Welcome, ${oldMember.toString()}`,
embeds: [embed]
});

Bot keeps crashing when wrong command is sent. [Discord JS]

I'm trying to make an Arby's Bot. Whenever someone sends a message in the channel, the bot crashes and bot doesn't work.
client.on("message", (message) => {
if (message.content.startsWith("arbys") || message.guild.channel == message.guild.channels.cache.get("843008525335920651")) {
} else
setTimeout(() => message.delete(), 1);
message.author.send("**arbys** Only Arbys. GOT IT?")
});
If someone could please help me that would be amazing.
its because message.guild does not have a channel property, instead do this
if (message.content.startsWith("arbys") || message.channel.id == "843008525335920651"){
hope this helped >:D
message.guild doesn't have a channel property, but that's not the only problem. You can't compare an object (message.guild.channel) to another object (message.guild.channels.cache.get("843008525335920651")) like that. You can, however, check if the channel the message is sent in has the same ID as you want (843008525335920651).
You can also delete the message after you sent a DM to the message author using the .then() method. Check out the code below:
client.on('message', (message) => {
if (
message.content.startsWith('arbys') ||
message.channel.id === '843008525335920651'
) {
// do something ?
console.log('Correct channel or command');
} else {
// send a DM to the author
message.author
.send('**arbys** Only Arbys. GOT IT?')
// and delete the original message
.then(() => message.delete())
// catch them errors :)
.catch((error) => console.log(error));
}
});

Why are users id being undefined for discord.js

Ok so I've been working with someone on a discord leveling system, and we are SO close to done, but when we make the leaderboard it constantly pops up with the error, "cannot read property of tag of undefined". We want to be able to use peoples discord names, rather than just their id, that way it's easier to know who is who on the leaderboard. We have tried many different things to replace this, but just can't seem to figure it out. I know that the issue is some users ids being undefined, thus the bot is unable to find their tag, im just unsure why some users id are being undefined in the first place. If you know a solution please let me know, it would be greatly appreciated.
const XP = require('quick.xp');
const xp = new XP.SQLiteManager({
deleteMessage: false
})
client.on('message', (message) => {
const level = xp.getLevel(message, message.author.id)
const userxp = xp.getXP(message, message.author.id)
if (message.author.bot) {
return;}
else {
xp.giveXP(message);
}
if (message.content === "?rank") message.channel.send(`You are on level ${level} and have ${userxp} XP`)
if (message.content === "?leaderboard") {
let lb = xp.leaderboard(message, message.guild.id, {limit: 10, raw: false});
const embed = new Discord.MessageEmbed()
.setTitle("Leaderboard")
.setColor("#FFFFFF")
lb.forEach(m => {
embed.addField(`${m.position}. ${client.users.cache.get(m.id).tag}`, `Level: ${xp.getLevel(message, m.id)}\n XP: ${m.xp}`)
})
message.channel.send(embed);
}
if (level === '10') {
member.role.add('788820930331017244')
}
})
Only .tag you try to acces in this code is:
embed.addField(`${m.position}. ${client.users.cache.get(m.id).tag}`, `Level: ${xp.getLevel(message, m.id)}\n XP: ${m.xp}`)
That means there is undefined returned from: client.users.cache.get(m.id)
As you have not provided this function just from the code here i can tell that function returns undefined - maybe if couldnt not find the given m.id in cache?
You should have some protection against such code for example
const userFromCache = client.users.cache.get(m.id);
embed.addField(`${m.position}. ${(userFromCache ? userFromCache.tag : '-- no tag --'}`, `Level: ${xp.getLevel(message, m.id)}\n XP: ${m.xp}`);

Discord.js guild.roles.cache.find returning undefined

Im trying to assign code a discord bot to give someone a role whenever they enter a server. This is my code right now:
client.on('guildMemberAdd', (member) => {
let role = guild.roles.cache.find(r => r.name === "Admin");
console.log(role);
if(!role){
console.log("Role doesen't exist.");
}
member.roles.add(role);
});
I tried running it, and this line executed: console.log("Role doesen't exist.");. I then went on to print the role variable, and it was undefined. What's the problem?
First Method
Everything might not be available in cache, so you need to fetch it, the only issue is that you need to fetch via the ID.
let role = guild.roles.cache.find(r => r.name === 'ADMIN') || await guild.roles.fetch('ROLEID');
Source: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=fetch
Second Method
This is a rather hacky solution, but you can fetch all roles on ready event.
client.guilds.cache.forEach(g => {
g.roles.fetch();
});

How Can My Discord.js Bot welcome new people to the server?

I'm trying to make it so the bot Will Auto Welcome new members on multiple servers, this is the code I have currently and it doesn't come up with an error but it doesn't work
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
if (!newUsers[guild.id]) newUsers[guild.id] = new Discord.Collection();
newUsers[guild.id].set(member.id, member.user);
if (newUsers[guild.id].size > 10) {
const userlist = newUsers[guild.id].map(u => u.toString()).join(" ");
guild.channels.find(channel => channel.name === "general").send("Welcome our new users!\n" + userlist);
newUsers[guild.id].clear();
}
});
client.on("guildMemberRemove", (member) => {
const guild = member.guild;
if (newUsers[guild.id].has(member.id)) newUsers.delete(member.id);
});```
Your problem lies within your third line of code. What you do here is create a new Collection everytime someone joins. This means that the collection can never be > 10 because it's always 1.
To fix this simply create the Collection at the top of your index file and not inside a listener.
On a sidenote, I assume you want to create the collection to keep track of who is in your discord server. Thats not really a good idea because it will be newly created every time the bot restarts and since it only gets updated when someone joins or leaves it won't be accurate. A lot easier to use is the guild.members collection.
EDIT: This is how you would do something like that
client.on('guildMemberAdd', member => {
const guild = member.guild;
const userlist = guild.members.cache.map(u => `\n${u.user.username}: ${u.user.id}`);
guild.channels.find(channel => channel.name === "general").send("Welcome our new user!\n Users" + userlist);
})
Please keep in mind that this will return all members of the guild. You can only use the guildMembersChunk listener to welcome multiple members and all of those need to come from the same guild which is rather unlikely.

Categories