Build a lo-fi cafe for your Discord Server in 5 minutes
I decided to have a chill voice channel where we all could sit together (virtually) and co-work while listening to a lo-fi audio stream and maybe have some occasional talks too.
We will be learning how to create a bot that automatically joins a voice channel whenever someone joins, starts broadcasting music & leaves after 5 minutes of inactivity.
Do you need something cool like this in your own server?
TL;DR here’s the github code with one click deploy button for heroku, ready.
Less gooo 🥳
Setup
Prerequisites
NodeJS LTS and VScode or IDE of your choice.
Pen
Pineapple
Apple
pen
Just kidding, let’s setup the project now,
1git init2npm init -y3npm i -s discord.js dotenv ytdl-core-discord lodashGo to Discord Developer Portal and create an application.
Go to Bot in menu
In the Build-A-Bot section here
Add copy the token and store it in a file. call it .env
1// in .env file2DISCORD_BOT_TOKEN="Your Bot Token here"Now let’s invite the bot to our server
Go to OAuth2 Page Scroll down to OAuth2 url generator andselect the bot permission Scroll more and select these botpermission, It allows the bot to connect, speak , viewchannels, and use voice activity After selecting the appropriatepermissions, click the ‘copy’ button abovethe permissions. That will copy a URL whichcan be used to add the bot to a server.
Paste the URL into your browser, choose aserver to invite the bot to, and click“Authorize”.
To add the bot, your account needs “ManageServer” permissions.
Now that you’ve created the bot user, we’ll start writing the NodeJS code for the bot.
Code
Here’s the file and folder structure →
1|—/client.js2|—/index.js3|—/.env4|—/.gitignore
We don’t want to push Petabytes of node modules to GitHub. so, we’ll create a .gitignore file. Whatever we add inside here will be ignored by git and that’s what we want.
1// in .gitignore23node_modules/4.env
Inside .env file you should have the bot token, If you don’t see the setup section once again. You skippin’ lines bro.
Copy your github server id and save it in your .env file. Also create a voice channel in your discord server, add the exact channel name in .env file. (avoid using ’ ’ in discord channel name.
1// in ./.env23DISCORD_BOT_TOKEN="Your Bot Token here"4DISCORD_GUILD_ID="Your discord server id here"5DISCORD_CHANNEL_NAME="lofi-channel-🎵"6VOICE_URLS="add more than two urls, seperated by comma"
Create a file called client.js and add these lines there. line number one implies that we are requiring dependency.
1// ./client23const Discord = require('discord.js');4require('dotenv').config();56const client = new Discord.Client();78client.login(process.env.DISCORD_BOT_TOKEN);910module.exports = client;
line number 2 means that we want to setup all variables, inside .env file to the environment variables. line number 6 and 8 wants the bot to login and then export it, so we can use it inside any file now.
Now that we have our client ready, Let’s code the Bot.
Create a file index.js and require client.js.
1// ./index23const client = require('./client');4const ytdl = require('ytdl-core-discord');5const _ = require('lodash')
This line means whenever the bot is ready (after login) announce it in console.
1// ./index23client.on('ready', async () => {4 console.log(`Bot client Logged in as ${client.user.tag}!`);5});
Now after the bot is ready, we will react on all the events that discord sends whenever there’s a voice activity using the line below, (voiceStateUpdate)
1// ./index23client.on('voiceStateUpdate', lofiCafe);
lofiCafe is a function that will handle this event, let’s declare the function above the voiceStateUpdate event handler.
1const lofiCafe = async (oldMember, newMember) => {2 const guild_id = process.env.DISCORD_GUILD_ID;3 const channel_name = process.env.DISCORD_CHANNEL_NAME;4 const VOICE_URLS = process.env.VOICE_URLS.split(',')56 // find the voice channel7 const voiceChannel = await guild.channels.cache.find(ch => ch.name === channel_name);89 let newUserChannel = newMember.channelID;10 let oldUserChannel = oldMember.channelID;1112 // a function to play audio in loop13 const play = async (connection) => connection.play(14 await ytdl(_.sample(VOICE_URLS)),15 { type: 'opus', highWaterMark: 50, volume: 0.7 },16 )17 // When the song is finished, play it again.18 .on('finish', play);1920 const Guild = await client.guilds.fetch(guild_id);21 const botUserId = await client.user.id;22 const discordBotUser = await Guild.members.cache.get(botUserId);2324 if (newUserChannel === voiceChannel.id) {25 // if a user joins lo-fi music channel2627 // if bot not in voice channel and users connected to the channel28 if (!discordBotUser.voice.channel && voiceChannel.members.size > 0) {29 // play music30 voiceChannel.join()31 .then(await play)32 .catch(console.error);33 }34 } else if (oldMember && oldMember.channel && oldMember.channel.members35 && !(oldMember.channel.members.size - 1) && oldUserChannel === voiceChannel.id36 && discordBotUser.voice.channel) {3738 // if there is only one member in the channel (bot itself)39 // leave the server after five minutes4041 setTimeout(() => {42 // wait five minutes43 if (!(oldMember.channel.members.size - 1)) {44 // if there's still 1 member,45 oldMember.channel.leave();46 }47 }, 60000); // leave in 1 minute48 }49};
After writing these files, your client.js and index.js files should look exactly like this repo.
Deploy
Login to your heroku account in cli
1heroku loginCreate a new app
1heroku createPush your local git repository to heroku
1git push heroku mainGo into your heroku app settings and add the config vars, like you added in .env . Just because .env file won’t be pushed to GitHub.
Enjoy 🎉
Have your friends sit and co-work in your new lo-fi cafe.
Acknowledgements
icon: Cafe by Andrejs Kirma from the Noun Project
background: Jack Berry on Unsplash