Skip to content

Latest commit

 

History

History
98 lines (72 loc) · 2.21 KB

README.md

File metadata and controls

98 lines (72 loc) · 2.21 KB

Choo Choo Discord Bot!

Discord Bot Tutorial

🚂🌈💖🤖 All aboard! Coding Train Tutorial Videos 🚂🌈💖🤖

Steps to create new bot

  1. Create node project and install discord.js module.
$ npm init
$ npm install discord.js
  1. Create an application - optionally set name, description, avatar.

  2. Select Bot from left navigation and "Add Bot" - set name and icon.

  3. Add bot to the A2Z server with the url: https://discord.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&scope=bot

  4. Write the code!

Login to bot account:

const Discord = require('discord.js');
const client = new Discord.Client();
client.login('YOUR BOT TOKEN');

Callback for when the bot is connected and ready:

client.once('ready', () => {
  console.log('Ready!');
});

Callback for when a message is posted:

client.on('message', gotMessage);

function gotMessage(msg) {
  console.log(msg.content);
}
  1. Run the bot!
$ node index.js

Limit to one server and one channel

  1. Enable developer mode in Discord (Settings->Appearance->Enable Developer Mode).
  2. Copy server ID.
  3. Copy channel ID.
const serverID = 'SERVER ID';
const channelID = 'CHANNEL ID';

client.on('message', gotMessage);

function gotMessage(msg) {
  // Only for this server and this channel
  if (msg.guild.id === serverID && msg.channel.id === channelID) {
    // Reply to the message ping!
    if (msg.content === 'ping') {
      msg.channel.send('pong');
    }
  }
}

Store token and other secrets in .env file.

  1. Install dotenv package.
$ npm install dotenv
  1. Create .env file:
SERVERID=123456789
CHANNELID=123456789
TOKEN=123456789
  1. Load environment variables using dotenv and .env:
require('dotenv').config();
const serverID = process.env.SERVERID;
const channelID = process.env.CHANNELID;
const TOKEN = process.env.TOKEN;