728x90
반응형
728x90
반응형
728x90
반응형

최근 유행했던 주사위 게임을 디스코드 봇으로 만들어 보았다.

 


https://discord.com/api/oauth2/authorize?client_id=671993218438791169&permissions=34880&scope=bot

 

Discord - A New Way to Chat with Friends & Communities

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

discord.com

제 봇을 추가해서 테스트해 볼 수 있습니다.

 

명령어: >야추

 


 

 

 

정확히는 디스코드랑 상호작용하는 부분만 만들고 실제로 주사위를 굴리거나 점수를 반환하는 실질적인 게임 부분은 깃허브에서 찾아서 사용했다.

 

사용한 API 코드:

 

https://github.com/dkpark95/yahtzee

 

dkpark95/yahtzee

Code for a simple game of Yahtzee built with JS/jQuery on top of a simple Express API. - dkpark95/yahtzee

github.com

위 API를 돌려서 값만 주고 받아서 사용하는 거다.

 


구조

 

project/

├── bot/

│ ├── app.js (봇)

│ └── emojiCharacters.js (이모지 모음)

└── yahtzee/ (https://github.com/dkpark95/yahtzee)

 

 

emojiCharacters.js 파일은 아래 링크를 참조하여 생성하시면 됩니다.

https://discordjs.guide/popular-topics/miscellaneous-examples.html#emoji-characters

 

Discord.js Guide

A guide made by the community of discord.js for its users.

discordjs.guide


코드 작성하기

 

 

개발환경 : UBUNTU 18.04.3

개발언어: NODE JS V12.13.0

모듈 : discord.js v12

텍스트 에디터: ATOM (편하신거 사용하시면 됩니다.)

 

nodejs와 discordjs의 버전을 확인해주세요. 버전이 다를 경우 문제가 생길 수 있습니다.

discord.js의 버전은 무조건 V12이어야 합니다.

 

 

 

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Extract the required classes from the discord.js module
const Discord = require('discord.js');
const rp = require('request-promise');
const emojiCharacters = require('./emojiCharacters');
 
// Create an instance of a Discord client
const client = new Discord.Client();
 
const botName = 'M4ndU';
const devURL = 'https://mandu-mandu.tistory.com';
const yatchURL = 'http://127.0.0.1:3400';
 
const token = 'TOKEN_HERE';
 
const PREFIX = '?';
 
function showScore(game, i){
  if (game.scorecard[i].locked === true) {
    return game.scorecard[i].points;
  } else {
    var score = '0';
    if (game.scorecard[i].points===null) {
      score = 0;
    }else {
      score = game.scorecard[i].points;
    }
    return "0(+"+score+")";
  }
}
 
function showScoreEmoji(game, i){
  if (game.scorecard[i].locked === true) {
    return ' ✅ ';
  } else {
    return ' ❌ ';
  }
}
 
function showBonusScore(game){
  if (game.scorecard[7].points===null) {
    return `0(${game.scorecard[6].points}/63)(+35)`;
  } else {
    return `${game.scorecard[7].points===null?0:game.scorecard[7].points}(${game.scorecard[6].points===null?0:game.scorecard[6].points}/63)`;
  }
}
 
function showBonusEmoji(game){
  if (game.scorecard[7].points===null) {
    return ' ❌ ';
  } else if (game.scorecard[7].points=== 0) {
    return ' ⛔️ ';
  } else {
    return ' ✅ ';
  }
}
 
function embedScoreMsg(newGame, r, log, turn){
  var dices = "";
  for (var i = 0; i < 5; i++) {
    dices += emojiCharacters[`${newGame.round.dice[i].value}`] +' ';
  }
 
  var gameBoardEmbed = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle(`야추! | 턴 ${turn}/13`)
    .setDescription('입력시간제한 : 1분')
    .setAuthor(botName, '''http://mandu-mandu.tistory.com/')
    .addFields(
      { name'주사위 🎲 ', value: `${dices}`, inline: true },
      { name'남은 횟수 🤹‍ ', value: `${r}`, inline: true },
      { name'점수 합계 🏆 ', value: `${newGame.scorecard[15].points===null?0:newGame.scorecard[15].points}`, inline: true },
      { name'-----------', value: '점수판', inline: false },
      { name: `#1: Ones${showScoreEmoji(newGame, 0)}`, value: `점수: ${ showScore(newGame, 0)}`, inline: true },
      { name: `#2: Twos${showScoreEmoji(newGame, 1)}`, value: `점수: ${ showScore(newGame, 1)}`, inline: true },
      { name: `#3: Threes${showScoreEmoji(newGame, 2)}`, value: `점수: ${ showScore(newGame, 2)}`, inline: true },
      { name: `#4: Fours${showScoreEmoji(newGame, 3)}`, value: `점수: ${ showScore(newGame, 3)}`, inline: true },
      { name: `#5: Fives${showScoreEmoji(newGame, 4)}`, value: `점수: ${ showScore(newGame, 4)}`, inline: true },
      { name: `#6: Sixs${showScoreEmoji(newGame, 5)}`, value: `점수: ${ showScore(newGame, 5)}`, inline: true },
      { name: `1-6 보너스!${showBonusEmoji(newGame)}`, value: `점수:${ showBonusScore(newGame)}`, inline: false },
      { name: `#7: Three of a Kind${showScoreEmoji(newGame, 8)}`, value: `점수: ${ showScore(newGame, 8)}`, inline: true },
      { name: `#8: Four of a Kind${showScoreEmoji(newGame, 9)}`, value: `점수: ${ showScore(newGame, 9)}`, inline: true },
      { name: `#9: Full House${showScoreEmoji(newGame, 10)}`, value: `점수: ${ showScore(newGame, 10)}`, inline: true },
      { name: `#10: Small Straight${showScoreEmoji(newGame, 11)}`, value: `점수: ${ showScore(newGame, 11)}`, inline: true },
      { name: `#11: Large Straight${showScoreEmoji(newGame, 12)}`, value: `점수: ${ showScore(newGame, 12)}`, inline: true },
      { name: `#12: Chance${showScoreEmoji(newGame, 13)}`, value: `점수: ${ showScore(newGame, 13)}`, inline: true },
      { name: `#13: Yahtzee${showScoreEmoji(newGame, 14)}`, value: `점수: ${ showScore(newGame, 14)}`, inline: true },
      { name'기록 📃', value: `${log}`, inline: false },
    )
    .setFooter('Made by M4ndU''');
 
    return gameBoardEmbed;
}
 
 
client.on('ready', async () => {
  console.log(`Logged in as ${client.user.tag}!`);
});
 
client.on('message', async msg => {
  if (msg.content.startsWith(PREFIX)) {
        const input = msg.content.slice(PREFIX.length).split(' ');
        var command = input.shift();
        var commandArgs = input;
 
    if (command === '야추') {
      //게임 시작
      const newGame = await rp({uri:yatchURL + '/api/game'}).then(function (repos) {
        return JSON.parse(repos);
      });
 
      var gameBoardEmbed = embedScoreMsg(newGame, 2,'.'1);
 
      var yachtmsg = await msg.channel.send(gameBoardEmbed).then(msg =>{
        return msg;
      });
 
      Promise.all([
            yachtmsg.react(emojiCharacters['1']),
            yachtmsg.react(emojiCharacters['2']),
            yachtmsg.react(emojiCharacters['3']),
        yachtmsg.react(emojiCharacters['4']),
        yachtmsg.react(emojiCharacters['5']),
        yachtmsg.react('🔁'), //주사위 굴리기
        yachtmsg.react('🔴'), //점수 바로 등록하기
        ]);
 
      //init
      var yachtGame = newGame;
      const filter = (reaction, user) => {
        return ['🔁','🔴'].includes(reaction.emoji.name&& user.id === msg.author.id;
      };
      var stopFlag = false;
      var exit = false;
      var options = {
          method: 'POST',
          uri:yatchURL + '/api/game/roll',
          body: yachtGame,
          json: true // Automatically stringifies the body to JSON
      };
      const filterm = response => {
        return ['1','2','3','4','5','6','7','8','9','10','11','12','13'].includes(response.content&& response.author.id === msg.author.id;
      };
      var choose = '0';
      var userReactions = new Object();
      //init
 
 
      //13턴 돌립니다.
      for (var gameTurn = 1; gameTurn < 14; gameTurn++) {
        //주사위 3라운드 굴리기
        for (var g = 2; g > 0; g--) {
          await yachtmsg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
            .then(async function(collected) {
              const reaction = collected.first();
              if (reaction.emoji.name === '🔁') {
                for (var yrdl = 0; yrdl < 5; yrdl++) {
                  yachtGame.round.dice[yrdl].locked = yachtmsg.reactions.cache.get(emojiCharacters[`${yrdl+1}`]).users.cache.has(msg.author.id);
                }
                //roll
                  } else {
                stopFlag = true;
                g = 1;
                  }
            }).catch(async function(collected) {
              gameBoardEmbed = embedScoreMsg(yachtGame, 0,'시간초과.', gameTurn);
              yachtmsg.edit(gameBoardEmbed);
              stopFlag = true;
              exit = true;
            });
          options = {
              method: 'POST',
              uri:yatchURL + '/api/game/roll',
              body: yachtGame,
              json: true // Automatically stringifies the body to JSON
          };
          if (exit) {
            break;
          }
          if (!stopFlag) {
            yachtGame = await rp(options).then(function (repos) {
              return repos;
            });
          }
 
          if (g === 1) {
            gameBoardEmbed = embedScoreMsg(yachtGame, g-1,'점수로 등록할 번호를 입력하세요.', gameTurn);
            await yachtmsg.edit(gameBoardEmbed);
            break;
          } else {
            gameBoardEmbed = embedScoreMsg(yachtGame, g-1,'잠시 기다려주세요', gameTurn);
          }
 
          await yachtmsg.edit(gameBoardEmbed);
 
          //2 react remove
          await yachtmsg.reactions.resolve('🔁').users.remove(msg.author.id);
          await yachtmsg.reactions.resolve('🔴').users.remove(msg.author.id);
 
          gameBoardEmbed = embedScoreMsg(yachtGame, g-1,'아래 이모지를 클릭해주세요.', gameTurn);
          await yachtmsg.edit(gameBoardEmbed);
        }
        if (exit) {
          break;
        }
 
        //점수 등록과정
        choose = '0';
        stopFlag = false;
        for (var rcc = 0; rcc < 5; rcc++) {
          await msg.channel.awaitMessages(filterm, { max: 1, time: 60000, errors: ['time'] })
                .then(async collected => {
              var resmsg = collected.first();
                    if (isNaN(resmsg.content|| Number(resmsg.content> 14 || Number(resmsg.content< 1 || !Number.isInteger(Number(resmsg.content))) {
                gameBoardEmbed = embedScoreMsg(yachtGame, 0,'1에서 14사이의 정수를 입력.');
                yachtmsg.edit(gameBoardEmbed);
              }else {
                if (resmsg.content < 7) {
                  choose = Number(resmsg.content-1;
                } else {
                  choose = Number(resmsg.content+1;
                }
                if (yachtGame.scorecard[Number(choose)].locked) {
                  gameBoardEmbed = embedScoreMsg(yachtGame, 0,'이미 등록된 번호. 다른번호로 입력.', gameTurn);
                  yachtmsg.edit(gameBoardEmbed);
                }else {
                  options = {
                      method: 'PUT',
                      uri:yatchURL + '/api/game/select/' + yachtGame.scorecard[choose].id,
                      body: yachtGame,
                      json: true // Automatically stringifies the body to JSON
                  };
                  yachtGame = await rp(options).then(function (repos) {
                    return repos;
                  });
                  stopFlag = true;
                }
              }
              resmsg.delete();
                })
                .catch(collected => {
              gameBoardEmbed = embedScoreMsg(yachtGame, 0,'시간초과.', gameTurn);
              yachtmsg.edit(gameBoardEmbed);
              stopFlag = true;
              exit = true;
                });
          if (stopFlag || exit) {
            break;
          }
        }
 
        stopFlag = false;
        if (exit) {
          break;
        }
 
        if (gameTurn === 13) {
          gameBoardEmbed = embedScoreMsg(yachtGame, 0,'게임종료', gameTurn);
          break;
        }else {
          gameBoardEmbed = embedScoreMsg(yachtGame, 2,'기다려주세요', gameTurn+1);
        }
 
        await yachtmsg.edit(gameBoardEmbed);
        //all react remove
        await yachtmsg.reactions.resolve(emojiCharacters['1']).users.remove(msg.author.id);
        await yachtmsg.reactions.resolve(emojiCharacters['2']).users.remove(msg.author.id);
        await yachtmsg.reactions.resolve(emojiCharacters['3']).users.remove(msg.author.id);
        await yachtmsg.reactions.resolve(emojiCharacters['4']).users.remove(msg.author.id);
        await yachtmsg.reactions.resolve(emojiCharacters['5']).users.remove(msg.author.id);
        await yachtmsg.reactions.resolve('🔁').users.remove(msg.author.id);
        await yachtmsg.reactions.resolve('🔴').users.remove(msg.author.id);
 
        gameBoardEmbed = embedScoreMsg(yachtGame, 2,'아래 이모지를 클릭!', gameTurn+1);
        await yachtmsg.edit(gameBoardEmbed);
      }
 
    }
  }
});
 
client.login(token);
 
cs

 


https://discord.com/api/oauth2/authorize?client_id=671993218438791169&permissions=34880&scope=bot

 

Discord - A New Way to Chat with Friends & Communities

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

discord.com

제 봇을 추가해서 테스트해 볼 수 있습니다.

 

명령어: >야추

728x90
반응형

+ Recent posts