Compare commits

..

1 Commits

Author SHA1 Message Date
4ad4f69f9f updated package info 2022-02-01 11:59:34 -06:00
19 changed files with 533 additions and 873 deletions

8
.gitignore vendored
View File

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

View File

@@ -1,10 +1,8 @@
<!-- markdownlint-disable MD033 --> <!-- markdownlint-disable MD033 -->
# 1800queue # 1800queue alt
## Invite info This version does not run continuously, and requires each tourney to be started with a command
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)('api.noUser'); throw (0, util_1.emsg)('Unable to find user');
else else
sendPlayerEmbed(interaction, data); sendPlayerEmbed(interaction, data);
} }

27
dist/discord.js vendored
View File

@@ -6,26 +6,18 @@ 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: 'open', name: 'queue',
description: 'open a queue for this channel', description: 'create a queue',
options: [ options: [
{ {
type: 4, type: 4,
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
min_value: 1, required: true,
required: true min_value: 1
} }
] ]
}, },
{
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'
@@ -34,6 +26,14 @@ 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,6 +60,7 @@ 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,57 +23,39 @@ 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.txt')) { if (!fs.existsSync('./token')) {
fs.writeFileSync('./token.txt', ''); fs.writeFileSync('./token', '');
console.error(lang_1.Lang.get('error.main.missingToken')); console.error('Missing Discord Token, please enter the bot token into the token file');
process.exit(1); process.exit(1);
} }
const TOKEN = fs.readFileSync('./token.txt').toString(); const TOKEN = fs.readFileSync('./token').toString();
//discord connections //discord connections
CLIENT.on('ready', client => { CLIENT.on('ready', client => {
console.log(lang_1.Lang.get('main.login', { console.log(`Logged in as ${client.user.tag}`);
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 {
switch (interaction.commandName) { if (interaction.commandName === 'queue')
//mod commands await (0, queue_1.createQueue)(interaction);
case 'open': else if (interaction.commandName === 'join')
await queue_1.QueueCommands.open(interaction); await (0, queue_1.joinQueue)(interaction);
break; else if (interaction.commandName === 'leave')
case 'close': await (0, queue_1.leaveQueue)(interaction);
await queue_1.QueueCommands.close(interaction); else if (interaction.commandName === 'ready')
break; await (0, queue_1.readyQueue)(interaction);
//general commands else if (interaction.commandName === 'cancel')
case 'queue': await (0, queue_1.cancelQueue)(interaction);
await queue_1.QueueCommands.queue(interaction); else if (interaction.commandName === 'player')
break; await (0, api_1.getPlayerInteraction)(interaction);
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
View File

@@ -1,79 +0,0 @@
"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 = {}));

405
dist/queue.js vendored
View File

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

83
package-lock.json generated
View File

@@ -1,21 +1,21 @@
{ {
"name": "1800queue", "name": "1800queue-alt",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "1800queue", "name": "1800queue-alt",
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"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"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^17.0.17", "@types/node": "^17.0.13",
"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"
@@ -150,9 +150,9 @@
"dev": true "dev": true
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "17.0.17", "version": "17.0.13",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.13.tgz",
"integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==" "integrity": "sha512-Y86MAxASe25hNzlDbsviXl8jQHb0RDvKt4c40ZJQ1Don0AAL0STLZSs4N+6gLEO55pedy7r2cLwS+ZDxPm/2Bw=="
}, },
"node_modules/@types/node-fetch": { "node_modules/@types/node-fetch": {
"version": "2.5.12", "version": "2.5.12",
@@ -662,7 +662,6 @@
"version": "0.26.1", "version": "0.26.1",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.26.1.tgz", "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.26.1.tgz",
"integrity": "sha512-T5PdMQ+Y1MEECYMV5wmyi9VEYPagEDEi4S0amgsszpWY0VB9JJ/hEvM6BgLhbdnKky4gfmZEXtEEtojN8ZKJQQ==", "integrity": "sha512-T5PdMQ+Y1MEECYMV5wmyi9VEYPagEDEi4S0amgsszpWY0VB9JJ/hEvM6BgLhbdnKky4gfmZEXtEEtojN8ZKJQQ==",
"deprecated": "No longer supported. Install the latest release!",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@@ -1212,9 +1211,9 @@
} }
}, },
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "3.1.1", "version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.1.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-reLxBcKUPNBnc/sVtAbxgRVFSegoGeLaSjmphNhcwcolhYLRgtJscn5mRl6YRZNQv40Y7P6JM2YhSIsbL9OB5A==", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"brace-expansion": "^1.1.7" "brace-expansion": "^1.1.7"
@@ -1575,9 +1574,9 @@
} }
}, },
"node_modules/signal-exit": { "node_modules/signal-exit": {
"version": "3.0.7", "version": "3.0.6",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==",
"dev": true "dev": true
}, },
"node_modules/string_decoder": { "node_modules/string_decoder": {
@@ -1689,9 +1688,9 @@
"integrity": "sha512-nXIb1fvdY5CBSrDIblLn73NW0qRDk5yJ0Sk1qPBF560OdJfQp9jhl+0tzcY09OZ9U+6GpeoI9RjwoIKFIoB9MQ==" "integrity": "sha512-nXIb1fvdY5CBSrDIblLn73NW0qRDk5yJ0Sk1qPBF560OdJfQp9jhl+0tzcY09OZ9U+6GpeoI9RjwoIKFIoB9MQ=="
}, },
"node_modules/ts-node": { "node_modules/ts-node": {
"version": "10.5.0", "version": "10.4.0",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.5.0.tgz", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz",
"integrity": "sha512-6kEJKwVxAJ35W4akuiysfKwKmjkbYxwQMTBaAxo9KKAx/Yd26mPUyhGz3ji+EsJoAgrLqVsYHNuuYwQe22lbtw==", "integrity": "sha512-g0FlPvvCXSIO1JDF6S232P5jPYqBkRL9qly81ZgAOSU7rwI0stphCgd2kLiCrU9DjQCrJMWEqcNSjQL02s6d8A==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@cspotcode/source-map-support": "0.7.0", "@cspotcode/source-map-support": "0.7.0",
@@ -1705,7 +1704,6 @@
"create-require": "^1.1.0", "create-require": "^1.1.0",
"diff": "^4.0.1", "diff": "^4.0.1",
"make-error": "^1.1.1", "make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.0",
"yn": "3.1.1" "yn": "3.1.1"
}, },
"bin": { "bin": {
@@ -1848,12 +1846,6 @@
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
"dev": true "dev": true
}, },
"node_modules/v8-compile-cache-lib": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz",
"integrity": "sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA==",
"dev": true
},
"node_modules/webidl-conversions": { "node_modules/webidl-conversions": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
@@ -1916,9 +1908,9 @@
} }
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.5.0", "version": "8.4.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.4.2.tgz",
"integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "integrity": "sha512-Kbk4Nxyq7/ZWqr/tarI9yIt/+iNNFOjBXEWgTb4ydaNHBNGgvf2QHbS9fdfsndfjFlFwEd4Al+mw83YkaD10ZA==",
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"
}, },
@@ -2064,9 +2056,9 @@
"dev": true "dev": true
}, },
"@types/node": { "@types/node": {
"version": "17.0.17", "version": "17.0.13",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.13.tgz",
"integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==" "integrity": "sha512-Y86MAxASe25hNzlDbsviXl8jQHb0RDvKt4c40ZJQ1Don0AAL0STLZSs4N+6gLEO55pedy7r2cLwS+ZDxPm/2Bw=="
}, },
"@types/node-fetch": { "@types/node-fetch": {
"version": "2.5.12", "version": "2.5.12",
@@ -2860,9 +2852,9 @@
"dev": true "dev": true
}, },
"minimatch": { "minimatch": {
"version": "3.1.1", "version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.1.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-reLxBcKUPNBnc/sVtAbxgRVFSegoGeLaSjmphNhcwcolhYLRgtJscn5mRl6YRZNQv40Y7P6JM2YhSIsbL9OB5A==", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"dev": true, "dev": true,
"requires": { "requires": {
"brace-expansion": "^1.1.7" "brace-expansion": "^1.1.7"
@@ -3127,9 +3119,9 @@
} }
}, },
"signal-exit": { "signal-exit": {
"version": "3.0.7", "version": "3.0.6",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==",
"dev": true "dev": true
}, },
"string_decoder": { "string_decoder": {
@@ -3220,9 +3212,9 @@
"integrity": "sha512-nXIb1fvdY5CBSrDIblLn73NW0qRDk5yJ0Sk1qPBF560OdJfQp9jhl+0tzcY09OZ9U+6GpeoI9RjwoIKFIoB9MQ==" "integrity": "sha512-nXIb1fvdY5CBSrDIblLn73NW0qRDk5yJ0Sk1qPBF560OdJfQp9jhl+0tzcY09OZ9U+6GpeoI9RjwoIKFIoB9MQ=="
}, },
"ts-node": { "ts-node": {
"version": "10.5.0", "version": "10.4.0",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.5.0.tgz", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz",
"integrity": "sha512-6kEJKwVxAJ35W4akuiysfKwKmjkbYxwQMTBaAxo9KKAx/Yd26mPUyhGz3ji+EsJoAgrLqVsYHNuuYwQe22lbtw==", "integrity": "sha512-g0FlPvvCXSIO1JDF6S232P5jPYqBkRL9qly81ZgAOSU7rwI0stphCgd2kLiCrU9DjQCrJMWEqcNSjQL02s6d8A==",
"dev": true, "dev": true,
"requires": { "requires": {
"@cspotcode/source-map-support": "0.7.0", "@cspotcode/source-map-support": "0.7.0",
@@ -3236,7 +3228,6 @@
"create-require": "^1.1.0", "create-require": "^1.1.0",
"diff": "^4.0.1", "diff": "^4.0.1",
"make-error": "^1.1.1", "make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.0",
"yn": "3.1.1" "yn": "3.1.1"
} }
}, },
@@ -3329,12 +3320,6 @@
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
"dev": true "dev": true
}, },
"v8-compile-cache-lib": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz",
"integrity": "sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA==",
"dev": true
},
"webidl-conversions": { "webidl-conversions": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
@@ -3388,9 +3373,9 @@
} }
}, },
"ws": { "ws": {
"version": "8.5.0", "version": "8.4.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.4.2.tgz",
"integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "integrity": "sha512-Kbk4Nxyq7/ZWqr/tarI9yIt/+iNNFOjBXEWgTb4ydaNHBNGgvf2QHbS9fdfsndfjFlFwEd4Al+mw83YkaD10ZA==",
"requires": {} "requires": {}
}, },
"xdg-basedir": { "xdg-basedir": {

View File

@@ -1,5 +1,5 @@
{ {
"name": "1800queue", "name": "1800queue-alt",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "dist/index.js", "main": "dist/index.js",
@@ -30,8 +30,7 @@
"author": "", "author": "",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/node": "^17.0.17", "@types/node": "^17.0.13",
"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"
@@ -39,6 +38,7 @@
"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.txt" ] && touch "token.txt" [ ! -f "token" ] && touch "token"
if [ ! -s "token.txt" ] if [ ! -s "token" ]
then then
printf "Enter your discord bot token: " printf "Enter your discord bot token: "
read token read token
printf $token > "token.txt" printf $token > "token"
fi fi

View File

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

View File

@@ -93,9 +93,9 @@ function readHTML(html: string): uniteApiData {
}; };
//filter down to just ones named "og:..." //filter down to just ones named "og:..."
metaElems = metaElems.filter((el: cheerio.Element) => el.attribs.property?.startsWith('og:')); metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
metaElems.forEach((el: cheerio.Element) => { metaElems.forEach(el => {
let attr = el.attribs; let attr = el.attribs;
if (attr.property === 'og:title') { if (attr.property === 'og:title') {
@@ -107,7 +107,7 @@ 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: string) => l.trim()), let lines = attr.content.split('\n').map(l => l.trim()),
extraLines: string[] = []; extraLines: string[] = [];
//ensure first line is correct //ensure first line is correct
@@ -162,9 +162,9 @@ function readHTML(html: string): uniteApiData {
lines.shift(); lines.shift();
//rest of lines //rest of lines
lines.forEach((line: string) => { lines.forEach(line => {
let split = line.split(':').map((l: string) => l.trim()), let 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];
@@ -245,7 +245,7 @@ export async function getPlayerInteraction(interaction: CommandInteraction) {
let data = await getPlayer(username); let data = await getPlayer(username);
if (data === null) if (data === null)
throw emsg('api.noUser'); throw emsg('Unable to find user');
else else
sendPlayerEmbed(interaction, data); sendPlayerEmbed(interaction, data);
} }

View File

@@ -4,27 +4,18 @@ 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: 'open', name: 'queue',
description: 'open a queue for this channel', description: 'create a queue',
options: [ options: [
{ {
type: 4, //INTEGER type: 4, //INTEGER
name: 'teamsize', name: 'teamsize',
description: 'size of each team', description: 'size of each team',
min_value: 1, required: true,
required: true min_value: 1
} }
] ]
}, },
{
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'
@@ -33,6 +24,14 @@ 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,8 +44,7 @@ const commands = [
} }
] ]
} }
]/*, ];
commandNames = commands.map(c => c.name);*/
/** /**
* register/reload commands on guild(s) * register/reload commands on guild(s)
@@ -67,6 +65,7 @@ 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,8 +3,7 @@ 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 { Lang } from './lang'; import { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } from './queue';
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] });
@@ -12,26 +11,18 @@ 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.txt')) { if (!fs.existsSync('./token')) {
fs.writeFileSync('./token.txt', ''); fs.writeFileSync('./token', '');
console.error(Lang.get('error.main.missingToken')); console.error('Missing Discord Token, please enter the bot token into the token file');
process.exit(1); process.exit(1);
} }
const TOKEN = fs.readFileSync('./token.txt').toString(); const TOKEN = fs.readFileSync('./token').toString();
//discord connections //discord connections
CLIENT.on('ready', client => { CLIENT.on('ready', client => {
console.log(Lang.get('main.login', { console.log(`Logged in as ${client.user.tag}`);
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 => {
@@ -39,31 +30,18 @@ CLIENT.on('interactionCreate', async interaction => {
try { try {
switch (interaction.commandName) { if (interaction.commandName === 'queue')
await createQueue(interaction);
//mod commands else if (interaction.commandName === 'join')
case 'open': await joinQueue(interaction);
await QueueCommands.open(interaction); else if (interaction.commandName === 'leave')
break; await leaveQueue(interaction);
case 'close': else if (interaction.commandName === 'ready')
await QueueCommands.close(interaction); await readyQueue(interaction);
break; else if (interaction.commandName === 'cancel')
await cancelQueue(interaction);
//general commands else if (interaction.commandName === 'player')
case 'queue': await getPlayerInteraction(interaction);
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) {

View File

@@ -1,108 +0,0 @@
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'
}
}
}
}
export namespace Lang {
var 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 => {
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
*/
export function get(id: string, args: {[keys: string]: string} = {}): string {//discord.error.noActiveQueue
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;
}
}

View File

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

View File

@@ -1,5 +1,4 @@
import { CommandInteraction, GuildMember, TextChannel } from "discord.js"; import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
import { Lang } from "./lang";
/** /**
* shuffles an array * shuffles an array
@@ -43,15 +42,18 @@ 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(Lang.get(`error.${msg}`), ephemeral); export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage(msg, ephemeral);
export interface queueInfoBase { export type queueInfo = {
teamsize: number players: GuildMember[],
} initiator: {
export interface queueInfo extends queueInfoBase{ interaction: CommandInteraction,
players: GuildMember[] member: GuildMember
},
teamsize: number,
timeout: NodeJS.Timeout
} }
/** /**
@@ -64,7 +66,7 @@ export function getMember(interaction: CommandInteraction): GuildMember {
let member = interaction.member; let member = interaction.member;
if (!(member instanceof GuildMember)) if (!(member instanceof GuildMember))
throw emsg('general.noMember'); throw emsg('Unable to retrieve guild member information, please try again');
return member; return member;
} }
@@ -79,18 +81,7 @@ export function getChannel(interaction: CommandInteraction): TextChannel {
let channel = interaction.channel; let channel = interaction.channel;
if (!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
throw emsg('general.noChannel'); throw emsg('Unable to retrieve text channel information, please try again');
return channel; return channel;
} }
export function memberIsMod(interaction: CommandInteraction): boolean {
let 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,10 +6,7 @@
"outDir": "./dist", "outDir": "./dist",
"esModuleInterop": true, "esModuleInterop": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"strict": true, "strict": true,
"noImplicitReturns": true, "skipLibCheck": true
"noUnusedLocals": true,
"noUnusedParameters": true,
} }
} }