Start up - DiscordJS(JavaScript)

Here is how you can start up the bot you have created!

First we have to install NodeJS in order to run a javascript file, you can download the latest file from nodejs page! https://nodejs.org/en

after downloading and installing nodejs, we have to init our first package.json!

npm init -y

now we can move onto installing packages!

npm install discord.js @discordjs/rest discord-api-types dotenv

after installing the required packages we move onto coding, something that is exciting for many. (Please note that this is just a guide, we won't include full code!)

Create a file called index.js

require('dotenv').config();
const { Client, GatewayIntentBits, Routes } = require('discord.js');
const { REST } = require('@discordjs/rest');
const { SlashCommandBuilder } = require('@discordjs/builders');

// Create a new client instance
const client = new Client({
  intents: [GatewayIntentBits.Guilds],
});

// Define your slash commands
const commands = [
  new SlashCommandBuilder().setName('first').setDescription('Replies with a funny message!'),
].map(command => command.toJSON());

const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

// Register the commands
(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(
      Routes.applicationCommands(client.user.id),
      { body: commands },
    );

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error(error);
  }
})();

// When the bot is ready
client.once('ready', () => {
  console.log('Bot is online and ready with slash commands!');
});

// Responding to slash commands
client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'first') {
    await interaction.reply('Congrats on your first command!');
  }
});

// Login to Discord with your app's token
client.login(process.env.DISCORD_TOKEN);

Oh yes! to access the variable process.env.DISCORD_TOKEN, we have to create a .env file and add this line inside of it. The token is the one you have gotten from developer page by resetting the token!

DISCORD_TOKEN=Token here

And for the end, we run the file we have just created,

node index.js or npm start if you have defined start script in package.json

And that's it!, Go to next page for typescript!

Last updated

The hosting company she told you not to worry about - SneakyHub 2021-2024