Startup - DiscordJs(TypeScript)

Here is how you can start up your bot using typescript!

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
npm install typescript @types/node @types/ws
npx tsc --init

now we can move onto installing packages!

npm install discord.js @discordjs/rest discord-api-types dotenv
npm install --save-dev @types/ws ts-node

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.ts

import { Client, GatewayIntentBits, Routes, Interaction } from 'discord.js';
import { REST } from '@discordjs/rest';
import { SlashCommandBuilder } from '@discordjs/builders';
import 'dotenv/config';

// 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: 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,

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

And that's it!

Last updated

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