Code Your Own Discord Bot - Event Handler & Command Handler V2 (2021)
HTML-код
- Опубликовано: 17 окт 2024
- Code your own Discord Bot! Event handlers and command handlers are the best way to organize your discord js bot. This will allow you to structure your code and provide a better and safer way to create a discord bot project. Code your own discord bot this way and you will see how useful these handlers can be. In the next following video, we are gonna start getting creative. Keep a lookout!
ScreenBar Plus Links:
BenQ Website: bit.ly/2ZIzWA3
Amazon Link: www.amazon.com...
Twitter: / usbenq
_______________________________________
🡺 Discord Server: / discord
🡺 Twitch Channel: / itzalesh
🡺 Second Chanel: / aleshgames
🡺 Playlist: • Code Your Own Discord ...
🡺 Twitter: / itzalesh
NodeJS: nodejs.org/en/
Visual Studio Code: code.visualstu...
Discord Developer Portal: discordapp.com...
Permissions Calculator: discordapi.com...
Come join my discord server -> discord.gg/lyon
I got banned from it for saying "Ni||ceCa||rs"
LMAO
@@BTWJrMo LMAO well at least you've memed
@CodeLyon the events dont work
@@AcridDragoon Join his discord and ask for help and they will help you. (And yes it still works)
For all those that struggle with adding a bot activity in the ready.js file listen!
Caution at 11:15 you need to switch Discord and client around so the order is (null, client, Discord). In every other file it's always client and then Discord.
This is the reason that your bot activity doesn't work when adding it to the ready.js file. If you look at the first line there (in the ready.js file) the order is client and then Discord and not the other way around as stated at 11:15.
Took me a while to figure that out but other than that great video!
i trusted you on this and it ended up breaking my code lol
@@squish162 to fix it just go to message.js at line 3 *module.exports = (Discord, client, message) => {* change it to:
*module.exports = (client, Discord, message) => {*
Thanks man i stayed hours looking for a solution and i didnt find liked and subbed (not an alt) for real
@@giahuynguyen1914 i dont have a message.js
@@giahuynguyen1914 cuz mine is saying codelyon is online even tho i dont have that set
Great tutorial, love your vids!! Just wanted to add if anyone's getting an error saying Dirs is not defined, change all 'Dirs' to 'Dir' and retry.
WE WANT MUSIC BOT PART 2!
YES WE DO!!!
Next week :)
@@CodeLyon Less gooooo
BEST MUSIC BOT HERE I COME.
LETS GO!!!!!!!!!!!!!!
@@CodeLyon It never came out :(
for those of you getting the error saying bind is not a function, its because you have 1 or more files without module.export setup properly or have 1 or more empty files in the events folder
yo... i like ure teaching style! and also the VSC theme
That moment when you fix errors and it actually works and you feel so relieved...
😎😎😎😎
i swear
We won't get the music part 2 ?
Next week :)
CodeLyon Can you do where it supports soundcloud as well ?
@@CodeLyon oooooh yay
@@CodeLyon can you make the music bot have a queue system, loop, skip, and play spotify songs? pls thanks!
why mine is not working, it says TypeError: Cannot read property 'forEach' of undefined
.forEach
I have a question, my commands stopped working after this, I checked, but still couldn't find any mistakes. Please help!!! Could you please maybe leave a pastebin as a link of your code for me to double check, please!
the same happened to me
remove try and catch, if inside catch has console.log(error) then no
I love watching the time in the corner
when i try to type !ping it sais:
TypeError: Cannot read properties of undefined (reading 'get')
Same error :(
same :(
Sa:(
I was getting the event.bind function error until I seen this comment from a user I can no longer find, It said to replace the "['command_handler', 'event_handler'] lines with this code instead
var handlers = ['command_handler', 'event_handler']
for(const handler of handlers){
require(`./handlers/${handler}`)(client, Discord)
it still not working for me
my bot is not responding to any of the commands i put on discord, but i have all the code copied exactly. Can someone give me any clues as to why it isn't working?
edit: this is my first time touching js ever so i have no clue how to debug this
I am getting an error from the event handler saying event.bind is not a function
I was literally working on my own command handler but im gonna use this because mine is very unoptimized
PS: i watched your how to make a discord bot tutorial back in november and 2 days ago my bot got verified! So thanks.
congrats!
ahahah i watched it too around november but i'm not getting mine verified any time soon cuz i'm making it personalized for my server so i only have it there, but i'm planning on doing one that i hope will get on many servers so i can get it verified ^^
nice
Great video! Cant wait for music part 2 though xD
Hi, can you create a video on how to get a bot to write the status of how many servers the bot is on?
please
🙏🏽
or if you want the server count instead of member count use client.guilds.cache.size instead
@@senoryx thanks, it worked
for servers: message.channel.send(client.guilds.cache.size)
Guilds Count - client.guilds.cache.size
Users Count - client.users.cache.size
Channels Count - client.channels.cache.size
Emojis Count - client.emojis.cache.size
it is easy just type client.on("ready", () => {
client.user.setPresence({ activity: { name: `>>help, Watching ${client.guilds.cache.size} servers!`}})
})
everything works fine and i can even add more things to the handler thanks a lot!
How would you implement the code from the Member Counter video in this manager? I tried but i keep getting errors like 'membercounter is not a function'
bump
To do the member counter, change your ready.js script to...
module.exports = (Discord, client, message) =>{
const memberCounter = require('../../counters/member-counter');
console.log('Tyrcnex Bot is online!');
memberCounter(client);
}
@@davmp4 To do the member counter, change your ready.js script to...
module.exports = (Discord, client, message) =>{
const memberCounter = require('../../counters/member-counter');
console.log('Tyrcnex Bot is online!');
memberCounter(client);
}
To properly add something like the guildMemberAdd function, add the .js file with the same name to your guild folder.
The code should look like:
module.exports = (Discord, client, guildMember) => {
let welcomeRole = guildMember.guild.roles.cache.find(role => role.name === 'member');
guildMember.roles.add(welcomeRole)
.then(client.channels.cache.find(channel => channel.name === 'general').send(`Welcome to our server.`));
}
It's important to notice that when we create the invite handler (ignoring the null input) we have two arguments (Discord and client). So our guildMemberAdd function must (!!) have those arguments in that order, plus the original variable of the old code when we just passed in guildMember. So in total 3 arguments.
Since NodeJS recently updated, old videos such as the Welcome message video does not work anymore. An updated tutorial or even a paste-bin fix would be lovely!!!
@CodeLyon pls do it
For me, it works fine. I have it set up in my Discord server.
Enable Intents
@@refraynn same
@@Ducxy how do you do that?
Happy New Year CodeLyon!!
WAIT!! YOU ACTUALLY COMMENTED IN DASHCRUFT video
@TK GamingHub Yoo Ubaid7
How to fix event.bind is not a function??
I also have this problem ):
I have the same problem, do you guys found the solution?
This is not really a solution, but I just kept deleting amd rewriting a whole bunch of code. event.bind is indeed a function so it is most likely that you have one tiny thing misspelled or written wrong. Also make sure to be running an event in the client folder when you start the bot for example the ready.js that he went over
this is for everyone thats having problems. make sure that the client, discord, message are in order. this took like a whole day to figure out....
thank you dude
Heya lyon! I started to create a new bot just a few weeks ago thx to ur channel, i love ur tutorials and u helped me a lot.
Just one question, if i can ask: the command for the reaction roles stops working after 24h plus or less and i cant find the problem. I host the bot with heroku cause a my friend told about it. Any suggestions? Or at least something to make it resend the embed with the reactions every, dunno 10h? Or something like that.
Sry for eventually grammar errors, but i m italian and i kinda suck in english :/
Ok solved, its an heroku problem cause that host sucks, you just have to find another one
Once i do this will the commands from the previous tutorials begone?
@codeLyon, can u add the code link?
Yes please do that!
so i got an error from message.js saying _const command = client.commands.get(cmd)_ is undefined
idk what i did wrong but _const command = message.client.commands.get(cmd);_ worked for me
Was banging my head on my desk for a good hour, you're doing gods work. Thank you.
@@erio6812also took me a while to find a fix, so i thought i should share it. glad i could help!
You are god ! I was so frustrated thank you so much.
Can you go trough your videos and do like #1 , #2 , #3 on the videos so people knows who to watch 1 after another?
Anyways great tutorials.
Anyone else getting an error in the message.js file. The command.execute is somehow giving me problems.
These are *so* helpful man
This is wayyyy better than the old command handler, when I tried clearing the message it kept on saying pong, now it does everything fine. *It actually listens to me.*
can you help me, the get command in "message.js" not working well...
(the terminal saying "Cannot read property 'get' of undefined")
Your variable order is wrong, make sure they match
*HANDLERS*
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
*EVENTS*
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
same
one problem. All commands work but if i do -play and type key word it wont play, only if it is url. any help?
this just broke all of my command. There are no error in the code, but all of my command doesn't work. Why is that ?
same
Not really sure if this will fix but here is a solution
Maybe the variable order is wrong
*HANDLERS*
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
*EVENTS*
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
@@DeathlyBower959 wow thanks for the solution, I'll try to check it maybe. But I'll stick to the old one. It works just fine for me. Thanks for solution though 😊
@@ud1n np
when i try to run a comnand i get this error:
const command = client.commands.get(cmd);
Cannot read properties of undefined (reading 'get')
I'm getting the same error. Not sure what I'm missing
I think you should make a quiz command video. I did one and I think other people would like to know about it too :)
yeah
It doesn't work with my old code from your video tutorial for some reason. It keeps on saying something is undefined.
just means you made an error or typo
Not really sure if this will fix but here is a solution
Maybe the variable order is wrong
*HANDLERS*
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
*EVENTS*
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
Very good video ;) / idea: Ticket command with Reaction!
I have an error where visual studio code keeps telling me MODULE_NOT_FOUND and keeps referencing the directory things you put in there like './handlers/${handler}'. I don't know what I've been doing wrong and I can't find any answers. I would very much appreciate help if someone else has found this too.
i know this is a tad late but if your still stuck on this replace the ' with `
Thank you so much! This helped me a lot
You mentioned there is a way to not have to pass Discord into every file at 14:30. Do you mind giving me a link or something to where I can learn how to go about doing that? Thanks!
did u ever figure this our bro
@@Fallenuk8 I haven't yet, sorry
can someone help me? so the code has no errors and the bot runs properly and is shown online at discord, but it's not responding to any commands whatsoever.. I don't know what I'm doing wrong. I have also already given it the proper permissions to be able to send messages.
Thank you for reding the documentation in our behalf :)
Suggestion, fun bot commands, maybe like the random image one you did in 2019 or like a mimic command
yes really that is required
To re-add the "GuildMemberAdd" just go to main.js and add this code under the "['command_handler', 'event_handler'] part:
edit the roleName variable to what your role name is
client.on('guildMemberAdd', guildMember =>{
const roleName = 'member';
let welcomeRole = guildMember.guild.roles.cache.get(role => role.name(roleName))
guildMember.roles.add(welcomeRole);
});
i did the event handler but now none of the kick/ban/mute commands work even tho i put client in front of them :/
did you fix it? I don't even know what to do with my commands
@@puresheep5863 no dude in discord server noone helps either
Not really sure if this will fix but here is a solution
Maybe the variable order is wrong
*HANDLERS*
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
*EVENTS*
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
Getting Error: Cannot find module ( name of my commands ) when i do node . any fix?
You might have messed up in naming the files. Check for any capitalisation error.
Or check out the path you've listed out
Imma gonna try it today anyway
The legend is back yayy
Your videos are amazing! How do you make the bot DM a user when they are banned/kicked with the reason? Keep up the great work!!
It will not work. Because when the user is not in a mutual server of bot it will not work due to discord privacy. If your bot is global than it will work
@@hasan9.11 no, you are wrong lmao, I figured this out a while ago
Yo amazing vide codelyon, pls continue the series
why im getting this error i checked the code 100000 times it is just the same as your codes!!!
TypeError: require(...) is not a function
at C:\Users\Ali\Desktop\discordbot\index.js:9:38
at Array.forEach ()
at Object. (C:\Users\Ali\Desktop\discordbot\index.js:8:38)
the line is:
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})
i really dont understand why im getting this error
Good video.
I have some problems implementing handlers and commands this way:
I lose every reference and autocompletion functions that Visual Code provides because the file references are done on execution time and not staticly (thats how I understand it). So, is there anyway I can make it work and do not lose those funcionalities?
Im a bit confused. In the main file i had more than just "client.on('ready')". If you have something like "client.on('guildMemberAdd', async guildMember => ..." what code you need to add to the guild file in the events folder?
@@yeetsaboi7727 HELP
i cannot get the guildMemberAdd to work with this... can anyone help me? i do not get any errors so i dont know where i did something wrong
Me too
@@canmann4485 To do the member counter, change your ready.js script to...
module.exports = (Discord, client, message) =>{
const memberCounter = require('../../counters/member-counter');
console.log('Tyrcnex Bot is online!');
memberCounter(client);
}
Hmm, So I am wondering is there any other reason besides how clean it looks?, would it for example run faster? will it be able to handle more at once ?. or does this not change
it just make it cleaner.
if you make it cleaner, you can work faster
It is easier to implement new functions
more efficient, less event listeners
i am getting something like 'TypeError: Cannot read property 'get' of undefined' can someone help me abt this?
in one of your files, you have the variable order wrong, make sure your variable orders line up
**HANDLERS**
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
**EVENTS**
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
same
How would I get the command handler to read subfolders? Also couldn't I put the handlers in the guild events folder?
exactly
I Keep On Getting This Error Can Someone Help Me Error: ENOENT: no such file or directory, scandir './events/client'
Thats happends for me too
@Squeaky Rubber Ducky Thats what I did.
@@blakejohnson7998 make sure events is not in handlers or any other subfolders
Amazing video. thank you so much!
please i need help. command handler doesn't works its just the erroe saying execute is undefined
Can i get a pastebin i have done it way too much time so is that pssible
The legend is back!!!
I have literally the same code but it says its missing intents, this doesn't work
Downgrade your discord.js to v13 or do some research
Suggestion: Could you do a video on these commands
Custom status
meme
Auto anti swearing
Help command
Mute channels
Auto-moderation
Games like discord tic tac toe or snakes
setting prefix
Also happy new year Alesh, thank you for the videos
i know how to do the custom status
client.once('ready', () => {
client.user.setActivity(`whatever you want in here`, {type: 'PLAYING'}) // PLAYING, WATCHING, LISTENING, STREAMING
console.log('your bot name is online!');
memberCounter(client);
});
you can do PLAYING, WATCHING, LISTENING, STREAMING in the place it says type so there you go
@@cheyennehamilton5423 Thank you! but where do I put it, cause it looks like it will be putted on main.js
Help you can do
Message.author.send(‘test’) // will send to the users ~DM’s
@@presenterhaven625 Could you DM on Discord so I know how to do it
Quick Question. Where does the code for adding a role to a new member instantly go? You change it so it doesn't go anywhere now?
@Raheb thanks bro
@Raheb in germany we call people like you "Ehrenmann"!, i tried so solve this problem for my own in the last 2 hours an nothing worked!
now my bot doesnt do anything for some commands
there are no errors too
please help
Not really sure if this will fix but here is a solution
Maybe the variable order is wrong
*HANDLERS*
event_handler.js:
module.exports = (client, Discord) => {
//the code
}
coommand_handler.js
module.exports = (client, Discord) => {
//the code
}
*EVENTS*
ready.js
module.exports = async (client, Discord) => {
console.log('Bot is online!')
}
message.js
module.exports = async (client, Discord, message) => {
//the code
}
index.js / main.js
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
If they are not in the right order, they pass in in the wrong variables
I have problem on main.js it writes: client.commands = new Discord.Collection(); | ReferenceError: client is not defined what i can do to fix it ?
Define the client. before you create client.commands, above it you need to first declare the client, so: const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
For All The People that struggled here is the ready.js file that works
Link:pastebin.com/zaYPbduL
can we get the code pls as i got some errors and people in your server did not help
for(const file of event_files){
^
ReferenceError: event_files is not defined
at module.exports (C:\Users\**\Downloads\------------\handlers\event_handler.js:8:23)
at C:\Users\Si\Downloads\SapBotBeta\index.js:10:37
at Array.forEach ()
at Object. (C:\Users\**\Downloads\------------\index.js:9:38)
Sorry can anyone help? When the prefix is sent in a channel, it does not run the command that was typed but no errors occur. What do I need to add?
edit: I fixed it. I accidentally wrote a , instead of a . where I add the file.endswith
Hi, I have this error
const command = client.commands.get(cmd);
^
TypeError: Cannot read property 'get' of undefined
client.command.get(cmd)
**you don't need the s in command**
@@Circlity Oh yeah sorry I never saw that comment, I managed to fix this.
got error:
TypeError: require(...) is not a function
at /home/runner/Polaroid/index.js:9:35
at Array.forEach ()
at /home/runner/Polaroid/index.js:8:37
at Script.runInContext (vm.js:130:18)
at Object. (/run_dir/interp.js:209:20)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
where did you define 'dirs'??? it says that dirs is not defined!
please answer fast!!!
So in const load_dir it’s = to dirs not dir I had to figure it out
@@gdmercy6969 i dont understand. I have a const load_dir = (dirs) and then a => but i dont understand wdym
it's dir not dirs
that just made my server.js drop from 680 lines to 120 thank you lmao
suggestion (maybe irrelevant, but i like it): how to group commands in categories
a lot of old references do not work after this, pls do a tutorial on how to fix it!
I replace the old command handler with this new one and now the embeds dont work.
Error: "TypeError: Discord.MessageEmbed is not a constructor"
I'm using discord.js v12 and the latest version of NodeJS. Idk what's the problem :/
@@chapel1337 i solved it, you need to write "const Discord = require('discord.js')" above the module.exports line
it doesnt work pls help i did everything but the bot won't respond
thank you so much for this code method, but after setting all this now my bot is replying more than one time. Please anyone help.
am i going crazy? why does client look like a file on your end not a folder? oh... i should've kept watching XD
Which theme do you use bro (of VS Code)
@@yeetsaboi7727 oh ok
thanks
i have this error :
PS C:\Users\svenn\OneDrive\cayo> node .
Cayo's manager is online
C:\Users\svenn\OneDrive\cayo\events\guild\message.js:3
if (!message.content.startsWith(prefix) || message.author.bot) return;
TypeError: Cannot read properties of undefined (reading 'startsWith')
at module.exports (C:\Users\svenn\OneDrive\cayo\events\guild\message.js:3:29)
Did you fix it
Followed everything in the video but still get
TypeError: event.bind is not a function
How would I fix this?
i just rewrote event_handler.js and it fixed somehow
There is a small error that I am not able to identify
"TypeError: Cannot read property 'content' of undefined"
how do I fix this?
Same here, but is recent. A month ago i didn't had this error
@@lorycave1292 do u still have the error?
@@gutluckbro9802 yes, i asked on the discord server and they helped me
@@lorycave1292 yeah same here, just got reminded of ur comment and I was curious if u still had the problem. Anyways good day!
@@gutluckbro9802 can you help me out?
What theme are you using???
warn system, suggestion & bug system, ticket system and perms
everytime i do node . it tells me ReferenceError: e is not defined
Where would I put the welcome and auto-role message for new members?
why is mine not working??? when I start running it it doesnt give any error it just doesnt run
great video but how would you send a message if user typed an incorrect command?
TypeError: Cannot read property 'get' of undefined
@@Armond777 in your message.js file, in module.exports = (Discord, client, message), change the order by switching client and Discord so it would look like this (client, Discord, message)
@@_Vap you're a lifesaver man, thank you!
@@_Vap I LOVE YOU I WAS STRUGGLING DOING CONSOLE LOGS TRYING TO UNDERSTAND WHY THE CLIENT WAS COMING OUT SO WEIRD THANK YOUUU
in what language is it better to write a bot? python or js
Depends on which one you can understand and do better
Can you post the code please? I really need it because i cannot find the issue i have
Thx for tutorial you are OP
how do u do that thing where he turned all his code grey
When I switched to this command handler, my bot stopped responding to my commands. Is there anything wrong with my code?
same here
do you get any errors?
@@luigiboy72 i fixed it :)
@@itzgoku07 How did you fix it? Mine still won't respond to any commands.
Have you installed ffmpeg and other packages
Awesome when are you going to finish your music series. I really need a music bot