Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ad4f69f9f |
@@ -1,56 +0,0 @@
|
|||||||
{
|
|
||||||
"root": true,
|
|
||||||
"extends": [
|
|
||||||
"eslint:recommended",
|
|
||||||
"plugin:@typescript-eslint/recommended"
|
|
||||||
],
|
|
||||||
"parser": "@typescript-eslint/parser",
|
|
||||||
"parserOptions": { "project": ["./tsconfig.eslint.json"] },
|
|
||||||
"plugins": [
|
|
||||||
"@typescript-eslint"
|
|
||||||
],
|
|
||||||
"rules": {
|
|
||||||
"@typescript-eslint/strict-boolean-expressions": [
|
|
||||||
2,
|
|
||||||
{
|
|
||||||
"allowString" : false,
|
|
||||||
"allowNumber" : false
|
|
||||||
}
|
|
||||||
],
|
|
||||||
|
|
||||||
/* important */
|
|
||||||
"prefer-const": "error",
|
|
||||||
"quotes": ["error", "single"],
|
|
||||||
|
|
||||||
"block-scoped-var": "error",
|
|
||||||
"camelcase": "error",
|
|
||||||
"consistent-this": ["error", "that"],
|
|
||||||
"no-else-return": "error",
|
|
||||||
"no-eq-null": "error",
|
|
||||||
"no-floating-decimal": "error",
|
|
||||||
"no-implicit-coercion": "error",
|
|
||||||
"no-implied-eval": "error",
|
|
||||||
"no-invalid-this": "error",
|
|
||||||
"require-await": "error",
|
|
||||||
"yoda": "error",
|
|
||||||
|
|
||||||
"semi": ["error", "always"],
|
|
||||||
"semi-style": ["error", "last"],
|
|
||||||
|
|
||||||
/* less important */
|
|
||||||
"no-unreachable-loop": "error",
|
|
||||||
"no-unused-private-class-members": "error",
|
|
||||||
"no-use-before-define": "error",
|
|
||||||
"no-unmodified-loop-condition": "error",
|
|
||||||
"no-duplicate-imports": "error",
|
|
||||||
"no-promise-executor-return": "error",
|
|
||||||
"no-self-compare": "error",
|
|
||||||
"no-constructor-return": "error",
|
|
||||||
"no-template-curly-in-string": "error",
|
|
||||||
"array-callback-return": "error",
|
|
||||||
"no-eval": "error",
|
|
||||||
"no-extend-native": "error",
|
|
||||||
"no-extra-bind": "error"
|
|
||||||
},
|
|
||||||
"ignorePatterns": ["src/**/*.test.ts", "src/frontend/generated/*"]
|
|
||||||
}
|
|
||||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,6 +1,4 @@
|
|||||||
.DS_Store
|
|
||||||
.vscode
|
|
||||||
log
|
|
||||||
node_modules
|
node_modules
|
||||||
queues.json
|
token
|
||||||
token.txt
|
.DS_Store
|
||||||
|
log
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -44,8 +46,6 @@ Download and install [Node.js](https://nodejs.org/en/)
|
|||||||
|
|
||||||
## Starting
|
## Starting
|
||||||
|
|
||||||
**Important**: the bot's invite needs permission to `Create Commands` and `Send Messages`
|
|
||||||
|
|
||||||
1. Open the `scripts` folder
|
1. Open the `scripts` folder
|
||||||
2. Open the folder that corresponds with your operating system
|
2. Open the folder that corresponds with your operating system
|
||||||
3. Run the `start` file
|
3. Run the `start` file
|
||||||
|
|||||||
98
dist/api.js
vendored
98
dist/api.js
vendored
@@ -23,11 +23,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|||||||
};
|
};
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.getPlayerInteraction = exports.getPlayer = void 0;
|
exports.getPlayerInteraction = exports.getPlayer = void 0;
|
||||||
/*eslint prefer-const: "error"*/
|
|
||||||
const cheerio = __importStar(require("cheerio"));
|
const cheerio = __importStar(require("cheerio"));
|
||||||
|
const discord_js_1 = require("discord.js");
|
||||||
const https_1 = __importDefault(require("https"));
|
const https_1 = __importDefault(require("https"));
|
||||||
const main_1 = require("./util/main");
|
const util_1 = require("./util");
|
||||||
const Lang = __importStar(require("./lang"));
|
|
||||||
const uniteApiRegex = {
|
const uniteApiRegex = {
|
||||||
//$1 = name, $2 = id
|
//$1 = name, $2 = id
|
||||||
ogtitle: /unite api - (.+) \((.*)\)/i,
|
ogtitle: /unite api - (.+) \((.*)\)/i,
|
||||||
@@ -74,25 +73,25 @@ function getHTML(name) {
|
|||||||
* @throws errorMessage class if the request fails
|
* @throws errorMessage class if the request fails
|
||||||
*/
|
*/
|
||||||
function readHTML(html) {
|
function readHTML(html) {
|
||||||
const $ = cheerio.load(html), foundData = {
|
let $ = cheerio.load(html);
|
||||||
name: '',
|
let metaElems = $('meta').toArray(), foundData = {
|
||||||
id: '',
|
name: "",
|
||||||
avatar: '',
|
id: "",
|
||||||
level: '',
|
avatar: "",
|
||||||
rank: '',
|
level: "",
|
||||||
|
rank: "",
|
||||||
elo: null,
|
elo: null,
|
||||||
class: null,
|
class: null,
|
||||||
battles: '',
|
battles: "",
|
||||||
wins: '',
|
wins: "",
|
||||||
winrate: ''
|
winrate: ""
|
||||||
};
|
};
|
||||||
let metaElems = $('meta').toArray();
|
|
||||||
//filter down to just ones named "og:..."
|
//filter down to just ones named "og:..."
|
||||||
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
|
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
|
||||||
metaElems.forEach(el => {
|
metaElems.forEach(el => {
|
||||||
const attr = el.attribs;
|
let attr = el.attribs;
|
||||||
if (attr.property === 'og:title') {
|
if (attr.property === 'og:title') {
|
||||||
const data = uniteApiRegex.ogtitle.exec(attr.content);
|
let data = uniteApiRegex.ogtitle.exec(attr.content);
|
||||||
if (data !== null && data.length >= 3) {
|
if (data !== null && data.length >= 3) {
|
||||||
foundData.name = data[1];
|
foundData.name = data[1];
|
||||||
foundData.id = data[2];
|
foundData.id = data[2];
|
||||||
@@ -100,16 +99,15 @@ function readHTML(html) {
|
|||||||
}
|
}
|
||||||
else if (attr.property === 'og:description') {
|
else if (attr.property === 'og:description') {
|
||||||
//all lines
|
//all lines
|
||||||
let lines = attr.content.split('\n').map(l => l.trim());
|
let lines = attr.content.split('\n').map(l => l.trim()), extraLines = [];
|
||||||
const extraLines = [];
|
|
||||||
//ensure first line is correct
|
//ensure first line is correct
|
||||||
while ((lines.length > 0) && !/pok.mon unite/i.test(lines[0])) {
|
while (lines.length && !/pok.mon unite/i.test(lines[0])) {
|
||||||
const line = lines.shift();
|
let line = lines.shift();
|
||||||
if (line !== undefined)
|
if (line)
|
||||||
extraLines.push(line);
|
extraLines.push(line);
|
||||||
}
|
}
|
||||||
if (lines.length === 0)
|
if (!lines.length)
|
||||||
throw (0, main_1.emsg)('Unable to read data, please try again');
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
//bring the first lines removed back into the data
|
//bring the first lines removed back into the data
|
||||||
lines = [
|
lines = [
|
||||||
...lines,
|
...lines,
|
||||||
@@ -118,19 +116,20 @@ function readHTML(html) {
|
|||||||
//first line
|
//first line
|
||||||
{
|
{
|
||||||
//will be only text after "pokemon unite:"
|
//will be only text after "pokemon unite:"
|
||||||
const line = lines[0].split(':').slice(1).join(':').trim(), regex = uniteApiRegex.ogdescription;
|
let line = lines[0].split(':').slice(1).join(':').trim();
|
||||||
|
let regex = uniteApiRegex.ogdescription;
|
||||||
if (regex[0].test(line)) { //is master/has elo
|
if (regex[0].test(line)) { //is master/has elo
|
||||||
const regexData = line.match(regex[0]);
|
let regexData = line.match(regex[0]);
|
||||||
if (!regexData || regexData.length < 4)
|
if (!regexData || regexData.length < 4)
|
||||||
throw (0, main_1.emsg)('Unable to read data, please try again');
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
foundData.level = regexData[1];
|
foundData.level = regexData[1];
|
||||||
foundData.rank = regexData[2];
|
foundData.rank = regexData[2];
|
||||||
foundData.elo = regexData[3];
|
foundData.elo = regexData[3];
|
||||||
}
|
}
|
||||||
else { //is not master/has a class
|
else { //is not master/has a class
|
||||||
const regexData = line.match(regex[1]);
|
let regexData = line.match(regex[1]);
|
||||||
if (!regexData || regexData.length < 4)
|
if (!regexData || regexData.length < 4)
|
||||||
throw (0, main_1.emsg)('Unable to read data, please try again');
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
foundData.level = regexData[1];
|
foundData.level = regexData[1];
|
||||||
foundData.rank = regexData[2];
|
foundData.rank = regexData[2];
|
||||||
foundData.class = regexData[3];
|
foundData.class = regexData[3];
|
||||||
@@ -139,7 +138,7 @@ function readHTML(html) {
|
|||||||
lines.shift();
|
lines.shift();
|
||||||
//rest of lines
|
//rest of lines
|
||||||
lines.forEach(line => {
|
lines.forEach(line => {
|
||||||
const split = line.split(':').map(l => l.trim()), key = split[0].toLowerCase().replace(/[^\w]/g, ''), value = split[1];
|
let split = line.split(':').map(l => l.trim()), key = split[0].toLowerCase().replace(/[^\w]/g, ''), value = split[1];
|
||||||
switch (key) {
|
switch (key) {
|
||||||
case 'battles':
|
case 'battles':
|
||||||
foundData.battles = value;
|
foundData.battles = value;
|
||||||
@@ -154,8 +153,7 @@ function readHTML(html) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const imgSrc = $('.player-card-image img').attr('src');
|
foundData.avatar = $('.player-card-image img').attr('src') || "";
|
||||||
foundData.avatar = imgSrc !== undefined ? imgSrc : '';
|
|
||||||
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
||||||
return foundData;
|
return foundData;
|
||||||
}
|
}
|
||||||
@@ -165,7 +163,7 @@ function readHTML(html) {
|
|||||||
* @returns boolean, valid or invalid
|
* @returns boolean, valid or invalid
|
||||||
*/
|
*/
|
||||||
function verifyData(data) {
|
function verifyData(data) {
|
||||||
if (data.id.length > 0)
|
if (data.id.length)
|
||||||
return true;
|
return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -175,30 +173,26 @@ function verifyData(data) {
|
|||||||
* @returns player data
|
* @returns player data
|
||||||
*/
|
*/
|
||||||
async function getPlayer(name) {
|
async function getPlayer(name) {
|
||||||
const html = await getHTML(name), data = readHTML(html);
|
let html = await getHTML(name);
|
||||||
|
let data = readHTML(html);
|
||||||
if (verifyData(data))
|
if (verifyData(data))
|
||||||
return data;
|
return data;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
exports.getPlayer = getPlayer;
|
exports.getPlayer = getPlayer;
|
||||||
async function sendPlayerEmbed(interaction, data) {
|
async function sendPlayerEmbed(interaction, data) {
|
||||||
let eloStr;
|
let embed = new discord_js_1.MessageEmbed()
|
||||||
if (data.elo !== null)
|
.setTitle(`${data.name} (${data.id})`)
|
||||||
eloStr = `(${data.elo})`;
|
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
|
||||||
else
|
.setTimestamp()
|
||||||
eloStr = `Class ${data.class}`;
|
.setThumbnail(data.avatar)
|
||||||
await interaction.editReply(Lang.getEmbed('api.player', {
|
.setDescription(`Level ${data.level}
|
||||||
name: data.name,
|
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
|
||||||
id: data.id,
|
|
||||||
nameEncoded: encodeURIComponent(data.name),
|
**Battles** ${data.battles}
|
||||||
avatar: data.avatar,
|
**Wins** ${data.wins}
|
||||||
level: data.level,
|
**Win Rate** ${data.winrate}`);
|
||||||
rank: data.rank,
|
await interaction.editReply({ embeds: [embed] });
|
||||||
elo: eloStr,
|
|
||||||
battles: data.battles,
|
|
||||||
wins: data.wins,
|
|
||||||
winrate: data.winrate
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* calls getPlayer() with the name from the interaction
|
* calls getPlayer() with the name from the interaction
|
||||||
@@ -206,11 +200,11 @@ async function sendPlayerEmbed(interaction, data) {
|
|||||||
* @throws errorMessage class if the user cannot be found
|
* @throws errorMessage class if the user cannot be found
|
||||||
*/
|
*/
|
||||||
async function getPlayerInteraction(interaction) {
|
async function getPlayerInteraction(interaction) {
|
||||||
const username = interaction.options.getString('username', true);
|
let username = interaction.options.getString('username', true);
|
||||||
await interaction.deferReply();
|
await interaction.deferReply();
|
||||||
const data = await getPlayer(username);
|
let data = await getPlayer(username);
|
||||||
if (data === null)
|
if (data === null)
|
||||||
throw (0, main_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
27
dist/discord.js
vendored
@@ -1,32 +1,23 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.registerCommands = void 0;
|
exports.registerCommands = void 0;
|
||||||
/* eslint-disable camelcase */
|
|
||||||
const rest_1 = require("@discordjs/rest");
|
const rest_1 = require("@discordjs/rest");
|
||||||
const v9_1 = require("discord-api-types/v9");
|
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'
|
||||||
@@ -35,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',
|
||||||
@@ -48,7 +47,6 @@ 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
|
||||||
@@ -62,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);
|
||||||
|
|||||||
54
dist/main.js → dist/index.js
vendored
54
dist/main.js → dist/index.js
vendored
@@ -23,60 +23,42 @@ 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 = __importStar(require("./lang"));
|
|
||||||
const queue_1 = require("./queue");
|
const queue_1 = require("./queue");
|
||||||
const main_1 = require("./util/main");
|
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.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 => (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;
|
|
||||||
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);
|
await (0, api_1.getPlayerInteraction)(interaction);
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
if (e instanceof main_1.errorMessage) {
|
if (e instanceof util_1.errorMessage) {
|
||||||
if (interaction.deferred || interaction.replied)
|
if (interaction.deferred || interaction.replied)
|
||||||
interaction.editReply(e.msg);
|
interaction.editReply(e.msg);
|
||||||
else
|
else
|
||||||
146
dist/lang.js
vendored
146
dist/lang.js
vendored
@@ -1,146 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.getEmbed = exports.get = exports.setLang = void 0;
|
|
||||||
const lang_1 = require("./util/lang");
|
|
||||||
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',
|
|
||||||
team: {
|
|
||||||
embed: true,
|
|
||||||
title: 'Team',
|
|
||||||
description: '{team}'
|
|
||||||
},
|
|
||||||
queue: {
|
|
||||||
embed: true,
|
|
||||||
title: 'Active Queue',
|
|
||||||
fields: [
|
|
||||||
{
|
|
||||||
name: 'Team Size',
|
|
||||||
value: '{teamsize}'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Players Joined',
|
|
||||||
value: '{playercount}'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
footer: 'type `/join`'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
api: {
|
|
||||||
player: {
|
|
||||||
embed: true,
|
|
||||||
title: '{name} ({id})',
|
|
||||||
url: 'https://uniteapi.dev/p/{nameEncoded}',
|
|
||||||
timestamp: true,
|
|
||||||
thumbnail: '{avatar}',
|
|
||||||
description: [
|
|
||||||
'Level {level}',
|
|
||||||
'{rank} {elo}',
|
|
||||||
'',
|
|
||||||
'**Battles** {battles}',
|
|
||||||
'**Wins** {wins}',
|
|
||||||
'**Win Rate** {winrate}'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
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'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
/* MAIN */
|
|
||||||
let 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';
|
|
||||||
}
|
|
||||||
exports.setLang = setLang;
|
|
||||||
/**
|
|
||||||
* reads language json (just strings)
|
|
||||||
* @param id ex: discord.error.noActiveQueue
|
|
||||||
* @param args list of key/value pairs to represent template values
|
|
||||||
* @returns language value, defaults to `id` parameter
|
|
||||||
*/
|
|
||||||
function get(id, args = {}) {
|
|
||||||
const keySpl = id.split('.').map(k => k.trim()).filter(k => k);
|
|
||||||
let finding = LANG[LANGID];
|
|
||||||
for (const key of keySpl) {
|
|
||||||
if (key in finding) {
|
|
||||||
const found = finding[key];
|
|
||||||
if (typeof found === 'string')
|
|
||||||
return (0, lang_1.template)(found, args);
|
|
||||||
if (found.embed === true)
|
|
||||||
return (0, lang_1.embedObjStr)(found, args, id);
|
|
||||||
finding = found;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
exports.get = get;
|
|
||||||
/**
|
|
||||||
* reads language json as an object (could be embed or just string)
|
|
||||||
* @param id ex: discord.error.noActiveQueue
|
|
||||||
* @param args list of key/value pairs to represent template values
|
|
||||||
* @param otherOptions values to be passed through to the return value
|
|
||||||
* @returns language value, defaults to `id` parameter
|
|
||||||
*/
|
|
||||||
function getEmbed(id, args = {}, otherOptions = {}) {
|
|
||||||
const embedData = {
|
|
||||||
...otherOptions,
|
|
||||||
embeds: []
|
|
||||||
};
|
|
||||||
const keySpl = id.split('.').map(k => k.trim()).filter(k => k);
|
|
||||||
let finding = LANG[LANGID];
|
|
||||||
for (const key of keySpl) {
|
|
||||||
if (key in finding) {
|
|
||||||
const found = finding[key];
|
|
||||||
if (typeof found === 'string') {
|
|
||||||
embedData.content = (0, lang_1.template)(found, args);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (found.embed === true) {
|
|
||||||
const embedObj = found, { content } = embedObj, embed = (0, lang_1.embedObjEmbed)(embedObj, args);
|
|
||||||
embedData.embeds.push(embed);
|
|
||||||
if (content !== undefined)
|
|
||||||
embedData.content = content;
|
|
||||||
return embedData;
|
|
||||||
}
|
|
||||||
finding = found;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return embedData;
|
|
||||||
}
|
|
||||||
exports.getEmbed = getEmbed;
|
|
||||||
281
dist/queue.js
vendored
281
dist/queue.js
vendored
@@ -1,98 +1,10 @@
|
|||||||
"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.queueContains = exports.discordInit = exports.queueRemove = exports.queueCreate = 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 Lang = __importStar(require("./lang"));
|
//maps ChannelID to QueueInfo
|
||||||
const discord_1 = require("./util/discord");
|
const QUEUE = new Map();
|
||||||
const main_1 = require("./util/main");
|
|
||||||
//load queues from file`
|
|
||||||
if (!fs.existsSync('./queues.json'))
|
|
||||||
fs.writeFileSync('./queues.json', '{}');
|
|
||||||
const _QUEUE = fs.readFileSync('./queues.json').toString(), QUEUE = new Map();
|
|
||||||
try {
|
|
||||||
const queueJson = JSON.parse(_QUEUE);
|
|
||||||
for (const channelId in queueJson) {
|
|
||||||
const { teamsize } = queueJson[channelId];
|
|
||||||
if (teamsize !== 0)
|
|
||||||
QUEUE.set(channelId, { teamsize, players: [] });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
//do nothing
|
|
||||||
}
|
|
||||||
function SaveQueue() {
|
|
||||||
const queueJson = Object.fromEntries(QUEUE), queueFileJson = {};
|
|
||||||
for (const channelId of QUEUE.keys())
|
|
||||||
queueFileJson[channelId] = { teamsize: queueJson[channelId].teamsize };
|
|
||||||
fs.writeFileSync('./queues.json', JSON.stringify(queueFileJson, null, 2));
|
|
||||||
}
|
|
||||||
async function checkQueue(channel) {
|
|
||||||
const info = QUEUE.get(channel.id);
|
|
||||||
if (!info)
|
|
||||||
return;
|
|
||||||
if (info.players.length >= info.teamsize) {
|
|
||||||
const team = info.players.splice(0, info.teamsize).map(m => m.toString());
|
|
||||||
await channel.send(Lang.getEmbed('discord.team', { team: team.join('\n') }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function queueCreate(channelId, teamsize) {
|
|
||||||
if (!QUEUE.has(channelId)) {
|
|
||||||
QUEUE.set(channelId, { teamsize, players: [] });
|
|
||||||
SaveQueue();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.queueCreate = queueCreate;
|
|
||||||
function queueRemove(channelId) {
|
|
||||||
if (QUEUE.has(channelId)) {
|
|
||||||
QUEUE.delete(channelId);
|
|
||||||
SaveQueue();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.queueRemove = queueRemove;
|
|
||||||
SaveQueue();
|
|
||||||
async function discordInit(client) {
|
|
||||||
for (const channelId of QUEUE.keys()) {
|
|
||||||
const info = QUEUE.get(channelId), channel = await client.channels.fetch(channelId);
|
|
||||||
if (!info) {
|
|
||||||
queueRemove(channelId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!channel || !(channel instanceof discord_js_1.TextChannel)) {
|
|
||||||
console.error(Lang.get('error.discord.noChannel'), {
|
|
||||||
channelId,
|
|
||||||
teamsize: info.teamsize
|
|
||||||
});
|
|
||||||
queueRemove(channelId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
channel.send(Lang.get('discord.botRestart'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.discordInit = discordInit;
|
|
||||||
/**
|
/**
|
||||||
* get the queueInfo of an interaction
|
* get the queueInfo of an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
@@ -100,11 +12,12 @@ exports.discordInit = discordInit;
|
|||||||
* @returns queue info
|
* @returns queue info
|
||||||
*/
|
*/
|
||||||
function getInfo(interaction) {
|
function getInfo(interaction) {
|
||||||
const info = QUEUE.get(interaction.channelId);
|
let info = QUEUE.get(interaction.channelId);
|
||||||
if (!info)
|
if (!info)
|
||||||
throw (0, main_1.emsg)('discord.noQueue');
|
throw (0, util_1.emsg)('There is not an active queue in this channel, type `/queue` to create one');
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
exports.getInfo = getInfo;
|
||||||
/**
|
/**
|
||||||
* compiles all the get functions above
|
* compiles all the get functions above
|
||||||
* @param interaction
|
* @param interaction
|
||||||
@@ -112,95 +25,165 @@ function getInfo(interaction) {
|
|||||||
* @returns object containing each
|
* @returns object containing each
|
||||||
*/
|
*/
|
||||||
const getAll = (interaction) => ({
|
const getAll = (interaction) => ({
|
||||||
member: (0, discord_1.getMember)(interaction),
|
member: (0, util_1.getMember)(interaction),
|
||||||
channel: (0, discord_1.getChannel)(interaction),
|
channel: (0, util_1.getChannel)(interaction),
|
||||||
info: getInfo(interaction)
|
info: getInfo(interaction)
|
||||||
});
|
});
|
||||||
|
exports.getAll = getAll;
|
||||||
/**
|
/**
|
||||||
* checks if the interaction data is already in the queue
|
* checks if the interaction data is already in the queue
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @returns boolean
|
* @returns boolean
|
||||||
*/
|
*/
|
||||||
function queueContains(interaction) {
|
function queueContains(interaction) {
|
||||||
const { member, info } = getAll(interaction);
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
if (info.players.map(m => m.id).includes(member.id))
|
if (info.players.map(m => m.id).includes(member.id))
|
||||||
return true;
|
return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
exports.queueContains = queueContains;
|
exports.queueContains = queueContains;
|
||||||
/**
|
/**
|
||||||
* opens a queue
|
* creates the timeout for the queue
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be left
|
* @returns time timeout identifier
|
||||||
*/
|
*/
|
||||||
function open(interaction) {
|
function setQueueTimeout(interaction) {
|
||||||
(0, discord_1.memberIsModThrow)(interaction);
|
let channel = (0, util_1.getChannel)(interaction);
|
||||||
const { channelId } = interaction, teamsize = interaction.options.getInteger('teamsize', true);
|
return setTimeout(() => {
|
||||||
const existing = QUEUE.get(channelId);
|
clearQueue(interaction);
|
||||||
if (existing)
|
channel.send('Queue has been reset due to inactivity');
|
||||||
throw (0, main_1.emsg)(Lang.get('error.discord.noCreate', {
|
}, 5 * 60 * 1000); //5 minutes
|
||||||
teamsize: existing.teamsize.toString()
|
|
||||||
}));
|
|
||||||
queueCreate(channelId, teamsize);
|
|
||||||
interaction.reply(Lang.get('discord.create', {
|
|
||||||
teamsize: teamsize.toString()
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* closes a queue
|
* updates the rich embed for the current queue
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function sendQueueEmbed(interaction, closed = false) {
|
||||||
|
let info = getInfo(interaction), origInteraction = info.initiator.interaction;
|
||||||
|
let embed = new discord_js_1.MessageEmbed()
|
||||||
|
.setTitle('Queue')
|
||||||
|
.setAuthor({
|
||||||
|
name: info.initiator.member.displayName,
|
||||||
|
iconURL: info.initiator.member.displayAvatarURL({ dynamic: true })
|
||||||
|
})
|
||||||
|
.addField('Team Size', info.teamsize.toString(), true)
|
||||||
|
.addField('Players Joined', info.players.length.toString(), true)
|
||||||
|
.setFooter({ text: closed ? 'queue is finished' : 'type /join' });
|
||||||
|
if (origInteraction.deferred || origInteraction.replied)
|
||||||
|
await origInteraction.editReply({ embeds: [embed] });
|
||||||
|
else
|
||||||
|
await origInteraction.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function sendTeamsEmbed(interaction, teams) {
|
||||||
|
let embed = new discord_js_1.MessageEmbed()
|
||||||
|
.setTitle('Teams');
|
||||||
|
teams.forEach((team, i) => {
|
||||||
|
team.map(m => m.user.tag);
|
||||||
|
embed.addField(`Title ${i + 1}`, team.join('\n'));
|
||||||
|
});
|
||||||
|
interaction.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function clearQueue(interaction) {
|
||||||
|
let info = getInfo(interaction);
|
||||||
|
sendQueueEmbed(interaction, true);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
QUEUE.delete(interaction.channelId);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* creates a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be created
|
||||||
|
*/
|
||||||
|
async function createQueue(interaction) {
|
||||||
|
let member = (0, util_1.getMember)(interaction), { channelId } = interaction, teamsize = interaction.options.getInteger('teamsize', true);
|
||||||
|
if (QUEUE.has(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'));
|
||||||
|
QUEUE.set(channelId, {
|
||||||
|
players: [
|
||||||
|
member
|
||||||
|
],
|
||||||
|
initiator: {
|
||||||
|
interaction,
|
||||||
|
member
|
||||||
|
},
|
||||||
|
teamsize: teamsize,
|
||||||
|
timeout: setQueueTimeout(interaction)
|
||||||
|
});
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
}
|
||||||
|
exports.createQueue = createQueue;
|
||||||
|
/**
|
||||||
|
* joins a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be joined
|
* @throws errorMessage class if it cannot be joined
|
||||||
*/
|
*/
|
||||||
async function close(interaction) {
|
async function joinQueue(interaction) {
|
||||||
(0, discord_1.memberIsModThrow)(interaction);
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
QUEUE.delete(interaction.channelId);
|
if (queueContains(interaction))
|
||||||
await interaction.reply(Lang.get('discord.close'));
|
throw (0, util_1.emsg)('You are already in the active queue');
|
||||||
|
info.players.push(member);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
info.timeout = setQueueTimeout(interaction);
|
||||||
|
QUEUE.set(interaction.channelId, info);
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
await interaction.reply('Joined the queue');
|
||||||
}
|
}
|
||||||
|
exports.joinQueue = joinQueue;
|
||||||
/**
|
/**
|
||||||
* gives info about the queue
|
* leaves a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be left
|
* @throws errorMessage class if it cannot be left
|
||||||
*/
|
*/
|
||||||
async function queue(interaction) {
|
async function leaveQueue(interaction) {
|
||||||
const info = getInfo(interaction);
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
await interaction.reply(Lang.getEmbed('discord.queue', {
|
if (!queueContains(interaction))
|
||||||
teamsize: info.teamsize.toString(),
|
throw (0, util_1.emsg)('You aren\'t in the active queue');
|
||||||
playercount: info.players.length.toString(),
|
info.players.splice(info.players.indexOf(member), 1);
|
||||||
}, {
|
clearTimeout(info.timeout);
|
||||||
ephemeral: true
|
info.timeout = setQueueTimeout(interaction);
|
||||||
}));
|
QUEUE.set(interaction.channelId, info);
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
await interaction.reply('Left the queue');
|
||||||
}
|
}
|
||||||
|
exports.leaveQueue = leaveQueue;
|
||||||
/**
|
/**
|
||||||
* joins a queue
|
* readys a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be readied
|
* @throws errorMessage class if it cannot be readied
|
||||||
*/
|
*/
|
||||||
async function join(interaction) {
|
async function readyQueue(interaction) {
|
||||||
const { member, info, channel } = getAll(interaction);
|
let { member, info } = (0, exports.getAll)(interaction), { initiator } = info;
|
||||||
if (queueContains(interaction))
|
if (member.id !== initiator.member.id)
|
||||||
throw (0, main_1.emsg)('discord.inQueue');
|
throw (0, util_1.emsg)('Only the queue initiator can ready the queue');
|
||||||
info.players.push(member);
|
clearQueue(interaction);
|
||||||
QUEUE.set(interaction.channelId, info);
|
if (info.players.filter(m => m.id !== initiator.member.id).length === 0)
|
||||||
await interaction.reply(Lang.get('discord.join'));
|
throw (0, util_1.emsg)('Nobody signed up for the queue, the queue has been reset');
|
||||||
checkQueue(channel);
|
//team data
|
||||||
|
let playerlist = (0, util_1.shuffle)(info.players), teams = [];
|
||||||
|
//fill team data
|
||||||
|
for (let i = 0; i < playerlist.length; i += info.teamsize)
|
||||||
|
teams.push(playerlist.slice(i, i + info.teamsize));
|
||||||
|
sendTeamsEmbed(interaction, teams);
|
||||||
}
|
}
|
||||||
|
exports.readyQueue = readyQueue;
|
||||||
/**
|
/**
|
||||||
* leaves a queue
|
* readys a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be reset
|
* @throws errorMessage class if it cannot be reset
|
||||||
*/
|
*/
|
||||||
async function leave(interaction) {
|
async function cancelQueue(interaction) {
|
||||||
const { member, info } = getAll(interaction);
|
let { info, member, channel } = (0, exports.getAll)(interaction);
|
||||||
if (!queueContains(interaction))
|
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
|
||||||
throw (0, main_1.emsg)('discord.notInQueue');
|
throw (0, util_1.emsg)('You do not have permission to run this command');
|
||||||
info.players.splice(info.players.indexOf(member), 1);
|
clearQueue(interaction);
|
||||||
QUEUE.set(interaction.channelId, info);
|
await interaction.reply('Queue has been reset');
|
||||||
await interaction.reply(Lang.get('discord.leave'));
|
|
||||||
}
|
}
|
||||||
exports.QueueCommands = {
|
exports.cancelQueue = cancelQueue;
|
||||||
open,
|
|
||||||
close,
|
|
||||||
queue,
|
|
||||||
join,
|
|
||||||
leave
|
|
||||||
};
|
|
||||||
|
|||||||
43
dist/util.js
vendored
43
dist/util.js
vendored
@@ -1,34 +1,13 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
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.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 = __importStar(require("./lang"));
|
|
||||||
/**
|
/**
|
||||||
* shuffles an array
|
* shuffles an array
|
||||||
* https://stackoverflow.com/a/2450976/2856416
|
* https://stackoverflow.com/a/2450976/2856416
|
||||||
* @param array an array
|
* @param array an array
|
||||||
* @returns an array but shuffled
|
* @returns an array but shuffled
|
||||||
*/
|
*/
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
function shuffle(array) {
|
function shuffle(array) {
|
||||||
let currentIndex = array.length, randomIndex;
|
let currentIndex = array.length, randomIndex;
|
||||||
// While there remain elements to shuffle...
|
// While there remain elements to shuffle...
|
||||||
@@ -57,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.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
|
||||||
@@ -66,9 +45,9 @@ exports.emsg = emsg;
|
|||||||
* @returns member
|
* @returns member
|
||||||
*/
|
*/
|
||||||
function getMember(interaction) {
|
function getMember(interaction) {
|
||||||
const 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;
|
||||||
@@ -79,19 +58,9 @@ exports.getMember = getMember;
|
|||||||
* @returns member
|
* @returns member
|
||||||
*/
|
*/
|
||||||
function getChannel(interaction) {
|
function getChannel(interaction) {
|
||||||
const 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) {
|
|
||||||
const 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;
|
|
||||||
|
|||||||
45
dist/util/discord.js
vendored
45
dist/util/discord.js
vendored
@@ -1,45 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.memberIsModThrow = exports.memberIsMod = exports.getChannel = exports.getMember = void 0;
|
|
||||||
const discord_js_1 = require("discord.js");
|
|
||||||
const main_1 = require("./main");
|
|
||||||
/**
|
|
||||||
* get the GuildMember of an interaction
|
|
||||||
* @throws errorMessage class if it cannot be read
|
|
||||||
*/
|
|
||||||
function getMember(interaction) {
|
|
||||||
const member = interaction.member;
|
|
||||||
if (!(member instanceof discord_js_1.GuildMember))
|
|
||||||
throw (0, main_1.emsg)('general.noMember');
|
|
||||||
return member;
|
|
||||||
}
|
|
||||||
exports.getMember = getMember;
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if it cannot be read
|
|
||||||
*/
|
|
||||||
function getChannel(interaction) {
|
|
||||||
const channel = interaction.channel;
|
|
||||||
if (!(channel instanceof discord_js_1.TextChannel))
|
|
||||||
throw (0, main_1.emsg)('general.noChannel');
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
exports.getChannel = getChannel;
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if the Member cannot be read
|
|
||||||
*/
|
|
||||||
function memberIsMod(interaction) {
|
|
||||||
const member = getMember(interaction);
|
|
||||||
return member.permissionsIn(interaction.channelId).has('MANAGE_MESSAGES');
|
|
||||||
}
|
|
||||||
exports.memberIsMod = memberIsMod;
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if the Member cannot be read or if Member is not a mod
|
|
||||||
*/
|
|
||||||
function memberIsModThrow(interaction) {
|
|
||||||
if (!memberIsMod(interaction))
|
|
||||||
throw (0, main_1.emsg)('discord.notMod');
|
|
||||||
}
|
|
||||||
exports.memberIsModThrow = memberIsModThrow;
|
|
||||||
119
dist/util/lang.js
vendored
119
dist/util/lang.js
vendored
@@ -1,119 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.embedObjEmbed = exports.embedObjStr = exports.resolveColor = exports.bigString = exports.template = void 0;
|
|
||||||
const discord_js_1 = require("discord.js");
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param str
|
|
||||||
* @param args
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
function template(str, args) {
|
|
||||||
return str.replace(/{\w+}/g, str => {
|
|
||||||
const key = str.substring(1, str.length - 1);
|
|
||||||
if (key in args)
|
|
||||||
return args[key];
|
|
||||||
return key;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.template = template;
|
|
||||||
/**
|
|
||||||
* converts bigString to string
|
|
||||||
*/
|
|
||||||
function bigString(bigStr) {
|
|
||||||
if (Array.isArray(bigStr))
|
|
||||||
return bigStr.join('\n');
|
|
||||||
return bigStr;
|
|
||||||
}
|
|
||||||
exports.bigString = bigString;
|
|
||||||
/**
|
|
||||||
* converts Hex Color string to an RGB array
|
|
||||||
*/
|
|
||||||
function resolveColor(color) {
|
|
||||||
color = color.replace(/[^0-9a-f]/gi, '');
|
|
||||||
const colorNum = [0, 0, 0];
|
|
||||||
if (color.length === 3 || color.length === 6) {
|
|
||||||
const colorSpl = /([0-9a-f]{1,2})([0-9a-f]{1,2})([0-9a-f]{1,2})/.exec(color);
|
|
||||||
if (!colorSpl)
|
|
||||||
return colorNum;
|
|
||||||
for (let i = 0; i < colorSpl.length && i < colorNum.length; i++)
|
|
||||||
colorNum[i] = parseInt(colorSpl[i], 16);
|
|
||||||
}
|
|
||||||
return colorNum;
|
|
||||||
}
|
|
||||||
exports.resolveColor = resolveColor;
|
|
||||||
/**
|
|
||||||
* converts embedObj to a string if applicable
|
|
||||||
* @param fallback the string to use if no valid strings can be found
|
|
||||||
*/
|
|
||||||
function embedObjStr(embedObj, args = {}, fallback = '') {
|
|
||||||
if (embedObj.content !== undefined)
|
|
||||||
return template(bigString(embedObj.content), args);
|
|
||||||
if (embedObj.description !== undefined)
|
|
||||||
return template(bigString(embedObj.description), args);
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
exports.embedObjStr = embedObjStr;
|
|
||||||
/**
|
|
||||||
* converts embedObj to Discord.MessageEmbed
|
|
||||||
*/
|
|
||||||
function embedObjEmbed(embedObj, args = {}) {
|
|
||||||
const embed = new discord_js_1.MessageEmbed(), { author, color, description, fields, footer, image, thumbnail, timestamp, title, url } = embedObj;
|
|
||||||
if (author !== undefined) {
|
|
||||||
let authorFix;
|
|
||||||
if (typeof author === 'string')
|
|
||||||
authorFix = {
|
|
||||||
name: template(author, args)
|
|
||||||
};
|
|
||||||
else {
|
|
||||||
const { name, icon, url } = author;
|
|
||||||
authorFix = {
|
|
||||||
name: template(name, args)
|
|
||||||
};
|
|
||||||
if (icon !== undefined)
|
|
||||||
authorFix.icon = template(icon, args);
|
|
||||||
if (url !== undefined)
|
|
||||||
authorFix.url = template(url, args);
|
|
||||||
}
|
|
||||||
embed.setAuthor(authorFix);
|
|
||||||
}
|
|
||||||
if (footer !== undefined) {
|
|
||||||
let footerFix;
|
|
||||||
if (typeof footer === 'string')
|
|
||||||
footerFix = {
|
|
||||||
text: template(footer, args)
|
|
||||||
};
|
|
||||||
else {
|
|
||||||
const { text, icon } = footer;
|
|
||||||
footerFix = {
|
|
||||||
text: template(text, args)
|
|
||||||
};
|
|
||||||
if (icon !== undefined)
|
|
||||||
footerFix.icon = template(icon, args);
|
|
||||||
}
|
|
||||||
embed.setFooter(footerFix);
|
|
||||||
}
|
|
||||||
if (color !== undefined)
|
|
||||||
embed.setColor(resolveColor(template(color, args)));
|
|
||||||
if (description !== undefined)
|
|
||||||
embed.setDescription(template(bigString(description), args));
|
|
||||||
if (image !== undefined)
|
|
||||||
embed.setImage(template(image, args));
|
|
||||||
if (thumbnail !== undefined)
|
|
||||||
embed.setThumbnail(template(thumbnail, args));
|
|
||||||
if (title !== undefined)
|
|
||||||
embed.setTitle(template(title, args));
|
|
||||||
if (url !== undefined)
|
|
||||||
embed.setURL(template(url, args));
|
|
||||||
if (timestamp === true)
|
|
||||||
embed.setTimestamp();
|
|
||||||
else if (typeof timestamp === 'string')
|
|
||||||
embed.setTimestamp(new Date(template(timestamp, args)));
|
|
||||||
else if (timestamp !== false)
|
|
||||||
embed.setTimestamp(timestamp);
|
|
||||||
fields?.forEach(field => {
|
|
||||||
embed.addField(template(field.name, args), template(bigString(field.value), args), field.inline);
|
|
||||||
});
|
|
||||||
return embed;
|
|
||||||
}
|
|
||||||
exports.embedObjEmbed = embedObjEmbed;
|
|
||||||
63
dist/util/main.js
vendored
63
dist/util/main.js
vendored
@@ -1,63 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
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 });
|
|
||||||
exports.emsg = exports.errorMessage = exports.shuffle = void 0;
|
|
||||||
const Lang = __importStar(require("../lang"));
|
|
||||||
/**
|
|
||||||
* shuffles an array
|
|
||||||
* https://stackoverflow.com/a/2450976/2856416
|
|
||||||
* @param array an array
|
|
||||||
* @returns an array but shuffled
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
function shuffle(array) {
|
|
||||||
let currentIndex = array.length, randomIndex;
|
|
||||||
// While there remain elements to shuffle...
|
|
||||||
while (currentIndex != 0) {
|
|
||||||
// Pick a remaining element...
|
|
||||||
randomIndex = Math.floor(Math.random() * currentIndex);
|
|
||||||
currentIndex--;
|
|
||||||
// And swap it with the current element.
|
|
||||||
[array[currentIndex], array[randomIndex]] = [
|
|
||||||
array[randomIndex], array[currentIndex]
|
|
||||||
];
|
|
||||||
}
|
|
||||||
return array;
|
|
||||||
}
|
|
||||||
exports.shuffle = shuffle;
|
|
||||||
/**
|
|
||||||
* use the emsg() function instead
|
|
||||||
*/
|
|
||||||
class errorMessage {
|
|
||||||
constructor(msg, ephemeral = true) {
|
|
||||||
this.msg = msg;
|
|
||||||
this.ephemeral = ephemeral;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.errorMessage = errorMessage;
|
|
||||||
/**
|
|
||||||
* a simple class to contain an error message and related data
|
|
||||||
* @param msg error message
|
|
||||||
* @param ephemeral (default=true)
|
|
||||||
* @returns new errorMessage
|
|
||||||
*/
|
|
||||||
const emsg = (msg, ephemeral = true) => new errorMessage(Lang.get(`error.${msg}`), ephemeral);
|
|
||||||
exports.emsg = emsg;
|
|
||||||
2476
package-lock.json
generated
2476
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "1800queue",
|
"name": "1800queue-alt",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "dist/main.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"start": "node .",
|
"start": "node .",
|
||||||
@@ -30,9 +30,7 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^17.0.17",
|
"@types/node": "^17.0.13",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.11.0",
|
|
||||||
"discord-api-types": "^0.26.1",
|
|
||||||
"npm-watch": "^0.11.0",
|
"npm-watch": "^0.11.0",
|
||||||
"ts-node": "^10.4.0",
|
"ts-node": "^10.4.0",
|
||||||
"typescript": "^4.5.5"
|
"typescript": "^4.5.5"
|
||||||
@@ -40,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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
|||||||
124
src/api.ts
124
src/api.ts
@@ -1,9 +1,8 @@
|
|||||||
/*eslint prefer-const: "error"*/
|
|
||||||
import * as cheerio from 'cheerio';
|
import * as cheerio from 'cheerio';
|
||||||
import { CommandInteraction } from 'discord.js';
|
import { CommandInteraction, MessageEmbed } from 'discord.js';
|
||||||
import http, { IncomingMessage } from 'http';
|
import { IncomingMessage } from 'http';
|
||||||
import { emsg } from './util/main';
|
import http from 'https';
|
||||||
import * as Lang from './lang';
|
import { emsg } from './util';
|
||||||
|
|
||||||
const uniteApiRegex = {
|
const uniteApiRegex = {
|
||||||
//$1 = name, $2 = id
|
//$1 = name, $2 = id
|
||||||
@@ -13,7 +12,21 @@ const uniteApiRegex = {
|
|||||||
/lv\.(\d+) (\w+) \((\d+)\)/i, //master
|
/lv\.(\d+) (\w+) \((\d+)\)/i, //master
|
||||||
/lv\.(\d+) (\w+): class (\d+)/i //other
|
/lv\.(\d+) (\w+): class (\d+)/i //other
|
||||||
]
|
]
|
||||||
};
|
}
|
||||||
|
|
||||||
|
type uniteApiData = {
|
||||||
|
name: string,
|
||||||
|
id: string,
|
||||||
|
avatar: string,
|
||||||
|
|
||||||
|
level: string,
|
||||||
|
rank: string,
|
||||||
|
class: string|null,
|
||||||
|
elo: string|null,
|
||||||
|
battles: string,
|
||||||
|
wins: string,
|
||||||
|
winrate: string
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* gets the html of the uniteApi page for the player
|
* gets the html of the uniteApi page for the player
|
||||||
@@ -26,8 +39,8 @@ function getHTML(name: string): Promise<string> {
|
|||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|
||||||
const opts = {
|
const init = {
|
||||||
host: '147.182.215.216',
|
host: 'uniteapi.dev',
|
||||||
path: `/p/${encodeURIComponent(name)}`,
|
path: `/p/${encodeURIComponent(name)}`,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
};
|
};
|
||||||
@@ -49,7 +62,7 @@ function getHTML(name: string): Promise<string> {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const req = http.request(opts, callback);
|
const req = http.request(init, callback);
|
||||||
req.end();
|
req.end();
|
||||||
|
|
||||||
});
|
});
|
||||||
@@ -63,31 +76,30 @@ function getHTML(name: string): Promise<string> {
|
|||||||
* @throws errorMessage class if the request fails
|
* @throws errorMessage class if the request fails
|
||||||
*/
|
*/
|
||||||
function readHTML(html: string): uniteApiData {
|
function readHTML(html: string): uniteApiData {
|
||||||
const $ = cheerio.load(html),
|
let $ = cheerio.load(html)
|
||||||
|
let metaElems = $('meta').toArray(),
|
||||||
foundData: uniteApiData = {
|
foundData: uniteApiData = {
|
||||||
name: '',
|
name: "",
|
||||||
id: '',
|
id: "",
|
||||||
avatar: '',
|
avatar: "",
|
||||||
|
|
||||||
level: '',
|
level: "",
|
||||||
rank: '',
|
rank: "",
|
||||||
elo: null,
|
elo: null,
|
||||||
class: null,
|
class: null,
|
||||||
battles: '',
|
battles: "",
|
||||||
wins: '',
|
wins: "",
|
||||||
winrate: ''
|
winrate: ""
|
||||||
};
|
};
|
||||||
|
|
||||||
let metaElems = $('meta').toArray();
|
|
||||||
|
|
||||||
//filter down to just ones named "og:..."
|
//filter down to just ones named "og:..."
|
||||||
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
|
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
|
||||||
|
|
||||||
metaElems.forEach(el => {
|
metaElems.forEach(el => {
|
||||||
const attr = el.attribs;
|
let attr = el.attribs;
|
||||||
|
|
||||||
if (attr.property === 'og:title') {
|
if (attr.property === 'og:title') {
|
||||||
const data = uniteApiRegex.ogtitle.exec(attr.content);
|
let data = uniteApiRegex.ogtitle.exec(attr.content);
|
||||||
if (data !== null && data.length >= 3) {
|
if (data !== null && data.length >= 3) {
|
||||||
foundData.name = data[1];
|
foundData.name = data[1];
|
||||||
foundData.id = data[2];
|
foundData.id = data[2];
|
||||||
@@ -95,17 +107,17 @@ function readHTML(html: string): uniteApiData {
|
|||||||
} else if (attr.property === 'og:description') {
|
} else if (attr.property === 'og:description') {
|
||||||
|
|
||||||
//all lines
|
//all lines
|
||||||
let lines = attr.content.split('\n').map(l => l.trim());
|
let lines = attr.content.split('\n').map(l => l.trim()),
|
||||||
const extraLines: string[] = [];
|
extraLines: string[] = [];
|
||||||
|
|
||||||
//ensure first line is correct
|
//ensure first line is correct
|
||||||
while ((lines.length > 0) && !/pok.mon unite/i.test(lines[0])) {
|
while (lines.length && !/pok.mon unite/i.test(lines[0])) {
|
||||||
const line = lines.shift();
|
let line = lines.shift();
|
||||||
if (line !== undefined)
|
if (line)
|
||||||
extraLines.push(line);
|
extraLines.push(line);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lines.length === 0)
|
if (!lines.length)
|
||||||
throw emsg('Unable to read data, please try again');
|
throw emsg('Unable to read data, please try again');
|
||||||
|
|
||||||
//bring the first lines removed back into the data
|
//bring the first lines removed back into the data
|
||||||
@@ -117,12 +129,13 @@ function readHTML(html: string): uniteApiData {
|
|||||||
//first line
|
//first line
|
||||||
{
|
{
|
||||||
//will be only text after "pokemon unite:"
|
//will be only text after "pokemon unite:"
|
||||||
const line = lines[0].split(':').slice(1).join(':').trim(),
|
let line = lines[0].split(':').slice(1).join(':').trim();
|
||||||
regex = uniteApiRegex.ogdescription;
|
|
||||||
|
let regex = uniteApiRegex.ogdescription;
|
||||||
|
|
||||||
if (regex[0].test(line)) { //is master/has elo
|
if (regex[0].test(line)) { //is master/has elo
|
||||||
|
|
||||||
const regexData = line.match(regex[0]);
|
let regexData = line.match(regex[0]);
|
||||||
|
|
||||||
if (!regexData || regexData.length < 4)
|
if (!regexData || regexData.length < 4)
|
||||||
throw emsg('Unable to read data, please try again');
|
throw emsg('Unable to read data, please try again');
|
||||||
@@ -133,7 +146,7 @@ function readHTML(html: string): uniteApiData {
|
|||||||
|
|
||||||
} else { //is not master/has a class
|
} else { //is not master/has a class
|
||||||
|
|
||||||
const regexData = line.match(regex[1]);
|
let regexData = line.match(regex[1]);
|
||||||
|
|
||||||
if (!regexData || regexData.length < 4)
|
if (!regexData || regexData.length < 4)
|
||||||
throw emsg('Unable to read data, please try again');
|
throw emsg('Unable to read data, please try again');
|
||||||
@@ -151,7 +164,7 @@ function readHTML(html: string): uniteApiData {
|
|||||||
//rest of lines
|
//rest of lines
|
||||||
lines.forEach(line => {
|
lines.forEach(line => {
|
||||||
|
|
||||||
const split = line.split(':').map(l => 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];
|
||||||
|
|
||||||
@@ -173,9 +186,7 @@ function readHTML(html: string): uniteApiData {
|
|||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const imgSrc = $('.player-card-image img').attr('src');
|
foundData.avatar = $('.player-card-image img').attr('src') || "";
|
||||||
|
|
||||||
foundData.avatar = imgSrc !== undefined ? imgSrc : '';
|
|
||||||
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
||||||
|
|
||||||
return foundData;
|
return foundData;
|
||||||
@@ -188,7 +199,7 @@ function readHTML(html: string): uniteApiData {
|
|||||||
* @returns boolean, valid or invalid
|
* @returns boolean, valid or invalid
|
||||||
*/
|
*/
|
||||||
function verifyData(data: uniteApiData): boolean {
|
function verifyData(data: uniteApiData): boolean {
|
||||||
if (data.id.length > 0)
|
if (data.id.length)
|
||||||
return true;
|
return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -199,8 +210,8 @@ function verifyData(data: uniteApiData): boolean {
|
|||||||
* @returns player data
|
* @returns player data
|
||||||
*/
|
*/
|
||||||
export async function getPlayer(name: string): Promise<uniteApiData|null> {
|
export async function getPlayer(name: string): Promise<uniteApiData|null> {
|
||||||
const html = await getHTML(name),
|
let html = await getHTML(name);
|
||||||
data = readHTML(html);
|
let data = readHTML(html);
|
||||||
if (verifyData(data))
|
if (verifyData(data))
|
||||||
return data;
|
return data;
|
||||||
return null;
|
return null;
|
||||||
@@ -208,24 +219,19 @@ export async function getPlayer(name: string): Promise<uniteApiData|null> {
|
|||||||
|
|
||||||
async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) {
|
async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) {
|
||||||
|
|
||||||
let eloStr: string;
|
let embed = new MessageEmbed()
|
||||||
if (data.elo !== null)
|
.setTitle(`${data.name} (${data.id})`)
|
||||||
eloStr = `(${data.elo})`;
|
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
|
||||||
else
|
.setTimestamp()
|
||||||
eloStr = `Class ${data.class}`;
|
.setThumbnail(data.avatar)
|
||||||
|
.setDescription(`Level ${data.level}
|
||||||
|
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
|
||||||
|
|
||||||
await interaction.editReply(Lang.getEmbed('api.player', {
|
**Battles** ${data.battles}
|
||||||
name: data.name,
|
**Wins** ${data.wins}
|
||||||
id: data.id,
|
**Win Rate** ${data.winrate}`);
|
||||||
nameEncoded: encodeURIComponent(data.name),
|
|
||||||
avatar: data.avatar,
|
await interaction.editReply({embeds: [embed]});
|
||||||
level: data.level,
|
|
||||||
rank: data.rank,
|
|
||||||
elo: eloStr,
|
|
||||||
battles: data.battles,
|
|
||||||
wins: data.wins,
|
|
||||||
winrate: data.winrate
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -234,12 +240,12 @@ async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiDa
|
|||||||
* @throws errorMessage class if the user cannot be found
|
* @throws errorMessage class if the user cannot be found
|
||||||
*/
|
*/
|
||||||
export async function getPlayerInteraction(interaction: CommandInteraction) {
|
export async function getPlayerInteraction(interaction: CommandInteraction) {
|
||||||
const username = interaction.options.getString('username', true);
|
let username = interaction.options.getString('username', true);
|
||||||
await interaction.deferReply();
|
await interaction.deferReply();
|
||||||
|
|
||||||
const 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,21 @@
|
|||||||
/* eslint-disable camelcase */
|
|
||||||
import { REST } from '@discordjs/rest';
|
import { REST } from '@discordjs/rest';
|
||||||
import { Routes } from 'discord-api-types/v9';
|
import { Routes } from 'discord-api-types/v9';
|
||||||
|
|
||||||
// list of commands to register with discord
|
// list of commands to register with discord
|
||||||
const commands = [
|
const commands = [
|
||||||
{
|
{
|
||||||
name: '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'
|
||||||
@@ -34,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',
|
||||||
@@ -47,7 +45,6 @@ const commands = [
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
/*commandNames = commands.map(c => c.name);*/
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* register/reload commands on guild(s)
|
* register/reload commands on guild(s)
|
||||||
@@ -68,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);
|
||||||
}
|
}
|
||||||
|
|||||||
63
src/index.ts
Normal file
63
src/index.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
|
||||||
|
import { Client, Intents } from 'discord.js';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import { getPlayerInteraction } from './api';
|
||||||
|
import { registerCommands } from './discord';
|
||||||
|
import { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } from './queue';
|
||||||
|
import { errorMessage } from './util';
|
||||||
|
const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
|
||||||
|
|
||||||
|
//init logs with a timestamp
|
||||||
|
console.log(new Date().toISOString()+'\n\n');
|
||||||
|
|
||||||
|
//get token
|
||||||
|
if (!fs.existsSync('./token')) {
|
||||||
|
fs.writeFileSync('./token', '');
|
||||||
|
console.error('Missing Discord Token, please enter the bot token into the token file');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const TOKEN = fs.readFileSync('./token').toString();
|
||||||
|
|
||||||
|
//discord connections
|
||||||
|
CLIENT.on('ready', client => {
|
||||||
|
console.log(`Logged in as ${client.user.tag}`);
|
||||||
|
client.guilds.fetch().then(guilds =>
|
||||||
|
registerCommands(TOKEN, client.user.id, guilds.map(g => g.id)));
|
||||||
|
});
|
||||||
|
|
||||||
|
CLIENT.on('interactionCreate', async interaction => {
|
||||||
|
if (!interaction.isCommand()) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
if (interaction.commandName === 'queue')
|
||||||
|
await createQueue(interaction);
|
||||||
|
else if (interaction.commandName === 'join')
|
||||||
|
await joinQueue(interaction);
|
||||||
|
else if (interaction.commandName === 'leave')
|
||||||
|
await leaveQueue(interaction);
|
||||||
|
else if (interaction.commandName === 'ready')
|
||||||
|
await readyQueue(interaction);
|
||||||
|
else if (interaction.commandName === 'cancel')
|
||||||
|
await cancelQueue(interaction);
|
||||||
|
else if (interaction.commandName === 'player')
|
||||||
|
await getPlayerInteraction(interaction);
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
|
||||||
|
if (e instanceof errorMessage) {
|
||||||
|
|
||||||
|
if (interaction.deferred || interaction.replied)
|
||||||
|
interaction.editReply(e.msg);
|
||||||
|
else
|
||||||
|
interaction.reply({
|
||||||
|
content: e.msg,
|
||||||
|
ephemeral: e.ephemeral
|
||||||
|
});
|
||||||
|
|
||||||
|
} else console.error(e);
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
CLIENT.login(TOKEN);
|
||||||
185
src/lang.ts
185
src/lang.ts
@@ -1,185 +0,0 @@
|
|||||||
import { embedObjEmbed, embedObjStr, template } from './util/lang';
|
|
||||||
|
|
||||||
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',
|
|
||||||
|
|
||||||
team: {
|
|
||||||
embed: true,
|
|
||||||
title: 'Team',
|
|
||||||
description: '{team}'
|
|
||||||
},
|
|
||||||
queue: {
|
|
||||||
embed: true,
|
|
||||||
title: 'Active Queue',
|
|
||||||
fields: [
|
|
||||||
{
|
|
||||||
name: 'Team Size',
|
|
||||||
value: '{teamsize}'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Players Joined',
|
|
||||||
value: '{playercount}'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
footer: 'type `/join`'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
api: {
|
|
||||||
player: {
|
|
||||||
embed: true,
|
|
||||||
title: '{name} ({id})',
|
|
||||||
url: 'https://uniteapi.dev/p/{nameEncoded}',
|
|
||||||
timestamp: true,
|
|
||||||
thumbnail: '{avatar}',
|
|
||||||
description: [
|
|
||||||
'Level {level}',
|
|
||||||
'{rank} {elo}',
|
|
||||||
'',
|
|
||||||
'**Battles** {battles}',
|
|
||||||
'**Wins** {wins}',
|
|
||||||
'**Win Rate** {winrate}'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
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'
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
/* MAIN */
|
|
||||||
|
|
||||||
let LANGID = 'en';
|
|
||||||
if (!(LANGID in LANG))
|
|
||||||
throw 'language id does not exist';
|
|
||||||
|
|
||||||
export function setLang(langid: string) {
|
|
||||||
if (langid in LANG)
|
|
||||||
LANGID = langid;
|
|
||||||
else
|
|
||||||
throw 'language id does not exist';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* reads language json (just strings)
|
|
||||||
* @param id ex: discord.error.noActiveQueue
|
|
||||||
* @param args list of key/value pairs to represent template values
|
|
||||||
* @returns language value, defaults to `id` parameter
|
|
||||||
*/
|
|
||||||
export function get(id: string, args: basicObjectStr = {}): string {
|
|
||||||
|
|
||||||
const keySpl = id.split('.').map(k => k.trim()).filter(k => k);
|
|
||||||
|
|
||||||
let finding = LANG[LANGID];
|
|
||||||
|
|
||||||
for (const key of keySpl) {
|
|
||||||
|
|
||||||
if (key in finding) {
|
|
||||||
|
|
||||||
const found = finding[key];
|
|
||||||
|
|
||||||
if (typeof found === 'string')
|
|
||||||
return template(found, args);
|
|
||||||
|
|
||||||
if (found.embed === true)
|
|
||||||
return embedObjStr(found as embedObj, args, id);
|
|
||||||
|
|
||||||
finding = found as LangObj;
|
|
||||||
|
|
||||||
} else
|
|
||||||
break;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* reads language json as an object (could be embed or just string)
|
|
||||||
* @param id ex: discord.error.noActiveQueue
|
|
||||||
* @param args list of key/value pairs to represent template values
|
|
||||||
* @param otherOptions values to be passed through to the return value
|
|
||||||
* @returns language value, defaults to `id` parameter
|
|
||||||
*/
|
|
||||||
export function getEmbed(id: string, args: basicObjectStr = {}, otherOptions: basicObject = {}): embedData {
|
|
||||||
|
|
||||||
const embedData: embedData = {
|
|
||||||
...otherOptions,
|
|
||||||
embeds: []
|
|
||||||
};
|
|
||||||
|
|
||||||
const keySpl = id.split('.').map(k => k.trim()).filter(k => k);
|
|
||||||
|
|
||||||
let finding = LANG[LANGID];
|
|
||||||
|
|
||||||
for (const key of keySpl) {
|
|
||||||
|
|
||||||
if (key in finding) {
|
|
||||||
|
|
||||||
const found = finding[key];
|
|
||||||
|
|
||||||
if (typeof found === 'string') {
|
|
||||||
embedData.content = template(found, args);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (found.embed === true) {
|
|
||||||
const embedObj = found as embedObj,
|
|
||||||
{content} = embedObj,
|
|
||||||
embed = embedObjEmbed(embedObj, args);
|
|
||||||
|
|
||||||
embedData.embeds.push(embed);
|
|
||||||
|
|
||||||
if (content !== undefined)
|
|
||||||
embedData.content = content;
|
|
||||||
|
|
||||||
return embedData;
|
|
||||||
}
|
|
||||||
|
|
||||||
finding = found as LangObj;
|
|
||||||
|
|
||||||
} else
|
|
||||||
break;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return embedData;
|
|
||||||
}
|
|
||||||
85
src/main.ts
85
src/main.ts
@@ -1,85 +0,0 @@
|
|||||||
|
|
||||||
import { Client, Intents } from 'discord.js';
|
|
||||||
import * as fs from 'fs';
|
|
||||||
import { getPlayerInteraction } from './api';
|
|
||||||
import { registerCommands } from './discord';
|
|
||||||
import * as Lang from './lang';
|
|
||||||
import { discordInit, QueueCommands } from './queue';
|
|
||||||
import { errorMessage } from './util/main';
|
|
||||||
const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
|
|
||||||
|
|
||||||
//init logs with a timestamp
|
|
||||||
console.log(new Date().toISOString()+'\n\n');
|
|
||||||
|
|
||||||
//get token
|
|
||||||
if (!fs.existsSync('./token.txt')) {
|
|
||||||
fs.writeFileSync('./token.txt', '');
|
|
||||||
console.error(Lang.get('error.main.missingToken'));
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
const TOKEN = fs.readFileSync('./token.txt').toString();
|
|
||||||
|
|
||||||
//discord connections
|
|
||||||
CLIENT.on('ready', client => {
|
|
||||||
console.log(Lang.get('main.login', {
|
|
||||||
user: client.user.tag
|
|
||||||
}));
|
|
||||||
client.guilds.fetch().then(guilds =>
|
|
||||||
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 => {
|
|
||||||
if (!interaction.isCommand()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
switch (interaction.commandName) {
|
|
||||||
|
|
||||||
//mod commands
|
|
||||||
case 'open':
|
|
||||||
await QueueCommands.open(interaction);
|
|
||||||
break;
|
|
||||||
case 'close':
|
|
||||||
await QueueCommands.close(interaction);
|
|
||||||
break;
|
|
||||||
|
|
||||||
//general commands
|
|
||||||
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) {
|
|
||||||
|
|
||||||
if (e instanceof errorMessage) {
|
|
||||||
|
|
||||||
if (interaction.deferred || interaction.replied)
|
|
||||||
interaction.editReply(e.msg);
|
|
||||||
else
|
|
||||||
interaction.reply({
|
|
||||||
content: e.msg,
|
|
||||||
ephemeral: e.ephemeral
|
|
||||||
});
|
|
||||||
|
|
||||||
} else console.error(e);
|
|
||||||
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
CLIENT.login(TOKEN);
|
|
||||||
299
src/queue.ts
299
src/queue.ts
@@ -1,101 +1,8 @@
|
|||||||
import { Client, CommandInteraction, TextChannel } from 'discord.js';
|
import { CommandInteraction, GuildMember, MessageEmbed } from "discord.js";
|
||||||
import * as fs from 'fs';
|
import { emsg, getChannel, getMember, queueInfo, shuffle } from "./util";
|
||||||
import * as Lang from './lang';
|
|
||||||
import { getChannel, getMember, memberIsModThrow } from './util/discord';
|
|
||||||
import { emsg } from './util/main';
|
|
||||||
|
|
||||||
//load queues from file`
|
//maps ChannelID to QueueInfo
|
||||||
if (!fs.existsSync('./queues.json'))
|
const QUEUE = new Map<string, queueInfo>();
|
||||||
fs.writeFileSync('./queues.json', '{}');
|
|
||||||
|
|
||||||
const _QUEUE = fs.readFileSync('./queues.json').toString(),
|
|
||||||
QUEUE = new Map<string, queueInfo>();
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
const queueJson = JSON.parse(_QUEUE);
|
|
||||||
|
|
||||||
for (const channelId in queueJson) {
|
|
||||||
const {teamsize} = queueJson[channelId] as queueInfoBase;
|
|
||||||
if (teamsize !== 0)
|
|
||||||
QUEUE.set(channelId, { teamsize, players: [] });
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch(e) {
|
|
||||||
//do nothing
|
|
||||||
}
|
|
||||||
|
|
||||||
function SaveQueue() {
|
|
||||||
|
|
||||||
const queueJson = Object.fromEntries(QUEUE),
|
|
||||||
queueFileJson: {[keys: string]: queueInfoBase} = {};
|
|
||||||
|
|
||||||
for (const channelId of QUEUE.keys())
|
|
||||||
queueFileJson[channelId] = { teamsize: queueJson[channelId].teamsize };
|
|
||||||
|
|
||||||
fs.writeFileSync('./queues.json', JSON.stringify(queueFileJson, null, 2));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkQueue(channel: TextChannel) {
|
|
||||||
const info = QUEUE.get(channel.id);
|
|
||||||
|
|
||||||
if (!info)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (info.players.length >= info.teamsize) {
|
|
||||||
|
|
||||||
const team = info.players.splice(0, info.teamsize).map(m => m.toString());
|
|
||||||
|
|
||||||
await channel.send(Lang.getEmbed('discord.team', { team: team.join('\n') }));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export function queueCreate(channelId: string, teamsize: number) {
|
|
||||||
if (!QUEUE.has(channelId)) {
|
|
||||||
QUEUE.set(channelId, {teamsize, players: []});
|
|
||||||
SaveQueue();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function queueRemove(channelId: string) {
|
|
||||||
if (QUEUE.has(channelId)) {
|
|
||||||
QUEUE.delete(channelId);
|
|
||||||
SaveQueue();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SaveQueue();
|
|
||||||
|
|
||||||
export async function discordInit(client: Client) {
|
|
||||||
|
|
||||||
for (const channelId of QUEUE.keys()) {
|
|
||||||
|
|
||||||
const info = QUEUE.get(channelId),
|
|
||||||
channel = await client.channels.fetch(channelId);
|
|
||||||
|
|
||||||
if (!info) {
|
|
||||||
queueRemove(channelId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!channel || !(channel instanceof TextChannel)) {
|
|
||||||
console.error(Lang.get('error.discord.noChannel'), {
|
|
||||||
channelId,
|
|
||||||
teamsize: info.teamsize
|
|
||||||
});
|
|
||||||
queueRemove(channelId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
channel.send(Lang.get('discord.botRestart'));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the queueInfo of an interaction
|
* get the queueInfo of an interaction
|
||||||
@@ -103,11 +10,11 @@ export async function discordInit(client: Client) {
|
|||||||
* @throws errorMessage class if it does not exist
|
* @throws errorMessage class if it does not exist
|
||||||
* @returns queue info
|
* @returns queue info
|
||||||
*/
|
*/
|
||||||
function getInfo(interaction: CommandInteraction): queueInfo {
|
export function getInfo(interaction: CommandInteraction): queueInfo {
|
||||||
const info = QUEUE.get(interaction.channelId);
|
let info = QUEUE.get(interaction.channelId);
|
||||||
|
|
||||||
if (!info)
|
if (!info)
|
||||||
throw emsg('discord.noQueue');
|
throw emsg('There is not an active queue in this channel, type `/queue` to create one');
|
||||||
|
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
@@ -118,7 +25,7 @@ function getInfo(interaction: CommandInteraction): queueInfo {
|
|||||||
* @throws if another get function throws
|
* @throws if another get function throws
|
||||||
* @returns object containing each
|
* @returns object containing each
|
||||||
*/
|
*/
|
||||||
const getAll = (interaction: CommandInteraction) => ({
|
export const getAll = (interaction: CommandInteraction) => ({
|
||||||
member: getMember(interaction),
|
member: getMember(interaction),
|
||||||
channel: getChannel(interaction),
|
channel: getChannel(interaction),
|
||||||
info: getInfo(interaction)
|
info: getInfo(interaction)
|
||||||
@@ -131,7 +38,7 @@ const getAll = (interaction: CommandInteraction) => ({
|
|||||||
*/
|
*/
|
||||||
export function queueContains(interaction: CommandInteraction): boolean {
|
export function queueContains(interaction: CommandInteraction): boolean {
|
||||||
|
|
||||||
const {member, info} = getAll(interaction);
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
if (info.players.map(m=>m.id).includes(member.id))
|
if (info.players.map(m=>m.id).includes(member.id))
|
||||||
return true;
|
return true;
|
||||||
@@ -141,109 +48,189 @@ export function queueContains(interaction: CommandInteraction): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* opens a queue
|
* creates the timeout for the queue
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be left
|
* @returns time timeout identifier
|
||||||
*/
|
*/
|
||||||
function open(interaction: CommandInteraction) {
|
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
|
||||||
|
}
|
||||||
|
|
||||||
memberIsModThrow(interaction);
|
/**
|
||||||
|
* 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;
|
||||||
|
|
||||||
const {channelId} = interaction,
|
let embed = new MessageEmbed()
|
||||||
|
.setTitle('Queue')
|
||||||
|
.setAuthor({
|
||||||
|
name: info.initiator.member.displayName,
|
||||||
|
iconURL: info.initiator.member.displayAvatarURL({dynamic: true})
|
||||||
|
})
|
||||||
|
.addField('Team Size', info.teamsize.toString(), true)
|
||||||
|
.addField('Players Joined', info.players.length.toString(), true)
|
||||||
|
.setFooter({text: closed ? 'queue is finished' : 'type /join'});
|
||||||
|
|
||||||
|
if (origInteraction.deferred || origInteraction.replied)
|
||||||
|
await origInteraction.editReply({embeds: [embed]});
|
||||||
|
else
|
||||||
|
await origInteraction.reply({embeds: [embed]});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function sendTeamsEmbed(interaction: CommandInteraction, teams: GuildMember[][]) {
|
||||||
|
let embed = new MessageEmbed()
|
||||||
|
.setTitle('Teams');
|
||||||
|
|
||||||
|
teams.forEach((team, i) => {
|
||||||
|
team.map(m => m.user.tag);
|
||||||
|
embed.addField(`Team ${i+1}`, team.join('\n'))
|
||||||
|
});
|
||||||
|
|
||||||
|
interaction.reply({embeds: [embed]});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function clearQueue(interaction: CommandInteraction) {
|
||||||
|
let info = getInfo(interaction);
|
||||||
|
sendQueueEmbed(interaction, true);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
QUEUE.delete(interaction.channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* creates a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be created
|
||||||
|
*/
|
||||||
|
export async function createQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
|
let member = getMember(interaction),
|
||||||
|
{channelId} = interaction,
|
||||||
teamsize = interaction.options.getInteger('teamsize', true);
|
teamsize = interaction.options.getInteger('teamsize', true);
|
||||||
|
|
||||||
const existing = QUEUE.get(channelId);
|
if (QUEUE.has(channelId))
|
||||||
if (existing)
|
throw emsg('There is already an active queue in this channel, ' + (queueContains(interaction) ? 'and you are already in it' : 'type `/join` to join'));
|
||||||
throw emsg(Lang.get('error.discord.noCreate', {
|
|
||||||
teamsize: existing.teamsize.toString()
|
|
||||||
}));
|
|
||||||
|
|
||||||
queueCreate(channelId, teamsize);
|
QUEUE.set(channelId, {
|
||||||
|
players: [
|
||||||
|
member
|
||||||
|
],
|
||||||
|
initiator: {
|
||||||
|
interaction,
|
||||||
|
member
|
||||||
|
},
|
||||||
|
teamsize: teamsize,
|
||||||
|
timeout: setQueueTimeout(interaction)
|
||||||
|
});
|
||||||
|
|
||||||
interaction.reply(Lang.get('discord.create', {
|
sendQueueEmbed(interaction);
|
||||||
teamsize: teamsize.toString()
|
|
||||||
}));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* closes a queue
|
* joins a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be joined
|
* @throws errorMessage class if it cannot be joined
|
||||||
*/
|
*/
|
||||||
async function close(interaction: CommandInteraction) {
|
export async function joinQueue(interaction: CommandInteraction) {
|
||||||
memberIsModThrow(interaction);
|
|
||||||
|
|
||||||
QUEUE.delete(interaction.channelId);
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
await interaction.reply(Lang.get('discord.close'));
|
if (queueContains(interaction))
|
||||||
|
throw emsg('You are already in the active queue');
|
||||||
|
|
||||||
|
info.players.push(member);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
info.timeout = setQueueTimeout(interaction)
|
||||||
|
|
||||||
|
QUEUE.set(interaction.channelId, info);
|
||||||
|
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
await interaction.reply('Joined the queue');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* gives info about the queue
|
* leaves a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be left
|
* @throws errorMessage class if it cannot be left
|
||||||
*/
|
*/
|
||||||
async function queue(interaction: CommandInteraction) {
|
export async function leaveQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
const info = getInfo(interaction);
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
await interaction.reply(Lang.getEmbed('discord.queue', {
|
if (!queueContains(interaction))
|
||||||
teamsize: info.teamsize.toString(),
|
throw emsg('You aren\'t in the active queue');
|
||||||
playercount: info.players.length.toString(),
|
|
||||||
}, {
|
info.players.splice(info.players.indexOf(member), 1);
|
||||||
ephemeral: true
|
clearTimeout(info.timeout);
|
||||||
}));
|
info.timeout = setQueueTimeout(interaction)
|
||||||
|
|
||||||
|
QUEUE.set(interaction.channelId, info);
|
||||||
|
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
await interaction.reply('Left the queue');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* joins a queue
|
* readys a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be readied
|
* @throws errorMessage class if it cannot be readied
|
||||||
*/
|
*/
|
||||||
async function join(interaction: CommandInteraction) {
|
export async function readyQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
const {member, info, channel} = getAll(interaction);
|
let {member, info} = getAll(interaction),
|
||||||
|
{initiator} = info;
|
||||||
|
|
||||||
if (queueContains(interaction))
|
if (member.id !== initiator.member.id)
|
||||||
throw emsg('discord.inQueue');
|
throw emsg('Only the queue initiator can ready the queue');
|
||||||
|
|
||||||
info.players.push(member);
|
clearQueue(interaction);
|
||||||
|
|
||||||
QUEUE.set(interaction.channelId, info);
|
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');
|
||||||
|
|
||||||
await interaction.reply(Lang.get('discord.join'));
|
//team data
|
||||||
|
let playerlist: GuildMember[] = shuffle(info.players),
|
||||||
|
teams: GuildMember[][] = [];
|
||||||
|
|
||||||
checkQueue(channel);
|
//fill team data
|
||||||
|
for (let i = 0; i < playerlist.length; i+= info.teamsize)
|
||||||
|
teams.push(playerlist.slice(i, i+info.teamsize));
|
||||||
|
|
||||||
|
sendTeamsEmbed(interaction, teams);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* leaves a queue
|
* readys a queue from an interaction
|
||||||
* @param interaction
|
* @param interaction
|
||||||
* @throws errorMessage class if it cannot be reset
|
* @throws errorMessage class if it cannot be reset
|
||||||
*/
|
*/
|
||||||
async function leave(interaction: CommandInteraction) {
|
export async function cancelQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
const {member, info} = getAll(interaction);
|
let {info, member, channel} = getAll(interaction);
|
||||||
|
|
||||||
if (!queueContains(interaction))
|
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
|
||||||
throw emsg('discord.notInQueue');
|
throw emsg('You do not have permission to run this command');
|
||||||
|
|
||||||
info.players.splice(info.players.indexOf(member), 1);
|
clearQueue(interaction);
|
||||||
|
|
||||||
QUEUE.set(interaction.channelId, info);
|
await interaction.reply('Queue has been reset');
|
||||||
|
|
||||||
await interaction.reply(Lang.get('discord.leave'));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const QueueCommands = {
|
|
||||||
open,
|
|
||||||
close,
|
|
||||||
queue,
|
|
||||||
join,
|
|
||||||
leave
|
|
||||||
};
|
|
||||||
16
src/types/api.d.ts
vendored
16
src/types/api.d.ts
vendored
@@ -1,16 +0,0 @@
|
|||||||
/**
|
|
||||||
* data taken from UniteAPI
|
|
||||||
*/
|
|
||||||
interface uniteApiData {
|
|
||||||
name: string,
|
|
||||||
id: string,
|
|
||||||
avatar: string,
|
|
||||||
|
|
||||||
level: string,
|
|
||||||
rank: string,
|
|
||||||
class: string|null,
|
|
||||||
elo: string|null,
|
|
||||||
battles: string,
|
|
||||||
wins: string,
|
|
||||||
winrate: string
|
|
||||||
}
|
|
||||||
104
src/types/lang.d.ts
vendored
104
src/types/lang.d.ts
vendored
@@ -1,104 +0,0 @@
|
|||||||
/**
|
|
||||||
* any indexable object
|
|
||||||
*/
|
|
||||||
//this is a generic type, and needs 'any'
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
type basicObject = {[keys: string]: any};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* any indexable object with string values
|
|
||||||
*/
|
|
||||||
type basicObjectStr = {[keys: string]: string};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* an abstract version of strings
|
|
||||||
*/
|
|
||||||
type bigString = string | string[];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* an object that contains embeds and can be passed directly to methods like `Discord.TextChannel.send()`
|
|
||||||
*/
|
|
||||||
interface embedData {
|
|
||||||
content?: string,
|
|
||||||
embeds: MessageEmbed[]
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a representation of an author in the LANG object
|
|
||||||
*
|
|
||||||
* `LANG > Language > Embed > Field`
|
|
||||||
*/
|
|
||||||
interface embedField {
|
|
||||||
name: string,
|
|
||||||
value: bigString,
|
|
||||||
inline?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a representation of an author in the LANG object
|
|
||||||
*
|
|
||||||
* `LANG > Language > Embed > Author`
|
|
||||||
*/
|
|
||||||
interface authorData {
|
|
||||||
name: string,
|
|
||||||
url?: string,
|
|
||||||
icon?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a representation of a footer in the LANG object
|
|
||||||
*
|
|
||||||
* `LANG > Language > Embed > Footer`
|
|
||||||
*/
|
|
||||||
interface footerData {
|
|
||||||
text: string,
|
|
||||||
icon?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a representation of an embed in the LANG object
|
|
||||||
*
|
|
||||||
* `LANG > Language > Embed`
|
|
||||||
*/
|
|
||||||
interface embedObj {
|
|
||||||
embed: true,
|
|
||||||
|
|
||||||
content?: string,
|
|
||||||
title?: string,
|
|
||||||
description?: bigString,
|
|
||||||
/**
|
|
||||||
* URL
|
|
||||||
*/
|
|
||||||
url?: string,
|
|
||||||
/**
|
|
||||||
* #FFFFFF
|
|
||||||
*/
|
|
||||||
color?: string,
|
|
||||||
footer?: string | footerData,
|
|
||||||
thumbnail?: string,
|
|
||||||
/**
|
|
||||||
* URL
|
|
||||||
*/
|
|
||||||
image?: string,
|
|
||||||
/**
|
|
||||||
* URL
|
|
||||||
*/
|
|
||||||
author?: string | authorData,
|
|
||||||
fields?: embedField[],
|
|
||||||
timestamp?: boolean | string | number
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a specific language in the LANG object
|
|
||||||
*
|
|
||||||
* `LANG > Language`
|
|
||||||
*/
|
|
||||||
type LangObj = { [keys:string]: LangObj | embedObj | string }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* the entire LANG object
|
|
||||||
*
|
|
||||||
* `LANG`
|
|
||||||
*/
|
|
||||||
type LangObjWhole = { [langid:string]: LangObj }
|
|
||||||
6
src/types/queue.d.ts
vendored
6
src/types/queue.d.ts
vendored
@@ -1,6 +0,0 @@
|
|||||||
interface queueInfoBase {
|
|
||||||
teamsize: number
|
|
||||||
}
|
|
||||||
interface queueInfo extends queueInfoBase {
|
|
||||||
players: GuildMember[]
|
|
||||||
}
|
|
||||||
87
src/util.ts
Normal file
87
src/util.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* shuffles an array
|
||||||
|
* https://stackoverflow.com/a/2450976/2856416
|
||||||
|
* @param array an array
|
||||||
|
* @returns an array but shuffled
|
||||||
|
*/
|
||||||
|
export function shuffle(array: any[]) {
|
||||||
|
let currentIndex = array.length, randomIndex;
|
||||||
|
|
||||||
|
// While there remain elements to shuffle...
|
||||||
|
while (currentIndex != 0) {
|
||||||
|
|
||||||
|
// Pick a remaining element...
|
||||||
|
randomIndex = Math.floor(Math.random() * currentIndex);
|
||||||
|
currentIndex--;
|
||||||
|
|
||||||
|
// And swap it with the current element.
|
||||||
|
[array[currentIndex], array[randomIndex]] = [
|
||||||
|
array[randomIndex], array[currentIndex]];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export class errorMessage {
|
||||||
|
public msg: string;
|
||||||
|
public ephemeral: boolean;
|
||||||
|
|
||||||
|
constructor(msg: string, ephemeral: boolean = true) {
|
||||||
|
this.msg = msg;
|
||||||
|
this.ephemeral = ephemeral;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a simple class to contain an error message and related data
|
||||||
|
* @param msg error message
|
||||||
|
* @param ephemeral (default=true)
|
||||||
|
* @returns new errorMessage
|
||||||
|
*/
|
||||||
|
export const emsg = (msg: string, ephemeral: boolean = true) => new errorMessage(msg, ephemeral);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export type queueInfo = {
|
||||||
|
players: GuildMember[],
|
||||||
|
initiator: {
|
||||||
|
interaction: CommandInteraction,
|
||||||
|
member: GuildMember
|
||||||
|
},
|
||||||
|
teamsize: number,
|
||||||
|
timeout: NodeJS.Timeout
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get the GuildMember of an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be read
|
||||||
|
* @returns member
|
||||||
|
*/
|
||||||
|
export function getMember(interaction: CommandInteraction): GuildMember {
|
||||||
|
let member = interaction.member;
|
||||||
|
|
||||||
|
if (!(member instanceof GuildMember))
|
||||||
|
throw emsg('Unable to retrieve guild member information, please try again');
|
||||||
|
|
||||||
|
return member;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get the TextChannel of an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be read
|
||||||
|
* @returns member
|
||||||
|
*/
|
||||||
|
export function getChannel(interaction: CommandInteraction): TextChannel {
|
||||||
|
let channel = interaction.channel;
|
||||||
|
|
||||||
|
if (!(channel instanceof TextChannel))
|
||||||
|
throw emsg('Unable to retrieve text channel information, please try again');
|
||||||
|
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { CommandInteraction, GuildMember, TextChannel } from 'discord.js';
|
|
||||||
import { emsg } from './main';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* get the GuildMember of an interaction
|
|
||||||
* @throws errorMessage class if it cannot be read
|
|
||||||
*/
|
|
||||||
export function getMember(interaction: CommandInteraction): GuildMember {
|
|
||||||
const member = interaction.member;
|
|
||||||
|
|
||||||
if (!(member instanceof GuildMember))
|
|
||||||
throw emsg('general.noMember');
|
|
||||||
|
|
||||||
return member;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if it cannot be read
|
|
||||||
*/
|
|
||||||
export function getChannel(interaction: CommandInteraction): TextChannel {
|
|
||||||
const channel = interaction.channel;
|
|
||||||
|
|
||||||
if (!(channel instanceof TextChannel))
|
|
||||||
throw emsg('general.noChannel');
|
|
||||||
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if the Member cannot be read
|
|
||||||
*/
|
|
||||||
export function memberIsMod(interaction: CommandInteraction): boolean {
|
|
||||||
const member = getMember(interaction);
|
|
||||||
return member.permissionsIn(interaction.channelId).has('MANAGE_MESSAGES');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* get the TextChannel of an interaction
|
|
||||||
* @throws errorMessage class if the Member cannot be read or if Member is not a mod
|
|
||||||
*/
|
|
||||||
export function memberIsModThrow(interaction: CommandInteraction) {
|
|
||||||
if (!memberIsMod(interaction))
|
|
||||||
throw emsg('discord.notMod');
|
|
||||||
}
|
|
||||||
162
src/util/lang.ts
162
src/util/lang.ts
@@ -1,162 +0,0 @@
|
|||||||
import { MessageEmbed } from 'discord.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param str
|
|
||||||
* @param args
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
export function template(str: string, args: basicObject): string {
|
|
||||||
|
|
||||||
return str.replace(/{\w+}/g, str => {
|
|
||||||
|
|
||||||
const key = str.substring(1, str.length-1);
|
|
||||||
|
|
||||||
if (key in args)
|
|
||||||
return args[key];
|
|
||||||
|
|
||||||
return key;
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* converts bigString to string
|
|
||||||
*/
|
|
||||||
export function bigString(bigStr: bigString): string {
|
|
||||||
if (Array.isArray(bigStr))
|
|
||||||
return bigStr.join('\n');
|
|
||||||
return bigStr;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* converts Hex Color string to an RGB array
|
|
||||||
*/
|
|
||||||
export function resolveColor(color: string): [number, number, number] {
|
|
||||||
color = color.replace(/[^0-9a-f]/gi, '');
|
|
||||||
|
|
||||||
const colorNum: [number, number, number] = [0, 0, 0];
|
|
||||||
|
|
||||||
if (color.length === 3 || color.length === 6) {
|
|
||||||
|
|
||||||
const colorSpl = /([0-9a-f]{1,2})([0-9a-f]{1,2})([0-9a-f]{1,2})/.exec(color);
|
|
||||||
|
|
||||||
if (!colorSpl)
|
|
||||||
return colorNum;
|
|
||||||
|
|
||||||
for (let i = 0; i < colorSpl.length && i < colorNum.length; i++)
|
|
||||||
colorNum[i] = parseInt(colorSpl[i], 16);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return colorNum;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* converts embedObj to a string if applicable
|
|
||||||
* @param fallback the string to use if no valid strings can be found
|
|
||||||
*/
|
|
||||||
export function embedObjStr(embedObj: embedObj, args: basicObjectStr = {}, fallback = ''): string {
|
|
||||||
|
|
||||||
if (embedObj.content !== undefined)
|
|
||||||
return template(bigString(embedObj.content), args);
|
|
||||||
|
|
||||||
if (embedObj.description !== undefined)
|
|
||||||
return template(bigString(embedObj.description), args);
|
|
||||||
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* converts embedObj to Discord.MessageEmbed
|
|
||||||
*/
|
|
||||||
export function embedObjEmbed(embedObj: embedObj, args: basicObjectStr = {}): MessageEmbed {
|
|
||||||
const embed = new MessageEmbed(),
|
|
||||||
{ author, color, description, fields, footer, image, thumbnail, timestamp, title, url } = embedObj;
|
|
||||||
|
|
||||||
if (author !== undefined) {
|
|
||||||
|
|
||||||
let authorFix: authorData;
|
|
||||||
|
|
||||||
if (typeof author === 'string')
|
|
||||||
authorFix = {
|
|
||||||
name: template(author, args)
|
|
||||||
};
|
|
||||||
else {
|
|
||||||
|
|
||||||
const {name, icon, url} = author;
|
|
||||||
|
|
||||||
authorFix = {
|
|
||||||
name: template(name, args)
|
|
||||||
};
|
|
||||||
|
|
||||||
if (icon !== undefined)
|
|
||||||
authorFix.icon = template(icon, args);
|
|
||||||
|
|
||||||
if (url !== undefined)
|
|
||||||
authorFix.url = template(url, args);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
embed.setAuthor(authorFix);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (footer !== undefined) {
|
|
||||||
|
|
||||||
let footerFix: footerData;
|
|
||||||
|
|
||||||
if (typeof footer === 'string')
|
|
||||||
footerFix = {
|
|
||||||
text: template(footer, args)
|
|
||||||
};
|
|
||||||
else {
|
|
||||||
|
|
||||||
const {text, icon} = footer;
|
|
||||||
|
|
||||||
footerFix = {
|
|
||||||
text: template(text, args)
|
|
||||||
};
|
|
||||||
|
|
||||||
if (icon !== undefined)
|
|
||||||
footerFix.icon = template(icon, args);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
embed.setFooter(footerFix);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (color !== undefined)
|
|
||||||
embed.setColor(resolveColor(template(color, args)));
|
|
||||||
|
|
||||||
if (description !== undefined)
|
|
||||||
embed.setDescription(template(bigString(description), args));
|
|
||||||
|
|
||||||
if (image !== undefined)
|
|
||||||
embed.setImage(template(image, args));
|
|
||||||
|
|
||||||
if (thumbnail !== undefined)
|
|
||||||
embed.setThumbnail(template(thumbnail, args));
|
|
||||||
|
|
||||||
if (title !== undefined)
|
|
||||||
embed.setTitle(template(title, args));
|
|
||||||
|
|
||||||
if (url !== undefined)
|
|
||||||
embed.setURL(template(url, args));
|
|
||||||
|
|
||||||
if (timestamp === true)
|
|
||||||
embed.setTimestamp();
|
|
||||||
else if (typeof timestamp === 'string')
|
|
||||||
embed.setTimestamp(new Date(template(timestamp, args)));
|
|
||||||
else if (timestamp !== false)
|
|
||||||
embed.setTimestamp(timestamp);
|
|
||||||
|
|
||||||
fields?.forEach(field => {
|
|
||||||
embed.addField(template(field.name, args), template(bigString(field.value), args), field.inline);
|
|
||||||
});
|
|
||||||
|
|
||||||
return embed;
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import * as Lang from '../lang';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* shuffles an array
|
|
||||||
* https://stackoverflow.com/a/2450976/2856416
|
|
||||||
* @param array an array
|
|
||||||
* @returns an array but shuffled
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
export function shuffle(array: any[]) {
|
|
||||||
let currentIndex = array.length, randomIndex;
|
|
||||||
|
|
||||||
// While there remain elements to shuffle...
|
|
||||||
while (currentIndex != 0) {
|
|
||||||
|
|
||||||
// Pick a remaining element...
|
|
||||||
randomIndex = Math.floor(Math.random() * currentIndex);
|
|
||||||
currentIndex--;
|
|
||||||
|
|
||||||
// And swap it with the current element.
|
|
||||||
[array[currentIndex], array[randomIndex]] = [
|
|
||||||
array[randomIndex], array[currentIndex]];
|
|
||||||
}
|
|
||||||
|
|
||||||
return array;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* use the emsg() function instead
|
|
||||||
*/
|
|
||||||
export class errorMessage {
|
|
||||||
public msg: string;
|
|
||||||
public ephemeral: boolean;
|
|
||||||
|
|
||||||
constructor(msg: string, ephemeral = true) {
|
|
||||||
this.msg = msg;
|
|
||||||
this.ephemeral = ephemeral;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* a simple class to contain an error message and related data
|
|
||||||
* @param msg error message
|
|
||||||
* @param ephemeral (default=true)
|
|
||||||
* @returns new errorMessage
|
|
||||||
*/
|
|
||||||
export const emsg = (msg: string, ephemeral = true) => new errorMessage(Lang.get(`error.${msg}`), ephemeral);
|
|
||||||
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
// Special typescript project file, used by eslint only.
|
|
||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"include": [
|
|
||||||
// repeated from base config's "include" setting
|
|
||||||
"src",
|
|
||||||
|
|
||||||
// these are the eslint-only inclusions
|
|
||||||
".eslintrc.json",
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -6,16 +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,
|
|
||||||
"typeRoots": [
|
|
||||||
"./src/types/"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"include": [
|
|
||||||
"src"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user