discord.js event handler welcome message - node.js

so I made an event handler for my discord bot so that the index.js file would be neat. But for some reason the welcome message that I made whenever someone joins the server doesn't work.
Here's my event handler code:
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, Discord, client));
} else {
client.on(event.name, (...args) => event.execute(...args, Discord, client));
}
}
And Here's my welcome message code:
module.exports = {
name: 'welcome',
once: false,
execute(Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
client.on('guildMemberAdd', (member) => {
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
})
}
}
I get no error, but whenever someone joins the server, he/she won't be given the role and the welcome message doesn't appear. I put the welcome message code on an events folder that the event handler is handling. Can anyone help?

The issue lies within the welcome code.
In the handler code you have the following line:
client.on(event.name, (...args) => event.execute(...args, Discord, client));
This triggers the client on the name property set in the welcome code.
You currently have it set to welcome, which is not a valid event.
The bot is now listening for a welcome event, which will never happen.
First course of action is setting the name property to guildMemberAdd like this:
module.exports = {
name: 'guildMemberAdd',
//the rest of the code
Then you have another issue.
Within the welcome code you have client.on() again.
This will never work, unless by some incredibly lucky chance 2 people join within a millisecond of each other, but even then you'll only have 1 welcome message.
Removing the following:
client.on('guildMemberAdd', (member) => {
//code
})
will fix that issue.
Then the last thing to do is having the member value being imported correctly.
We do this by changing the following line:
execute(Discord, client) {
to:
execute(member, Discord, client) {
//code
The resulting code will look like this:
module.exports = {
name: 'guildMemberAdd',
once: false,
execute(member, Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
}
}
Happy coding!

Related

Using Node.js and I want to code a welcome bot for my server

I'm working in MacOS with node.js and I have a bot that sends messages in a channel but I want to get rid of MEE6 and only use my bot. So I want to add a welcome action when people join my server. I've looked on google for coding examples but none of the examples work with the current node.js build. I would like to send a welcome message in a dedicated channel. I want the bot to use the user's username in the message and give a message when someone joins and when someone leaves. Here is my current code.
// Require the necessary discord.js classes
const { Client, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
client.on('guildMemberAdd', guildMember => {
guildMember.guild.channels.cache.get('1010768161349587035').send(`**Welcome to the discord server, <#${guildMember.user.id}>!**`);
});
const randomMsg = ['message 1', 'message 2', 'message 3']
const random = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
const sendRandomMsg = () => {
client.channels.cache.get('1006941719666905089').send(randomMsg[random(0, randomMsg.length - 1)]);
}
setInterval(function(){ sendRandomMsg() }, 1000 * 60 );
});
console.log('(。··)_且');
// Login to Discord with your client's token
client.login(token);
I tried adding more intents from this example:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS //also enable in discord developer portal
]
})
But when I add these intents as they are coded, it returns an error saying "Intents" isn't defined. I added SERVER MEMBERS INTENT on the discord developer portal. But when I join the server with my alt account nothing happens in the welcome channel. Any help is appreciated.
Here's an example from a bot of mine. Hope this helps! :D
[ keep in mind you'll need to adjust some things to make it work how you want :) ]
// Import Discord.js
const {
Client,
Collection,
GatewayIntentBits,
Partials
} = require('discord.js');
// I like importing the intents and partials this way, just to make things a little more visible. But the main things we're importing here are the Guild, and GuildMembers [PLURAL]
const { Guilds, GuildMembers, MessageContent, GuildMessages } = GatewayIntentBits;
// And here, we're importing the GuildMember [SINGULAR] for our Partials
const { User, Message, Channel, GuildMember } = Partials;
// Create Discord Client
const client = new Client({
intents: [
Guilds,
GuildMembers, // IMPORTANT
GuildMessages,
MessageContent,
],
partials: [
User,
Channel,
Message,
GuildMember, // IMPORTANT
],
});
// Adding the GuildMembers to our intents, and GuildMember to our partials allows for us to receive the info we need for a welcome message; ei. when a member joins
// And lastly, when a member joins. I noticed you had the event inside your ready event, but it needs to be outside the ready so be sure to double check that :)
client.on('guildMemberAdd', async (guildMember) => {
console.log(guildMember); // View the member data
await guildMember.guild.channels.cache.get('ChannelID').send(`Hello, World! ${guildMember.user.username + "#" + guildMember.user.discriminator}`);
});
// The goodbye message is pretty much the exact same, but we'll use the guildMemberRemove event
your ready event, but it needs to be outside the ready so be sure to double check that :)
client.on('guildMemberRemove', async (guildMember) => {
console.log(guildMember); // View the member data
await guildMember.guild.channels.cache.get('ChannelID').send(`Goodbye, World! ${guildMember.user.username + "#" + guildMember.user.discriminator}`);
});
// Add bot login, ready event, etc.
I decided to go with an embedded message because it is cleaner and gives more writing and linking options. Thank you so much #baeonette for laying out the code in a different way so I could understand what I am doing a little better. Here is the error free code:
// Import Discord.js
const {
Client,
Collection,
GatewayIntentBits,
Partials,
EmbedBuilder
} = require('discord.js');
const { token } = require('./config.json');
// I like importing the intents and partials this way, just to make things a little more visible.
// But the main things we're importing here are the Guild, and GuildMembers [PLURAL]
const { Guilds, GuildMembers, MessageContent, GuildMessages } = GatewayIntentBits;
// And here, we're importing the GuildMember [SINGULAR] for our Partials
const { User, Message, Channel, GuildMember } = Partials;
// Create Discord Client
const client = new Client({
intents: [
Guilds,
GuildMembers, // IMPORTANT
GuildMessages,
MessageContent,
],
partials: [
User,
Channel,
Message,
GuildMember, // IMPORTANT
],
});
// When the client is ready, run this code (only once)
client.once('ready', () => {
// Adding the GuildMembers to our intents, and GuildMember to our partials allows for us to
// receive the info we need for a welcome message; ei. when a member joins
// And lastly, when a member joins. I noticed you had the event inside your ready event,
// but it needs to be outside the ready so be sure to double check that :)
client.on('guildMemberAdd', async (GuildMember) => {
console.log(GuildMember); // View the member data
});
client.on('guildMemberAdd', guildMember =>{
const embed7 = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('A title')
.setURL('https://paypal.me/tripbranch')
.setAuthor({name: `${guildMember.user.username}`, iconURL: guildMember.displayAvatarURL({dynamic: true}), url: 'https://paypal.me/tripbranch'})
.setThumbnail(`A picture.PNG`)
.setDescription('A description')
.setImage(`A picture.PNG`)
.setTimestamp()
.setFooter({ text: 'A footer', iconURL: `A picture.PNG` });
guildMember.guild.channels.cache.get('Channel ID here').send({embeds: [embed7]})
});
client.on('guildMemberRemove', async (GuildMember) => {
console.log(GuildMember); // View the member data
});
client.on('guildMemberRemove', guildMember =>{
const embed8 = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('A title')
.setURL('https://paypal.me/tripbranch')
.setAuthor({name: `${guildMember.user.username}`, iconURL: guildMember.displayAvatarURL({dynamic: true}), url: 'https://paypal.me/tripbranch'})
.setThumbnail(`A picture.PNG`)
.setDescription('A description')
.setImage(`A picture.PNG`)
.setTimestamp()
.setFooter({ text: 'A footer', iconURL: `A picture.PNG` });
guildMember.guild.channels.cache.get('Channel ID here').send({embeds: [embed8]})
});
console.log('ready');
});
// Login to Discord with your client's token
client.login(token);

