Compare commits

...

11 Commits

Author SHA1 Message Date
4ad4f69f9f updated package info 2022-02-01 11:59:34 -06:00
dc0cc6685d typo 2022-01-31 21:20:12 -06:00
c04cd2ef12 i hate windows 2022-01-31 21:18:43 -06:00
763892443d there were some extra newlines 2022-01-31 19:46:09 -06:00
9646d9f941 updated version number and dependencies 2022-01-31 19:35:28 -06:00
fe866050d5 improved messages and general cleanup 2022-01-31 19:33:39 -06:00
00d04c787d added inactivity timeout 2022-01-31 17:47:43 -06:00
f0283145dc added cancel command 2022-01-31 17:39:06 -06:00
50c297bfea removed dev comments 2022-01-31 17:07:59 -06:00
c2c59e53ca updated comments 2022-01-31 17:06:40 -06:00
85d0e833dd cleaned up queue code 2022-01-31 17:06:34 -06:00
14 changed files with 532 additions and 284 deletions

View File

@@ -1,6 +1,8 @@
<!-- markdownlint-disable MD033 --> <!-- markdownlint-disable MD033 -->
# 1800queue # 1800queue alt
This version does not run continuously, and requires each tourney to be started with a command
## Prerequirements ## Prerequirements

70
dist/api.js vendored
View File

@@ -24,31 +24,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getPlayerInteraction = exports.getPlayer = void 0; exports.getPlayerInteraction = exports.getPlayer = void 0;
const cheerio = __importStar(require("cheerio")); const cheerio = __importStar(require("cheerio"));
const discord_js_1 = require("discord.js");
const https_1 = __importDefault(require("https")); const https_1 = __importDefault(require("https"));
//making long regex rather than splitting the string at ":" because regex would be easier to debug than logic in the case the website changes const util_1 = require("./util");
//while names cant have spaces, the name slot in ogtitle could be shown as "No Player Name" which has spaces
const uniteApiRegex = { const uniteApiRegex = {
//$1 = name, $2 = id //$1 = name, $2 = id
ogtitle: /unite api - (.+) \((.*)\)/i, ogtitle: /unite api - (.+) \((.*)\)/i,
//$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line) //$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line)
ogdescription: [ ogdescription: [
//line 1 /lv\.(\d+) (\w+) \((\d+)\)/i,
[ /lv\.(\d+) (\w+): class (\d+)/i //other
/lv\.(\d+) (\w+) \((\d+)\)/i,
/lv\.(\d+) (\w+): class (\d+)/i //other
],
] ]
}; };
/*
og:title
Unite API - IanWhysp (X188GF7)
og:description
Pokémon Unite : Lv.40 Master (1741)
Battles : 1089
Wins : 576
Win Rate : 52%
*/
/** /**
* gets the html of the uniteApi page for the player * gets the html of the uniteApi page for the player
* @param name name of player * @param name name of player
@@ -68,11 +55,10 @@ function getHTML(name) {
return; return;
} }
let result = Buffer.alloc(0); let result = Buffer.alloc(0);
response.on('data', function (chunk) { response.on('data', chunk => {
result = Buffer.concat([result, chunk]); result = Buffer.concat([result, chunk]);
}); });
response.on('end', function () { response.on('end', () => {
// result has response body buffer
resolve(result.toString()); resolve(result.toString());
}); });
}; };
@@ -84,11 +70,14 @@ function getHTML(name) {
* interprets the html from getHTML() * interprets the html from getHTML()
* @param name name of player * @param name name of player
* @returns player data from site * @returns player data from site
* @throws errorMessage class if the request fails
*/ */
function readHTML(html) { function readHTML(html) {
let metaElems = cheerio.load(html)('meta').toArray(), foundData = { let $ = cheerio.load(html);
let metaElems = $('meta').toArray(), foundData = {
name: "", name: "",
id: "", id: "",
avatar: "",
level: "", level: "",
rank: "", rank: "",
elo: null, elo: null,
@@ -118,7 +107,7 @@ function readHTML(html) {
extraLines.push(line); extraLines.push(line);
} }
if (!lines.length) if (!lines.length)
throw 'Unable to read data, please try again'; throw (0, util_1.emsg)('Unable to read data, please try again');
//bring the first lines removed back into the data //bring the first lines removed back into the data
lines = [ lines = [
...lines, ...lines,
@@ -128,11 +117,11 @@ function readHTML(html) {
{ {
//will be only text after "pokemon unite:" //will be only text after "pokemon unite:"
let line = lines[0].split(':').slice(1).join(':').trim(); let line = lines[0].split(':').slice(1).join(':').trim();
let regex = uniteApiRegex.ogdescription[0]; let regex = uniteApiRegex.ogdescription;
if (regex[0].test(line)) { //is master/has elo if (regex[0].test(line)) { //is master/has elo
let regexData = line.match(regex[0]); let regexData = line.match(regex[0]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw 'Unable to read data, please try again'; throw (0, util_1.emsg)('Unable to read data, please try again');
foundData.level = regexData[1]; foundData.level = regexData[1];
foundData.rank = regexData[2]; foundData.rank = regexData[2];
foundData.elo = regexData[3]; foundData.elo = regexData[3];
@@ -140,7 +129,7 @@ function readHTML(html) {
else { //is not master/has a class else { //is not master/has a class
let regexData = line.match(regex[1]); let regexData = line.match(regex[1]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw 'Unable to read data, please try again'; throw (0, util_1.emsg)('Unable to read data, please try again');
foundData.level = regexData[1]; foundData.level = regexData[1];
foundData.rank = regexData[2]; foundData.rank = regexData[2];
foundData.class = regexData[3]; foundData.class = regexData[3];
@@ -162,17 +151,10 @@ function readHTML(html) {
break; break;
} }
}); });
/*let data = uniteApiRegex.ogdescription.exec(attr.content);
if (data !== null && data.length >= 7) {
foundData.level = data[1];
foundData.rank = data[2];
foundData.elo = data[3];
foundData.battles = data[4];
foundData.wins = data[5];
foundData.winrate = data[6];
}*/
} }
}); });
foundData.avatar = $('.player-card-image img').attr('src') || "";
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
return foundData; return foundData;
} }
/** /**
@@ -198,18 +180,32 @@ async function getPlayer(name) {
return null; return null;
} }
exports.getPlayer = getPlayer; exports.getPlayer = getPlayer;
async function sendPlayerEmbed(interaction, data) {
let embed = new discord_js_1.MessageEmbed()
.setTitle(`${data.name} (${data.id})`)
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
.setTimestamp()
.setThumbnail(data.avatar)
.setDescription(`Level ${data.level}
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
**Battles** ${data.battles}
**Wins** ${data.wins}
**Win Rate** ${data.winrate}`);
await interaction.editReply({ embeds: [embed] });
}
/** /**
* calls getPlayer() with the name from the interaction * calls getPlayer() with the name from the interaction
* @param interaction discord interaction * @param interaction discord interaction
* @throws errorMessage class if the user cannot be found
*/ */
async function getPlayerInteraction(interaction) { async function getPlayerInteraction(interaction) {
let username = interaction.options.getString('username', true); let username = interaction.options.getString('username', true);
await interaction.deferReply(); await interaction.deferReply();
let data = await getPlayer(username); let data = await getPlayer(username);
if (data === null) if (data === null)
await interaction.editReply('Unable to find user'); throw (0, util_1.emsg)('Unable to find user');
else else
await interaction.editReply('```\n' + JSON.stringify(data, null, 2) + '\n```'); sendPlayerEmbed(interaction, data);
} }
exports.getPlayerInteraction = getPlayerInteraction; exports.getPlayerInteraction = getPlayerInteraction;
//await getPlayer('IanWhysp')

