Discord bot with node.js 練習

Wei zen Liu
Dennisliuu 筆記空間
4 min readFeb 18, 2019

維基百科:Discord是一種閉源免費實時通話軟體,初始版本開發於2015年3月,主要用於遊戲玩家,這款軟體可以在Microsoft Windows、macOS、Android、iOS、Linux和網頁上執行。Benchmark Capital和騰訊等公司看好此軟體的前景並對營運商投資超過三千萬美元。

小練習大概只需 30 分鐘,17 行程式,利用簡單的 node js 建立一個翻譯功能的 discord bot。

第一步,註冊或登入 discord https://discordapp.com/login 帳號:

第二步,到 https://discordapp.com/developers/applications/ 點擊右上的 New Application 建立 bot,名字暫為 my application。

產生完後會導向至另一個頁面,點擊左欄的 bot,並新增一個 bot。

產生完後會有一組 token,之後會在 node.js 中用到。

以上建置 bot 的基本工作就完成了,到 discord 聊天界面中產生一個新的伺服。

點擊建立並隨意取一個名字,並將以下內容貼至聊天視窗

https://discordapp.com/oauth2/authorize?&client_id=ENTER_YOUR_BOT_CLIENT_ID_HERE&scope=bot&permissions=8

並點擊網址,將管理員權限拿掉並授權

此時應該可以看到 bot 加入聊天室了!

接著便可以進入程式的部份。

以下環境為:Ubuntu 18.04 / node 10.15.1 / npm 6.4.1

首先先建立一個 folder,並 npm init,一路 entry 即可

mkdir discord-test && npm init

安裝 discord.js 以操作 discord bot

npm install discord.js / yarn add discord.js

由於這次的範例會是翻譯,因此會用到 Yandex 的 api。

先至 Yandex 網站註冊並取的 free api key。

並安裝 axios 以取得 Yandex 功能

npm install axios / yarn add axios

回到 discord-test 資料夾,建立一個 index.js

touch index.js

接下來便要建立我們的 node.js app

以上為 index.js 中的程式碼

前兩行為產生 discord 的 client 端,client 會持續監聽 bot 所接收到的 message,在接到 message 後再透過 axios 連接至 Yandex 的 Api 翻譯功能,並將內容傳回至聊天室。

--

--

Wei zen Liu
Dennisliuu 筆記空間

Front-end developer / Mobile application developer, Study in NTUT. Skills: Html / SCSS / Javascript(es6) / gulp.js / Vue.js / Git / bash / linux / C / C++ /