Discord.js music bot stops playing

My discord.js music bot randomly stops playing music.
Here's the error report:
Emitted 'error' event on B instance at:
at OggDemuxer.t (/Users/myName/Bot/node_modules/#discordjs/voice/dist/index.js:8:288)
It says the error type is an "ECONNRESET" (code: 'ECONNRESET')
After this error the bot shortly goes offline and the code stops running (all commands don't work)
The code that I use to play music is as follows:
const { Client, Intents, MessageEmbed } = require('discord.js');
const { token } = require('./config.json');
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('#discordjs/voice');
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
client.once('ready', () => {
console.log('Ready!');
});
const videoFinder = async (search) => {
const videoResult = await ytSearch(search)
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
client.on('messageCreate', msg => {
if(msg.content === '!join') {
connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
})
if (msg.content.substring(0, 6) === '!play ') {
let searchContent = msg.content.substring(6)
async function playChosen() {
let ourVideo = await videoFinder(searchContent)
const stream = ytdl(ourVideo.url, { filter: 'audioonly' })
const player = createAudioPlayer()
let resource = createAudioResource(stream)
player.play(resource)
connection.subscribe(player)
}
playChosen()
}
}
client.on('error', error => {
console.error('The WebSocket encountered an error:', error);
});
client.login(token);
I know the code is kinda messy, but if anybody could help, I'd really appreciate it! Also, I use discord.js v13, and the bot will typically play part of the song before this error comes up.
Yet again, I've posted a question that I quickly found an answer to lol. The problem here was being caused by ytdl-core, which would just randomly shut off for some reason. Play-dl worked much better to combat this. Here's a link to the place where I got this info:
Discord.js/voice How to create an AudioResource?
play-dl link:
https://www.npmjs.com/package/play-dl
example:
https://github.com/play-dl/play-dl/blob/5a780517efca39c2ffb36790ac280abfe281a9e6/examples/YouTube/play%20-%20search.js
for the example I would suggest still using yt-search to obtain the url as I got some wonky results using their search method. Thank you!

How to code a bot to send a message if they ping the owner

I am trying to make a bot say a message when the owner is pinged, a bit like this.
User: #JetSamsterGaming please respond.
Bot: (deletes message) #User You cannot ping JetSamsterGaming!
Thanks!
The Message has a property called mentions (MessageMentions) which contains all the mentions (roles, channels, members, users).
You can use MessageMentions.has() to check if the owner was mentioned in the message.
const Discord = require("discord.js");
const client = new Discord.Client();
const ownerId = "ID";
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(ownerId)) {
await message.delete();
message.reply(`You cannot ping my owner!`);
};
});
client.login(process.env.DISCORD_AUTH_TOKEN);
//setup stuff
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
//real code
client.on('message', msg => { //when a message is sent
if(msg.content.includes("<#!id>")){//checks if they pinged the owner.
// you can get the id by right-clicking the profile and copy id. you will need to turn on developer mode
msg.channel.send('You cannot ping that user');
msg.delete() //deletes the message
}
});
client.login('id');

channel.send is not a function? (Discord.JS)

Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}

How to get all the mentions from an user in a channel discord.js

So, I'm trying to create a simple bot that when the user writes:
!howmanypoints {user}
It should just go to a specific channel, and search how many times it was mentioned in the specific channel.
As of now, I encountered the function fetchMentions() but it seems deprecated and the API doesn't like it when a bot tries to do this..
Any input or at least a better approach for this. Maybe I'm fixated with making it work.
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('message', msg => {
if (msg.content.includes('!howmanypoints') || msg.content.includes('!cuantospuntos')) {
const canal_de_share = client.channels.find('name', 'dev')
const id_user = client.user.id
client.user.fetchMentions({guild: id_user })
.then(console.log)
.catch(console.error);
}
})
ClientUser.fetchMentions() is deprecated, and only available for user accounts.
As an alternative, you could fetch all the messages of the channel and iterate over each, checking for mentions.
Example:
let mentions = 0;
const channel = client.channels.find(c => c.name === 'dev');
const userID = client.user.id;
channel.fetchMessages()
.then(messages => {
for (let message of messages) {
if (message.mentions.users.get(userID)) mentions++;
}
console.log(mentions);
})
.catch(console.error);

Resources