Navigate back to the homepage

Build a lo-fi cafe for your Discord Server in 5 minutes.

Ayush Chauhan
June 14th, 2021 · 2 min read

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 init
    2npm init -y
    3npm i -s discord.js dotenv ytdl-core-discord lodash
  • Go to Discord Developer Portal and create an application.

    image0

  • Go to Bot in menu

    ./images/1.png

    In the Build-A-Bot section here

    ./images/2.png

    Add copy the token and store it in a file. call it .env

    1// in .env file
    2DISCORD_BOT_TOKEN="Your Bot Token here"
  • Now let’s invite the bot to our server
    Go to OAuth2 Page

    ./images/3.png
    Scroll down to OAuth2 url generator andselect the bot permission
    ./images/4.png
    Scroll more and select these botpermission, It allows the bot to connect, speak , viewchannels, and use voice activity
    ./images/5.png
    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.js
2|/index.js
3|/.env
4|/.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 .gitignore
2
3node_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 ./.env
2
3DISCORD_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// ./client
2
3const Discord = require('discord.js');
4require('dotenv').config();
5
6const client = new Discord.Client();
7
8client.login(process.env.DISCORD_BOT_TOKEN);
9
10module.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// ./index
2
3const 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// ./index
2
3client.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// ./index
2
3client.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(',')
5
6 // find the voice channel
7 const voiceChannel = await guild.channels.cache.find(ch => ch.name === channel_name);
8
9 let newUserChannel = newMember.channelID;
10 let oldUserChannel = oldMember.channelID;
11
12 // a function to play audio in loop
13 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);
19
20 const Guild = await client.guilds.fetch(guild_id);
21 const botUserId = await client.user.id;
22 const discordBotUser = await Guild.members.cache.get(botUserId);
23
24 if (newUserChannel === voiceChannel.id) {
25 // if a user joins lo-fi music channel
26
27 // if bot not in voice channel and users connected to the channel
28 if (!discordBotUser.voice.channel && voiceChannel.members.size > 0) {
29 // play music
30 voiceChannel.join()
31 .then(await play)
32 .catch(console.error);
33 }
34 } else if (oldMember && oldMember.channel && oldMember.channel.members
35 && !(oldMember.channel.members.size - 1) && oldUserChannel === voiceChannel.id
36 && discordBotUser.voice.channel) {
37
38 // if there is only one member in the channel (bot itself)
39 // leave the server after five minutes
40
41 setTimeout(() => {
42 // wait five minutes
43 if (!(oldMember.channel.members.size - 1)) {
44 // if there's still 1 member,
45 oldMember.channel.leave();
46 }
47 }, 60000); // leave in 1 minute
48 }
49};

After writing these files, your client.js and index.js files should look exactly like this repo.

Deploy

  • Install Heroku CLI

  • Login to your heroku account in cli

    1heroku login
  • Create a new app

    1heroku create
  • Push your local git repository to heroku

    1git push heroku main
  • Go 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

Join our email list and get notified about new content

Be the first to receive our latest content with the ability to opt-out at anytime. We promise to not spam your inbox or share your email with any third parties.

More articles from Blogs and Stories by heyAyush

Scott Hanselman in Microsoft Student Ambassador Summit '21

Attitude & Style Inclusion isn't "being asked to dance". Diversity is going to a party, Inclusion is being a member of party-planning…

March 7th, 2021 · 2 min read

Micromastery

Micromastery: Learn Small, Learn Fast, and Unlock Your Potential to Achieve Anything About the book: Micromastery (2017) teaches you how to…

August 13th, 2020 · 3 min read
© 2018–2021 Blogs and Stories by heyAyush
Link to $https://twitter.com/heyayushhLink to $https://github.com/heyayushhLink to $https://instagram.com/heyayushhLink to $https://www.linkedin.com/in/heyayushh/