DISCORD bot 제작

nodejs 2021. 10. 22. 23:48

DISCORD bot 제작

출처 :  https://mmsesang.tistory.com/19

 

nodejs 버전 14.10 설정

apt-get install build-essential libssl-dev
 


curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
 


source ~/.bashrc

 

nvm install 14.10.0

nvm use v14.10.0

nvm alias default v14.10.0
node --version

 

package.json

{
  "name": "bot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "discord.js": "^12.3.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

기본으로 npm install discord.js 설치한 13버전은 동작하지 않았슴

dependencies    discord버전을 12.3으로 명시해서

npm init

npm install을 하는게 좋음

 

 

index.js

const Discord = require("discord.js");
const config = require("./config.json");
const prefix = "!";


const client = new Discord.Client();


client.on("message", function(message) {
    // message 작성자가 봇이면 그냥 return
    if (message.author.bot) return;
    // message 시작이 prefix가 아니면 return
    if (!message.content.startsWith(prefix)) return;


    const commandBody = message.content.slice(prefix.length);
    const args = commandBody.split(' ');
    const command = args.shift().toLowerCase();
   
    if (command === "ping") {
        message.reply(`pong!`);
    } else if (command === "sum") {
        const numArgs = args.map(x => parseFloat(x));
        const sum = numArgs.reduce((counter, x) => counter += x);
        message.reply(`Sum result: ${sum}`);
    }
});


client.login(config.BOT_TOKEN);


config.json

{
    "BOT_TOKEN": "본인토큰값"
}

실행하기

root@server:~/bot# node index.js

 

!ping   명령어를 치면 

봇이 pong! 으로 응답하고

!sum 1 2 3  입력하면

Sum result : 6 반환한다.

다양한 봇을 작성할수가 있다.

 

 

 

 

 

'nodejs' 카테고리의 다른 글

nodejs so파일  (0) 2021.09.10
MongoError: Cannot use a session that has ended  (0) 2021.07.20
nodejs 버전 업데이트 하기  (0) 2021.07.15
nodemon 설정 방법  (0) 2020.12.09
axios 전송  (0) 2020.12.08
블로그 이미지

iesay

,