Lewati ke konten utama
Pemrograman8 min baca

Cara Membuat Bot Discord dengan Node.js dan discord.js v14

Dari membuat aplikasi di Developer Portal sampai slash command pertama. Semua langkahnya bisa diikuti kalau kamu sudah paham dasar JavaScript.

Bot Discord adalah program yang terhubung ke gateway Discord dan merespons perintah. Bot bisa mengirim pesan, mengelola member, memutar musik, atau mengambil data dari API lain.

Di tutorial ini kita membuat bot dengan satu slash command /ping, mendaftarkannya ke server, lalu menyiapkan struktur yang bisa ditambah command lain. Semua kode memakai Node.js dan discord.js v14.

Prasyarat

  • Node.js v18 atau lebih baru.
  • Akun Discord dan akses ke Developer Portal.
  • Editor kode. VS Code cukup.
  • Pemahaman dasar JavaScript, terutama async dan await.

Langkah 1: Buat aplikasi di Developer Portal

  1. Buka Discord Developer Portal.
  2. Klik New Application, beri nama bot.
  3. Masuk ke tab Bot, lalu klik Add Bot.
  4. Di bagian Token, klik Reset Token dan salin nilainya. Simpan di tempat aman, jangan pernah commit ke Git.
  5. Aktifkan Message Content Intent kalau bot akan membaca pesan biasa. Untuk slash command saja, intent ini tidak wajib.

Langkah 2: Undang bot ke server

Buka OAuth2 > URL Generator. Centang scope bot dan applications.commands, lalu pilih permission yang dibutuhkan. Untuk bot contoh ini, cukup Send Messages, Read Message History, dan Use Slash Commands.

Salin URL yang muncul, buka di browser, dan pilih server tujuan. Kamu perlu izin Manage Server di server itu.

Langkah 3: Siapkan project

mkdir discord-bot
cd discord-bot
npm init -y
npm install discord.js dotenv

Buat file .env:

DISCORD_TOKEN=token_bot_kamu_disini
CLIENT_ID=application_id_kamu
GUILD_ID=id_server_discord_kamu

GUILD_ID dipakai saat mendaftarkan command ke satu server. Pendaftaran model ini langsung muncul, berbeda dengan command global yang bisa butuh waktu lebih lama.

Langkah 4: Struktur project

discord-bot/
├── src/
│   ├── commands/
│   │   └── ping.js
│   ├── events/
│   │   ├── ready.js
│   │   └── interactionCreate.js
│   └── deploy-commands.js
├── index.js
├── .env
└── package.json

Memisahkan command dan event membuat file utama tetap pendek saat bot bertambah besar.

Langkah 5: File utama

index.js:

require('dotenv').config()
const { Client, GatewayIntentBits, Collection } = require('discord.js')
const fs = require('fs')
const path = require('path')

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
})

client.commands = new Collection()

const commandsPath = path.join(__dirname, 'src', 'commands')
const commandFiles = fs.readdirSync(commandsPath).filter(f => f.endsWith('.js'))

for (const file of commandFiles) {
  const command = require(path.join(commandsPath, file))
  if (command.data && command.execute) {
    client.commands.set(command.data.name, command)
  }
}

const eventsPath = path.join(__dirname, 'src', 'events')
const eventFiles = fs.readdirSync(eventsPath).filter(f => f.endsWith('.js'))

for (const file of eventFiles) {
  const event = require(path.join(eventsPath, file))
  if (event.once) {
    client.once(event.name, (...args) => event.execute(...args))
  } else {
    client.on(event.name, (...args) => event.execute(...args))
  }
}

client.login(process.env.DISCORD_TOKEN)

Langkah 6: Slash command pertama

src/commands/ping.js:

const { SlashCommandBuilder } = require('discord.js')

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Cek latency bot'),

  async execute(interaction) {
    const latency = Date.now() - interaction.createdTimestamp
    await interaction.reply({
      content: `🏓 Pong! Latency: **${latency}ms** | API: **${interaction.client.ws.ping}ms**`,
      ephemeral: false
    })
  }
}

Langkah 7: Event handler

src/events/ready.js:

module.exports = {
  name: 'ready',
  once: true,
  execute(client) {
    console.log(`✅ Bot aktif sebagai ${client.user.tag}`)
    client.user.setActivity('TOKOPTERO Hosting', { type: 'WATCHING' })
  }
}

src/events/interactionCreate.js:

module.exports = {
  name: 'interactionCreate',
  async execute(interaction) {
    if (!interaction.isChatInputCommand()) return

    const command = interaction.client.commands.get(interaction.commandName)
    if (!command) return

    try {
      await command.execute(interaction)
    } catch (error) {
      console.error(error)
      const msg = { content: 'Terjadi error saat menjalankan perintah ini.', ephemeral: true }
      interaction.replied ? await interaction.followUp(msg) : await interaction.reply(msg)
    }
  }
}

Langkah 8: Daftarkan command

src/deploy-commands.js:

require('dotenv').config()
const { REST, Routes } = require('discord.js')
const fs = require('fs')
const path = require('path')

const commands = []
const commandsPath = path.join(__dirname, 'commands')
const commandFiles = fs.readdirSync(commandsPath).filter(f => f.endsWith('.js'))

for (const file of commandFiles) {
  const command = require(path.join(commandsPath, file))
  commands.push(command.data.toJSON())
}

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

rest.put(
  Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
  { body: commands }
).then(() => console.log('✅ Slash commands berhasil didaftarkan'))
  .catch(console.error)

Jalankan sekali setiap kali command berubah, lalu nyalakan bot:

node src/deploy-commands.js
node index.js

Command yang sering dibuat

CommandFungsiTingkat kesulitan
/pingCek latency botMudah
/userinfoInfo member serverSedang
/ban dan /kickModerasi memberSedang
/playBot musikSulit
/ticketSistem tiketMenengah
/economySistem ekonomi virtualMenengah

Deploy ke Panel Pterodactyl

  1. Buat server baru dengan egg Node.js.
  2. Upload project, kecuali folder node_modules.
  3. Isi DISCORD_TOKEN, CLIENT_ID, dan GUILD_ID di environment variable panel.
  4. Jalankan npm install lewat console.
  5. Set startup command ke node index.js, lalu start server.

Panel sudah mengawasi proses dan menyalakannya lagi kalau berhenti. PM2 tidak diperlukan di dalam Pterodactyl, dan menumpuk dua process manager justru bisa membuat bot berjalan dua kali.

Setelah bot online, cek console untuk memastikan tidak ada error login. Kalau token tidak terbaca, periksa nama environment variable dan restart server.

Tags:cara membuat bot discorddiscord.js v14node.js bot discordslash command discorddeploy bot discord

Siap coba?

Bot Discord yang sudah jalan di lokal bisa dipindah ke Panel Pterodactyl supaya online terus.

Lihat paket hosting bot

Artikel Lainnya