Compare commits

..

25 Commits

Author SHA1 Message Date
f5ab2b4297 eslint 2022-02-13 21:39:29 -06:00
983f742f0d useless change 2022-02-13 21:04:40 -06:00
84482be886 updated tsconfig 2022-02-13 20:11:37 -06:00
3d69a9375e i thought i already updated this 2022-02-13 19:56:53 -06:00
39deb13f5a typo 2022-02-13 19:53:41 -06:00
ab76d7edbc updated lang 2022-02-13 19:51:30 -06:00
343ed640ae updated lang strings 2022-02-13 19:35:16 -06:00
b1d01b414e register commands for new guilds 2022-02-13 19:29:10 -06:00
17643dc730 updated lang strings 2022-02-13 19:23:28 -06:00
f225bf924a updated lang strings 2022-02-13 19:15:55 -06:00
9da9650f92 created lang file 2022-02-13 18:56:12 -06:00
a1a387880c updated gitignore 2022-02-13 18:55:47 -06:00
943512d354 updated packages 2022-02-13 18:50:24 -06:00
edb786ec04 finished(?) renaming commands 2022-02-11 13:51:16 -06:00
525904de5a updated command name 2022-02-11 13:50:45 -06:00
4fdb233bd6 yet another dumb mistake 2022-02-11 13:44:00 -06:00
00c3fa8219 info for later 2022-02-11 13:29:32 -06:00
610ca41195 more command renaming 2022-02-11 13:29:23 -06:00
827dafbb99 more dumb issues 2022-02-11 13:29:17 -06:00
3ed56b7927 renamed/moved commands 2022-02-11 13:18:17 -06:00
e444167f07 dumb mistake 2022-02-11 13:08:27 -06:00
fcdf8dea06 shifted dependency 2022-02-07 14:44:54 -06:00
148d93aaab updated file names 2022-02-07 14:39:05 -06:00
81ea71328a updated builds 2022-02-07 14:38:55 -06:00
cf453957e9 remade queue logic 2022-02-01 13:47:52 -06:00
21 changed files with 3302 additions and 511 deletions

55
.eslintrc.json Normal file
View File

@@ -0,0 +1,55 @@
{
"root": true,
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": { "project": ["./tsconfig.json"] },
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/strict-boolean-expressions": [
2,
{
"allowString" : false,
"allowNumber" : false
}
],
/* important */
"prefer-const": "error",
"quotes": ["error", "single"],
"block-scoped-var": "error",
"camelcase": "error",
"consistent-this": ["error", "that"],
"no-else-return": "error",
"no-eq-null": "error",
"no-floating-decimal": "error",
"no-implicit-coercion": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"require-await": "error",
"yoda": "error",
"semi": ["error", "always"],
"semi-style": ["error", "last"],
/* less important */
"no-unreachable-loop": "error",
"no-unused-private-class-members": "error",
"no-use-before-define": "error",
"no-unmodified-loop-condition": "error",
"no-duplicate-imports": "error",
"no-promise-executor-return": "error",
"no-self-compare": "error",
"no-constructor-return": "error",
"no-template-curly-in-string": "error",
"array-callback-return": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error"
},
"ignorePatterns": ["src/**/*.test.ts", "src/frontend/generated/*"]
}

6
.gitignore vendored
View File

@@ -1,4 +1,6 @@
node_modules
token
.DS_Store .DS_Store
.vscode
log log
node_modules
queues.json
token.txt

View File

@@ -1,8 +1,10 @@
<!-- markdownlint-disable MD033 --> <!-- markdownlint-disable MD033 -->
# 1800queue alt # 1800queue
This version does not run continuously, and requires each tourney to be started with a command ## Invite info
needs: create commands/send messages
## Prerequirements ## Prerequirements

2
dist/api.js vendored
View File

@@ -204,7 +204,7 @@ async function getPlayerInteraction(interaction) {
await interaction.deferReply(); await interaction.deferReply();
let data = await getPlayer(username); let data = await getPlayer(username);
if (data === null) if (data === null)
throw (0, util_1.emsg)('Unable to find user'); throw (0, util_1.emsg)('api.noUser');
else else
sendPlayerEmbed(interaction, data); sendPlayerEmbed(interaction, data);
} }

27
dist/discord.js vendored
View File

