Build a Discord bot 🤖 with Daniel Shiffman of The Coding Train 🚂

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello friends welcome to coding garden with CJ welcome to a very special episode where I will be coding with the coding train please say hello hello I'm here yes we're actually not in the same room together even though it looks like it and there are lots of there we go nice nice there are lots of jobs happening on the screen so we'll just been a few minutes saying hello to everyone and then we're gonna get started but the plan today is to build a discord bot so if you go to github.com slash coding garden slash intro - discord - bot that's where all the code we're gonna write today is we have a pretty simple to-do list which we're gonna get to in a minute and that's the plan and if you are not subscribed to the coding train please do you probably are a lot of the viewers here on the coding garden came from the coding train so and let's see how interesting it's fun it's fun to see like what my channel looks like from a different account which action actually that's one of the things that I actually never did so confusing the YouTube interface there's like different ways to configure what your channel landing page looks like and you can you can configure to look at it from different perspectives I never understand but it's good to see that this I don't know if this is what I intended it to be now it's a same thing happens on my channel just trying to configure it but can we do a virtual high five real quick yes I can't I don't see where I'm reaching - okay oh I can do this is as far as my camera goes welcome to the show and if you look at my screen show you can see all the chats that I'm mmm in hello a great game what's happening okay I recognize a lot of these names coding drain viewers yeah okay hello code with Dinesh welcome oh no my app has broken okay we'll just scroll um I have this effect on other YouTube channels I come in and I break all the technical stuff since I'm always having technical issues yeah oh and uh let us know if you're watching live can you hear Dan okay can you hear me okay how are the levels and thanks for the twitch follow tank 337 welcome to the show what's up for us hello hello infi what's up welcome hello cool brick hello Dan hello Paulo dan says I already can code bots I need to go All Right see you later hello Pam who says I have exams to Mary and there are quite a few people mentioning it they have exams so I can watch watch the vod's later and hello Danielle welcome we're gonna be streaming for a little over oh no little less than hour and a half we'll say at least an hour for sure and thanks for the twitch follow X Romeo yeah this will be a shorter one yes I actually have always just put it out there that I'm getting my hair cut so tomorrow I would a live stream tomorrow okay you'd see this Harry will be gone if I make it to the appointment and everything goes according to plan it's been quite a while yeah yeah and this collaboration is definitely a long time coming so like over a year ago yeah in September of 2018 I was actually in New York City and I got to do a livestream in dance studio and so that was fun but this collab that that collaboration in particular I kind of just had a lesson planned and just kind of taught it this time we're gonna try to be a lot more interactive and code together and pair and do all that good stuff I feels like that was so much more recent then I mean I guess it still it's less than two years ago cuz it was September ya know and in that video has definitely got a resurgence recently yes it's very strange how this and we've talked about this but it's very strange how YouTube whatever the mysteries are behind how it recommends videos but I've had certain videos well just that are years old well just for a few days suddenly be watched by thousands of people and then go right back to like you know being at the bottom of the pile yeah and you know for better or worse it's sort of like a fun thing to track but the that coating guarded collaboration it's like currently on this like big guys must they must have known somehow they're like hacked into our emails or discord messages about planning yeah they know what's gonna happen yeah thanks for the twitch follow our June Danielle says good luck on your papers and exams yes good luck to everyone out there that's how to have his exams recently good luck to your papers and exam yeah we were a little bit behind but I'm pretty I'm pretty glad we got all that most of the technical difficulties worked out before the stream started so crossing my fingers cool all right I think that's enough catch up there's so much chat well I'll try to keep keep track if I can and I pull out I will keep the the chat open on my screen but there's a lot of people watching so we may not get to all of the chat messages cool and I'm seeing them as well because I'm seeing your screen share so if I notice something as you're talking and doing stuff I can reply to it yeah feel free okay so I know you're all enjoying the drop game but I am gonna disable it cuz it's very distracting alright one last drop from Aaron I know bin Aaron Dahmer and a drop from Doc oh yeah a nice drop doc okay it's going now awesome okay so the plan today is to just build a very basic discord bot and we are going to be going to be using discord j/s which is a javascript library for interacting with discord and the plan is to kind of just walk through how do you create a bot how do you add it to a server get a basic bot going and then we'll create some basic commands like an echo command like you send the bottom message and we'll send it right back and then something like an Eightball command where it can give you a random prediction of some yes or no question and then if we have time which may not some other command which I have in mind and maybe we'll get to that so I guess first up Dan what do you know about discs or J yes sir escort BOTS well I know so did discord is actually pretty new to me I had been trying to find ways to engage with the community that viewers of the coding trade outside of just the YouTube chat YouTube comments and for a while I had been using like an unpaid slack and that I had available for just for people who signed up as patreon or members or whatever and so recently I switched everything over to discord there's a public discord I don't you know I don't know to what extent people have room for so many different discord in their lives so if you're in the coding garden one and that's where you're kind of like talk about code and get your help just stay there but if you want to join both they're also a coding trade discord as well and so I'm kind of new just figuring out I'm really enjoying it but and so in terms of actually working with programming a pot for discord I know next to nothing but I have worked with a pis and other kinds of thoughts I have a tutorial series about making a Twitter bot the tutorial serious about making a mastodon bot and one of my goals for this is kind of like to learn a bit about how to build a discord bot so because I have all these tutorials around text generation and text analysis so if we could if I can learn through this about a little more about discord BOTS I want to see if I can do some of my own tutorials about building a discord box with like different machine learning models if I yeah and the cool thing about it is it's all JavaScript and node.js so like anything you can do with JavaScript you can just bring into this node but awesome okay so I got a donation so shout out to critters for the five dollar donation and we got rated by a pixologic dev I believe let me catch up are you familiar with raids in a raid yes I'm only familiar with raids because coding garden raids coding training yes I love that yeah so YouTube does have that feature so we tried like a cross-platform rate I was like here's the here's the live link let's everybody go over there but on twitch you can actually look like an actual thing yeah it's like an official thing yeah so here is pixologic dev rated with 27 viewers welcome everyone welcome to the show we actually are just getting started and the plan today as you might have heard is we're building at his court bot yeah so basically everybody that was in pixologic dev stream is now potentially watching my stream and thanks for all the followers there's a lot of chats coming in so I won't be able to acknowledge everything but I really appreciate it thanks thanks for dropping by everyone hello hello hello and floran is asking where are you guys I I'm in Denver Colorado and he's are you in Brooklyn New York I mean yeah I'm in Brooklyn New York cool it's an illusion magic yeah and I'm pretty excited to get this set up because it looks like we're in the same room which is cool and the interesting thing is on my streams I'm always on this side of the screen and on your streams you're always on that side that's right so it worked yeah and I have the monitor setup where I'm looking directly at cj over there and so that I believe I don't actually see in the live stream but I believe it looks like to the viewers like I'm looking and gesturing right - yeah and there's another tip from Jorge Pascoe for $2 who says keep it up you guys you're awesome and a huge inspiration to me Thank You Jorge much appreciated thanks pixologic WI we'll see you around yeah so we look like we're in the same place but we're not okay so let's get to it so here's here's the plan first we're just gonna set up the project and I will let you run all of these commands down so you should be able to on my screen so currently we are in this discord bot directory there's nothing here so let's initialize it as an NPM project so if you just do a NPM init space - why this is so freaky I mean it shouldn't be because it's just like I'm typing into a computer but the fact that it's like through this magic of this screen so uh and what is it NPM in it oh right I need sayin it at first space stash y-yeah what's the - why it will not ask you any questions if you hit enter it uses all of my defaults oh I did not know that was the thing amazing yeah so now it basically because I've answered all those questions before it automatically yeah and the author and the license and all that good stuff how did it get the URL for the repo that was already initialized so it was already initialized okay Fred you already had as a remote okay wait sorry yeah so because I had already created as a git repo it pick that up and added that in I gotta to cool and then we need our dependencies so the first one is discord jst if you just do NPM I it's quite I not - I sometimes it doesn't pick up my typing how interesting okay is it dot J s or just discord all right I don't see anything I am yeah it didn't pick it up okay now it's got it has it NPM space come on space oh no it says I am controlling yeah we might have to set up a live share if this doesn't work yeah I think I think I was like I think that's worth trying well okay just just because there won't be any lag cuz I can actually share my terminal through fia's code live share oh okay so I'm gonna hide my screen for just a second in the drop game I'm not going so if you want to play it okay I have never used live share before so I'm kind of excited to try this I've always been curious as to whether live share is something would make sense for physical in-person teaching like students in a classroom like 16 students all having digital studio code and like so the stuff that I'm typing would appear on their computers could be something for me to try yes this is going time and I've done that live on stream before because you can create a read-only session so that way people can connect and they can see all of your code and files but they can't edit anything so actually works really great for people that are like learning they want to see the code so I just shared a link with you if you click that on your laptop it should launch vs code and then you'll have to log in if you're not yet logged in yeah okay okay joining don't have installed the extent Visual Studio code okay install the extension I might not have this is actually it's not installed so it's installing the extension okay would you like to reload the window and open the URL yes and so let's sign and continue so I should sign in and I'll sign in I guess with with github baby yeah yeah so authorize visual studio code lifeshare open visual studio code Wow so many things that's asking me to do enter the URL of the collaboration session yeah so now that you're logged in you probably just can click the link again yeah okay and mint in the chat asks what vs code extensions do I use if you type exclamation mark vs code in the chat you'll get a link yeah there you go somebody did you'll get a link to all of my BS code settings alright it says you think I'm in ok so let me share a terminal now one thing I'm curious about is it using my settings in terms of like font size so if I mess with those am i messing no so it's what people see is just my screen so if you zoom in or out they're not going to see that and I just shared my terminal so it should have popped open for you do you see it yep I see it cool so now you can actually over here and let me share the screen again all right we're back and now let's try typing in that terminal so in p.m. space I see NPM space I just Gore Jas and that's really and I think that's the only dependency Oh we're also gonna install a dot E and V so that we couldn't hide our bots token so NPM eye space do T E and V it's not letting me use up arrow how interesting okay yes you can your ways or MPN awesome and then the next thing we'll do is set up PS lint so because we're gonna be pair programming we want to have some rules for doing that so yeah and - capital D installs it as a dev dependency got it and do you already is it where is it pulling the kind of configuration rules for eslint or is it using a default sort of configuration we're gonna set that up Nick so that come in NP X yes lint in it that will ask you a bunch of questions and we can talk about our like whether it's gonna be like we're dying to get anything done cuz we're gonna just talk about semicolon I think we have very similar coding styles okay okay and now let's try to do that so NP x yes lint space - - in it it's gonna ask us some questions so let's choose the bottom one to check syntax find problems and enforce code style okay we are using common JSO arrow down to that one because this is and what is common jail yeah so that's require in module dot exports and then like import-export is the new es2015 no syntax we are using neither of those so you can say none of these and then no texture this is going well all your code run right yep so you press spacebar to check it and then uncheck I'm gonna start doing this by the way I had no idea this is so cool use a popular style guide yes this is where it comes in so usually I just I use the Airbnb style guide cuz it has a lot of the things that I prefer like semicolons single quotes instead of double quotes preferring Const over that but let's answer questions cuz it's it's a thing to see oh yes okay I'll let you answer all the questions so okay okay oh my goodness I have so much power in this stream choose JavaScript that's what I prefer not JSON yeah and then you can answer the rest questions spaces I actually agree hey do you like a single quotes I like so four spaces do you like a two space tab or a four space tab I like a two space tab me too everybody should love their own amount of spaces yeah I'm very I'm very open-minded so when I pair program with Elka he actually prefers tabs so here's the interest he might have converted me to tabs because if you choose tabs then I can view the code with a two space cat tab and he can view it with the four space tab and it doesn't actually have effective but a few spaces then he has to see it as a two space tab right well that that's very reasonable I would okay I prefer single quote UNIX yes oh my god yes that's it yeah those are the only questions I had answer I was expecting I really was expecting like how question so I mean you can definitely add a lot more like rules to it and so the if you look at the es lint rcj s that's the file that got generated and under E and V here this we accidentally said yes for browser but I'm just gonna remove that because okay this is all notes we can rid of that and then on line 18 this is the number of spaces in the tab and I'm gonna change this to 2 instead of 4 God and that should do it yeah cuz it's requires to make Owens require quotes so we actually have a very similar code style and before JavaScript I did see sharp which requires semicolons right I know that you didn't for me it was Java exactly yes which is basically the same yeah all right next up let's actually code the thing so what I prefer to do is actually put all of my source code in a folder so I'm gonna create a folder called SRC and what's nice about that is you can point yes lint at a folder and it will automatically lint all the files in that folder instead of having all the stuff in the root so I'll just present our index J s in there awesome and Elka's here hello Elka who says I love semicolons city cool winds for life yeah there's there's quite a quite a few differing opinions in the chat I feel safe with them and they're just like my friends and I want them to be at the I want to always be with them they to me it feels like the period on the end of a sentence and my my pinky is just like so accustomed to pressing the semicolons I don't know I actually like I'm like I'm like white what do a lot of like white boarding to teach different concepts and I find if I'm like writing things that have no code I'll start just like putting semicolons this is like - like punctuate a pointer movement definitely okay so that's awesome where our codes ready to go we can set up like a lint script really quick so if you look in the package.json I'm just gonna set up under scripts lint and we can do es lint SRC slash and so now if we have a run npm run lint it'll automatically tell us if there's any any errors like a missing semicolon or something like that does the autoformat of Visual Studio code pick up these settings or like I have like for example I have something that's like say format on save then I use and then I either I can't remember whether it's beautify our whatever I'm using to do like some auto beautification whenever I save is that tied to es lint or those are totally separate you might have to set that up separately but what I do so if you do command shift P that brings up the command palette yes and then if you search for es lint fix all auto fixable problems it's like where do I write this down somebody remind I wouldn't be live-streaming tomorrow somebody remind me about this I'm sure the internet will take care of it yeah basically there's a command in vs code that uses your linter rules to automatically fix things if it can which is similar to like beautify right okay so next up we need to actually create a bot so so if you look at my screen share you'll be able to like see my browser so you can kind of like walk through the stuff got it yep and so discord j/s guide is an awesome resource I believe its body the actual maintainer zuv the discord j/s library and so this is actually separate from the discord j/s documentation which is actually pretty terse and it's basically just like describing all of the classes and all of the methods available but the discord jeaious guide is very like user friendly and kind of like walks you through all the things that you need so this is absolutely great resource and over here we're gonna set up a bot so let's go there so basically you go to discord and login and then you can go to the developer portal so the developer portal is discord app comm slash developer slash applications you can see that I have two apps here we have the coding garden bot and my coding garden app and we'll just create a new application I think we're gonna call this a choo-choo bot perfect yes and then what we need to do so applications can be used for a lot of different things like you can use them for web hooks you can use them for like ooofff if you want to have people log in with discord but specifically we want to use this as a bot basically it wants to listen for messages and send messages in the channel so we want this to be a bot account so if we click bot over here and then click add bot this is what it says adding about user gives your app visible life in discord however this action is irrevocable choose wisely this is actually what we wanted to so I'll say yes and now we have a bot and I created that actually a very special image for this let's see if it oh I was gonna say I can quickly funnel you an image but it sounds like you've got something already here we go it's coding garden themed tree so this is our but and then the next step is to actually add this to a discord channel so if you look at the guide tell us how to do it so you basically have to go to this link as the owner of a discord server and so the client ID actually comes from the bot itself so in terms of like secret things you should never show the this token right here where it says click to reveal broken right that's if someone has that token they can do anything on behalf of the bot and if the bot has super admin privileges they could do like they could remove users and send spam messages so you absolutely want to keep that secret but you could quickly if you quick if it was revealed you could quickly just press regenerate and then that older token would be invalid exactly but you would need to update your like deployed application with the new yes yes yes yes yeah so cool keep that secret but if you look at general information that has the client ID and this is totally fine to share oh yeah and people are telling me in the chat make sure I hide the screen when we show that token I have revealed tokens on stream so many times so oh and I'm gonna choose the icon for the main application here as well cool so this client ID is what we need to actually add the bot to a disk where server got it so can could there be multiple BOTS per application is it is the application like a container for multiple things there's only one as far as I know there's only one bot per application got it but you can create as many applications as you want right it's just weird that there's like the application and the I guess it's not weird it's just that because I'm thinking only about making BOTS I'm not thinking about the other aspects yeah so like the other aspects are like web hooks ooofff different like that right okay so what we can do is we can get this link and we basically just need to replace the client ID with the client ID of our bot so I'm gonna grab that change it here and when I go to this link it's going to use my logged in account to determine what servers I can add it to so you'll see when I go here it's asking me to login don't scan that QR code that happened to me yeah basically if you scan that QR code I'll have full access to your account so please don't do that yes I'm gonna hide my screen for a second and log in to discord yeah I actually went back and in the archive of the video YouTube has a feature where you can blur stuff out so like after something's been broadcasted so I went back and like blurred the whole section where somebody had logged in by accident nice I forgot my password okay I'm gonna need to reset my password [Laughter] just give me one moment yeah assets Park has guests my password one two three four five no if it was that I wouldn't have to reset it yeah and someone's mentioning that's my password manager to just reset your password it used to be like I would remember remember no passwords and then every time I needed to login just reset it for like everything it's like a poor-man's two-factor authentication yeah okay don't scan the qr-code people they can't see much beer I know oh they can't see it I've seen it because I'm seeing screenshare exactly okay I don't I just telling myself don't see it definitely okay so I will show my screen again here we go so because I crafted that link so if you look at it again it's this thing and then change the client ID to be your actual client ID right it'll take you to a page like this and in the drop down you'll see all of the servers that you are basically an administrator of all the servers that you are able to add bots to so if you were had a certain level of privileges on the coding train discord you would be able to add the bots to it directly right now exactly that's my break timer if you want to take a quick stretch or take a drink of water oh I should definitely have a break timer hello Darryl welcome to the stream cool so yeah if you have access if you have the rights to add a bot to a server it's gonna show up here on the account you're logged in with and then we'll add the bot there so I'm gonna actually add it to the coding garden discord and then we can test our commands in there and one thing I'll point out is by default it doesn't have any like super admin privileges by default it's kind of just like a regular user it can see messages and channels it can send messages and channels if you want to change or if you want to give the bot more access you can change the URL and so in the and the guide they show you how to do that but basically but for a good starter bot it's just gonna interact by like replying to things and saying hello you don't need any more permissions exactly it's only if you need to like say hey bot add me to this role or you know delete my account or things like that exactly and also just really quick the basically the bots that I built for the coding garden discord it needs all of those those types of privileges because when you join the coding garden discord it actually adds you to this role called germinating which means you're not allowed to send messages in any of the main channels or see any of the main channel so it puts you in germinating and then once you respond emoji respond here it adds the seedling role although it keeps track of that and then if you send an introduction message it'll add you to the seedling rule so right that that bot needed those permissions and there actually is there is an existing coding train bot that operates in a very very similar way it was created by Kobe or Saint plays there's a bunch of different people have different nicknames and other people have contributed but I haven't I haven't actually looked at it or participated in the development of that so and I'm excited after this to like get more engaged with that particular bot and adding some of my own too as well definitely and you probably find it in the guides later but basically there's just another query parameter set the permission kind and that red give it those kind of versions all right can you you can adjust the permissions later after you've created the bar um after the know that from the outset you might have to remove it from the server and riad it I've never done that but well it would be possible yeah alright so I'm going to click authorize and and actually just a second ago it said it was used in one servers so someone probably saw my client ID and like added this to their own server for some reason but that's fine I'll show you when we're listening to message we can my name is yes somebody in the chat saying they did ok oh and Linus for the lulz but I'll show you in the bot handler you can make sure that messages are coming from a specific server and only respond in that case ok and so I am not a robot I'm making a robot but I am NOT a robot that's a statue I'm part robot ok confirmed I am NOT a robot and cool and so it says authorized and if we look we can see that the choo-choo bot actually got added to the coding garden with CJ I'm gonna look at yeah and so my other bot added it to the terminating role so I'm actually just gonna make it a seedling so it can actually listen for messages and channels and such and remove the terminating role yeah cool so my choo-choo bot is ready to go and I'm actually just going to create like a bot spam channel where we can do all of our testing so it's add a channel just call it bot spam and we'll create that channel and this is we're gonna do all of our testing and then once it's good to go we can listen like in other channels and infi is first in this channel welcome everyone awesome is that adding bots what are you doing - okay now let's actually write some code so if you look at the the guy they show you how to create like your basic bot here so you require in discord jeaious create a new client and then when it's ready you can it'll say ready and you actually pass in the token here so let's get that going so in index J yes I'll let you do this require in discord is and put it in a variable called capital de discord okay hold on I'm okay you go like this awesome yep and then we'll create an instance of a client so you can just say Const client equals new discord dot capital C client and vocht wait yeah not capital and then invoke it with a parenthesis whoops with I just mean like like that okay okay so we have one program we have it and then we can listen for events so if you say client dot on or sorry client dot once and I think both of them are available once will only get called one time on will get called every time it happens but in this scenario we only want to know when the things ready once you can invoke that yeah and then the first parameter is ready in a string and then the second parameter is just a function that will get called when it's ready so should I should I be do we like to program this way today we do okay nice little arrow function and then inside of there we're just gonna log that the body is ready what's so connected I am ready nice and alka is mentioning we should install the types let's see if I get some autocomplete you actually do get autocomplete so in your editor if you type discord dot you should see like all of the different things that are available to you I I see a list of things yeah and so the and that's the the actual things they can create instances of and stuff like that but I think we get the the types by default which is good all right and then we now actually need to log in so right there just say client dot log in and will invoke it and pass in process C and V dot bot token which will have to create let's make it all kind of does all caps with an underscore under between bots token nice cool and so this is we were mentioning earlier like the token needs to remain secret we would never commit this to get and push it up to github so that's there and then we actually need a dot env file so a second ago we actually did install the dot env package which will allow us to create a dot env file so I'll create that because the actually I don't know if V is like if live sure actually shares a dot env file we'll find out okay but I'm gonna create one and then I'm going to create a variable called bot token and this is gonna have the actual value right now I just have like a dummy value and then I'm also going to create a dot e NV dot sample or dot example right put that there so that way if someone clones down my code they know they need they know what needs to go in the dot E and Ram cool because later on we can add other environment variables like serve guilds guild ID so that way if we're making a bot that is only listening for message in one specific server we can put that as an environment variable cool so that's there so I see the dot and V dot sample but I do not see the dot env file okay and so the bots will probably will just be running on my machine you'll still be able to see like the output in the console or in the terminal but you won't be able to see my token I guess which is a good thing but cool so I'm gonna hide my screen and look at all those drops and hello get the bots token from that discord app page so reveal the token copy and see you doing this and then in my dotty and V file I'm going to put the actual token there like that and then close that file and never open it again on stream and I'll show my screen again let me make sure it's not being shown anywhere cool all right back to it cool so the one thing we need to do in this file is to actually bring in that dotty and V file so just up at the top here I'm gonna require in dot env and just say da config which automatically which automatically reads in that file and now bot token will actually exist on the environment if I recall I think I have an entire video about using dot env with this data API series I could last oh nice all right and now we can start it up and let's actually just add a start script so in the package.json I'm gonna add a start script and this is just going to be node source slash index that is and then I should be able to just do in p.m. start and it's ready beep beep I'm ready so the token actually worked mish means it was able to login and the bot is ready to go so now we can start listening for messages and commands and things like that can you see my Sturman all still oh sorry yes I can cool I was looking to try to increase the font size of the terminal I couldn't find if it's fine okay awesome so now we can actually like start building a command so I'll direct you now to the discord j/s documentation so this is the actual official talk official Docs API documentation all the stuff that's available and there is a lot there are so many different things you can do and so on my channel probably probably a little over a year ago is when I made the the discord bot for my my discord Channel and I did a live stream where I knew nothing about discord Jes and I just like tried to build a bot but that stream was like 6 hours long because it's just me trying to understand the docs and then I streamed again a couple days later and like fixed a bunch of things that I figured out but there's definitely a lot here the thing that we want to look for is I guess events let me see if I can find it or actually under client and I assume like what kind of what we're looking for is like a just like on message event so like if there's somebody post a message exactly and so in the docs here I went to classes client because that's the one we created the instance of to write extra client and this shows you all of the events that you can listen for over on the right here so you can listen for when channels are created deleted listen when members are added so in terms of like terminology guild is a discord server I took me a while to even figure that out maybe they they might have changed the official wording but it used to be called guild but now guild is actually just think of it as a server so yeah any any separate icon that's in your discord up that's a guild and we want to listen for message yes so there's this event here message and this is emitted whenever a message is created and I don't recall did we do something specific to only allow the bot access to the bot spam channel or not yet not yet so we'll have to do that inside of the the message handler basically we'll say make sure that the guild is this ID and the channel is this idea in that case we'll respond right it has permission to do anything that a seedling currently does exactly so you can do that through the code we did that through the discord interface by giving it that role exactly got it nice so let's yeah let's listen for the message event so I would put this right above client login and then yeah we'll do a client dot on and we're listening for message and is there I'm assuming I just making up is there an argument like message oh there is yeah and then awesome and yeah and so the in the API documentation they can say the parameter you get is message in its of type message so if we go into the message documentation that shows you all the properties that it has so this is going to have the channel it's gonna have the guild which is the server it'll have the idea of the message all that good stuff so we could do something like this well we have - it's gonna be an ID for now let's just log them at the entire thing yeah so just yeah console log message and then I'm going to restart the bot your space has got in there and now any message that comes into the coding garden or in any server that this thing is in we're gonna see it logged yes so there's there's a bunch of stuff and we can see yeah this is a message from - dev and you can see all the properties now there's a ton of stuff so there's the channel that it was in and you can see channel name has the actual name yeah yes we can use that so let's just wrap it in an if statement and say if message channel name equals man cool then we're gonna do something with it awesome the other thing we want to check is to make sure that it is only this discord server because we don't want to listen in other distort server smoothies for now there are some public BOTS out there that are in like thousands of discord servers and they can issue commands to all of those different servers but we're gonna build one that just works with one one specific server and I think what we can do is on discord if you enable developer settings you can actually do things like this so are you looking at my screen I am yes so if you right-click a server that actually gives you things like copy the ID of the server or if you're in the channel you can copy okay so we could have used using the ideas better because if the channel gets renamed exactly it'll still work exactly yeah and so I think we'll do that so yeah let's just copy the ID here and it's the property oh there's so much logging the property we want is oh I think was right there channel dot message channel dot ID exactly and then I'll just let's put that in there and it does come across as a string even though it's like a really big number cool so that's the channel ID and I think that should be unique across servers but I am just gonna double check that the message is actually being sent in this server as well and so you can see message guild ID that's the actual server ID so I want to make sure that that's the same as well so I'll just say message guild ID is equal to that and that and it's probably better if we set these up as just like variables let me do that great a guild ID channel ID and then again if we wanted this code to be really reusable by other people we could make those environment variables but this is good right now awesome now let's actually do something so when we get a message I'm thinking right now we just do actually we could do like a ping command so if somebody sends a message that says ping will send back a message that says Punk so let's do that and so we need to find the property of the actual like message contents and for now I'm gonna actually just kill the server because there's a lot of messages coming in so if I look back at the docs message dot content is the actual content of the message so for now we can just say if message dot content equals ping I'm you know like I keep going here and I'm controlling your screen yes yeah you are let me uh let me undo that was it just message that content I think so yep and should we allow people to use any let's make it not case-sensitive I like that and then I probably do something like some kind of scent oh no client probably client yeah client client that send most likely but let me pull up the docs real quick so if we go back to I like to just guess well yeah and you should actually get some autocomplete like if I do client dot oh no I don't see it I might be broadcast I'm guessing let's see but we'll find out we can look we can look it up so if we get the claim oh touch it's in chant Oh message dot reply or message channel dot sin is what okay what's koto liasing okay let's do that reply sounds good cuz it should be tied to that message there might be something that it's doing that actually knows it's a reply to that specific message sure I mean could it really there must be a callback for this or sorry this is asynchronous it's promise based yeah so we can actually mean yeah we can make this an async function and then await the reply and then after that let's just log message was sent or reply was sent in people in the chat or message Channel dot send in like really big text but we figured it out and reply should work I like that too because it's kind of like send it back in the exact same channel yes essentially to the person I mean there are no threaded messages in discord but right that's good so what one thing that I'm curious about is it seems very common that people adopt a convention like if you say exclamation point something that's like a command for the bot or the first word there's almost like a command-line argument that has that's broken up split but the maybe discord digest doesn't have any helper function for any of that it's really up to you just get the message and you chop it up and and figure out your own messaging protocol and what means what exactly so yeah and not that I and not that I know of you can see in the disk or jeaious guide they do have instructions on command handling and basically they just have some like basic codes that does exactly what you were saying it's example code yeah so like it would be my provide but that's the hell I would prefer to do it anyway because but it's just interesting to think about where are the sort of standards and conventions like what level are they adopted in use and in what's interesting is I don't think I'd seen this before but in your discord server what's the channel where people can request like the announcement role or the oh where can that be okay yeah and so the the convention for these bot messages which is just set up in the code that whoever created the bot did it but is like TR exclamation mark something so TR is not a discord thing that was probably picked to be like train exactly yeah and so they they basically just have a handle or just like we do and they're saying if the message begins with TR do something special yeah okay okay so let's start this up and hopefully the bots will start responding so if we go back to discord in the bot spam channel and we just say ping it should try to Roque we're getting we're getting some rejections let's see what's going on oh I see it's not a client not reply its message not reply oh right of course of course all right let's try it again Jing there we go oh I see and the reply automatically adds the user's name in front of it yeah with a comma how interesting that's pretty cool yeah I like that cool and so uh just to see it happen instead of using reply let's use that other method that people mentioning message channel that send so let's just comment that one out and yeah and so what's cool about discord j/s is they attach like so many extra properties to the message like you have the channel you have the guild you write the user and then each one of those has methods that you could use like you could say message dot author dot like DM it's probably a little more a little different than that but basically you could respond directly to the user if you wanted to okay and so let's kill it and do this instead and I can't wait to make up sort of like weird machine learning chat BOTS that you could just chat with I'm like I could try you don't having to do is I'm going to train I should trade a GPT GPT to is kind of like the new all the rage the model architecture for training text generator and so one of the things I could do which I should actually not enough time in the day but just download all the captions of all my videos and train a model and then I could just have people ask questions did you have to direct message me just direct message the AI trained on every video ever made and it'll talk to you that's awesome yeah because it's words that you said and it's yeah yeah an in feein the discourse says it's very fast it actually it is really fast it could be that because my this is running on my computer which I have like a gigabit internet connection so it's like really fast right and typically when you I mean I know we're not there yet but when you deploy the this sort of but same way that I've done things with Twitter bots you know it kind of $5.00 months or almost like Amazon free tier typically will kind of like run this kind of micro service exactly and so the what I'm using is a AWS lightsail it's one of the cheapest I found lets us base so you can get a Linux server with like half a gig of ram and one one processor for like three dollars and fifty cents a month if do you run multiple bots on the same instance or do you always get like a new instance for different bots a different project it depends on the load cuz I mean like this the discord bot for my channel even though it's it's always running and like anybody can join it somebody's trying to rickroll me but even though you can join at any time and it's always listening it actually doesn't take up that much processing power so it's really up to like the load of the bots like is it calling other api's that kind of thing right yeah cool so we made a basic bot virtual high five wow we have so much time left so let's do I guess an Eightball command yeah and then we can get into a little bit of like the command parsing of like making sure it begins with exclamation mark actual I'm searching what the actual 8-ball options are okay cool and and while you're doing that I'll just point people to the the discord bot that actually built for for my discord server so if you go to coding so github calm slash coding garden slash discord - manager all of this stuff I've been talking about of like a bot that adds a role to a user and listens for messages all of that is here on the discord manager and in the source directory you can actually see some of the commands that I've built so I have built an Eightball come in before but we're gonna build this from from scratch I also have a fortune command so it just responds with like a random quote we built a poll command so you can actually do exclamation mark poll give it a list of options and it will add emoji reactions for people to vote on those options and I have an uptime command so it'll tell you how long the bot has been up so I guess what would be the protocol here like so if someone's asking the magic 8-ball you would you would you would issue a command to ask and then you'd also ask the question yeah so I would want to look for just like the first the first word in the message the first character check if it has an exclamation point what would be the standard way of doing yeah so what I'm thinking is if the message starts with exclamation mark eight-ball we just respond with a random random one from this array though we could also double check to make sure that it says they have that and then they have some text like well my lunch be tasty right so to make sure it has so we could do this with a regular expression okay let's do it so and like right now I mean technically you could put all of your command handlers in this one function right and actually I think I think roll all right let's write it and then we'll refactor it to kind of like okay make it a little more scalable cool so I think a regular expression would be this is at the start of a string and then this is a special character so that probably needs to be escaped and then this is just a literal and we want to look for this just if it oh and then I suppose we want to know if it has at least and then there should be a space and then there should be at least one other character should we say there has to be at least a certain like at least five other characters did you ask a question yes what's up well I mean yeah we could do that and then the bots could respond you must your your question must be at least five characters we could do validation like that if we want to do right well let's just leave it like this right now okay well this is just what is the curly brace do is that there I think oh there shouldn't be a curly brace I don't know that regex so I don't know if I did that correctly it's been a while since I've made a regex in reg expression JavaScript and then I I think we also want to make it case insensitive sure I'll do that and we don't need it to be global because it really should only appear once at the beginning of the script string exactly so I think then I forget how regular expressions work in JavaScript even though I have a whole set of video tutorials about that I would say if you can read Jack you can do regex exec yeah you can go either way so regex not exec and then you pass it up string does it match exactly yeah I think that's what I would want here right oh but I want to capture the thing is I want to capture the no I don't need to capture the question we don't care what the question is yeah nevermind so we're just gonna give it a response then we're going to have an index which is based on the arrays length oh no wait hold on and and then I would say response or the reply is eight-ball that index and then I think this one we should mention the the person who asks I like that so I'm gonna say message dot reply reply that's weird and why is it giving me these tabs okay so in if you look at my screen for a second you might have for space tabs on right now so in the bottom right of yes code you can click spaces and make sure you say indent using spaces - wait I missed where the beginning of that bottom right was down here at the bottom it says spaces you see that down here at the bottom bottom right envious come you let me go back to my vs code yeah I've done oh yeah yeah of course of course yeah cool and my break timers up if you want to take a quick stretch how do I change its paces that using spaces change for YouTube got it yes okay so what do we think about this this should be good or yeah I mean I think one thing I'll just do really quick is move this array outside cuz it yeah it can exist all the time yes and I don't know if that's actually all the responses that was just a quick there's nothing there's more items I just 20 answers but I think this is fine we can just use these right scientifically accurate eight ball right that's eight eight ball should have eight though eight 8 that's 8 responses so good perfect okay so that should do it so now if someone sends a command that begins with exclamation mark 8 ball space something it should reply with a random random thing so let's try it I'm gonna restart the server ok oh yeah it's people are already using it and so right now we're uh I guess if you have two spaces wait where did that eight-ball emoji come from oh I totally forgot my other BOTS has an Eightball command Oh bots are applying my existing bought the CG bot he just puts a little uh poor she it doesn't they they don't doesn't have a gender it just puts a eight-ball emoji at the end of the message so but I think if we do eight balls space space okay our bot doesn't respond if we do that okay right we could fix that very easily but also I'm noticing it's interesting like you're not using the reply because there's no comma exactly yeah and the commas kind of bothering me I said it seems weird like because because visually this is so silly to get hung up on this but because visually the fact that the @ mention is you know has its own color and is highlighted in that way it doesn't feel like in a sense if you were saying somebody's name I feel like you'd want the comma but I never at mention somebody and then put comma so it feels weird let's let's remove the comment we should change that to message channel dot send and then I assume I just need to somewhere in that message is probably the username if I believe it's messaged author and what's actually pretty cool is its if we yeah if we do a template string and you just put messaged author in there it will automatically add the OP the @ sign like that and then reply needs to be parametrized - yep I think this should do it yeah all right we need the closing quote well yeah I made one more change restarted oh yeah okay cool I forgot that I could control the term yeah absolutely and it looks like it's working so now it automatically adds the the user oh geez come on somebody's spamming oh yeah this is why we can't have nice things yes cool okay and we're back okay yeah I think for right now I'm actually gonna make the I'm going to I'm gonna disable disappear attic people joining my discord until at least the streams over speaking of being particular about code syntax I really like to have spaces around the asterisk when I'm multiplying different things okay I'm just filling ty why is how interesting I'm getting a weird little oh it's basically you don't need to escape the exclamation work like that oh yeah why don't I exclamation point mark means not but I guess only in certain context maybe in a character class yeah cuz actually I believe the hat like the carrot also means not in certain sir right so oh no it means yeah cuz it means big industry but also I don't know yeah reg X is confusing I am getting a weird warning around exact What's it saying or I just have like a little squiggly line underneath maybe it's actually underneath the xm8 is it underneath the exclamation point or over the parenthesis it's underneath thee exclamation point weird it doesn't like it I'm gonna not worry about that right now oh yeah I don't see it on your screen I don't know why I'm getting that sometimes vs code live shares like a little behind ya okay in the what you what you did was just out of space here oh no yes yeah I like that we're very agreeable on our code style all right and it looks like it is responding with the train emoji so that's cool awesome alright let's let's refactor so instead of having both of these command handlers all in this one function we can basically create a separate file for every command that we want to have oh interesting so I'm gonna create a folder called commands and I'm gonna create a new file called pink dodge a yes that's gonna have the ping command got it create a new file called eight-ball Jas that's gonna have 8-ball command and I'm gonna create an index J yes and this is gonna be the command Handler it's going to decide which function to call when a when a message comes in okay and for now we can take this this entire like async message here and pull then pull that into the index j s so I'll let you do that okay hold on let me go back to visual studio code so I'm gonna take the full async function out and I'm gonna put that that's gonna go in the index of command yeah so commands index tjs and then does that functioning to be named well we need to exploit it yeah so actually you can just in front of the async say module dot exports equals module dot X port is it exports plural or yours export plural plural and then does this function need a name it doesn't no actually you poke you can't name arrow functions oh we could turn it into a regular function I think you can I think you can in a weird way you create a variable yeah so you can create a variable and assign it but technically that's just a function inside of a variable instead of the phone right right right okay and actually I'm gonna have you use the EES lint auto fix things so press command shift P and then search for es lint Auto fix all fixable Auto I don't think it's all auto fixable problems okay I ran that I ran it - I don't might not have worked okay but usually that's how you get it to kind of do that Auto yeah correct awesome yeah okay and now we're missing a few things so I'm just gonna pull I'm gonna bring that 8ball function back into our index or start a ball array and then I'm gonna bring the channel and guild ID back into that file so those variables exist cool and now we need to update the main index js2 require in that frame so let's put that like right below yeah that's fine so we could call this receive command or something let's call command handler command okay command handler handler equals require stood commands so if you just do that it looks for index exactly got it and then that would go in here exactly yep and so now when a command comes in its gonna use that function that's in that separate file let's at least make sure this works but we're like one step closer to the rightful refactor so restarting the bot without it well our bot needs a question is that is the bot as I see it yes it is certain nice so the buy the bots still working that's great now let's actually extract these both both of these functions in two separate files so first let's extract that ping command so basically it's the just the first if statement yeah well and actually we really don't even need this this check because we're gonna do all of the checking of like what the command name is in this in this function and let's actually do that first so what I'm thinking is once we've validated that we're in the right guild in the right channel right we're now going to create an object that has like the name of the command and potentially any arguments on the command got it and actually I learned this trick from Elko when we were building twitch BOTS but what we do is we'll say args equals message content dot split oh right myspace so like we we turn we take their entire message and split it on spaces and then we'll say that command is args dot because I'm obsessed with regular expressions I might do this can you put a regular expression in a split definitely okay and then I'm gonna do args dot shift which actually removes the first argument from that array and in this case that first argument should be the name of the command that we want to run and also we can remove the exclamation mark so I think we can do like substring at one so this will basically don't we need to check to make sure there actually is an exclamation mark [Music] yes we could do that too yeah that's that's that's a good point um but basically our revalidating is it only of all is it only a command we want to respond to if it has an explanation yes and that's basically what I'm saying so right right now our ping command doesn't require an excellent school I see you're gonna shift you to check is it an exclamation yeah but I I think we're gonna now require so shifting it will grab the first thing and then sub stringing it will remove the exclamation mark and then now we have the actual command and so what we're gonna do is we're gonna create like a list of all possible commands and we're gonna see if the command exists in all possible commands and then we can invoke that specific function I think is war but for now let's just yes although technically this would work if someone did like % which is fine I'm not worried about that it was putting that out like we could first check like if args index zero dot I mean I'm not saying this is a good way to do it looks are at zero equals you know exclamation I like that because that now we're just verifying that it actually has that and what we could do is just like an early return so like if it doesn't equal that we're done don't write don't even try to do anything else but if it does now we can actually grab the commander cool because that might fail by the way if it's an mg is it can a message have empty contents maybe it can't well yeah if you split on spaces with a string that begins with the space Chara zero would still be undefined which is no I just more mean like do we need to say if R as long as our cut length is Grit is if arcs out length equals zero or yeah that's that's cool too so if the message is totally empty or it doesn't run again with an exclamation mark okay awesome we're doing validation and then we have the actual command and so let's extract these these other these handlers like the ping Handler and the eight ball handler so in ping Jas we're just going to export a function that takes in the arguments command yes yes we might as well always take the argument in the in the message itself so in pink is let's just do module dot exports equals and async function awesome and we can as cake the arts yeah and I think we'll also take in the message as well because the message has the author and the channel and all that good stuff yeah so should be good [Music] and then we're basically going to a grab this yeah and we actually don't even need the if statement cuz we're gonna handle that in a second right really just need the actual just this yep and if I do yes let's fix all problems whoops wants to do that no it's not doing that whatever yeah it could be just live sure you know it's amazing things that cool so and in this case we actually don't need to take in the args we could technically say like if args length is not zero then don't send back the pong but basically if a message begins with exclamation mark ping we're always going to yeah alright someone's saying something's happening on line 20 yeah well we're gonna we're about to get there um so that's that's pink great and then we want to do the same thing with 8-ball so if I take this and in this case put it in a ball yeah I'm thinking we actually won't even need the regex anymore but yellow because we're gonna write and then in index we're basically saying take this and [Music] put this here and then I need the the a Paul replies which we had here exactly yeah so grab that I'm in eight ball here I'll fix it cuz I don't I don't think your yours is not do that yeah it's not beautiful looks beautiful and in this case I think one thing will do is what's very similar to the regular expression that we were doing before we're basically making sure that there's something after the eight ball command well in this case we could just say if args dot length is greater than C than one or something yeah so if it or even just like truth II fall see if it doesn't have a link right we're not gonna respond to that but it still has does it still have the command dinner the command was actually taken out oh um well the commands taken out yeah cuz in okay great yeah I'm thinking that we we don't know it should it should be yeah yeah and so if someone keeps keep saying so I have a typo line nine needs to be substr not sub turn okay awesome but now now that we have extracted those two separate separate files will basically create like our list of all possible commands well check you know I'm realizing sorry I'm sorry I'm realizing something I so I did this weird thing where I wanted to like add this regular expression in for splitting but splitting we actually we actually really just want the single space yeah cuz you want to take everything that comes it's we're not splitting by spaces we're not doing like word tokenization yeah we're just saying give me the first thing and then everything after that first space exactly so though because it would be although does it split no it I'm confusing myself this is a small detail but I think this is what we want cuz it maintains if there were multiple spaces together maybe we wanted that and we're giving that to the command handle or so they can do something yes yes exactly yeah okay and then again line nine when we do this shift it's actually going to remove the command if it was at the beginning right so now arts only has the and then substring is kind of remove that exclamation mark and now we can list out all of our commands so in this commands file I'm going to bring in both of our our commands so I'm gonna say ping equals require ping and eight-ball you got to write out the word yeah that's a file name can that's interesting yeah and then I'll do this I'll say my commands is an object and I'm going to like this is the very simple case where every command only has one possible name so here I'm just gonna put a ping on there and I'm going to put eight ball on there but actually I'm gonna put it as eight ball so yeah you have to do that for that quote so it matches the name of the command and you can you can do you can mix this idea of like whatever it's called the eye I forgot what the name for this is where you create an object where the property name and the value is the same yeah you can mix and match definitely you can mix and match yeah so cuz this is saying create a crop property called ping that is this function and this is create and then we would just say like yeah commands command execute exactly I mean the only thing I would do is to make sure it actually exists so like right if that and let's see yeah so if that's a thing and really we're gonna say yeah that's if that's a function then let's invoke it and we might even go a little bit deeper because sometimes you want your commands to have multiple like that I have aliases basically and so instead of just assigning it the function directly right you can basically add a bunch of metadata so say like the handler is this function goddess and aliases are an array and then we could basically iterate over the aliases to see if that command exists there but we'll say that there and in this should be good and so if the command exists and actually I'm gonna do this if command in commands yeah this has a potential for people doing naughty things like accessing prototype functions of the object right right innumerable properties okay oh and we need to pass in the message and the arcs when we invoke right awesome oh okay so did Daniel not notice we have check HTML on the chat yet I think if you just say but I not noticed what so people you people can send HTML and it actually renders in my chat manager okay and this is this should be it will start it up and we can try sending commands so now you have to do exclamation mark ping it does respond with pong that's good and if you do exclamation mark eight-ball was this stream okay nice about to say yes let's ask the eight-ball should I get a haircuts today great the eight-balls gave me different answers I'm gonna take the advice of the coding train line one we built today and so you can see people who are trying to hack it so a proto constructor someone was like do two string and is that actually in an object let me see really quick I know I don't let's see but anyway we yeah oh it does say true okay there's a to do fix this so prop we could do something where we keep an actual separate list of valid commands would that be like the most secure way or just like be better about checking let's see we could even do this we could say if object keys okay of commands includes command this has to search an array every time but that's a little more secure because it's not gonna it's not going to give us to string or constructor or anything right right alright one last try and then we'll wrap up are we close to finishing awesome so I think that's pretty much all the time we have and it is basically what we wanted to do so it's pretty successful awesome do you have any like final questions or thoughts about this kind of stuff no I guess I'm you know thinking about what I'm gonna do next with this I mean I you know these are my one one question in my head is like if I'm gonna make a like a set of step-by-step tutorials about how to program a discord box I you know to what extent would it be just basically exactly what we did today do I want to do like a different example so I'm not saying answer these questions this is what's in my and then and then II yeah that's no I don't know this is like this is awesome cool what's your wen Zi Rui but when's your next livestream um I don't have it scheduled but I'm I might stream this evening I don't want to say that cuz this was one day is probably Friday I'll say my next livestream is Friday and are you doing one tomorrow so I am planning now currently I was like playing around with like pushing it to Friday but I'm trying to get Thursday to be my livestream day because it actually works out much better for me so if all goes according to plan my livestream tomorrow Thursday will be approximately 1 p.m. Eastern and I'm just continuing this nature of code series awesome so that's that's and I haven't posted it yet but that's kind of the plan cool and oh just real quick infi is saying that discord jeaious does have a built-in command handler I guess I hadn't seen it before but that's something to look into at a future time yeah um but thank you so much for doing this with this with me this was awesome yeah this is super funny I've done some I recently did something with like mpj and fun fun function I've done a couple I've had people like physically present like like you when you came to visit yeah but this has been like a really excellent like collab remote collaboration setup yes so I Rick very excited to discover this and hopefully we could do more of these or that this setup can work with for you with other people and vice-versa so thank you so much for the opportunity and teaching I like this is like great like a check off my to-do list and like learn to program with discord by like I get like I'm getting tremendous value out of this so thank you so much yeah absolutely it was awesome to have you and everyone should definitely check out the coding train on YouTube if you have it you probably already have but if you haven't subscribed to the coding train he'll be streaming tomorrow and would we are going to raid some what we're gonna raid against a fluff so it's the blow in stuff fluff is a super awesome very wholesome streamer he he's like super kind the chat is always so friendly and he does coding every now and then and it looks like today they're gonna build a dyslexia friendly twitch chat reader interesting and so yeah he's he has 36 people watching right now but we're gonna go hang out over there so if you are watching on YouTube please head over to twitch twitch TV slash coding garden you can participate in this raid and we'll do that now but again thank you so much Dan thanks everyone for watching I realized there's tons of chats happening we didn't get to all of it but we did see it every which is good and we can continue in a coding garden discord I'm hanging out there as well we could continue this discussion there absolutely maybe the bots will answer all your quite to the coming food in the future I'm actually gonna start working on that today cool because I have a one of the tools I use them in my channels the thing called runway ml and they have a new module for training gt2 models so coming later today and all the code that we just wrote is gonna be on github you can click the link in the YouTube description but uh yeah wherever you are in the world have a wonderful morning afternoon evening or night and until next time here's this [Music] you
Info
Channel: Coding Garden
Views: 37,019
Rating: undefined out of 5
Keywords: mechanical keyboard, node.js, live coding, web development, css, beginner, javascript, learn node.js, live streaming, full stack javascript, lesson, html, full stack web development, educational, full stack, learn javascript, vscode
Id: gzM7kj6gV5I
Channel Id: undefined
Length: 92min 39sec (5559 seconds)
Published: Wed Feb 26 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.