13
dist/discord.js vendored
View File

@@ -13,7 +13,8 @@ const commands = [
type: 4, type: 4,
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
required: true required: true,
min_value: 1
} }
] ]
}, },
@@ -30,17 +31,17 @@ const commands = [
description: 'ready the queue and display team info' description: 'ready the queue and display team info'
}, },
{ {
name: 'queueinfo', name: 'cancel',
description: 'get info of the current queue' description: 'cancels the current queue (must have the Manage Messages permission)'
}, },
{ {
name: 'elo', name: 'player',
description: 'display elo information', description: 'display player information',
options: [ options: [
{ {
type: 3, type: 3,
name: 'username', name: 'username',
description: 'in game name', description: 'in game name or UniteApi short link',
required: true required: true
} }
] ]

16
dist/index.js vendored
View File

@@ -24,6 +24,7 @@ const fs = __importStar(require("fs"));
const api_1 = require("./api"); const api_1 = require("./api");
const discord_1 = require("./discord"); const discord_1 = require("./discord");
const queue_1 = require("./queue"); const queue_1 = require("./queue");
const util_1 = require("./util");
const CLIENT = new discord_js_1.Client({ intents: [discord_js_1.Intents.FLAGS.GUILDS] }); const CLIENT = new discord_js_1.Client({ intents: [discord_js_1.Intents.FLAGS.GUILDS] });
//init logs with a timestamp //init logs with a timestamp
console.log(new Date().toISOString() + '\n\n'); console.log(new Date().toISOString() + '\n\n');
@@ -51,17 +52,20 @@ CLIENT.on('interactionCreate', async (interaction) => {
await (0, queue_1.leaveQueue)(interaction); await (0, queue_1.leaveQueue)(interaction);
else if (interaction.commandName === 'ready') else if (interaction.commandName === 'ready')
await (0, queue_1.readyQueue)(interaction); await (0, queue_1.readyQueue)(interaction);
else if (interaction.commandName === 'queueinfo') else if (interaction.commandName === 'cancel')
await (0, queue_1.queueInfo)(interaction); await (0, queue_1.cancelQueue)(interaction);
else if (interaction.commandName === 'elo') else if (interaction.commandName === 'player')
await (0, api_1.getPlayerInteraction)(interaction); await (0, api_1.getPlayerInteraction)(interaction);
} }
catch (e) { catch (e) {
if (typeof e === 'string') { if (e instanceof util_1.errorMessage) {
if (interaction.deferred || interaction.replied) if (interaction.deferred || interaction.replied)
interaction.editReply(e); interaction.editReply(e.msg);
else else
interaction.reply(e); interaction.reply({
content: e.msg,
ephemeral: e.ephemeral
});
} }
else else
console.error(e); console.error(e);

179
dist/queue.js vendored
View File

@@ -1,120 +1,189 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.queueInfo = exports.readyQueue = exports.leaveQueue = exports.joinQueue = exports.createQueue = void 0; exports.cancelQueue = exports.readyQueue = exports.leaveQueue = exports.joinQueue = exports.createQueue = exports.queueContains = exports.getAll = exports.getInfo = void 0;
const discord_js_1 = require("discord.js"); const discord_js_1 = require("discord.js");
const util_1 = require("./util"); const util_1 = require("./util");
//maps ChannelID to QueueInfo //maps ChannelID to QueueInfo
const QUEUE = new Map(); const QUEUE = new Map();
/**
* get the GuildMember of an interaction
* @param interaction
* @throws string message if it cannot be read
* @returns member
*/
function getMember(interaction) {
let member = interaction.member;
if (!(member instanceof discord_js_1.GuildMember))
throw 'Unable to retrieve guild member information, please try again';
return member;
}
/** /**
* get the queueInfo of an interaction * get the queueInfo of an interaction
* @param interaction * @param interaction
* @throws string message if it does not exist * @throws errorMessage class if it does not exist
* @returns queue info * @returns queue info
*/ */
function getInfo(interaction) { function getInfo(interaction) {
let info = QUEUE.get(interaction.channelId); let info = QUEUE.get(interaction.channelId);
if (!info) if (!info)
throw 'There is not an active queue in this channel, type `/queue` to create one'; throw (0, util_1.emsg)('There is not an active queue in this channel, type `/queue` to create one');
return info; return info;
} }
exports.getInfo = getInfo;
/**
* compiles all the get functions above
* @param interaction
* @throws if another get function throws
* @returns object containing each
*/
const getAll = (interaction) => ({
member: (0, util_1.getMember)(interaction),
channel: (0, util_1.getChannel)(interaction),
info: getInfo(interaction)
});
exports.getAll = getAll;
/**
* checks if the interaction data is already in the queue
* @param interaction
* @returns boolean
*/
function queueContains(interaction) {
let { member, info } = (0, exports.getAll)(interaction);
if (info.players.map(m => m.id).includes(member.id))
return true;
return false;
}
exports.queueContains = queueContains;
/**
* creates the timeout for the queue
* @param interaction
* @returns time timeout identifier
*/
function setQueueTimeout(interaction) {
let channel = (0, util_1.getChannel)(interaction);
return setTimeout(() => {
clearQueue(interaction);
channel.send('Queue has been reset due to inactivity');
}, 5 * 60 * 1000); //5 minutes
}
/**
* updates the rich embed for the current queue
* @param interaction
*/
async function sendQueueEmbed(interaction, closed = false) {
let info = getInfo(interaction), origInteraction = info.initiator.interaction;
let embed = new discord_js_1.MessageEmbed()
.setTitle('Queue')
.setAuthor({
name: info.initiator.member.displayName,
iconURL: info.initiator.member.displayAvatarURL({ dynamic: true })
})
.addField('Team Size', info.teamsize.toString(), true)
.addField('Players Joined', info.players.length.toString(), true)
.setFooter({ text: closed ? 'queue is finished' : 'type /join' });
if (origInteraction.deferred || origInteraction.replied)
await origInteraction.editReply({ embeds: [embed] });
else
await origInteraction.reply({ embeds: [embed] });
}
/**
* sends the list of teams
* @param interaction
*/
async function sendTeamsEmbed(interaction, teams) {
let embed = new discord_js_1.MessageEmbed()
.setTitle('Teams');
teams.forEach((team, i) => {
team.map(m => m.user.tag);
embed.addField(`Title ${i + 1}`, team.join('\n'));
});
interaction.reply({ embeds: [embed] });
}
/**
* sends the list of teams
* @param interaction
*/
async function clearQueue(interaction) {
let info = getInfo(interaction);
sendQueueEmbed(interaction, true);
clearTimeout(info.timeout);
QUEUE.delete(interaction.channelId);
}
/** /**
* creates a queue from an interaction * creates a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be created * @throws errorMessage class if it cannot be created
*/ */
async function createQueue(interaction) { async function createQueue(interaction) {
let { channelId } = interaction, member = getMember(interaction), teamsize = interaction.options.getInteger('teamsize', true); let member = (0, util_1.getMember)(interaction), { channelId } = interaction, teamsize = interaction.options.getInteger('teamsize', true);
if (QUEUE.has(channelId)) if (QUEUE.has(channelId))
throw 'There is already an active queue in this channel, type `/join` to join'; //and you are already in it throw (0, util_1.emsg)('There is already an active queue in this channel, ' + (queueContains(interaction) ? 'and you are already in it' : 'type `/join` to join'));
QUEUE.set(channelId, { QUEUE.set(channelId, {
players: [ players: [
member member
], ],
initiator: member, initiator: {
teamsize: teamsize interaction,
member
},
teamsize: teamsize,
timeout: setQueueTimeout(interaction)
}); });
await interaction.reply(`Queue for teams of ${teamsize} has been created, and you have joined`); sendQueueEmbed(interaction);
} }
exports.createQueue = createQueue; exports.createQueue = createQueue;
/** /**
* joins a queue from an interaction * joins a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be joined * @throws errorMessage class if it cannot be joined
*/ */
async function joinQueue(interaction) { async function joinQueue(interaction) {
let member = getMember(interaction), info = getInfo(interaction); let { member, info } = (0, exports.getAll)(interaction);
if (info.players.map(m => m.id).includes(member.id)) if (queueContains(interaction))
throw 'You are already in the active queue'; throw (0, util_1.emsg)('You are already in the active queue');
info.players.push(member); info.players.push(member);
clearTimeout(info.timeout);
info.timeout = setQueueTimeout(interaction);
QUEUE.set(interaction.channelId, info); QUEUE.set(interaction.channelId, info);
sendQueueEmbed(interaction);
await interaction.reply('Joined the queue'); await interaction.reply('Joined the queue');
} }
exports.joinQueue = joinQueue; exports.joinQueue = joinQueue;
/** /**
* leaves a queue from an interaction * leaves a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be left * @throws errorMessage class if it cannot be left
*/ */
async function leaveQueue(interaction) { async function leaveQueue(interaction) {
let member = getMember(interaction), info = getInfo(interaction); let { member, info } = (0, exports.getAll)(interaction);
if (!info.players.map(m => m.id).includes(member.id)) if (!queueContains(interaction))
throw 'You aren\'t in the active queue'; throw (0, util_1.emsg)('You aren\'t in the active queue');
info.players.splice(info.players.indexOf(member), 1); info.players.splice(info.players.indexOf(member), 1);
clearTimeout(info.timeout);
info.timeout = setQueueTimeout(interaction);
QUEUE.set(interaction.channelId, info); QUEUE.set(interaction.channelId, info);
sendQueueEmbed(interaction);
await interaction.reply('Left the queue'); await interaction.reply('Left the queue');
} }
exports.leaveQueue = leaveQueue; exports.leaveQueue = leaveQueue;
/** /**
* readys a queue from an interaction * readys a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be readied * @throws errorMessage class if it cannot be readied
*/ */
async function readyQueue(interaction) { async function readyQueue(interaction) {
let member = getMember(interaction), info = getInfo(interaction), { initiator } = info; let { member, info } = (0, exports.getAll)(interaction), { initiator } = info;
if (member.id !== initiator.id) if (member.id !== initiator.member.id)
throw 'Only the queue initiator can ready the queue'; throw (0, util_1.emsg)('Only the queue initiator can ready the queue');
//reset queue clearQueue(interaction);
QUEUE.delete(interaction.channelId); if (info.players.filter(m => m.id !== initiator.member.id).length === 0)
if (info.players.filter(m => m.id !== initiator.id).length === 0) throw (0, util_1.emsg)('Nobody signed up for the queue, the queue has been reset');
throw 'Nobody signed up for the queue, the queue has been reset';
//team data //team data
let playerlist = (0, util_1.shuffle)(info.players), teams = []; let playerlist = (0, util_1.shuffle)(info.players), teams = [];
//fill team data //fill team data
for (let i = 0; i < playerlist.length; i += info.teamsize) for (let i = 0; i < playerlist.length; i += info.teamsize)
teams.push(playerlist.slice(i, i + info.teamsize)); teams.push(playerlist.slice(i, i + info.teamsize));
//convert teams to strings sendTeamsEmbed(interaction, teams);
let teamsStr = [];
teams.forEach((team, i) => {
let str = [`Team ${i + 1}`];
team.forEach(m => str.push(` ${m.user.tag}`));
teamsStr.push(str.join('\n'));
});
await interaction.reply('```\n' + teamsStr.join('\n\n') + '\n```');
} }
exports.readyQueue = readyQueue; exports.readyQueue = readyQueue;
/** /**
* sends the queue information from an interaction * readys a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be read * @throws errorMessage class if it cannot be reset
*/ */
async function queueInfo(interaction) { async function cancelQueue(interaction) {
let info = getInfo(interaction); let { info, member, channel } = (0, exports.getAll)(interaction);
await interaction.reply('```' + ` if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
players: ${info.players.map(p => p.user.tag).join('\n ')} throw (0, util_1.emsg)('You do not have permission to run this command');
initiator: ${info.initiator.user.tag} clearQueue(interaction);
teamsize: ${info.teamsize} await interaction.reply('Queue has been reset');
` + '```');
} }
exports.queueInfo = queueInfo; exports.cancelQueue = cancelQueue;

44
dist/util.js vendored
View File

@@ -1,6 +1,7 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.shuffle = void 0; exports.getChannel = exports.getMember = exports.emsg = exports.errorMessage = exports.shuffle = void 0;
const discord_js_1 = require("discord.js");
/** /**
* shuffles an array * shuffles an array
* https://stackoverflow.com/a/2450976/2856416 * https://stackoverflow.com/a/2450976/2856416
@@ -22,3 +23,44 @@ function shuffle(array) {
return array; return array;
} }
exports.shuffle = shuffle; exports.shuffle = shuffle;
class errorMessage {
constructor(msg, ephemeral = true) {
this.msg = msg;
this.ephemeral = ephemeral;
}
}
exports.errorMessage = errorMessage;
/**
* a simple class to contain an error message and related data
* @param msg error message
* @param ephemeral (default=true)
* @returns new errorMessage
*/
const emsg = (msg, ephemeral = true) => new errorMessage(msg, ephemeral);
exports.emsg = emsg;
/**
* get the GuildMember of an interaction
* @param interaction
* @throws errorMessage class if it cannot be read
* @returns member
*/
function getMember(interaction) {
let member = interaction.member;
if (!(member instanceof discord_js_1.GuildMember))
throw (0, exports.emsg)('Unable to retrieve guild member information, please try again');
return member;
}
exports.getMember = getMember;
/**
* get the TextChannel of an interaction
* @param interaction
* @throws errorMessage class if it cannot be read
* @returns member
*/
function getChannel(interaction) {
let channel = interaction.channel;
if (!(channel instanceof discord_js_1.TextChannel))
throw (0, exports.emsg)('Unable to retrieve text channel information, please try again');
return channel;
}
exports.getChannel = getChannel;

86
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "1800queue", "name": "1800queue-alt",
"version": "0.0.1", "version": "1.0.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "1800queue", "name": "1800queue-alt",
"version": "0.0.1", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@discordjs/rest": "^0.3.0", "@discordjs/rest": "^0.3.0",
@@ -58,17 +58,6 @@
"npm": ">=7.0.0" "npm": ">=7.0.0"
} }
}, },
"node_modules/@discordjs/builders/node_modules/@sindresorhus/is": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.4.0.tgz",
"integrity": "sha512-QppPM/8l3Mawvh4rn9CNEYIU9bxpXUCRMaX9yUpvBk1nMKusLKpfXGDEKExKaPhLzcn3lzil7pR6rnJ11HgeRQ==",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sindresorhus/is?sponsor=1"
}
},
"node_modules/@discordjs/collection": { "node_modules/@discordjs/collection": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-0.4.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-0.4.0.tgz",
@@ -96,30 +85,32 @@
} }
}, },
"node_modules/@sapphire/async-queue": { "node_modules/@sapphire/async-queue": {
"version": "1.1.9", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.1.9.tgz", "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.2.0.tgz",
"integrity": "sha512-CbXaGwwlEMq+l1TRu01FJCvySJ1CEFKFclHT48nIfNeZXaAAmmwwy7scUKmYHPUa3GhoMp6Qr1B3eAJux6XgOQ==", "integrity": "sha512-O5ND5Ljpef86X5oy8zXorQ754TMjWALcPSAgPBu4+76HLtDTrNoDyzU2uGE2G4A8Wv51u0MXHzGQ0WZ4GMtpIw==",
"engines": { "engines": {
"node": ">=v14.0.0", "node": ">=v14.0.0",
"npm": ">=7.0.0" "npm": ">=7.0.0"
} }
}, },
"node_modules/@sapphire/snowflake": { "node_modules/@sapphire/snowflake": {
"version": "3.0.1", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.0.1.tgz", "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.1.0.tgz",
"integrity": "sha512-v+wCC2q9DK3OhG7Vcdt/8A/INAYiyhlMD5snakmXGBN1usLBwSGJVJBjDHv4VGI5C9YYl4UdW5Ovr3arvYsJXQ==", "integrity": "sha512-K+OiqXSx4clIaXcoaghrCV56zsm3bZZ5SBpgJkgvAKegFFdETMntHviUfypjt8xVleIuDaNyQA4APOIl3BMcxg==",
"engines": { "engines": {
"node": ">=v14.0.0", "node": ">=v14.0.0",
"npm": ">=7.0.0" "npm": ">=7.0.0"
} }
}, },
"node_modules/@sindresorhus/is": { "node_modules/@sindresorhus/is": {
"version": "0.14.0", "version": "4.4.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.4.0.tgz",
"integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", "integrity": "sha512-QppPM/8l3Mawvh4rn9CNEYIU9bxpXUCRMaX9yUpvBk1nMKusLKpfXGDEKExKaPhLzcn3lzil7pR6rnJ11HgeRQ==",
"dev": true,
"engines": { "engines": {
"node": ">=6" "node": ">=10"
},
"funding": {
"url": "https://github.com/sindresorhus/is?sponsor=1"
} }
}, },
"node_modules/@szmarczak/http-timer": { "node_modules/@szmarczak/http-timer": {
@@ -896,6 +887,15 @@
"node": ">=8.6" "node": ">=8.6"
} }
}, },
"node_modules/got/node_modules/@sindresorhus/is": {
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz",
"integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==",
"dev": true,
"engines": {
"node": ">=6"
}
},
"node_modules/graceful-fs": { "node_modules/graceful-fs": {
"version": "4.2.9", "version": "4.2.9",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz",
@@ -1986,13 +1986,6 @@
"ts-mixer": "^6.0.0", "ts-mixer": "^6.0.0",
"tslib": "^2.3.1", "tslib": "^2.3.1",
"zod": "^3.11.6" "zod": "^3.11.6"
},
"dependencies": {
"@sindresorhus/is": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.4.0.tgz",
"integrity": "sha512-QppPM/8l3Mawvh4rn9CNEYIU9bxpXUCRMaX9yUpvBk1nMKusLKpfXGDEKExKaPhLzcn3lzil7pR6rnJ11HgeRQ=="
}
} }
}, },
"@discordjs/collection": { "@discordjs/collection": {
@@ -2015,20 +2008,19 @@
} }
}, },
"@sapphire/async-queue": { "@sapphire/async-queue": {
"version": "1.1.9", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.1.9.tgz", "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.2.0.tgz",
"integrity": "sha512-CbXaGwwlEMq+l1TRu01FJCvySJ1CEFKFclHT48nIfNeZXaAAmmwwy7scUKmYHPUa3GhoMp6Qr1B3eAJux6XgOQ==" "integrity": "sha512-O5ND5Ljpef86X5oy8zXorQ754TMjWALcPSAgPBu4+76HLtDTrNoDyzU2uGE2G4A8Wv51u0MXHzGQ0WZ4GMtpIw=="
}, },
"@sapphire/snowflake": { "@sapphire/snowflake": {
"version": "3.0.1", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.0.1.tgz", "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.1.0.tgz",
"integrity": "sha512-v+wCC2q9DK3OhG7Vcdt/8A/INAYiyhlMD5snakmXGBN1usLBwSGJVJBjDHv4VGI5C9YYl4UdW5Ovr3arvYsJXQ==" "integrity": "sha512-K+OiqXSx4clIaXcoaghrCV56zsm3bZZ5SBpgJkgvAKegFFdETMntHviUfypjt8xVleIuDaNyQA4APOIl3BMcxg=="
}, },
"@sindresorhus/is": { "@sindresorhus/is": {
"version": "0.14.0", "version": "4.4.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.4.0.tgz",
"integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", "integrity": "sha512-QppPM/8l3Mawvh4rn9CNEYIU9bxpXUCRMaX9yUpvBk1nMKusLKpfXGDEKExKaPhLzcn3lzil7pR6rnJ11HgeRQ=="
"dev": true
}, },
"@szmarczak/http-timer": { "@szmarczak/http-timer": {
"version": "1.1.2", "version": "1.1.2",
@@ -2618,6 +2610,14 @@
"p-cancelable": "^1.0.0", "p-cancelable": "^1.0.0",
"to-readable-stream": "^1.0.0", "to-readable-stream": "^1.0.0",
"url-parse-lax": "^3.0.0" "url-parse-lax": "^3.0.0"
},
"dependencies": {
"@sindresorhus/is": {
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz",
"integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==",
"dev": true
}
} }
}, },
"graceful-fs": { "graceful-fs": {

View File

@@ -1,6 +1,6 @@
{ {
"name": "1800queue", "name": "1800queue-alt",
"version": "0.0.1", "version": "1.0.0",
"description": "", "description": "",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {

View File

@@ -3,9 +3,6 @@
@REM change to ccurrent directory @REM change to ccurrent directory
cd %~f0\..\..\..\ cd %~f0\..\..\..\
@REM run
npm install
@REM discord token @REM discord token
if not exist "token" copy NUL "token" if not exist "token" copy NUL "token"
@@ -14,3 +11,6 @@ if %size% equ 0 (
set /p token="Enter your discord bot token: " set /p token="Enter your discord bot token: "
echo | set /p=%id% > "token" echo | set /p=%id% > "token"
) )
@REM run
npm install

View File

@@ -1,27 +1,23 @@
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { CommandInteraction } from 'discord.js'; import { CommandInteraction, MessageEmbed } from 'discord.js';
import { IncomingMessage } from 'http'; import { IncomingMessage } from 'http';
import http from 'https'; import http from 'https';
import { emsg } from './util';
//making long regex rather than splitting the string at ":" because regex would be easier to debug than logic in the case the website changes
//while names cant have spaces, the name slot in ogtitle could be shown as "No Player Name" which has spaces
const uniteApiRegex = { const uniteApiRegex = {
//$1 = name, $2 = id //$1 = name, $2 = id
ogtitle: /unite api - (.+) \((.*)\)/i, ogtitle: /unite api - (.+) \((.*)\)/i,
//$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line) //$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line)
ogdescription: [ ogdescription: [ //just the first line
//line 1 /lv\.(\d+) (\w+) \((\d+)\)/i, //master
[ /lv\.(\d+) (\w+): class (\d+)/i //other
/lv\.(\d+) (\w+) \((\d+)\)/i, //master
/lv\.(\d+) (\w+): class (\d+)/i //other
],
] ]
} }
type uniteApiData = { type uniteApiData = {
name: string, name: string,
id: string, id: string,
avatar: string,
level: string, level: string,
rank: string, rank: string,
@@ -31,16 +27,6 @@ type uniteApiData = {
wins: string, wins: string,
winrate: string winrate: string
} }
/*
og:title
Unite API - IanWhysp (X188GF7)
og:description
Pokémon Unite : Lv.40 Master (1741)
Battles : 1089
Wins : 576
Win Rate : 52%
*/
/** /**
* gets the html of the uniteApi page for the player * gets the html of the uniteApi page for the player
@@ -67,12 +53,11 @@ function getHTML(name: string): Promise<string> {
} }
let result = Buffer.alloc(0); let result = Buffer.alloc(0);
response.on('data', function(chunk) { response.on('data', chunk => {
result = Buffer.concat([result, chunk]); result = Buffer.concat([result, chunk]);
}); });
response.on('end', function() { response.on('end', () => {
// result has response body buffer
resolve(result.toString()); resolve(result.toString());
}); });
}; };
@@ -88,12 +73,15 @@ function getHTML(name: string): Promise<string> {
* interprets the html from getHTML() * interprets the html from getHTML()
* @param name name of player * @param name name of player
* @returns player data from site * @returns player data from site
* @throws errorMessage class if the request fails
*/ */
function readHTML(html: string): uniteApiData { function readHTML(html: string): uniteApiData {
let metaElems = cheerio.load(html)('meta').toArray(), let $ = cheerio.load(html)
let metaElems = $('meta').toArray(),
foundData: uniteApiData = { foundData: uniteApiData = {
name: "", name: "",
id: "", id: "",
avatar: "",
level: "", level: "",
rank: "", rank: "",
@@ -130,7 +118,7 @@ function readHTML(html: string): uniteApiData {
} }
if (!lines.length) if (!lines.length)
throw 'Unable to read data, please try again'; throw emsg('Unable to read data, please try again');
//bring the first lines removed back into the data //bring the first lines removed back into the data
lines = [ lines = [
@@ -143,14 +131,14 @@ function readHTML(html: string): uniteApiData {
//will be only text after "pokemon unite:" //will be only text after "pokemon unite:"
let line = lines[0].split(':').slice(1).join(':').trim(); let line = lines[0].split(':').slice(1).join(':').trim();
let regex = uniteApiRegex.ogdescription[0]; let regex = uniteApiRegex.ogdescription;
if (regex[0].test(line)) { //is master/has elo if (regex[0].test(line)) { //is master/has elo
let regexData = line.match(regex[0]); let regexData = line.match(regex[0]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw 'Unable to read data, please try again'; throw emsg('Unable to read data, please try again');
foundData.level = regexData[1]; foundData.level = regexData[1];
foundData.rank = regexData[2]; foundData.rank = regexData[2];
@@ -161,7 +149,7 @@ function readHTML(html: string): uniteApiData {
let regexData = line.match(regex[1]); let regexData = line.match(regex[1]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw 'Unable to read data, please try again'; throw emsg('Unable to read data, please try again');
foundData.level = regexData[1]; foundData.level = regexData[1];
foundData.rank = regexData[2]; foundData.rank = regexData[2];
@@ -194,19 +182,12 @@ function readHTML(html: string): uniteApiData {
}); });
/*let data = uniteApiRegex.ogdescription.exec(attr.content);
if (data !== null && data.length >= 7) {
foundData.level = data[1];
foundData.rank = data[2];
foundData.elo = data[3];
foundData.battles = data[4];
foundData.wins = data[5];
foundData.winrate = data[6];
}*/
} }
}) });
foundData.avatar = $('.player-card-image img').attr('src') || "";
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
return foundData; return foundData;
@@ -236,9 +217,27 @@ export async function getPlayer(name: string): Promise<uniteApiData|null> {
return null; return null;
} }
async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) {
let embed = new MessageEmbed()
.setTitle(`${data.name} (${data.id})`)
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
.setTimestamp()
.setThumbnail(data.avatar)
.setDescription(`Level ${data.level}
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
**Battles** ${data.battles}
**Wins** ${data.wins}
**Win Rate** ${data.winrate}`);
await interaction.editReply({embeds: [embed]});
}
/** /**
* calls getPlayer() with the name from the interaction * calls getPlayer() with the name from the interaction
* @param interaction discord interaction * @param interaction discord interaction
* @throws errorMessage class if the user cannot be found
*/ */
export async function getPlayerInteraction(interaction: CommandInteraction) { export async function getPlayerInteraction(interaction: CommandInteraction) {
let username = interaction.options.getString('username', true); let username = interaction.options.getString('username', true);
@@ -246,9 +245,7 @@ export async function getPlayerInteraction(interaction: CommandInteraction) {
let data = await getPlayer(username); let data = await getPlayer(username);
if (data === null) if (data === null)
await interaction.editReply('Unable to find user'); throw emsg('Unable to find user');
else else
await interaction.editReply('```\n'+JSON.stringify(data, null, 2)+'\n```'); sendPlayerEmbed(interaction, data);
} }
//await getPlayer('IanWhysp')

View File

@@ -11,7 +11,8 @@ const commands = [
type: 4, //INTEGER type: 4, //INTEGER
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
required: true required: true,
min_value: 1
} }
] ]
}, },
@@ -28,17 +29,17 @@ const commands = [
description: 'ready the queue and display team info' description: 'ready the queue and display team info'
}, },
{ {
name: 'queueinfo', name: 'cancel',
description: 'get info of the current queue' description: 'cancels the current queue (must have the Manage Messages permission)'
}, },
{ {
name: 'elo', name: 'player',
description: 'display elo information', description: 'display player information',
options: [ options: [
{ {
type: 3, //STRING type: 3, //STRING
name: 'username', name: 'username',
description: 'in game name', description: 'in game name or UniteApi short link',
required: true required: true
} }
] ]

View File

@@ -3,7 +3,8 @@ import { Client, Intents } from 'discord.js';
import * as fs from 'fs'; import * as fs from 'fs';
import { getPlayerInteraction } from './api'; import { getPlayerInteraction } from './api';
import { registerCommands } from './discord'; import { registerCommands } from './discord';
import { createQueue, joinQueue, leaveQueue, queueInfo, readyQueue } from './queue'; import { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } from './queue';
import { errorMessage } from './util';
const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] }); const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
//init logs with a timestamp //init logs with a timestamp
@@ -37,18 +38,23 @@ CLIENT.on('interactionCreate', async interaction => {
await leaveQueue(interaction); await leaveQueue(interaction);
else if (interaction.commandName === 'ready') else if (interaction.commandName === 'ready')
await readyQueue(interaction); await readyQueue(interaction);
else if (interaction.commandName === 'queueinfo') else if (interaction.commandName === 'cancel')
await queueInfo(interaction); await cancelQueue(interaction);
else if (interaction.commandName === 'elo') else if (interaction.commandName === 'player')
await getPlayerInteraction(interaction); await getPlayerInteraction(interaction);
} catch (e) { } catch (e) {
if (typeof e === 'string') { if (e instanceof errorMessage) {
if (interaction.deferred || interaction.replied) if (interaction.deferred || interaction.replied)
interaction.editReply(e); interaction.editReply(e.msg);
else else
interaction.reply(e); interaction.reply({
content: e.msg,
ephemeral: e.ephemeral
});
} else console.error(e); } else console.error(e);
} }

View File

@@ -1,89 +1,165 @@
import { info } from "console"; import { CommandInteraction, GuildMember, MessageEmbed } from "discord.js";
import { CommandInteraction, GuildMember } from "discord.js"; import { emsg, getChannel, getMember, queueInfo, shuffle } from "./util";
import { shuffle } from "./util";
type queueInfo = {
players: GuildMember[],
initiator: GuildMember,
teamsize: number
}
//maps ChannelID to QueueInfo //maps ChannelID to QueueInfo
const QUEUE = new Map<string, queueInfo>(); const QUEUE = new Map<string, queueInfo>();
/**
* get the GuildMember of an interaction
* @param interaction
* @throws string message if it cannot be read
* @returns member
*/
function getMember(interaction: CommandInteraction): GuildMember {
let member = interaction.member;
if (!(member instanceof GuildMember))
throw 'Unable to retrieve guild member information, please try again';
return member;
}
/** /**
* get the queueInfo of an interaction * get the queueInfo of an interaction
* @param interaction * @param interaction
* @throws string message if it does not exist * @throws errorMessage class if it does not exist
* @returns queue info * @returns queue info
*/ */
function getInfo(interaction: CommandInteraction): queueInfo { export function getInfo(interaction: CommandInteraction): queueInfo {
let info = QUEUE.get(interaction.channelId); let info = QUEUE.get(interaction.channelId);
if (!info) if (!info)
throw 'There is not an active queue in this channel, type `/queue` to create one'; throw emsg('There is not an active queue in this channel, type `/queue` to create one');
return info; return info;
} }
/**
* compiles all the get functions above
* @param interaction
* @throws if another get function throws
* @returns object containing each
*/
export const getAll = (interaction: CommandInteraction) => ({
member: getMember(interaction),
channel: getChannel(interaction),
info: getInfo(interaction)
});
/**
* checks if the interaction data is already in the queue
* @param interaction
* @returns boolean
*/
export function queueContains(interaction: CommandInteraction): boolean {
let {member, info} = getAll(interaction);
if (info.players.map(m=>m.id).includes(member.id))
return true;
return false;
}
/**
* creates the timeout for the queue
* @param interaction
* @returns time timeout identifier
*/
function setQueueTimeout(interaction: CommandInteraction) {
let channel = getChannel(interaction);
return setTimeout(() => {
clearQueue(interaction);
channel.send('Queue has been reset due to inactivity');
}, 5*60*1000) //5 minutes
}
/**
* updates the rich embed for the current queue
* @param interaction
*/
async function sendQueueEmbed(interaction: CommandInteraction, closed: boolean = false) {
let info = getInfo(interaction),
origInteraction = info.initiator.interaction;
let embed = new MessageEmbed()
.setTitle('Queue')
.setAuthor({
name: info.initiator.member.displayName,
iconURL: info.initiator.member.displayAvatarURL({dynamic: true})
})
.addField('Team Size', info.teamsize.toString(), true)
.addField('Players Joined', info.players.length.toString(), true)
.setFooter({text: closed ? 'queue is finished' : 'type /join'});
if (origInteraction.deferred || origInteraction.replied)
await origInteraction.editReply({embeds: [embed]});
else
await origInteraction.reply({embeds: [embed]});
}
/**
* sends the list of teams
* @param interaction
*/
async function sendTeamsEmbed(interaction: CommandInteraction, teams: GuildMember[][]) {
let embed = new MessageEmbed()
.setTitle('Teams');
teams.forEach((team, i) => {
team.map(m => m.user.tag);
embed.addField(`Team ${i+1}`, team.join('\n'))
});
interaction.reply({embeds: [embed]});
}
/**
* sends the list of teams
* @param interaction
*/
async function clearQueue(interaction: CommandInteraction) {
let info = getInfo(interaction);
sendQueueEmbed(interaction, true);
clearTimeout(info.timeout);
QUEUE.delete(interaction.channelId);
}
/** /**
* creates a queue from an interaction * creates a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be created * @throws errorMessage class if it cannot be created
*/ */
export async function createQueue(interaction: CommandInteraction) { export async function createQueue(interaction: CommandInteraction) {
let {channelId} = interaction, let member = getMember(interaction),
member = getMember(interaction), {channelId} = interaction,
teamsize = interaction.options.getInteger('teamsize', true); teamsize = interaction.options.getInteger('teamsize', true);
if (QUEUE.has(channelId)) if (QUEUE.has(channelId))
throw 'There is already an active queue in this channel, type `/join` to join'; //and you are already in it throw emsg('There is already an active queue in this channel, ' + (queueContains(interaction) ? 'and you are already in it' : 'type `/join` to join'));
QUEUE.set(channelId, { QUEUE.set(channelId, {
players: [ players: [
member member
], ],
initiator: member, initiator: {
teamsize: teamsize interaction,
member
},
teamsize: teamsize,
timeout: setQueueTimeout(interaction)
}); });
await interaction.reply(`Queue for teams of ${teamsize} has been created, and you have joined`); sendQueueEmbed(interaction);
} }
/** /**
* joins a queue from an interaction * joins a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be joined * @throws errorMessage class if it cannot be joined
*/ */
export async function joinQueue(interaction: CommandInteraction) { export async function joinQueue(interaction: CommandInteraction) {
let member = getMember(interaction), let {member, info} = getAll(interaction);
info = getInfo(interaction);
if (info.players.map(m=>m.id).includes(member.id)) if (queueContains(interaction))
throw 'You are already in the active queue'; throw emsg('You are already in the active queue');
info.players.push(member); info.players.push(member);
clearTimeout(info.timeout);
info.timeout = setQueueTimeout(interaction)
QUEUE.set(interaction.channelId, info); QUEUE.set(interaction.channelId, info);
sendQueueEmbed(interaction);
await interaction.reply('Joined the queue'); await interaction.reply('Joined the queue');
} }
@@ -91,20 +167,22 @@ export async function joinQueue(interaction: CommandInteraction) {
/** /**
* leaves a queue from an interaction * leaves a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be left * @throws errorMessage class if it cannot be left
*/ */
export async function leaveQueue(interaction: CommandInteraction) { export async function leaveQueue(interaction: CommandInteraction) {
let member = getMember(interaction), let {member, info} = getAll(interaction);
info = getInfo(interaction);
if (!info.players.map(m=>m.id).includes(member.id)) if (!queueContains(interaction))
throw 'You aren\'t in the active queue'; throw emsg('You aren\'t in the active queue');
info.players.splice(info.players.indexOf(member), 1); info.players.splice(info.players.indexOf(member), 1);
clearTimeout(info.timeout);
info.timeout = setQueueTimeout(interaction)
QUEUE.set(interaction.channelId, info); QUEUE.set(interaction.channelId, info);
sendQueueEmbed(interaction);
await interaction.reply('Left the queue'); await interaction.reply('Left the queue');
} }
@@ -112,22 +190,20 @@ export async function leaveQueue(interaction: CommandInteraction) {
/** /**
* readys a queue from an interaction * readys a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be readied * @throws errorMessage class if it cannot be readied
*/ */
export async function readyQueue(interaction: CommandInteraction) { export async function readyQueue(interaction: CommandInteraction) {
let member = getMember(interaction), let {member, info} = getAll(interaction),
info = getInfo(interaction),
{initiator} = info; {initiator} = info;
if (member.id !== initiator.id) if (member.id !== initiator.member.id)
throw 'Only the queue initiator can ready the queue'; throw emsg('Only the queue initiator can ready the queue');
//reset queue clearQueue(interaction);
QUEUE.delete(interaction.channelId);
if (info.players.filter(m => m.id !== initiator.id).length === 0) if (info.players.filter(m => m.id !== initiator.member.id).length === 0)
throw 'Nobody signed up for the queue, the queue has been reset'; throw emsg('Nobody signed up for the queue, the queue has been reset');
//team data //team data
let playerlist: GuildMember[] = shuffle(info.players), let playerlist: GuildMember[] = shuffle(info.players),
@@ -137,33 +213,24 @@ export async function readyQueue(interaction: CommandInteraction) {
for (let i = 0; i < playerlist.length; i+= info.teamsize) for (let i = 0; i < playerlist.length; i+= info.teamsize)
teams.push(playerlist.slice(i, i+info.teamsize)); teams.push(playerlist.slice(i, i+info.teamsize));
//convert teams to strings sendTeamsEmbed(interaction, teams);
let teamsStr: string[] = [];
teams.forEach((team, i) => {
let str = [`Team ${i+1}`];
team.forEach(m => str.push(` ${m.user.tag}`));
teamsStr.push(str.join('\n'));
});
await interaction.reply('```\n'+teamsStr.join('\n\n')+'\n```');
} }
/** /**
* sends the queue information from an interaction * readys a queue from an interaction
* @param interaction * @param interaction
* @throws string message if it cannot be read * @throws errorMessage class if it cannot be reset
*/ */
export async function queueInfo(interaction: CommandInteraction) { export async function cancelQueue(interaction: CommandInteraction) {
let info = getInfo(interaction); let {info, member, channel} = getAll(interaction);
await interaction.reply('```'+` if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
players: ${info.players.map(p => p.user.tag).join('\n ')} throw emsg('You do not have permission to run this command');
initiator: ${info.initiator.user.tag}
teamsize: ${info.teamsize}
`+'```');
} clearQueue(interaction);
await interaction.reply('Queue has been reset');
}

View File

@@ -1,3 +1,4 @@
import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
/** /**
* shuffles an array * shuffles an array
@@ -22,3 +23,65 @@ export function shuffle(array: any[]) {
return array; return array;
} }
export class errorMessage {
public msg: string;
public ephemeral: boolean;
constructor(msg: string, ephemeral: boolean = true) {
this.msg = msg;
this.ephemeral = ephemeral;
}
}
/**
* a simple class to contain an error message and related data
* @param msg error message
* @param ephemeral (default=true)
* @returns new errorMessage
*/
export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage(msg, ephemeral);
export type queueInfo = {
players: GuildMember[],
initiator: {
interaction: CommandInteraction,
member: GuildMember
},
teamsize: number,
timeout: NodeJS.Timeout
}
/**
* get the GuildMember of an interaction
* @param interaction
* @throws errorMessage class if it cannot be read
* @returns member
*/
export function getMember(interaction: CommandInteraction): GuildMember {
let member = interaction.member;
if (!(member instanceof GuildMember))
throw emsg('Unable to retrieve guild member information, please try again');
return member;
}
/**
* get the TextChannel of an interaction
* @param interaction
* @throws errorMessage class if it cannot be read
* @returns member
*/
export function getChannel(interaction: CommandInteraction): TextChannel {
let channel = interaction.channel;
if (!(channel instanceof TextChannel))
throw emsg('Unable to retrieve text channel information, please try again');
return channel;
}