@@ -6,18 +6,26 @@ const v9_1 = require("discord-api-types/v9");
// list of commands to register with discord // list of commands to register with discord
const commands = [ const commands = [
{ {
name: 'queue', name: 'open',
description: 'create a queue', description: 'open a queue for this channel',
options: [ options: [
{ {
type: 4, type: 4,
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
required: true, min_value: 1,
min_value: 1 required: true
} }
] ]
}, },
{
name: 'close',
description: 'close the queue for this channel'
},
{
name: 'queue',
description: 'view queue info'
},
{ {
name: 'join', name: 'join',
description: 'join the active queue' description: 'join the active queue'
@@ -26,14 +34,6 @@ const commands = [
name: 'leave', name: 'leave',
description: 'leave the active queue' description: 'leave the active queue'
}, },
{
name: 'ready',
description: 'ready the queue and display team info'
},
{
name: 'cancel',
description: 'cancels the current queue (must have the Manage Messages permission)'
},
{ {
name: 'player', name: 'player',
description: 'display player information', description: 'display player information',
@@ -46,7 +46,7 @@ const commands = [
} }
] ]
} }
]; ], commandNames = commands.map(c => c.name);
/** /**
* register/reload commands on guild(s) * register/reload commands on guild(s)
* @param token discord bot token * @param token discord bot token
@@ -60,7 +60,6 @@ async function registerCommands(token, clientId, guildIds) {
for (let i = 0; i < guildIds.length; i++) { for (let i = 0; i < guildIds.length; i++) {
try { try {
await rest.put(v9_1.Routes.applicationGuildCommands(clientId, guildIds[i]), { body: commands }); await rest.put(v9_1.Routes.applicationGuildCommands(clientId, guildIds[i]), { body: commands });
console.log(`[${guildIds[i]}] registered command`);
} }
catch (error) { catch (error) {
console.error(error); console.error(error);

52
dist/index.js vendored
View File

@@ -23,39 +23,57 @@ const discord_js_1 = require("discord.js");
const fs = __importStar(require("fs")); 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 lang_1 = require("./lang");
const queue_1 = require("./queue"); const queue_1 = require("./queue");
const util_1 = require("./util"); 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');
//get token //get token
if (!fs.existsSync('./token')) { if (!fs.existsSync('./token.txt')) {
fs.writeFileSync('./token', ''); fs.writeFileSync('./token.txt', '');
console.error('Missing Discord Token, please enter the bot token into the token file'); console.error(lang_1.Lang.get('error.main.missingToken'));
process.exit(1); process.exit(1);
} }
const TOKEN = fs.readFileSync('./token').toString(); const TOKEN = fs.readFileSync('./token.txt').toString();
//discord connections //discord connections
CLIENT.on('ready', client => { CLIENT.on('ready', client => {
console.log(`Logged in as ${client.user.tag}`); console.log(lang_1.Lang.get('main.login', {
user: client.user.tag
}));
client.guilds.fetch().then(guilds => (0, discord_1.registerCommands)(TOKEN, client.user.id, guilds.map(g => g.id))); client.guilds.fetch().then(guilds => (0, discord_1.registerCommands)(TOKEN, client.user.id, guilds.map(g => g.id)));
(0, queue_1.discordInit)(client);
});
CLIENT.on('guildCreate', guild => {
if (guild.client.user)
(0, discord_1.registerCommands)(TOKEN, guild.client.user.id, guild.id);
}); });
CLIENT.on('interactionCreate', async (interaction) => { CLIENT.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) if (!interaction.isCommand())
return; return;
try { try {
if (interaction.commandName === 'queue') switch (interaction.commandName) {
await (0, queue_1.createQueue)(interaction); //mod commands
else if (interaction.commandName === 'join') case 'open':
await (0, queue_1.joinQueue)(interaction); await queue_1.QueueCommands.open(interaction);
else if (interaction.commandName === 'leave') break;
await (0, queue_1.leaveQueue)(interaction); case 'close':
else if (interaction.commandName === 'ready') await queue_1.QueueCommands.close(interaction);
await (0, queue_1.readyQueue)(interaction); break;
else if (interaction.commandName === 'cancel') //general commands
await (0, queue_1.cancelQueue)(interaction); case 'queue':
else if (interaction.commandName === 'player') await queue_1.QueueCommands.queue(interaction);
await (0, api_1.getPlayerInteraction)(interaction); break;
case 'join':
await queue_1.QueueCommands.join(interaction);
break;
case 'leave':
await queue_1.QueueCommands.leave(interaction);
break;
case 'player':
await (0, api_1.getPlayerInteraction)(interaction);
break;
}
} }
catch (e) { catch (e) {
if (e instanceof util_1.errorMessage) { if (e instanceof util_1.errorMessage) {

79
dist/lang.js vendored Normal file
View File

@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lang = void 0;
const LANG = {
en: {
main: {
login: 'Logged in as {user}'
},
discord: {
botRestart: 'The bot has just restarted, anybody previously in the queue has been reset',
create: 'A queue for teams of {teamsize} has been created',
close: 'Queue has been closed',
join: 'Joined the queue',
leave: 'Left the queue'
},
error: {
main: {
missingToken: 'Missing Discord Token, please enter the bot token into the token file'
},
discord: {
noQueue: 'There is not an active queue in this channel, type `/open` to create one',
noChannel: 'Unable to find channel {channelId} for teams of {teamsize}',
noCreate: 'There is already an active queue in this channel for teams of ${teamsize}',
inQueue: 'You are already in the queue',
notInQueue: 'You aren\'t in the queue',
notMod: 'Member is not a moderator'
},
general: {
noMember: 'Unable to retrieve guild member information, please try again',
noChannel: 'Unable to retrieve text channel information, please try again'
},
api: {
noUser: 'Unable to find user'
}
}
}
};
var Lang;
(function (Lang) {
var LANGID = 'en';
if (!(LANGID in LANG))
throw 'language id does not exist';
function setLang(langid) {
if (langid in LANG)
LANGID = langid;
else
throw 'language id does not exist';
}
Lang.setLang = setLang;
function template(str, args) {
return str.replace(/{\w+}/g, str => {
let key = str.substring(1, str.length - 1);
if (key in args)
return args[key];
return key;
});
}
/**
* reads language json
* @param id ex: discord.error.noActiveQueue
* @returns language value, defaults to `id` parameter
*/
function get(id, args = {}) {
let keySpl = id.split('.').map(k => k.trim()).filter(k => k);
let finding = LANG[LANGID];
for (let key of keySpl) {
if (key in finding) {
let found = finding[key];
if (typeof found === 'string')
return template(found, args);
finding = found;
}
else
break;
}
return id;
}
Lang.get = get;
})(Lang = exports.Lang || (exports.Lang = {}));

409
dist/queue.js vendored
View File

