Creating a Discord slash command bot

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
Was just waiting for something like this! Thinking of starting a discord community. Find this blog interesting ππππππ
Glad you enjoy it! Looking forward to your bots π
Now this one reminds me of my first attempt at scripting. Modifying an existing Bot in Internet Relay Chat (IRC). Quite awhile ago now but little did I know it had sown the seeds of coding!
Nice to hear that! I'm really enjoying building these things. Cool to get something you scripted to interact with you.
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

You might have seen slash command bots on random discord servers. These commands start with a slash / and perform a certain action.
This article will create one of these bots that will listen to the /randomice command and return a random mouse. (See what I did there π).
The bot will look like this once we finish.

The first thing we need to do is register a new discord bot. For this, we need to visit the discord developer portal.
Once you are there, we can register a new application by clicking the button in the top right corner.

Once this step is done, you should automatically enter the new application and see the bot section on the left. Press this and add a new bot.

On the following screen, copy the token of this bot into a save place. We'll need this in a second.

While we are still in the developer portal, let's note down the application ID, as we also need to use this.

Now that our bot is set up, we can add this bot to our server. To do this, we can follow the following URL format.
https://discord.com/oauth2/authorize?client_id={APPLICATION_ID}&scope=applications.commands
Make sure to modify the APPLICATION_ID with the retrieved application id.
Open this link and follow the steps to add it to your desired server.

That's it. This bot can now access our server and act on the slash commands.
This step wasn't clear to me initially, but slash commands need to be registered on a specific application!
Discords preferred way is to use guild commands, but we'll use a global one. (Downside: It can take an hour to refresh if you change commands)
You can either perform a CURL request or create a script that does this for us to register commands.
We will be using the discord.js package, so we can leverage the registration part from there.
Let's quickly set up a new project and have all the packages installed.
# Create folder
mkdir discord-slash-bot && cd discord-slash-bot
# Initialise node
npm init
# Add packages
npm i discord.js @discordjs/rest discord-api-types dotenv
Now let's create a .env file to keep our two secret elements in a save spot.
APP_ID={APPLICATION_ID}
TOKEN={YOUR_BOT_TOKEN}
And then let's make a new file called register.js. This file will handle the command registration with discord.
const {REST} = require('@discordjs/rest');
const {Routes} = require('discord-api-types/v9');
const commands = [
{
name: 'randomice',
description: 'Return a random mouse',
},
];
const rest = new REST({version: '9'}).setToken(process.env.TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(process.env.APP_ID), {
body: commands,
});
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
As you can see, we define our command with a name and description.
Then we perform a PUT request to Routes.applicationCommands and pass our APP_ID.
This will register the commands we defined for this app.
Let's add a new script to run this command quickly with our environment variables.
Add the following in your package.json file.
"scripts": {
"register": "node -r dotenv/config register.js",
},
Then you can execute npm run register, and it should show an output like this.

Note: You can verify the registered commands by performing a GET request to this endpoint.
I quickly tested this in Insomnia. You can use a URL like so:
https://discord.com/api/v9/applications/{APP_ID}/commands
You can set an Authorization header like so:
Authorization: Bot {TOKEN}

Alright, so far, we have our bot setup and added to our discord server, and we registered our command with discord. But the commands don't exist yet.
For this, we'll be creating an index.js file.
Let's start by loading the discord client.
const {Client, Intents} = require('discord.js');
const client = new Client({intents: [Intents.FLAGS.GUILDS]});
Note: The intents flag is needed here to register a client.
Then we can listen and see when we are connected.
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
Then I went ahead and created an array of random mouse things.
const options = [
'π',
'https://media.giphy.com/media/wJZTbXayokOgbCfyQe/giphy.gif',
'https://media.giphy.com/media/QXh9XnIJetPi0/giphy.gif',
'π',
];
The next step is to listen to all interactions and fire an event when our action is met.
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'randomice') {
await interaction.reply(options[Math.floor(Math.random() * options.length)]);
}
});
If we hit the randomice command, you can see that we reply with one of our options in random order.
The last step is to call the login command with our bots token.
client.login(process.env.TOKEN);
And then let's also add a script in our package.json for this file.
"scripts": {
"register": "node -r dotenv/config register.js",
"start": "node -r dotenv/config index.js"
},
We can now run npm run start and spool up our bot.
And once it's ready, we can start typing our command, and it should show up as an action.

And that's it! We created our very own slash command discord bot.
You can find the completed project on GitHub.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter