-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraft.js
More file actions
305 lines (290 loc) · 10.1 KB
/
draft.js
File metadata and controls
305 lines (290 loc) · 10.1 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
const pack = require('./pack');
const Emitter = require('events').EventEmitter;
const Permissions = require('eris').Constants.Permissions;
const participant = {
user: 0,
channel: 0,
chosen: 0,
pack: [],
cards: [],
};
const welcomeMessage = [
'Welcome to another Undercards Draft!',
'Choose a card with `!pick <# or Card Name>`, for more help use `!help`.',
].join('\n');
module.exports = class Draft extends Emitter {
constructor(connection, server, {
// finishOnThreshold = false,
cardThreshold = 40,
packSize = 8,
pick = 1,
users = [],
packs = ['dr', 'dr'],
defaultPack = 'ut',
owner = {
id: 0,
},
} = {}) {
super();
if (!connection && !server) return; // Shortcircuit fake drafts
this.id = 1;
this.server = server.id || server;
this.round = 0;
this.packSize = packSize;
this.packs = packs;
this.defaultPack = defaultPack;
this.running = false;
this.owner = owner;
const participants = [participant];
participants.shift(); // delete fake participant
let category = null;
this.channels = [''];
this.channels.pop();
this.participants = participants;
function sendMessage(draftee, message) {
return connection.createMessage(draftee.channel, message);
}
function showCards(draftee) {
const message = [
`**Choose ${pick - draftee.chosen}:**`,
draftee.pack.map((card, i) => `${i + 1}: ${card.name}`).join('\n')
].join('\n');
return sendMessage(draftee, message);
}
const process = (context) => {
if (this.running !== true) return;
// Check if still waiting
const waiting = participants.some((draftee) => draftee.chosen !== pick);
if (!waiting || !participants.length) {
this.emit('nextRound');
} else if (context) {
const draftee = participants.find((draftee) => draftee.user === context.user.id);
if (draftee.chosen !== pick) {
showCards(draftee);
}
}
};
this.on('start', (context) => {
if (this.running) {
context.reply(`Draft${this.id}: ${this.running === true ? 'Already running' : 'Finished'}.`);
return;
}
if (!participants.length) {
context.reply(`Draft${this.id}: No participants`);
return;
}
const guildID = context.guildID;
this.running = true;
connection.createChannel(guildID, `draft${this.id}`, 4).then((cat) => {
category = cat;
const promises = [];
participants.forEach((draftee, i) => {
// Create a channel for the user
promises.push(connection.createChannel(guildID, `room${i + 1}`, 0, {
parentID: category.id,
permissionOverwrites: [{ // Everyone role
id: guildID,
type: 'role',
allow: 0,
deny: Permissions.readMessages,
}, { // Bot member
id: connection.user.id,
type: 'member',
allow: Permissions.readMessages,
deny: 0,
}, { // Owner
id: draftee.user,
type: 'member',
allow: Permissions.readMessages,
deny: 0,
}],
}).then(({ id }) => {
draftee.channel = id;
this.channels.push(id);
return sendMessage(draftee, welcomeMessage);
}));
});
return Promise.all(promises);
}).then(() => {
this.emit('nextRound');
context.reply(`Draft${this.id}: Started!`);
}).catch(() => {
context.reply(`Error starting Draft${this.id}`);
this.running = false;
});
});
this.on('nextRound', () => {
if (this.running !== true) return;
if (!participants.length) {
this.emit('clear');
return;
}
// Check threshold
if (participants[0].cards.length >= cardThreshold) {
this.emit('finish');
return;
}
if (!participants[0].pack.length) {
// Give people new cards
participants.forEach((draftee) => {
draftee.pack = this.nextPack();
});
this.round += 1;
} else {
// Rotate packs
const temp = participants[0].pack;
let i = 0;
while (i < participants.length - 1) {
participants[i++].pack = participants[i].pack;
}
participants[i].pack = temp;
}
// Message current pack
participants.forEach((draftee) => {
draftee.chosen = 0;
showCards(draftee);
});
});
this.on('pick', (context, card = '') => {
if (this.running !== true) return undefined;
const { channel, user } = context;
const draftee = participants.find((draftee) => draftee.user === (user.id || user));
if (!draftee) {
return context.reply('Not registered to Draft.');
} else if (draftee.channel !== (channel.id || channel)) {
return context.reply('Move to your draft room to use this command.');
} else if (draftee.chosen === pick) {
return context.reply('You have already chosen. Please wait for the others to choose.');
}
const number = Number(card);
if (Number.isNaN(number) && card.length > 1) {
const i = 1 + draftee.pack.findIndex((slot) => {
// Simple checks
if (slot.name === card || slot.name.indexOf(card) >= 0) return true;
// Mutate checks
const lower1 = slot.name.toLowerCase();
const lower2 = card.toLowerCase();
return lower1 === lower2 || lower1.indexOf(lower2) >= 0;
});
if (!i) {
return context.reply(`Invalid input: ${card}`);
}
card = i;
} else if (!Number.isFinite(number) || number < 1 || number > draftee.pack.length) {
return context.reply(`Invalid input: \`${card}\``);
}
const selected = draftee.pack.splice(card - 1, 1)[0];
draftee.cards.push(selected);
draftee.chosen += 1;
return context.reply(`Chosen card ${card}: ${selected.name}`);
});
this.on('pick', process);
this.on('finish', () => {
if (this.running === 'finished') return;
this.running = 'finished';
if (!category) return;
// Send decks to participants
participants.forEach((draftee) => {
const deck = draftee.cards.map((card, i) => `${i + 1}: ${card.name}`).join('\n');
connection.createMessage(draftee.channel, `Your deck:\n${deck}`);
});
});
this.on('kick', (context, users = []) => {
if (this.running !== true) return;
const resp = [];
if (isNotOwner(context, owner.id || owner)) {
return context.reply('Only owner can kick.');
}
users.forEach((user) => {
resp.push(new Promise((res) => {
const draftee = participants.find((draftee) => draftee.user === (user.id || user));
if (!draftee) {
return res('Not found');
}
const promise = Promise.resolve(draftee.channel ? connection.deleteChannel(draftee.channel) : 'No channel');
res(promise.then(() => {
participants.splice(participants.indexOf(draftee), 1);
return 'Kicked';
}).catch(() => 'Failed to kick'));
}).then(resp => `${user.nick || user.username && `${user.username}#${user.discriminator}` || user}: ${resp}`));
});
Promise.all(resp)
.then(responses => context.reply(responses.join('\n') || 'Invalid syntax.'))
.then(() => process());
});
this.on('clear', (context) => {
if (!category) return;
if (context && isNotOwner(context, owner.id || owner)) {
this.emit('cleared', 'Missing Permissions');
return context.reply('Only owner can clear draft.');
}
const promises = category.channels.map((channel) => connection.deleteChannel(channel.id));
return Promise.all(promises)
.then(() => connection.deleteChannel(category.id))
.catch((e) => {
if (e.message !== 'Unknown Channel') {
throw e;
}
}).then(() => {
this.emit('cleared');
category = null;
return `Cleared.`;
}).catch((e = '') => {
this.emit('cleared', e);
return `Error clearing draft: ${e.message || e}`;
}).then((msg) => {
if (context && msg) {
context.reply(`Draft${this.id}: ${msg}`);
}
});
});
this.on('status', (context) => {
const embed = {
title: `Draft ${this.id}: ${this.running === true ? 'Ongoing' : 'Finished'}`,
color: 1794964,
fields: [{
name: '❯ Settings',
value: [
`Deck Size: ${cardThreshold}`,
`Pack Size: ${packSize}`,
`Pick: ${pick}`,
`Default Pack: ${defaultPack}`,
`Pack Sets: ${packs.join(', ')}`,
].join('\n'),
}],
};
if (participants.length) {
embed.fields.push({
name: '❯ Participants',
value: participants.map((draftee) => {
const user = context.guild.members.get(draftee.user);
return `${user && user.mention || draftee.user} (${draftee.cards.length}/${cardThreshold})${this.running === true && draftee.chosen !== pick ? `: Picking cards (${draftee.chosen}/${pick})` : ''}`
}).join('\n'),
});
}
context.reply({ embed });
});
this.on('leave', (context) => {
if (this.running !== true) return;
const draftee = participants.find((draftee) => draftee.user === context.user.id);
if (!draftee) return context.reply('You are not in this draft.');
participants.splice(participants.indexOf(draftee), 1);
context.reply('You have left the draft.');
});
this.on('leave', () => process());
users.forEach((user) => participants.push({
user: user.id || user, // User object or ID
channel: 0,
chosen: 0,
pack: [],
cards: [],
}));
}
nextPack() {
const type = this.packs[this.round] || this.defaultPack || 'ut'; // fall back to UT incase a setting is broken
return pack(this.packSize, type);
}
};
function isNotOwner(context, ownerID) {
return context.user.id !== ownerID && !context.isAdmin();
}