@@ -1,189 +1,232 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); /* TODO
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"); join message should contain your current position in the queue, editing it to keep it current
const util_1 = require("./util"); */
//maps ChannelID to QueueInfo var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
const QUEUE = new Map(); if (k2 === undefined) k2 = k;
/** Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
* get the queueInfo of an interaction }) : (function(o, m, k, k2) {
* @param interaction if (k2 === undefined) k2 = k;
* @throws errorMessage class if it does not exist o[k2] = m[k];
* @returns queue info }));
*/ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
function getInfo(interaction) { Object.defineProperty(o, "default", { enumerable: true, value: v });
let info = QUEUE.get(interaction.channelId); }) : function(o, v) {
if (!info) o["default"] = v;
throw (0, util_1.emsg)('There is not an active queue in this channel, type `/queue` to create one');
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; var __importStar = (this && this.__importStar) || function (mod) {
/** if (mod && mod.__esModule) return mod;
* checks if the interaction data is already in the queue var result = {};
* @param interaction if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
* @returns boolean __setModuleDefault(result, mod);
*/ return result;
function queueContains(interaction) { };
let { member, info } = (0, exports.getAll)(interaction); Object.defineProperty(exports, "__esModule", { value: true });
if (info.players.map(m => m.id).includes(member.id)) exports.QueueCommands = exports.discordInit = void 0;
return true; const discord_js_1 = require("discord.js");
return false; const fs = __importStar(require("fs"));
const util_1 = require("./util");
const lang_1 = require("./lang");
//load queues from file
if (!fs.existsSync('./queues.json'))
fs.writeFileSync('./queues.json', '{}');
const _QUEUE = fs.readFileSync('./queues.json').toString(), QUEUE = new Map();
try {
let queueJson = JSON.parse(_QUEUE);
for (let channelId in queueJson) {
let { teamsize } = queueJson[channelId];
if (teamsize)
QUEUE.set(channelId, { teamsize, players: [] });
}
} }
exports.queueContains = queueContains; catch (e) { }
/** function SaveQueue() {
* creates the timeout for the queue let queueJson = Object.fromEntries(QUEUE), queueFileJson = {};
* @param interaction for (let channelId of QUEUE.keys())
* @returns time timeout identifier queueFileJson[channelId] = { teamsize: queueJson[channelId].teamsize };
*/ fs.writeFileSync('./queues.json', JSON.stringify(queueFileJson, null, 2));
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
} }
/** async function checkQueue(channel) {
* updates the rich embed for the current queue let info = QUEUE.get(channel.id);
* @param interaction if (!info)
*/ return;
async function sendQueueEmbed(interaction, closed = false) { if (info.players.length >= info.teamsize) {
let info = getInfo(interaction), origInteraction = info.initiator.interaction; let team = info.players.splice(0, info.teamsize).map(m => m.toString());
let embed = new discord_js_1.MessageEmbed() //TODO add embeds to lang.ts
.setTitle('Queue') let embed = new discord_js_1.MessageEmbed()
.setAuthor({ .setTitle('Team')
name: info.initiator.member.displayName, .setDescription(team.join('\n'));
iconURL: info.initiator.member.displayAvatarURL({ dynamic: true }) await channel.send({ embeds: [embed] });
}) }
.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] });
} }
/** var Queue;
* sends the list of teams (function (Queue) {
* @param interaction function create(channelId, teamsize) {
*/ if (!QUEUE.has(channelId)) {
async function sendTeamsEmbed(interaction, teams) { QUEUE.set(channelId, { teamsize, players: [] });
let embed = new discord_js_1.MessageEmbed() SaveQueue();
.setTitle('Teams'); }
teams.forEach((team, i) => { }
team.map(m => m.user.tag); Queue.create = create;
embed.addField(`Title ${i + 1}`, team.join('\n')); function remove(channelId) {
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
SaveQueue();
}
}
Queue.remove = remove;
function addPlayer(channelId, member) {
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
}
}
Queue.addPlayer = addPlayer;
function removePlayer(channelId, member) {
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
}
}
Queue.removePlayer = removePlayer;
})(Queue || (Queue = {}));
SaveQueue();
async function discordInit(client) {
for (let channelId of QUEUE.keys()) {
let info = QUEUE.get(channelId), channel = await client.channels.fetch(channelId);
if (!info) { //no idea what could cause this but TS complains
Queue.remove(channelId);
continue;
}
if (!channel || !(channel instanceof discord_js_1.TextChannel)) {
console.error(lang_1.Lang.get('error.discord.noChannel'), {
channelId,
teamsize: info.teamsize
});
Queue.remove(channelId);
continue;
}
channel.send(lang_1.Lang.get('discord.botRestart'));
}
}
exports.discordInit = discordInit;
var QueueCommands;
(function (QueueCommands) {
/**
* get the queueInfo of an interaction
* @param interaction
* @throws errorMessage class if it does not exist
* @returns queue info
*/
function getInfo(interaction) {
let info = QUEUE.get(interaction.channelId);
if (!info)
throw (0, util_1.emsg)('discord.noQueue');
return info;
}
/**
* 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)
}); });
interaction.reply({ embeds: [embed] }); /**
} * checks if the interaction data is already in the queue
/** * @param interaction
* sends the list of teams * @returns boolean
* @param interaction */
*/ function queueContains(interaction) {
async function clearQueue(interaction) { let { member, info } = getAll(interaction);
let info = getInfo(interaction); if (info.players.map(m => m.id).includes(member.id))
sendQueueEmbed(interaction, true); return true;
clearTimeout(info.timeout); return false;
QUEUE.delete(interaction.channelId); }
} QueueCommands.queueContains = queueContains;
/** /**
* creates a queue from an interaction * creates a queue from an interaction
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be created * @throws errorMessage class if it cannot be left
*/ */
async function createQueue(interaction) { function queueCreate(interaction) {
let member = (0, util_1.getMember)(interaction), { channelId } = interaction, teamsize = interaction.options.getInteger('teamsize', true); (0, util_1.memberIsModThrow)(interaction);
if (QUEUE.has(channelId)) let { channelId } = interaction, teamsize = interaction.options.getInteger('teamsize', true);
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')); let existing = QUEUE.get(channelId);
QUEUE.set(channelId, { if (existing)
players: [ throw (0, util_1.emsg)(lang_1.Lang.get('error.discord.noCreate', {
member teamsize: existing.teamsize.toString()
], }));
initiator: { Queue.create(channelId, teamsize);
interaction, interaction.reply(lang_1.Lang.get('discord.create', {
member teamsize: teamsize.toString()
}, }));
teamsize: teamsize, }
timeout: setQueueTimeout(interaction) QueueCommands.queueCreate = queueCreate;
}); /**
sendQueueEmbed(interaction); * opens a queue
} * @param interaction
exports.createQueue = createQueue; * @throws errorMessage class if it cannot be left
/** */
* joins a queue from an interaction async function open(interaction) {
* @param interaction queueCreate(interaction);
* @throws errorMessage class if it cannot be joined }
*/ QueueCommands.open = open;
async function joinQueue(interaction) { /**
let { member, info } = (0, exports.getAll)(interaction); * closes a queue
if (queueContains(interaction)) * @param interaction
throw (0, util_1.emsg)('You are already in the active queue'); * @throws errorMessage class if it cannot be joined
info.players.push(member); */
clearTimeout(info.timeout); async function close(interaction) {
info.timeout = setQueueTimeout(interaction); (0, util_1.memberIsModThrow)(interaction);
QUEUE.set(interaction.channelId, info); QUEUE.delete(interaction.channelId);
sendQueueEmbed(interaction); await interaction.reply(lang_1.Lang.get('discord.close'));
await interaction.reply('Joined the queue'); }
} QueueCommands.close = close;
exports.joinQueue = joinQueue; /**
/** * gives info about the queue
* leaves a queue from an interaction * @param interaction
* @param interaction * @throws errorMessage class if it cannot be left
* @throws errorMessage class if it cannot be left */
*/ async function queue(interaction) {
async function leaveQueue(interaction) { let info = getInfo(interaction);
let { member, info } = (0, exports.getAll)(interaction); let embed = new discord_js_1.MessageEmbed()
if (!queueContains(interaction)) .setTitle('Active Queue')
throw (0, util_1.emsg)('You aren\'t in the active queue'); .addField('Team Size', info.teamsize.toString(), true)
info.players.splice(info.players.indexOf(member), 1); .addField('Players Joined', info.players.length.toString(), true)
clearTimeout(info.timeout); .setFooter({ text: 'type /join' }); //TODO
info.timeout = setQueueTimeout(interaction); await interaction.reply({ embeds: [embed], ephemeral: true });
QUEUE.set(interaction.channelId, info); }
sendQueueEmbed(interaction); QueueCommands.queue = queue;
await interaction.reply('Left the queue'); /**
} * joins a queue
exports.leaveQueue = leaveQueue; * @param interaction
/** * @throws errorMessage class if it cannot be readied
* readys a queue from an interaction */
* @param interaction async function join(interaction) {
* @throws errorMessage class if it cannot be readied let { member, info, channel } = getAll(interaction);
*/ if (queueContains(interaction))
async function readyQueue(interaction) { throw (0, util_1.emsg)('discord.inQueue');
let { member, info } = (0, exports.getAll)(interaction), { initiator } = info; info.players.push(member);
if (member.id !== initiator.member.id) QUEUE.set(interaction.channelId, info);
throw (0, util_1.emsg)('Only the queue initiator can ready the queue'); await interaction.reply(lang_1.Lang.get('discord.join'));
clearQueue(interaction); checkQueue(channel);
if (info.players.filter(m => m.id !== initiator.member.id).length === 0) }
throw (0, util_1.emsg)('Nobody signed up for the queue, the queue has been reset'); QueueCommands.join = join;
//team data /**
let playerlist = (0, util_1.shuffle)(info.players), teams = []; * leaves a queue
//fill team data * @param interaction
for (let i = 0; i < playerlist.length; i += info.teamsize) * @throws errorMessage class if it cannot be reset
teams.push(playerlist.slice(i, i + info.teamsize)); */
sendTeamsEmbed(interaction, teams); async function leave(interaction) {
} let { member, info } = getAll(interaction);
exports.readyQueue = readyQueue; if (!queueContains(interaction))
/** throw (0, util_1.emsg)('discord.notInQueue');
* readys a queue from an interaction info.players.splice(info.players.indexOf(member), 1);
* @param interaction QUEUE.set(interaction.channelId, info);
* @throws errorMessage class if it cannot be reset await interaction.reply(lang_1.Lang.get('discord.leave'));
*/ }
async function cancelQueue(interaction) { QueueCommands.leave = leave;
let { info, member, channel } = (0, exports.getAll)(interaction); })(QueueCommands = exports.QueueCommands || (exports.QueueCommands = {}));
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
throw (0, util_1.emsg)('You do not have permission to run this command');
clearQueue(interaction);
await interaction.reply('Queue has been reset');
}
exports.cancelQueue = cancelQueue;

19
dist/util.js vendored
View File

@@ -1,7 +1,8 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getChannel = exports.getMember = exports.emsg = exports.errorMessage = exports.shuffle = void 0; exports.memberIsModThrow = exports.memberIsMod = exports.getChannel = exports.getMember = exports.emsg = exports.errorMessage = exports.shuffle = void 0;
const discord_js_1 = require("discord.js"); const discord_js_1 = require("discord.js");
const lang_1 = require("./lang");
/** /**
* shuffles an array * shuffles an array
* https://stackoverflow.com/a/2450976/2856416 * https://stackoverflow.com/a/2450976/2856416
@@ -36,7 +37,7 @@ exports.errorMessage = errorMessage;
* @param ephemeral (default=true) * @param ephemeral (default=true)
* @returns new errorMessage * @returns new errorMessage
*/ */
const emsg = (msg, ephemeral = true) => new errorMessage(msg, ephemeral); const emsg = (msg, ephemeral = true) => new errorMessage(lang_1.Lang.get(`error.${msg}`), ephemeral);
exports.emsg = emsg; exports.emsg = emsg;
/** /**
* get the GuildMember of an interaction * get the GuildMember of an interaction
@@ -47,7 +48,7 @@ exports.emsg = emsg;
function getMember(interaction) { function getMember(interaction) {
let member = interaction.member; let member = interaction.member;
if (!(member instanceof discord_js_1.GuildMember)) if (!(member instanceof discord_js_1.GuildMember))
throw (0, exports.emsg)('Unable to retrieve guild member information, please try again'); throw (0, exports.emsg)('general.noMember');
return member; return member;
} }
exports.getMember = getMember; exports.getMember = getMember;
@@ -60,7 +61,17 @@ exports.getMember = getMember;
function getChannel(interaction) { function getChannel(interaction) {
let channel = interaction.channel; let channel = interaction.channel;
if (!(channel instanceof discord_js_1.TextChannel)) if (!(channel instanceof discord_js_1.TextChannel))
throw (0, exports.emsg)('Unable to retrieve text channel information, please try again'); throw (0, exports.emsg)('general.noChannel');
return channel; return channel;
} }
exports.getChannel = getChannel; exports.getChannel = getChannel;
function memberIsMod(interaction) {
let member = getMember(interaction);
return member.permissionsIn(interaction.channelId).has('MANAGE_MESSAGES');
}
exports.memberIsMod = memberIsMod;
function memberIsModThrow(interaction) {
if (!memberIsMod(interaction))
throw (0, exports.emsg)('discord.notMod');
}
exports.memberIsModThrow = memberIsModThrow;

2476
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
{ {
"name": "1800queue-alt", "name": "1800queue",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "dist/index.js", "main": "dist/index.js",
@@ -30,7 +30,9 @@
"author": "", "author": "",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/node": "^17.0.13", "@types/node": "^17.0.17",
"@typescript-eslint/eslint-plugin": "^5.11.0",
"discord-api-types": "^0.26.1",
"npm-watch": "^0.11.0", "npm-watch": "^0.11.0",
"ts-node": "^10.4.0", "ts-node": "^10.4.0",
"typescript": "^4.5.5" "typescript": "^4.5.5"
@@ -38,7 +40,6 @@
"dependencies": { "dependencies": {
"@discordjs/rest": "^0.3.0", "@discordjs/rest": "^0.3.0",
"cheerio": "^1.0.0-rc.10", "cheerio": "^1.0.0-rc.10",
"discord-api-types": "^0.26.1",
"discord.js": "^13.6.0" "discord.js": "^13.6.0"
} }
} }

View File

@@ -8,11 +8,11 @@ cd ../..
npm install npm install
#discord token #discord token
[ ! -f "token" ] && touch "token" [ ! -f "token.txt" ] && touch "token.txt"
if [ ! -s "token" ] if [ ! -s "token.txt" ]
then then
printf "Enter your discord bot token: " printf "Enter your discord bot token: "
read token read token
printf $token > "token" printf $token > "token.txt"
fi fi

View File

@@ -4,12 +4,12 @@
cd %~f0\..\..\..\ cd %~f0\..\..\..\
@REM discord token @REM discord token
if not exist "token" copy NUL "token" if not exist "token.txt" copy NUL "token.txt"
for /f %%i in ("token") do set size=%%~zi for /f %%i in ("token.txt") do set size=%%~zi
if %size% equ 0 ( 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.txt"
) )
@REM run @REM run

View File

@@ -1,3 +1,4 @@
/*eslint prefer-const: "error"*/
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { CommandInteraction, MessageEmbed } from 'discord.js'; import { CommandInteraction, MessageEmbed } from 'discord.js';
import { IncomingMessage } from 'http'; import { IncomingMessage } from 'http';
@@ -12,7 +13,7 @@ const uniteApiRegex = {
/lv\.(\d+) (\w+) \((\d+)\)/i, //master /lv\.(\d+) (\w+) \((\d+)\)/i, //master
/lv\.(\d+) (\w+): class (\d+)/i //other /lv\.(\d+) (\w+): class (\d+)/i //other
] ]
} };
type uniteApiData = { type uniteApiData = {
name: string, name: string,
@@ -76,30 +77,30 @@ function getHTML(name: string): Promise<string> {
* @throws errorMessage class if the request fails * @throws errorMessage class if the request fails
*/ */
function readHTML(html: string): uniteApiData { function readHTML(html: string): uniteApiData {
let $ = cheerio.load(html) const $ = cheerio.load(html),
let metaElems = $('meta').toArray(),
foundData: uniteApiData = { foundData: uniteApiData = {
name: "", name: '',
id: "", id: '',
avatar: "", avatar: '',
level: "", level: '',
rank: "", rank: '',
elo: null, elo: null,
class: null, class: null,
battles: "", battles: '',
wins: "", wins: '',
winrate: "" winrate: ''
}; };
let metaElems = $('meta').toArray();
//filter down to just ones named "og:..." //filter down to just ones named "og:..."
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:')); metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
metaElems.forEach(el => { metaElems.forEach(el => {
let attr = el.attribs; const attr = el.attribs;
if (attr.property === 'og:title') { if (attr.property === 'og:title') {
let data = uniteApiRegex.ogtitle.exec(attr.content); const data = uniteApiRegex.ogtitle.exec(attr.content);
if (data !== null && data.length >= 3) { if (data !== null && data.length >= 3) {
foundData.name = data[1]; foundData.name = data[1];
foundData.id = data[2]; foundData.id = data[2];
@@ -107,17 +108,17 @@ function readHTML(html: string): uniteApiData {
} else if (attr.property === 'og:description') { } else if (attr.property === 'og:description') {
//all lines //all lines
let lines = attr.content.split('\n').map(l => l.trim()), let lines = attr.content.split('\n').map(l => l.trim());
extraLines: string[] = []; const extraLines: string[] = [];
//ensure first line is correct //ensure first line is correct
while (lines.length && !/pok.mon unite/i.test(lines[0])) { while ((lines.length > 0) && !/pok.mon unite/i.test(lines[0])) {
let line = lines.shift(); const line = lines.shift();
if (line) if (line !== undefined)
extraLines.push(line); extraLines.push(line);
} }
if (!lines.length) if (lines.length === 0)
throw emsg('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
@@ -129,13 +130,12 @@ function readHTML(html: string): uniteApiData {
//first line //first line
{ {
//will be only text after "pokemon unite:" //will be only text after "pokemon unite:"
let line = lines[0].split(':').slice(1).join(':').trim(); const line = lines[0].split(':').slice(1).join(':').trim(),
regex = uniteApiRegex.ogdescription;
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]); const regexData = line.match(regex[0]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw emsg('Unable to read data, please try again'); throw emsg('Unable to read data, please try again');
@@ -146,7 +146,7 @@ function readHTML(html: string): uniteApiData {
} else { //is not master/has a class } else { //is not master/has a class
let regexData = line.match(regex[1]); const regexData = line.match(regex[1]);
if (!regexData || regexData.length < 4) if (!regexData || regexData.length < 4)
throw emsg('Unable to read data, please try again'); throw emsg('Unable to read data, please try again');
@@ -164,7 +164,7 @@ function readHTML(html: string): uniteApiData {
//rest of lines //rest of lines
lines.forEach(line => { lines.forEach(line => {
let split = line.split(':').map(l => l.trim()), const split = line.split(':').map(l => l.trim()),
key = split[0].toLowerCase().replace(/[^\w]/g, ''), key = split[0].toLowerCase().replace(/[^\w]/g, ''),
value = split[1]; value = split[1];
@@ -186,7 +186,9 @@ function readHTML(html: string): uniteApiData {
}); });
foundData.avatar = $('.player-card-image img').attr('src') || ""; const imgSrc = $('.player-card-image img').attr('src');
foundData.avatar = imgSrc !== undefined ? imgSrc : '';
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/'); foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
return foundData; return foundData;
@@ -199,7 +201,7 @@ function readHTML(html: string): uniteApiData {
* @returns boolean, valid or invalid * @returns boolean, valid or invalid
*/ */
function verifyData(data: uniteApiData): boolean { function verifyData(data: uniteApiData): boolean {
if (data.id.length) if (data.id.length > 0)
return true; return true;
return false; return false;
} }
@@ -210,8 +212,8 @@ function verifyData(data: uniteApiData): boolean {
* @returns player data * @returns player data
*/ */
export async function getPlayer(name: string): Promise<uniteApiData|null> { export async function getPlayer(name: string): Promise<uniteApiData|null> {
let html = await getHTML(name); const html = await getHTML(name),
let data = readHTML(html); data = readHTML(html);
if (verifyData(data)) if (verifyData(data))
return data; return data;
return null; return null;
@@ -219,13 +221,19 @@ export async function getPlayer(name: string): Promise<uniteApiData|null> {
async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) { async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) {
let embed = new MessageEmbed() let eloStr: string;
if (data.elo !== null)
eloStr = `(${data.elo})`;
else
eloStr = `Class ${data.class}`;
const embed = new MessageEmbed()
.setTitle(`${data.name} (${data.id})`) .setTitle(`${data.name} (${data.id})`)
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`) .setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
.setTimestamp() .setTimestamp()
.setThumbnail(data.avatar) .setThumbnail(data.avatar)
.setDescription(`Level ${data.level} .setDescription(`Level ${data.level}
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`} ${data.rank} ${eloStr}
**Battles** ${data.battles} **Battles** ${data.battles}
**Wins** ${data.wins} **Wins** ${data.wins}
@@ -240,12 +248,12 @@ ${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
* @throws errorMessage class if the user cannot be found * @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); const username = interaction.options.getString('username', true);
await interaction.deferReply(); await interaction.deferReply();
let data = await getPlayer(username); const data = await getPlayer(username);
if (data === null) if (data === null)
throw emsg('Unable to find user'); throw emsg('api.noUser');
else else
sendPlayerEmbed(interaction, data); sendPlayerEmbed(interaction, data);
} }

View File

@@ -1,21 +1,31 @@
/* eslint-disable camelcase */
import { REST } from '@discordjs/rest'; import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v9'; import { Routes } from 'discord-api-types/v9';
// list of commands to register with discord // list of commands to register with discord
const commands = [ const commands = [
{ {
name: 'queue', name: 'open',
description: 'create a queue', description: 'open a queue for this channel',
options: [ options: [
{ {
type: 4, //INTEGER type: 4, //INTEGER
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
required: true, min_value: 1,
min_value: 1 required: true
} }
] ]
}, },
{
name: 'close',
description: 'close the queue for this channel'
},
{
name: 'queue',
description: 'view queue info'
},
{ {
name: 'join', name: 'join',
description: 'join the active queue' description: 'join the active queue'
@@ -24,14 +34,6 @@ const commands = [
name: 'leave', name: 'leave',
description: 'leave the active queue' description: 'leave the active queue'
}, },
{
name: 'ready',
description: 'ready the queue and display team info'
},
{
name: 'cancel',
description: 'cancels the current queue (must have the Manage Messages permission)'
},
{ {
name: 'player', name: 'player',
description: 'display player information', description: 'display player information',
@@ -45,6 +47,7 @@ const commands = [
] ]
} }
]; ];
/*commandNames = commands.map(c => c.name);*/
/** /**
* register/reload commands on guild(s) * register/reload commands on guild(s)
@@ -65,7 +68,6 @@ export async function registerCommands(token: string, clientId: string, guildIds
Routes.applicationGuildCommands(clientId, guildIds[i]), Routes.applicationGuildCommands(clientId, guildIds[i]),
{ body: commands }, { body: commands },
); );
console.log(`[${guildIds[i]}] registered command`);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }

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 { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } from './queue'; import * as Lang from './lang';
import { discordInit, QueueCommands } from './queue';
import { errorMessage } from './util'; import { errorMessage } from './util';
const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] }); const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
@@ -11,18 +12,26 @@ const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
console.log(new Date().toISOString()+'\n\n'); console.log(new Date().toISOString()+'\n\n');
//get token //get token
if (!fs.existsSync('./token')) { if (!fs.existsSync('./token.txt')) {
fs.writeFileSync('./token', ''); fs.writeFileSync('./token.txt', '');
console.error('Missing Discord Token, please enter the bot token into the token file'); console.error(Lang.get('error.main.missingToken'));
process.exit(1); process.exit(1);
} }
const TOKEN = fs.readFileSync('./token').toString(); const TOKEN = fs.readFileSync('./token.txt').toString();
//discord connections //discord connections
CLIENT.on('ready', client => { CLIENT.on('ready', client => {
console.log(`Logged in as ${client.user.tag}`); console.log(Lang.get('main.login', {
user: client.user.tag
}));
client.guilds.fetch().then(guilds => client.guilds.fetch().then(guilds =>
registerCommands(TOKEN, client.user.id, guilds.map(g => g.id))); registerCommands(TOKEN, client.user.id, guilds.map(g => g.id)));
discordInit(client);
});
CLIENT.on('guildCreate', guild => {
if (guild.client.user)
registerCommands(TOKEN, guild.client.user.id, guild.id);
}); });
CLIENT.on('interactionCreate', async interaction => { CLIENT.on('interactionCreate', async interaction => {
@@ -30,18 +39,31 @@ CLIENT.on('interactionCreate', async interaction => {
try { try {
if (interaction.commandName === 'queue') switch (interaction.commandName) {
await createQueue(interaction);
else if (interaction.commandName === 'join') //mod commands
await joinQueue(interaction); case 'open':
else if (interaction.commandName === 'leave') await QueueCommands.open(interaction);
await leaveQueue(interaction); break;
else if (interaction.commandName === 'ready') case 'close':
await readyQueue(interaction); await QueueCommands.close(interaction);
else if (interaction.commandName === 'cancel') break;
await cancelQueue(interaction);
else if (interaction.commandName === 'player') //general commands
await getPlayerInteraction(interaction); case 'queue':
await QueueCommands.queue(interaction);
break;
case 'join':
await QueueCommands.join(interaction);
break;
case 'leave':
await QueueCommands.leave(interaction);
break;
case 'player':
await getPlayerInteraction(interaction);
break;
}
} catch (e) { } catch (e) {

105
src/lang.ts Normal file
View File

@@ -0,0 +1,105 @@
type LangObj = { [keys:string]: LangObj | string }
type LangObjWhole = { [langid:string]: LangObj }
const LANG: LangObjWhole = {
en: {
main: {
login: 'Logged in as {user}'
},
discord: {
botRestart: 'The bot has just restarted, anybody previously in the queue has been reset',
create: 'A queue for teams of {teamsize} has been created',
close: 'Queue has been closed',
join: 'Joined the queue',
leave: 'Left the queue'
},
error: {
main: {
missingToken: 'Missing Discord Token, please enter the bot token into the token file'
},
discord: {
noQueue: 'There is not an active queue in this channel, type `/open` to create one',
noChannel: 'Unable to find channel {channelId} for teams of {teamsize}',
noCreate: 'There is already an active queue in this channel for teams of {teamsize}',
inQueue: 'You are already in the queue',
notInQueue: 'You aren\'t in the queue',
notMod: 'Member is not a moderator'
},
general: {
noMember: 'Unable to retrieve guild member information, please try again',
noChannel: 'Unable to retrieve text channel information, please try again'
},
api: {
noUser: 'Unable to find user'
}
}
}
};
let LANGID = 'en';
if (!(LANGID in LANG))
throw 'language id does not exist';
export function setLang(langid: string) {
if (langid in LANG)
LANGID = langid;
else
throw 'language id does not exist';
}
function template(str: string, args: {[keys: string]: string}): string {
return str.replace(/{\w+}/g, str => {
const key = str.substring(1, str.length-1);
if (key in args)
return args[key];
return key;
});
}
/**
* reads language json
* @param id ex: discord.error.noActiveQueue
* @returns language value, defaults to `id` parameter
*/
export function get(id: string, args: {[keys: string]: string} = {}): string {//discord.error.noActiveQueue
const keySpl = id.split('.').map(k => k.trim()).filter(k => k);
let finding = LANG[LANGID];
for (const key of keySpl) {
if (key in finding) {
const found = finding[key];
if (typeof found === 'string')
return template(found, args);
finding = found;
} else
break;
}
return id;
}

View File

@@ -1,8 +1,110 @@
import { CommandInteraction, GuildMember, MessageEmbed } from "discord.js"; /* TODO
import { emsg, getChannel, getMember, queueInfo, shuffle } from "./util";
//maps ChannelID to QueueInfo join message should contain your current position in the queue, editing it to keep it current
const QUEUE = new Map<string, queueInfo>(); */
import { Client, CommandInteraction, MessageEmbed, TextChannel } from 'discord.js';
import * as fs from 'fs';
import { emsg, getChannel, getMember, memberIsModThrow, queueInfo, queueInfoBase } from './util';
import * as Lang from './lang';
//load queues from file
if (!fs.existsSync('./queues.json'))
fs.writeFileSync('./queues.json', '{}');
const _QUEUE = fs.readFileSync('./queues.json').toString(),
QUEUE = new Map<string, queueInfo>();
try {
const queueJson = JSON.parse(_QUEUE);
for (const channelId in queueJson) {
const {teamsize} = queueJson[channelId] as queueInfoBase;
if (teamsize !== 0)
QUEUE.set(channelId, { teamsize, players: [] });
}
} catch(e) {
//do nothing
}
function SaveQueue() {
const queueJson = Object.fromEntries(QUEUE),
queueFileJson: {[keys: string]: queueInfoBase} = {};
for (const channelId of QUEUE.keys())
queueFileJson[channelId] = { teamsize: queueJson[channelId].teamsize };
fs.writeFileSync('./queues.json', JSON.stringify(queueFileJson, null, 2));
}
async function checkQueue(channel: TextChannel) {
const info = QUEUE.get(channel.id);
if (!info)
return;
if (info.players.length >= info.teamsize) {
const team = info.players.splice(0, info.teamsize).map(m => m.toString());
//TODO add embeds to lang.ts
const embed = new MessageEmbed()
.setTitle('Team')
.setDescription(team.join('\n'));
await channel.send({embeds: [embed]});
}
}
export function queueCreate(channelId: string, teamsize: number) {
if (!QUEUE.has(channelId)) {
QUEUE.set(channelId, {teamsize, players: []});
SaveQueue();
}
}
export function queueRemove(channelId: string) {
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
SaveQueue();
}
}
SaveQueue();
export async function discordInit(client: Client) {
for (const channelId of QUEUE.keys()) {
const info = QUEUE.get(channelId),
channel = await client.channels.fetch(channelId);
if (!info) { //no idea what could cause this but TS complains
queueRemove(channelId);
continue;
}
if (!channel || !(channel instanceof TextChannel)) {
console.error(Lang.get('error.discord.noChannel'), {
channelId,
teamsize: info.teamsize
});
queueRemove(channelId);
continue;
}
channel.send(Lang.get('discord.botRestart'));
}
}
/** /**
* get the queueInfo of an interaction * get the queueInfo of an interaction
@@ -10,11 +112,11 @@ const QUEUE = new Map<string, queueInfo>();
* @throws errorMessage class if it does not exist * @throws errorMessage class if it does not exist
* @returns queue info * @returns queue info
*/ */
export function getInfo(interaction: CommandInteraction): queueInfo { function getInfo(interaction: CommandInteraction): queueInfo {
let info = QUEUE.get(interaction.channelId); const info = QUEUE.get(interaction.channelId);
if (!info) if (!info)
throw emsg('There is not an active queue in this channel, type `/queue` to create one'); throw emsg('discord.noQueue');
return info; return info;
} }
@@ -25,7 +127,7 @@ export function getInfo(interaction: CommandInteraction): queueInfo {
* @throws if another get function throws * @throws if another get function throws
* @returns object containing each * @returns object containing each
*/ */
export const getAll = (interaction: CommandInteraction) => ({ const getAll = (interaction: CommandInteraction) => ({
member: getMember(interaction), member: getMember(interaction),
channel: getChannel(interaction), channel: getChannel(interaction),
info: getInfo(interaction) info: getInfo(interaction)
@@ -38,7 +140,7 @@ export const getAll = (interaction: CommandInteraction) => ({
*/ */
export function queueContains(interaction: CommandInteraction): boolean { export function queueContains(interaction: CommandInteraction): boolean {
let {member, info} = getAll(interaction); const {member, info} = getAll(interaction);
if (info.players.map(m=>m.id).includes(member.id)) if (info.players.map(m=>m.id).includes(member.id))
return true; return true;
@@ -48,189 +150,110 @@ export function queueContains(interaction: CommandInteraction): boolean {
} }
/** /**
* creates the timeout for the queue * opens a 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
* @param interaction
* @throws errorMessage class if it cannot be created
*/
export async function createQueue(interaction: CommandInteraction) {
let member = getMember(interaction),
{channelId} = interaction,
teamsize = interaction.options.getInteger('teamsize', true);
if (QUEUE.has(channelId))
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, {
players: [
member
],
initiator: {
interaction,
member
},
teamsize: teamsize,
timeout: setQueueTimeout(interaction)
});
sendQueueEmbed(interaction);
}
/**
* joins a queue from an interaction
* @param interaction
* @throws errorMessage class if it cannot be joined
*/
export async function joinQueue(interaction: CommandInteraction) {
let {member, info} = getAll(interaction);
if (queueContains(interaction))
throw emsg('You are already in the active queue');
info.players.push(member);
clearTimeout(info.timeout);
info.timeout = setQueueTimeout(interaction)
QUEUE.set(interaction.channelId, info);
sendQueueEmbed(interaction);
await interaction.reply('Joined the queue');
}
/**
* leaves a queue from an interaction
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be left * @throws errorMessage class if it cannot be left
*/ */
export async function leaveQueue(interaction: CommandInteraction) { function open(interaction: CommandInteraction) {
let {member, info} = getAll(interaction); memberIsModThrow(interaction);
if (!queueContains(interaction)) const {channelId} = interaction,
throw emsg('You aren\'t in the active queue'); teamsize = interaction.options.getInteger('teamsize', true);
info.players.splice(info.players.indexOf(member), 1); const existing = QUEUE.get(channelId);
clearTimeout(info.timeout); if (existing)
info.timeout = setQueueTimeout(interaction) throw emsg(Lang.get('error.discord.noCreate', {
teamsize: existing.teamsize.toString()
}));
QUEUE.set(interaction.channelId, info); queueCreate(channelId, teamsize);
sendQueueEmbed(interaction); interaction.reply(Lang.get('discord.create', {
await interaction.reply('Left the queue'); teamsize: teamsize.toString()
}));
} }
/** /**
* readys a queue from an interaction * closes a queue
* @param interaction
* @throws errorMessage class if it cannot be joined
*/
async function close(interaction: CommandInteraction) {
memberIsModThrow(interaction);
QUEUE.delete(interaction.channelId);
await interaction.reply(Lang.get('discord.close'));
}
/**
* gives info about the queue
* @param interaction
* @throws errorMessage class if it cannot be left
*/
async function queue(interaction: CommandInteraction) {
const info = getInfo(interaction);
const embed = new MessageEmbed()
.setTitle('Active Queue')
.addField('Team Size', info.teamsize.toString(), true)
.addField('Players Joined', info.players.length.toString(), true)
.setFooter({text: 'type /join'}); //TODO
await interaction.reply({embeds: [embed], ephemeral: true});
}
/**
* joins a queue
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be readied * @throws errorMessage class if it cannot be readied
*/ */
export async function readyQueue(interaction: CommandInteraction) { async function join(interaction: CommandInteraction) {
let {member, info} = getAll(interaction), const {member, info, channel} = getAll(interaction);
{initiator} = info;
if (member.id !== initiator.member.id) if (queueContains(interaction))
throw emsg('Only the queue initiator can ready the queue'); throw emsg('discord.inQueue');
clearQueue(interaction); info.players.push(member);
if (info.players.filter(m => m.id !== initiator.member.id).length === 0) QUEUE.set(interaction.channelId, info);
throw emsg('Nobody signed up for the queue, the queue has been reset');
//team data await interaction.reply(Lang.get('discord.join'));
let playerlist: GuildMember[] = shuffle(info.players),
teams: GuildMember[][] = [];
//fill team data checkQueue(channel);
for (let i = 0; i < playerlist.length; i+= info.teamsize)
teams.push(playerlist.slice(i, i+info.teamsize));
sendTeamsEmbed(interaction, teams);
} }
/** /**
* readys a queue from an interaction * leaves a queue
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be reset * @throws errorMessage class if it cannot be reset
*/ */
export async function cancelQueue(interaction: CommandInteraction) { async function leave(interaction: CommandInteraction) {
let {info, member, channel} = getAll(interaction); const {member, info} = getAll(interaction);
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES')) if (!queueContains(interaction))
throw emsg('You do not have permission to run this command'); throw emsg('discord.notInQueue');
clearQueue(interaction); info.players.splice(info.players.indexOf(member), 1);
await interaction.reply('Queue has been reset'); QUEUE.set(interaction.channelId, info);
await interaction.reply(Lang.get('discord.leave'));
} }
export const QueueCommands = {
open,
close,
queue,
join,
leave
};

0
src/queueCommands.ts Normal file
View File

View File

@@ -1,4 +1,5 @@
import { CommandInteraction, GuildMember, TextChannel } from "discord.js"; import { CommandInteraction, GuildMember, TextChannel } from 'discord.js';
import * as Lang from './lang';
/** /**
* shuffles an array * shuffles an array
@@ -6,6 +7,7 @@ import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
* @param array an array * @param array an array
* @returns an array but shuffled * @returns an array but shuffled
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function shuffle(array: any[]) { export function shuffle(array: any[]) {
let currentIndex = array.length, randomIndex; let currentIndex = array.length, randomIndex;
@@ -30,7 +32,7 @@ export class errorMessage {
public msg: string; public msg: string;
public ephemeral: boolean; public ephemeral: boolean;
constructor(msg: string, ephemeral: boolean = true) { constructor(msg: string, ephemeral = true) {
this.msg = msg; this.msg = msg;
this.ephemeral = ephemeral; this.ephemeral = ephemeral;
} }
@@ -42,18 +44,15 @@ export class errorMessage {
* @param ephemeral (default=true) * @param ephemeral (default=true)
* @returns new errorMessage * @returns new errorMessage
*/ */
export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage(msg, ephemeral); export const emsg = (msg: string, ephemeral = true) => new errorMessage(Lang.get(`error.${msg}`), ephemeral);
export type queueInfo = { export interface queueInfoBase {
players: GuildMember[], teamsize: number
initiator: { }
interaction: CommandInteraction, export interface queueInfo extends queueInfoBase{
member: GuildMember players: GuildMember[]
},
teamsize: number,
timeout: NodeJS.Timeout
} }
/** /**
@@ -63,10 +62,10 @@ export type queueInfo = {
* @returns member * @returns member
*/ */
export function getMember(interaction: CommandInteraction): GuildMember { export function getMember(interaction: CommandInteraction): GuildMember {
let member = interaction.member; const member = interaction.member;
if (!(member instanceof GuildMember)) if (!(member instanceof GuildMember))
throw emsg('Unable to retrieve guild member information, please try again'); throw emsg('general.noMember');
return member; return member;
} }
@@ -78,10 +77,21 @@ export function getMember(interaction: CommandInteraction): GuildMember {
* @returns member * @returns member
*/ */
export function getChannel(interaction: CommandInteraction): TextChannel { export function getChannel(interaction: CommandInteraction): TextChannel {
let channel = interaction.channel; const channel = interaction.channel;
if (!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
throw emsg('Unable to retrieve text channel information, please try again'); throw emsg('general.noChannel');
return channel; return channel;
} }
export function memberIsMod(interaction: CommandInteraction): boolean {
const member = getMember(interaction);
return member.permissionsIn(interaction.channelId).has('MANAGE_MESSAGES');
}
export function memberIsModThrow(interaction: CommandInteraction) {
if (!memberIsMod(interaction))
throw emsg('discord.notMod');
}

View File

@@ -6,7 +6,10 @@
"outDir": "./dist", "outDir": "./dist",
"esModuleInterop": true, "esModuleInterop": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"strict": true, "strict": true,
"skipLibCheck": true "noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
} }
} }