Create a simple discord bot

黃彥鈞
2 min readMar 22, 2020

--

心血來潮想試著做一個 Discord bot

稍微找了一些資料後發現,製作 Discord bot 的方式也是不少,而身為一個前端工程師,沒有經過太多思考決定窩在舒適圈。

掏出 Node 開幹。

首先,需要到 discord 官網 新增一個 Application,並且新增一個 bot ,在此步驟中可設定此 bot 的名稱、頭像、描述等等,如果有需要也可以開啟OAuth 2.0

接下來就是 node 上場的時候了。

建立專案

npm init -y

安裝 discord.js, nodemon

npm install discord.js nodemon

建立 config.json

{
"prefix": "!" //指令的前綴字
"token": "your token" //更換成 Bot 的 token
}

建立 index.js

const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
}
);
client.on('message', msg => {
if (msg.content === 'ping'){
msg.reply('pong');
}
});

試著跑起來看看ㄅ

nodemon index.js

如果 terminal 沒有出現甚麼錯誤的話,就可以試著照以下步驟把 bot 加入 自己的 discord channel 囉!

進入 這裡

  1. 選擇自己所需的權限,懶的選也可直接選 Administrator
  2. 帶入自己的 Client id 後點選 copy
  3. 開一個新分頁連到複製的網址
  4. 選擇要加入的頻道

至此已經建立了一個簡單的機器人,接下來就可以依照需求延伸功能囉

這裡提供一個範本,內含一些基本的測試指令

--

--