DEVELOP/discord-bot

[뉴스검색봇] 1. 개발환경 세팅

shurimp 2022. 5. 1. 17:06

discord.js를 설치하기 위해 nodejs v16.6.0이상이 필요하다.

 

우선 nvm을 먼저 설치해준다. 설치는 scoop으로 진행했다.

nvm은 nodejs의 버전 별 설치와 버전을 바꿔서 작업할 수 있게 해준다.

(nvm 설치 없이 바로 nodejs만 설치해도 된다.)

> scoop install nvm

 

nvm을 설치했으면,

lts버전(안정화 버전) nodejs를 설치한다.

> nvm install lts

 

설치가 완료되면 이 버전을 사용하려면 해당 문구를 타이핑하라는 문장이 나온다.

그대로 입력 후 node -v로 버전이 맞게 세팅됐는지 확인한다.

만약 exit1 오류가 나면 명령 프롬프트를 관리자 권한으로 실행하면 된다.

 

 

nodejs를 설치후,

> npm init-y
> npm install discord.js

를 입력해 discord.js를 설치한다.

 

init은 package.json 파일을 만들어주고, -y옵션은 간편설치같은 옵션이다.

-y를 붙이지 않으면 파일 생성시 정보를 따로 입력할 수 있다.

* 주의할 점은, 봇을 만들 프로젝트 폴더로 경로 이동 후 실행해주어야 한다!

 

+) 추가적으로, 코드 작성 중 syntax 에러 등을 잡아주기 위해 linter를 설치하면 좋다고 해서 설치했다.

vscode 이용자는 ESlint extension을 설치하면된다.

 

프로젝트 폴더 내에 .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"
	}
}

(해당 설정에 대한 자세한 정보는

https://discordjs.guide/preparations/setting-up-a-linter.html#setting-up-eslint-rules 참고)


여기까지 진행되었으면,

discord에서 봇을 생성한다.

 

https://discord.com/developers/applications

 

Discord Developer Portal — API Docs for Bots and Developers

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

discord.com

해당 사이트에서 로그인 후 생성하면 된다.

이 과정은 이미 해두어서 생략한다. 간단히 클릭 몇번 하면 생성할 수 있다.

 

SETTINGS메뉴의 BOT - Build-A-Bot을 활성화시키면 저런 창이 뜨는데 ,

봇 토큰은 여기에서 발급된다.

 

봇 토큰 주의사항

1. 토큰은 딱 한번만 노출되고, 다시 보여주지 않으니 반드시 복사해서 따로 저장해두어야 한다!!
2. 토큰을 잃어버렸을 시 Reset Token을 눌러 재발급받을 수 있으며, 기존 토큰번호가 들어간 코드라인을 새 토큰으로 수정해야한다.
3. 소스코드를 git에 올릴 때 토큰번호가 공개되어선 안된다. gitignore를 통해 토큰 번호가 들어있는 파일을 제외하고 커밋할것!!

 


봇을 생성했으면, 서버에 추가해야한다.

기본 url은 다음과 같다.

https://discord.com/api/oauth2/authorize?client_id=123456789012345678&permissions=0&scope=bot%20applications.commands

client_id에 봇의 APPLICATION_ID를 입력하면 된다.

 

 

 

해당 URL을 주소창에 붙여넣기하면 봇 추가 창이 뜨고, 승인하면 서버에 봇이 잘 들어온 것을 확인할 수 있다.

 


 

이제 봇을 온라인 상태로 만들어주어야 한다.

 

초기파일 생성 작업은 다음과 같이 하면 된다.

 

1. config.json파일 생성

토큰번호를 여기에 저장해둔다.

{
	"clientId": "봇 클라이언트 아이디 입력",
	"guildId": "서버 아이디 입력",
	"token": "토큰 번호 입력"
}

이렇게하면 내 서버에서만 봇이 동작하는데, 나중에 봇을 완성하면 다른 서버에서도 사용할 수 있게 전역설정을

따로 해줘야한다. 개발단계에서는 그럴 필요가 없으니 이렇게 설정하고 나중에 바꾸면 된다.

 

2. gitignore

소스코드 공유시 올리고 싶지 않은 내용을 .gitignore 파일에 지정한다.

중요한 파일이나 모듈폴더 등을 제외해줬다.

node_modules
.env
token.txt
config.json

 

3. index.js 파일 생성

처음 실행할 때 골격은 다음과 같다.

// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.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);

 

4. terminal에서 실행

> node index.js
> node .

둘 중 하나를 입력하면 Ready!라는 메시지와 함께 봇이 온라인 상태로 전환된다!

 

 

 

+) 이 과정에서 Cannot find module 'node:events' 오류가 났다.

찾아보니 nodejs 버전이 16.6.0 이상이어야 정상적으로 실행된다고 하는데,

나는 그보다 높은 16.15.0버전이었는데도 자꾸 이 오류가 났다.

 

그래서 그냥 버전을 16.6.0으로 바꾸고 다시 실행하니 정상적으로 동작했다.

일시적 오류인지, 해당 버전의 버그인지는 잘 모르겠다.

+) 다시 16.15.0 버전으로 실행하니 잘 된다. 일시적인 오류였던걸로...

 

참고로 nodejs 버전 바꾸는 방법은

> nvm install 16.6.0
> nvm use 16.6.0

을 차례대로 실행하면 된다.

 

이렇게 하면 봇을 개발하기 위한 기본세팅이 완료된다.