aslain.dev
0%
← Tüm makaleler

Building a Discord Bot with Node.js: Step by Step (discord.js)

One of the best ways to keep a Discord community alive is a Discord bot that automates the boring parts. Building a Discord bot is easier than you think: with Node.js and the discord.js library you can run your first command in minutes. In this guide we'll build a bot from scratch and, like my own Runa2 Bot, end with a real command that talks to a game database.

Requirements

  • Node.js 18+ and npm.
  • Create an application + bot in the Discord Developer Portal and grab the token.
  • Invite the bot to your server (OAuth2 → scopes: bot, applications.commands).
  • In your project: npm install discord.js mysql2.

Your first bot: a working /ping

The core of a bot is a Client. The intents decide which events the bot receives:

// index.js
const { Client, GatewayIntentBits, Events } = require('discord.js');

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

client.once(Events.ClientReady, (c) => {
  console.log(`Giris yapildi: ${c.user.tag}`);
});

client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName === 'ping') {
    await interaction.reply('Pong! 🏓');
  }
});

client.login(process.env.TOKEN);

Never hard-code the token; store it as TOKEN in a .env file.

Registering slash commands

Modern bots use slash commands (/ping). Commands must be registered with Discord via the REST API before users can invoke them:

// deploy-commands.js
const { REST, Routes, SlashCommandBuilder } = require('discord.js');

const commands = [
  new SlashCommandBuilder().setName('ping').setDescription('Pong ile yanitlar'),
].map((c) => c.toJSON());

const rest = new REST().setToken(process.env.TOKEN);

await rest.put(
  Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
  { body: commands },
);

Tip: During development use applicationGuildCommands (a single server) — it updates instantly. Global commands can take up to an hour to propagate.

The real world: connecting to a game database

What makes Runa2 Bot special is that it can read from the game's MySQL database and write data through commands. With mysql2, a command that queries a player's level looks like this:

const mysql = require('mysql2/promise');
const db = await mysql.createConnection({
  host: 'localhost', user: 'bot', password: '***', database: 'player',
});

// /seviye komutu icinde:
const [rows] = await db.execute(
  'SELECT level FROM player WHERE name = ?', [name]
);
await interaction.reply(`${name} seviye ${rows[0].level}`);

Note: always use parameters (?) in queries — injecting user input straight into SQL opens the door to SQL injection.

Running the bot 24/7

When you turn off your computer, the bot stops. To keep it running, start it on a VPS with a process manager like pm2: pm2 start index.js. pm2 auto-restarts the bot if it crashes and keeps logs.

Frequently asked questions

Node.js or Python?

Both work great. Node.js (discord.js) is very comfortable for real-time, event-driven work; Python (discord.py) reads cleanly for data/automation-heavy tasks. I use both.

What if the bot token is leaked?

Anyone with the token can control your bot. If it leaks, regenerate it in the Developer Portal immediately and never put it in code or on GitHub.

Can I host the bot for free?

There are free tiers for small bots, but for a serious bot that connects to a game database, a small VPS is the safest choice.

Want a custom bot for your community? I build bots that connect to game databases, moderate, or run events — get in touch.

Devamı için