Compare commits

..

9 Commits

Author SHA1 Message Date
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
14 changed files with 594 additions and 475 deletions

3
.gitignore vendored
View File

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

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

26
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'
@@ -27,12 +35,8 @@ const commands = [
description: 'leave the active queue' description: 'leave the active queue'
}, },
{ {
name: 'ready', name: 'stop',
description: 'ready the queue and display team info' description: 'stops the current queue (must have the Manage Messages permission)'
},
{
name: 'cancel',
description: 'cancels the current queue (must have the Manage Messages permission)'
}, },
{ {
name: 'player', name: 'player',
@@ -46,7 +50,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

41
dist/index.js vendored
View File

@@ -29,33 +29,44 @@ const CLIENT = new discord_js_1.Client({ intents: [discord_js_1.Intents.FLAGS.GU
//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('Missing Discord Token, please enter the bot token into the token file');
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(`Logged in as ${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('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) {

399
dist/queue.js vendored
View File

@@ -1,189 +1,222 @@
"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");
//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() let embed = new discord_js_1.MessageEmbed()
.setTitle('Queue') .setTitle('Team')
.setAuthor({ .setDescription(team.join('\n'));
name: info.initiator.member.displayName, await channel.send({ embeds: [embed] });
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] });
} }
/** 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 in 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(`Unable to find channel ${channelId} for teams of ${info?.teamsize}`);
Queue.remove(channelId);
continue;
}
channel.send('The bot has just restarted and anybody in the queues have been reset');
}
}
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)('There is not an active queue in this channel, type `/queue` to create one');
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')); if (QUEUE.has(channelId))
QUEUE.set(channelId, { throw (0, util_1.emsg)(`There is already an active queue in this channel for teams of ${QUEUE.get(channelId)?.teamsize}`);
players: [ Queue.create(channelId, teamsize);
member interaction.reply(`A queue for teams of ${teamsize} has been started`);
], }
initiator: { QueueCommands.queueCreate = queueCreate;
interaction, /**
member * opens a queue
}, * @param interaction
teamsize: teamsize, * @throws errorMessage class if it cannot be left
timeout: setQueueTimeout(interaction) */
}); async function open(interaction) {
sendQueueEmbed(interaction); queueCreate(interaction);
} }
exports.createQueue = createQueue; QueueCommands.open = open;
/** /**
* joins a queue from an interaction * closes a queue
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be joined * @throws errorMessage class if it cannot be joined
*/ */
async function joinQueue(interaction) { async function close(interaction) {
let { member, info } = (0, exports.getAll)(interaction); (0, util_1.memberIsModThrow)(interaction);
if (queueContains(interaction)) QUEUE.delete(interaction.channelId);
throw (0, util_1.emsg)('You are already in the active queue'); await interaction.reply('Queue has been reset');
info.players.push(member); }
clearTimeout(info.timeout); QueueCommands.close = close;
info.timeout = setQueueTimeout(interaction); /**
QUEUE.set(interaction.channelId, info); * gives info about the queue
sendQueueEmbed(interaction); * @param interaction
await interaction.reply('Joined the queue'); * @throws errorMessage class if it cannot be left
} */
exports.joinQueue = joinQueue; async function queue(interaction) {
/** let info = getInfo(interaction);
* leaves a queue from an interaction let embed = new discord_js_1.MessageEmbed()
* @param interaction .setTitle('Active Queue')
* @throws errorMessage class if it cannot be left .addField('Team Size', info.teamsize.toString(), true)
*/ .addField('Players Joined', info.players.length.toString(), true)
async function leaveQueue(interaction) { .setFooter({ text: 'type /join' });
let { member, info } = (0, exports.getAll)(interaction); await interaction.reply({ embeds: [embed], ephemeral: true });
if (!queueContains(interaction)) }
throw (0, util_1.emsg)('You aren\'t in the active queue'); QueueCommands.queue = queue;
info.players.splice(info.players.indexOf(member), 1); /**
clearTimeout(info.timeout); * joins a queue
info.timeout = setQueueTimeout(interaction); * @param interaction
QUEUE.set(interaction.channelId, info); * @throws errorMessage class if it cannot be readied
sendQueueEmbed(interaction); */
await interaction.reply('Left the queue'); async function join(interaction) {
} let { member, info, channel } = getAll(interaction);
exports.leaveQueue = leaveQueue; if (queueContains(interaction))
/** throw (0, util_1.emsg)('You are already in the queue');
* readys a queue from an interaction info.players.push(member);
* @param interaction QUEUE.set(interaction.channelId, info);
* @throws errorMessage class if it cannot be readied await interaction.reply('Joined the queue');
*/ checkQueue(channel);
async function readyQueue(interaction) { }
let { member, info } = (0, exports.getAll)(interaction), { initiator } = info; QueueCommands.join = join;
if (member.id !== initiator.member.id) /**
throw (0, util_1.emsg)('Only the queue initiator can ready the queue'); * leaves a queue
clearQueue(interaction); * @param interaction
if (info.players.filter(m => m.id !== initiator.member.id).length === 0) * @throws errorMessage class if it cannot be reset
throw (0, util_1.emsg)('Nobody signed up for the queue, the queue has been reset'); */
//team data async function leave(interaction) {
let playerlist = (0, util_1.shuffle)(info.players), teams = []; let { member, info } = getAll(interaction);
//fill team data if (!queueContains(interaction))
for (let i = 0; i < playerlist.length; i += info.teamsize) throw (0, util_1.emsg)('You aren\'t in the queue');
teams.push(playerlist.slice(i, i + info.teamsize)); info.players.splice(info.players.indexOf(member), 1);
sendTeamsEmbed(interaction, teams); QUEUE.set(interaction.channelId, info);
} await interaction.reply('Left the queue');
exports.readyQueue = readyQueue; }
/** QueueCommands.leave = leave;
* readys a queue from an interaction })(QueueCommands = exports.QueueCommands || (exports.QueueCommands = {}));
* @param interaction
* @throws errorMessage class if it cannot be reset
*/
async function cancelQueue(interaction) {
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;

12
dist/util.js vendored
View File

@@ -1,6 +1,6 @@
"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");
/** /**
* shuffles an array * shuffles an array
@@ -64,3 +64,13 @@ function getChannel(interaction) {
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)('Member is not a moderator');
}
exports.memberIsModThrow = memberIsModThrow;

6
package-lock.json generated
View File

@@ -1,21 +1,21 @@
{ {
"name": "1800queue-alt", "name": "1800queue",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "1800queue-alt", "name": "1800queue",
"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.13", "@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"

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",
@@ -33,12 +33,12 @@
"@types/node": "^17.0.13", "@types/node": "^17.0.13",
"npm-watch": "^0.11.0", "npm-watch": "^0.11.0",
"ts-node": "^10.4.0", "ts-node": "^10.4.0",
"discord-api-types": "^0.26.1",
"typescript": "^4.5.5" "typescript": "^4.5.5"
}, },
"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

@@ -4,18 +4,27 @@ 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'
@@ -25,12 +34,8 @@ const commands = [
description: 'leave the active queue' description: 'leave the active queue'
}, },
{ {
name: 'ready', name: 'stop',
description: 'ready the queue and display team info' description: 'stops the current queue (must have the Manage Messages permission)'
},
{
name: 'cancel',
description: 'cancels the current queue (must have the Manage Messages permission)'
}, },
{ {
name: 'player', name: 'player',
@@ -44,7 +49,8 @@ const commands = [
} }
] ]
} }
]; ],
commandNames = commands.map(c => c.name);
/** /**
* register/reload commands on guild(s) * register/reload commands on guild(s)

View File

@@ -3,7 +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 { 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] });
@@ -11,18 +11,19 @@ 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('Missing Discord Token, please enter the bot token into the token file');
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(`Logged in as ${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('interactionCreate', async interaction => { CLIENT.on('interactionCreate', async interaction => {
@@ -30,18 +31,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) {

View File

@@ -1,236 +1,266 @@
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, GuildMember, MessageEmbed, TextChannel } from "discord.js";
* get the queueInfo of an interaction import * as fs from 'fs';
* @param interaction import { emsg, getChannel, getMember, memberIsModThrow, queueInfo, queueInfoBase } from "./util";
* @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)
throw emsg('There is not an active queue in this channel, type `/queue` to create one'); return;
if (info.players.length >= info.teamsize) {
let team = info.players.splice(0, info.teamsize).map(m => m.toString());
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) {
* 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 }
*/ }
export const getAll = (interaction: CommandInteraction) => ({
member: getMember(interaction),
channel: getChannel(interaction),
info: getInfo(interaction)
});
/** export function remove(channelId: string) {
* checks if the interaction data is already in the queue if (QUEUE.has(channelId)) {
* @param interaction QUEUE.delete(channelId);
* @returns boolean SaveQueue();
*/ }
export function queueContains(interaction: CommandInteraction): boolean { }
let {member, info} = getAll(interaction); export function addPlayer(channelId: string, member: GuildMember) {
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
}
}
if (info.players.map(m=>m.id).includes(member.id)) export function removePlayer(channelId: string, member: GuildMember) {
return true; if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
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;
let embed = new MessageEmbed() for (let channelId in QUEUE.keys()) {
.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) let info = QUEUE.get(channelId),
await origInteraction.editReply({embeds: [embed]}); channel = await client.channels.fetch(channelId);
else
await origInteraction.reply({embeds: [embed]});
}
/** if (!info) { //no idea what could cause this but TS complains
* sends the list of teams Queue.remove(channelId);
* @param interaction continue;
*/ }
async function sendTeamsEmbed(interaction: CommandInteraction, teams: GuildMember[][]) {
let embed = new MessageEmbed()
.setTitle('Teams');
teams.forEach((team, i) => { if (!channel || !(channel instanceof TextChannel)) {
team.map(m => m.user.tag); console.error(`Unable to find channel ${channelId} for teams of ${info?.teamsize}`);
embed.addField(`Team ${i+1}`, team.join('\n')) Queue.remove(channelId);
}); continue;
}
interaction.reply({embeds: [embed]}); channel.send('The bot has just restarted and anybody in the queues have been reset')
}
/** }
* 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 {
/** /**
* joins a queue from an interaction * get the queueInfo of an interaction
* @param interaction * @param interaction
* @throws errorMessage class if it cannot be joined * @throws errorMessage class if it does not exist
*/ * @returns queue info
export async function joinQueue(interaction: CommandInteraction) { */
function getInfo(interaction: CommandInteraction): queueInfo {
let info = QUEUE.get(interaction.channelId);
let {member, info} = getAll(interaction); if (!info)
throw emsg('There is not an active queue in this channel, type `/queue` to create one');
if (queueContains(interaction)) return info;
throw emsg('You are already in the active queue'); }
info.players.push(member); /**
clearTimeout(info.timeout); * compiles all the get functions above
info.timeout = setQueueTimeout(interaction) * @param 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 {
sendQueueEmbed(interaction); let {member, info} = getAll(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
*/ /**
export async function leaveQueue(interaction: CommandInteraction) { * creates a queue from an interaction
* @param interaction
let {member, info} = getAll(interaction); * @throws errorMessage class if it cannot be left
*/
if (!queueContains(interaction)) export function queueCreate(interaction: CommandInteraction) {
throw emsg('You aren\'t in the active queue'); memberIsModThrow(interaction);
info.players.splice(info.players.indexOf(member), 1); let {channelId} = interaction,
clearTimeout(info.timeout); teamsize = interaction.options.getInteger('teamsize', true);
info.timeout = setQueueTimeout(interaction)
if (QUEUE.has(channelId))
QUEUE.set(interaction.channelId, info); throw emsg(`There is already an active queue in this channel for teams of ${QUEUE.get(channelId)?.teamsize}`);
sendQueueEmbed(interaction); Queue.create(channelId, teamsize);
await interaction.reply('Left the queue');
interaction.reply(`A queue for teams of ${teamsize} has been started`)
}
}
/**
* readys a queue from an interaction /**
* @param interaction * opens a queue
* @throws errorMessage class if it cannot be readied * @param interaction
*/ * @throws errorMessage class if it cannot be left
export async function readyQueue(interaction: CommandInteraction) { */
export async function open(interaction: CommandInteraction) {
let {member, info} = getAll(interaction),
{initiator} = info; queueCreate(interaction);
if (member.id !== initiator.member.id) }
throw emsg('Only the queue initiator can ready the queue');
/**
clearQueue(interaction); * closes a queue
* @param interaction
if (info.players.filter(m => m.id !== initiator.member.id).length === 0) * @throws errorMessage class if it cannot be joined
throw emsg('Nobody signed up for the queue, the queue has been reset'); */
export async function close(interaction: CommandInteraction) {
//team data memberIsModThrow(interaction);
let playerlist: GuildMember[] = shuffle(info.players),
teams: GuildMember[][] = []; QUEUE.delete(interaction.channelId);
//fill team data await interaction.reply('Queue has been reset');
for (let i = 0; i < playerlist.length; i+= info.teamsize)
teams.push(playerlist.slice(i, i+info.teamsize)); }
sendTeamsEmbed(interaction, teams); /**
* gives info about the queue
} * @param interaction
* @throws errorMessage class if it cannot be left
/** */
* readys a queue from an interaction export async function queue(interaction: CommandInteraction) {
* @param interaction
* @throws errorMessage class if it cannot be reset let info = getInfo(interaction);
*/
export async function cancelQueue(interaction: CommandInteraction) { let embed = new MessageEmbed()
.setTitle('Active Queue')
let {info, member, channel} = getAll(interaction); .addField('Team Size', info.teamsize.toString(), true)
.addField('Players Joined', info.players.length.toString(), true)
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES')) .setFooter({text: 'type /join'});
throw emsg('You do not have permission to run this command');
await interaction.reply({embeds: [embed], ephemeral: true});
clearQueue(interaction);
}
await interaction.reply('Queue has been reset');
/**
* 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('You are already in the queue');
info.players.push(member);
QUEUE.set(interaction.channelId, info);
await interaction.reply('Joined the queue');
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('You aren\'t in the queue');
info.players.splice(info.players.indexOf(member), 1);
QUEUE.set(interaction.channelId, info);
await interaction.reply('Left the queue');
}
} }

View File

@@ -46,14 +46,11 @@ export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage
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
} }
/** /**
@@ -85,3 +82,14 @@ export function getChannel(interaction: CommandInteraction): TextChannel {
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('Member is not a moderator');
}