이전 글에서 봇을 생성하고 채널에 추가까지 해보았는데 이번 포스팅은 서버 설정이다.
서버는 node.js 로 꾸밀 것이고 간단하게 저번에 만들어둔 보일러 플레이트를 활용할 것이다.
$ npm install create-next-express
$ npx create-next-express ./discord-bot
깃과 연동 후 discord.js 다운로드
$ npm install discord.js
22/10/09일 현재 보일러플레이트의 node.js 버전이 v15.6.0 이라 discord.js 패키지 설치 시 수많은 모듈 취약점 경고가 나오게 됐다. (discord 에서 권장하는 node 버전은 최소 v16.9.0)
때문에 이번 프로젝트는 nvm 으로 v16.9.0 으로 설치 후 진행한다.
$ nvm install v16.9.0
$ nvm use v16.9.0
코딩하는 동안 수많은 구문 오류가 발생하거나 일관성 없는 스타일의 코드가 발생할 수 있습니다. 이러한 문제를 완화 하려면 린터를 설치 해야 합니다 . 코드 편집기는 일반적으로 구문 오류를 지적할 수 있지만 린터는 구성에 정의된 대로 코드를 특정 스타일로 강제합니다. 이것이 필수는 아니지만 권장됩니다.
평소에 린터를 써보려고했지만 귀찮아서 그냥 넘긴 적이 많은데 discord 봇 만들때 린터를 권장해서 이번 프로젝트에 린터도 추가를 해봤다. 보일러 코드에도 추가해줘야겠다
.eslintrc.json
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2021
},
"rules": {
"arrow-spacing": ["warn", { "before": true, "after": true }],
"brace-style": ["error", "stroustrup", { "allowSingleLine": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
"indent": ["error", "tab"],
"keyword-spacing": "error",
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
"no-trailing-spaces": ["error"],
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"yoda": "error"
}
}
express 에는 특정 버전 이상 eslint 가 자동으로 설치가 되어있어서 .eslintrc.json
파일에 추가만 해주면 된다. (discord 에서 권장하는 코드 스타일)
설정 리스트는 아래와 같다
이전 글에서 만들어둔 토큰을 환경변수에 저장해두자. 필자는 dotenv 활용
// .env
DISCORD_BOT_TOKEN="토큰"
// discord.js
const express = require('express');
const router = express.Router();
// Require the necessary discord.js classes
const { Client, GatewayIntentBits } = require('discord.js');
const token = process.env.DISCORD_BOT_TOKEN;
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Login to Discord with your client's token
client.login(token);
module.exports = router;
npm run dev
로 실행시켜주면 아래와같이 Ready! 콘솔이 찍힌것을 볼 수 있다.
여기까지 오면서 필자가 겪었던 오류들을 정리해 보려고한다
# 1
Error: Cannot find module 'node:events'
해당 오류는 node 버전이 16미만이라 나오는 오류로 node 버전업을 해줘야한다
# 2
Error [TokenInvalid]: An invalid token was provided.
discord.js
파일에서 token 을 제대로 못불러와서 생기는 에러였다.
node ./discord.js
파일로 discord 파일만 실행시키면 환경 변수값을 찾을 수 없어 프로젝트 전체를 node 로 실행 시켜줬다