Compare commits

..

1 Commits

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

3
.gitignore vendored
View File

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

View File

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

4
package-lock.json generated
View File

@@ -1,11 +1,11 @@
{ {
"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": {

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",

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

@@ -5,12 +5,13 @@ import { Routes } from 'discord-api-types/v9';
const commands = [ const commands = [
{ {
name: 'queue', name: 'queue',
description: 'get queue info or initialize 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',
required: true,
min_value: 1 min_value: 1
} }
] ]
@@ -24,8 +25,12 @@ const commands = [
description: 'leave the active queue' description: 'leave the active queue'
}, },
{ {
name: 'stop', name: 'ready',
description: 'stops the current queue (must have the Manage Messages permission)' 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',

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 { discordInit, QueueCommands } from './queue'; import { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } 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,8 +11,8 @@ 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('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);
} }
@@ -23,7 +23,6 @@ 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 => {
@@ -32,13 +31,15 @@ CLIENT.on('interactionCreate', async interaction => {
try { try {
if (interaction.commandName === 'queue') if (interaction.commandName === 'queue')
await QueueCommands.queue(interaction); await createQueue(interaction);
else if (interaction.commandName === 'join') else if (interaction.commandName === 'join')
await QueueCommands.join(interaction); await joinQueue(interaction);
else if (interaction.commandName === 'leave') else if (interaction.commandName === 'leave')
await QueueCommands.leave(interaction); await leaveQueue(interaction);
else if (interaction.commandName === 'stop') else if (interaction.commandName === 'ready')
await QueueCommands.stop(interaction); await readyQueue(interaction);
else if (interaction.commandName === 'cancel')
await cancelQueue(interaction);
else if (interaction.commandName === 'player') else if (interaction.commandName === 'player')
await getPlayerInteraction(interaction); await getPlayerInteraction(interaction);

View File

@@ -1,262 +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, GuildMember, 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
* @throws errorMessage class if it does not exist
//load queues from file * @returns queue info
if (!fs.existsSync('./queues')) */
fs.writeFileSync('./queues', '{}'); export function getInfo(interaction: CommandInteraction): queueInfo {
let info = QUEUE.get(interaction.channelId);
const _QUEUE = fs.readFileSync('./queues').toString(),
QUEUE = new Map<string, queueInfo>();
try {
let queueJson = JSON.parse(_QUEUE);
for (let channelId of 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 in 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());
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 {
export function addPlayer(channelId: string, member: GuildMember) { let {member, info} = getAll(interaction);
if (QUEUE.has(channelId)) {
QUEUE.delete(channelId);
}
}
export function removePlayer(channelId: string, member: GuildMember) { if (info.players.map(m=>m.id).includes(member.id))
if (QUEUE.has(channelId)) { return true;
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;
for (let channelId in 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(`Unable to find channel ${channelId} for teams of ${info?.teamsize}`); team.map(m => m.user.tag);
Queue.remove(channelId); embed.addField(`Team ${i+1}`, team.join('\n'))
continue; });
}
channel.send('The bot has just restarted and anybody in the queues have been reset') 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('There is not an active queue in this channel, type `/queue` to create one');
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)
if (QUEUE.has(channelId))
throw emsg(`There is already an active queue in this channel for teams of ${QUEUE.get(channelId)?.teamsize}`); QUEUE.set(interaction.channelId, info);
Queue.create(channelId, teamsize); sendQueueEmbed(interaction);
await interaction.reply('Left the queue');
interaction.reply(`A queue for teams of ${teamsize} has been started`)
}
}
/**
/** * readys a queue from an interaction
* creates a queue from an interaction * @param interaction
* @param interaction * @throws errorMessage class if it cannot be readied
* @throws errorMessage class if it cannot be left */
*/ export async function readyQueue(interaction: CommandInteraction) {
export async function queue(interaction: CommandInteraction) {
let {member, info} = getAll(interaction),
let teamsize = interaction.options.getInteger('teamsize'); {initiator} = info;
if (teamsize) { if (member.id !== initiator.member.id)
queueCreate(interaction); throw emsg('Only the queue initiator can ready the queue');
return;
} clearQueue(interaction);
let info = getInfo(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');
let embed = new MessageEmbed()
.setTitle('Active Queue') //team data
.addField('Team Size', info.teamsize.toString(), true) let playerlist: GuildMember[] = shuffle(info.players),
.addField('Players Joined', info.players.length.toString(), true) teams: GuildMember[][] = [];
.setFooter({text: 'type /join'});
//fill team data
await interaction.reply({embeds: [embed], ephemeral: true}); for (let i = 0; i < playerlist.length; i+= info.teamsize)
teams.push(playerlist.slice(i, i+info.teamsize));
}
sendTeamsEmbed(interaction, teams);
/**
* stops a queue from an interaction }
* @param interaction
* @throws errorMessage class if it cannot be joined /**
*/ * readys a queue from an interaction
export async function stop(interaction: CommandInteraction) { * @param interaction
memberIsModThrow(interaction); * @throws errorMessage class if it cannot be reset
*/
QUEUE.delete(interaction.channelId); export async function cancelQueue(interaction: CommandInteraction) {
await interaction.reply('Queue has been reset'); let {info, member, channel} = getAll(interaction);
} if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
throw emsg('You do not have permission to run this command');
/**
* joins a queue from an interaction clearQueue(interaction);
* @param interaction
* @throws errorMessage class if it cannot be readied await interaction.reply('Queue has been reset');
*/
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 from an interaction
* @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,11 +46,14 @@ export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage
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
} }
/** /**
@@ -82,14 +85,3 @@ 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');
}