Learnhow to create a Discord Music Bot from scratch with Typescript to bring some tunes to your next gaming session. This bot will include a basic play and stop command which takes a Youtube link as an argument and then plays the audio of that Youtube video.
There are also so many ways to extend the bot to your liking. Add a queuing system or add an autoplay feature to fill the queue with songs similar to the last one played with the Spotify API to name a few. I have actually implemented these features in the "Fltenbot" project which is actively being used by me and my friends.
I tried to keep the amount of dependencies as low as possible here but some are still needed. Discord.js is used to connect to your Discord Bot, ytdl-core is used to stream Youtube videos and dotenv is used to load environment variables. Install these along with Typescript and some types and create a basic Typescript config.
Next, the prefix is stripped from the message and the message is split by spaces. The first entry is of course the command (play, stop, etc.) so that is taken out of the args into a separate variable.
If the command is "play" then the first entry in args must be the url. There is currently no validation in place to make sure there actually is a url, but this would be a good idea down the road. Before doing anything else, this checks whether the user invoking the command is actually in a voice channel. If so, this creates a stream of the supplied Youtube video with the discord-ytdl-core library and then the bot joins the same voice channel as the user. Finally the stream is piped into the voice connection to play the audio.
The .on("close") handler makes sure the bot leaves the voice channel once the playback is done. This is similar to the "stop" command. The "stop" command checks for the voice channel again and tries to connect to that. Since the bot should already be in the voice channel, this is not doing anything but providing a reference to the connection. This reference can then be used to disconnect from that channel.
Copy that and replace "ID" in this link: " _id=ID&scope=bot". Then you can visit this link and you should have the option to invite your bot to a Discord server of your choice. Keep in mind that you need the permission to invite bots to that server though.
I ran the bot locally for a bit but then decided to deploy it to Digital Ocean for 24/7 uptime and better performance. You can get 100$ starting credit on Digital Ocean with my referral link. For the 5$/month droplet you can host the bot (and much more by the way) for 20 month.
3a8082e126