Compare commits
38 Commits
93b7aea301
...
alt
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ad4f69f9f | |||
| dc0cc6685d | |||
| c04cd2ef12 | |||
| 763892443d | |||
| 9646d9f941 | |||
| fe866050d5 | |||
| 00d04c787d | |||
| f0283145dc | |||
| 50c297bfea | |||
| c2c59e53ca | |||
| 85d0e833dd | |||
| 1e990abdd5 | |||
| 5ce68086b8 | |||
| 5ee97cfd08 | |||
| 5167a25626 | |||
| a3a7acf9a8 | |||
| 7ae2cb8db0 | |||
| d7adc4afde | |||
| ae7093ae1d | |||
| e719eaef95 | |||
| c3855c31bc | |||
| f43c6ab4a6 | |||
| aa0fffdc94 | |||
| 588365e558 | |||
| fcfb3e290f | |||
| 1bf5e9d64f | |||
| 219d3e55e7 | |||
| 4f696e8b21 | |||
| f6adafe735 | |||
| c9f9ba366a | |||
| 9067a67bd5 | |||
| 8d2ec0ce02 | |||
| 92f2409768 | |||
| 66818a40be | |||
| 53db0f47b9 | |||
| adc15f0555 | |||
| e2d3097829 | |||
| 72ddf229ec |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
node_modules
|
node_modules
|
||||||
token
|
token
|
||||||
|
.DS_Store
|
||||||
|
log
|
||||||
92
README.md
92
README.md
@@ -1,17 +1,99 @@
|
|||||||
# 1800queue
|
<!-- markdownlint-disable MD033 -->
|
||||||
|
|
||||||
|
# 1800queue alt
|
||||||
|
|
||||||
|
This version does not run continuously, and requires each tourney to be started with a command
|
||||||
|
|
||||||
## Prerequirements
|
## Prerequirements
|
||||||
|
|
||||||
Download and install [Node.js](https://nodejs.org/en/)
|
Download and install [Node.js](https://nodejs.org/en/)
|
||||||
|
|
||||||
## Installation
|
<details>
|
||||||
|
<summary><b>Your bot's token</b></summary>
|
||||||
|
<br>
|
||||||
|
<p>Your bot's token can be found in your <a href="https://discord.com/developers/applications">Discord dev portal</a></p>
|
||||||
|
<ol>
|
||||||
|
<li>
|
||||||
|
Create or choose your application
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Go to the <code>Bot</code> section
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
click <code>Add Bot</code> if you haven't already
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Copy your token
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## Automatic Installation/Updating
|
||||||
|
|
||||||
|
1. Download and extract this repository
|
||||||
|
2. Open the `scripts` folder
|
||||||
|
3. Open the folder that corresponds with your operating system
|
||||||
|
4. Run the `install` file
|
||||||
|
|
||||||
|
## Manual Installation/Updating
|
||||||
|
|
||||||
1. Download and extract this repository
|
1. Download and extract this repository
|
||||||
2. Open the directory that contains `package.json` in your command prompt or terminal
|
2. Open the directory that contains `package.json` in your command prompt or terminal
|
||||||
3. Run the command `npm install`
|
3. Run the command `npm install`
|
||||||
4. Create a file called `token` in the same directory and enter your bot client's token
|
4. Create a file called `token` in the same directory and enter your bot client's token
|
||||||
|
|
||||||
## Running
|
## Starting
|
||||||
|
|
||||||
1. Open the directory that contains `package.json` in your command prompt or terminal
|
1. Open the `scripts` folder
|
||||||
2. Run the command `npm start`
|
2. Open the folder that corresponds with your operating system
|
||||||
|
3. Run the `start` file
|
||||||
|
|
||||||
|
## Other Start Scripts
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Mac/Linux Screen</b></summary>
|
||||||
|
<br>
|
||||||
|
<p>Screen allows the bot to run in the background without a terminal present</p>
|
||||||
|
<p><a href="https://linuxize.com/post/how-to-use-linux-screen/">Tutorial for usage</a>, check if it's installed already before installing</p>
|
||||||
|
<p><b>Installing</b></p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p>Mac</p>
|
||||||
|
<ol>
|
||||||
|
<li>Install <a href="https://formulae.brew.sh/"><code>Homebrew</code></a></li>
|
||||||
|
<li>Open the terminal and run the command <code>brew install screen</code></li>
|
||||||
|
</ol>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Linux</p>
|
||||||
|
<ul>
|
||||||
|
<li>Use your distribution's package manager to find <code>screen</code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Mac/Linux Tmux</b></summary>
|
||||||
|
<br>
|
||||||
|
<p>Tmux allows the bot to run in the background without a terminal present</p>
|
||||||
|
<p><a href="https://linuxize.com/post/getting-started-with-tmux/">Tutorial for usage</a>, check if it's installed already before installing</p>
|
||||||
|
<p><b>Installing</b></p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p>Mac</p>
|
||||||
|
<ol>
|
||||||
|
<li>Install <a href="https://formulae.brew.sh/"><code>Homebrew</code></a></li>
|
||||||
|
<li>Open the terminal and run the command <code>brew install tmux</code></li>
|
||||||
|
</ol>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Linux</p>
|
||||||
|
<ul>
|
||||||
|
<li>Use your distribution's package manager to find <code>tmux</code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
|||||||
163
dist/api.js
vendored
163
dist/api.js
vendored
@@ -18,47 +18,31 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|||||||
__setModuleDefault(result, mod);
|
__setModuleDefault(result, mod);
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
return (mod && mod.__esModule) ? mod : { "default": 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;
|
||||||
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"));
|
||||||
//making long regex rather than splitting the string at ":" because regex would be easier to debug than logic in the case the website changes
|
const util_1 = require("./util");
|
||||||
//while names cant have spaces, the name slot in ogtitle could be shown as "No Player Name" which has spaces
|
|
||||||
const uniteApiRegex = {
|
const uniteApiRegex = {
|
||||||
//$1 = name, $2 = id
|
//$1 = name, $2 = id
|
||||||
ogtitle: /Unite API - ([\w\d ]+) \((.*)\)/,
|
ogtitle: /unite api - (.+) \((.*)\)/i,
|
||||||
//$1 = level, $2 = rank, $3 = elo, $4 = battles, $5 = wins, $6 = win rate
|
//$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line)
|
||||||
ogdescription: /Pokémon Unite : Lv.(\d+) (\w+) \((\d+)\)\n Battles : (\d+)\n Wins : (\d+)\n Win Rate : (\d+)%/,
|
ogdescription: [
|
||||||
|
/lv\.(\d+) (\w+) \((\d+)\)/i,
|
||||||
|
/lv\.(\d+) (\w+): class (\d+)/i //other
|
||||||
|
]
|
||||||
};
|
};
|
||||||
/*
|
|
||||||
og:title
|
|
||||||
Unite API - IanWhysp (X188GF7)
|
|
||||||
|
|
||||||
og:description
|
|
||||||
Pokémon Unite : Lv.40 Master (1741)
|
|
||||||
Battles : 1089
|
|
||||||
Wins : 576
|
|
||||||
Win Rate : 52%
|
|
||||||
*/
|
|
||||||
/**
|
/**
|
||||||
* gets the html of the uniteApi page for the player
|
* gets the html of the uniteApi page for the player
|
||||||
* @param name name of player
|
* @param name name of player
|
||||||
* @returns the html of the page through a promise (rejects if the page status is not 200)
|
* @returns the html of the page through a promise (rejects if the page status is not 200)
|
||||||
*/
|
*/
|
||||||
function getHTML(name) {
|
function getHTML(name) {
|
||||||
name = name.replace(/[^\w\d]/g, '');
|
//name = name.replace(/[^\w\d]/g, '');
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const init = {
|
const init = {
|
||||||
host: 'uniteapi.dev',
|
host: 'uniteapi.dev',
|
||||||
@@ -71,11 +55,10 @@ function getHTML(name) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let result = Buffer.alloc(0);
|
let result = Buffer.alloc(0);
|
||||||
response.on('data', function (chunk) {
|
response.on('data', chunk => {
|
||||||
result = Buffer.concat([result, chunk]);
|
result = Buffer.concat([result, chunk]);
|
||||||
});
|
});
|
||||||
response.on('end', function () {
|
response.on('end', () => {
|
||||||
// result has response body buffer
|
|
||||||
resolve(result.toString());
|
resolve(result.toString());
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -87,20 +70,24 @@ function getHTML(name) {
|
|||||||
* interprets the html from getHTML()
|
* interprets the html from getHTML()
|
||||||
* @param name name of player
|
* @param name name of player
|
||||||
* @returns player data from site
|
* @returns player data from site
|
||||||
|
* @throws errorMessage class if the request fails
|
||||||
*/
|
*/
|
||||||
function readHTML(html) {
|
function readHTML(html) {
|
||||||
let metaElems = cheerio.load(html)('meta').toArray(), foundData = {
|
let $ = cheerio.load(html);
|
||||||
|
let metaElems = $('meta').toArray(), foundData = {
|
||||||
name: "",
|
name: "",
|
||||||
id: "",
|
id: "",
|
||||||
|
avatar: "",
|
||||||
level: "",
|
level: "",
|
||||||
rank: "",
|
rank: "",
|
||||||
elo: "",
|
elo: null,
|
||||||
|
class: null,
|
||||||
battles: "",
|
battles: "",
|
||||||
wins: "",
|
wins: "",
|
||||||
winrate: ""
|
winrate: ""
|
||||||
};
|
};
|
||||||
//filter down to just ones named "og:..."
|
//filter down to just ones named "og:..."
|
||||||
metaElems = metaElems.filter(el => { var _a; return (_a = el.attribs.property) === null || _a === void 0 ? void 0 : _a.startsWith('og:'); });
|
metaElems = metaElems.filter(el => el.attribs.property?.startsWith('og:'));
|
||||||
metaElems.forEach(el => {
|
metaElems.forEach(el => {
|
||||||
let attr = el.attribs;
|
let attr = el.attribs;
|
||||||
if (attr.property === 'og:title') {
|
if (attr.property === 'og:title') {
|
||||||
@@ -111,17 +98,63 @@ function readHTML(html) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (attr.property === 'og:description') {
|
else if (attr.property === 'og:description') {
|
||||||
let data = uniteApiRegex.ogdescription.exec(attr.content);
|
//all lines
|
||||||
if (data !== null && data.length >= 7) {
|
let lines = attr.content.split('\n').map(l => l.trim()), extraLines = [];
|
||||||
foundData.level = data[1];
|
//ensure first line is correct
|
||||||
foundData.rank = data[2];
|
while (lines.length && !/pok.mon unite/i.test(lines[0])) {
|
||||||
foundData.elo = data[3];
|
let line = lines.shift();
|
||||||
foundData.battles = data[4];
|
if (line)
|
||||||
foundData.wins = data[5];
|
extraLines.push(line);
|
||||||
foundData.winrate = data[6];
|
|
||||||
}
|
}
|
||||||
|
if (!lines.length)
|
||||||
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
|
//bring the first lines removed back into the data
|
||||||
|
lines = [
|
||||||
|
...lines,
|
||||||
|
...extraLines.filter(d => d)
|
||||||
|
];
|
||||||
|
//first line
|
||||||
|
{
|
||||||
|
//will be only text after "pokemon unite:"
|
||||||
|
let line = lines[0].split(':').slice(1).join(':').trim();
|
||||||
|
let regex = uniteApiRegex.ogdescription;
|
||||||
|
if (regex[0].test(line)) { //is master/has elo
|
||||||
|
let regexData = line.match(regex[0]);
|
||||||
|
if (!regexData || regexData.length < 4)
|
||||||
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
|
foundData.level = regexData[1];
|
||||||
|
foundData.rank = regexData[2];
|
||||||
|
foundData.elo = regexData[3];
|
||||||
|
}
|
||||||
|
else { //is not master/has a class
|
||||||
|
let regexData = line.match(regex[1]);
|
||||||
|
if (!regexData || regexData.length < 4)
|
||||||
|
throw (0, util_1.emsg)('Unable to read data, please try again');
|
||||||
|
foundData.level = regexData[1];
|
||||||
|
foundData.rank = regexData[2];
|
||||||
|
foundData.class = regexData[3];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.shift();
|
||||||
|
//rest of lines
|
||||||
|
lines.forEach(line => {
|
||||||
|
let split = line.split(':').map(l => l.trim()), key = split[0].toLowerCase().replace(/[^\w]/g, ''), value = split[1];
|
||||||
|
switch (key) {
|
||||||
|
case 'battles':
|
||||||
|
foundData.battles = value;
|
||||||
|
break;
|
||||||
|
case 'wins':
|
||||||
|
foundData.wins = value;
|
||||||
|
break;
|
||||||
|
case 'winrate':
|
||||||
|
foundData.winrate = value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
foundData.avatar = $('.player-card-image img').attr('src') || "";
|
||||||
|
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
||||||
return foundData;
|
return foundData;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -139,26 +172,40 @@ function verifyData(data) {
|
|||||||
* @param name name of player
|
* @param name name of player
|
||||||
* @returns player data
|
* @returns player data
|
||||||
*/
|
*/
|
||||||
function getPlayer(name) {
|
async function getPlayer(name) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
let html = await getHTML(name);
|
||||||
let html = yield getHTML(name);
|
let data = readHTML(html);
|
||||||
let data = readHTML(html);
|
if (verifyData(data))
|
||||||
if (verifyData(data))
|
return data;
|
||||||
return data;
|
return null;
|
||||||
return null;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
exports.getPlayer = getPlayer;
|
exports.getPlayer = getPlayer;
|
||||||
function getPlayerInteraction(interaction) {
|
async function sendPlayerEmbed(interaction, data) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
let embed = new discord_js_1.MessageEmbed()
|
||||||
let username = interaction.options.getString('username', true);
|
.setTitle(`${data.name} (${data.id})`)
|
||||||
interaction.deferReply();
|
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
|
||||||
let data = yield getPlayer(username);
|
.setTimestamp()
|
||||||
if (data === null)
|
.setThumbnail(data.avatar)
|
||||||
yield interaction.reply('Unable to find user');
|
.setDescription(`Level ${data.level}
|
||||||
else
|
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
|
||||||
yield interaction.reply('```\n' + JSON.stringify(data, null, 2) + '\n```');
|
|
||||||
});
|
**Battles** ${data.battles}
|
||||||
|
**Wins** ${data.wins}
|
||||||
|
**Win Rate** ${data.winrate}`);
|
||||||
|
await interaction.editReply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* calls getPlayer() with the name from the interaction
|
||||||
|
* @param interaction discord interaction
|
||||||
|
* @throws errorMessage class if the user cannot be found
|
||||||
|
*/
|
||||||
|
async function getPlayerInteraction(interaction) {
|
||||||
|
let username = interaction.options.getString('username', true);
|
||||||
|
await interaction.deferReply();
|
||||||
|
let data = await getPlayer(username);
|
||||||
|
if (data === null)
|
||||||
|
throw (0, util_1.emsg)('Unable to find user');
|
||||||
|
else
|
||||||
|
sendPlayerEmbed(interaction, data);
|
||||||
}
|
}
|
||||||
exports.getPlayerInteraction = getPlayerInteraction;
|
exports.getPlayerInteraction = getPlayerInteraction;
|
||||||
//await getPlayer('IanWhysp')
|
|
||||||
|
|||||||
59
dist/discord.js
vendored
59
dist/discord.js
vendored
@@ -1,50 +1,47 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.registerCommands = void 0;
|
exports.registerCommands = void 0;
|
||||||
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
|
||||||
const commands = [
|
const commands = [
|
||||||
{
|
{
|
||||||
name: 'queue',
|
name: 'queue',
|
||||||
description: 'creates a queue',
|
description: 'create a queue',
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
type: 4,
|
type: 4,
|
||||||
name: 'teamsize',
|
name: 'teamsize',
|
||||||
description: 'size of each team',
|
description: 'size of each team',
|
||||||
required: true
|
required: true,
|
||||||
|
min_value: 1
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'join',
|
name: 'join',
|
||||||
description: 'joins the active queue'
|
description: 'join the active queue'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'leave',
|
||||||
|
description: 'leave the active queue'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'ready',
|
name: 'ready',
|
||||||
description: 'readys the queue and displays team info'
|
description: 'ready the queue and display team info'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'queueinfo',
|
name: 'cancel',
|
||||||
description: 'gets info of the current queue'
|
description: 'cancels the current queue (must have the Manage Messages permission)'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'elo',
|
name: 'player',
|
||||||
description: 'displays your elo information',
|
description: 'display player information',
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
type: 3,
|
type: 3,
|
||||||
name: 'username',
|
name: 'username',
|
||||||
description: 'your in game name',
|
description: 'in game name or UniteApi short link',
|
||||||
required: true
|
required: true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -56,20 +53,18 @@ const commands = [
|
|||||||
* @param clientId discord bot client id
|
* @param clientId discord bot client id
|
||||||
* @param guildIds discord guild id(s)
|
* @param guildIds discord guild id(s)
|
||||||
*/
|
*/
|
||||||
function registerCommands(token, clientId, guildIds) {
|
async function registerCommands(token, clientId, guildIds) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
const rest = new rest_1.REST({ version: '9' }).setToken(token);
|
||||||
const rest = new rest_1.REST({ version: '9' }).setToken(token);
|
if (typeof guildIds === 'string')
|
||||||
if (typeof guildIds === 'string')
|
guildIds = [guildIds];
|
||||||
guildIds = [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 });
|
||||||
yield rest.put(v9_1.Routes.applicationGuildCommands(clientId, guildIds[i]), { body: commands });
|
console.log(`[${guildIds[i]}] registered command`);
|
||||||
console.log(`[${guildIds[i]}] registered command`);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
exports.registerCommands = registerCommands;
|
exports.registerCommands = registerCommands;
|
||||||
|
|||||||
55
dist/index.js
vendored
55
dist/index.js
vendored
@@ -18,44 +18,57 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|||||||
__setModuleDefault(result, mod);
|
__setModuleDefault(result, mod);
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const discord_js_1 = require("discord.js");
|
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 queue_1 = require("./queue");
|
const queue_1 = require("./queue");
|
||||||
|
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
|
||||||
|
console.log(new Date().toISOString() + '\n\n');
|
||||||
|
//get token
|
||||||
if (!fs.existsSync('./token')) {
|
if (!fs.existsSync('./token')) {
|
||||||
fs.writeFileSync('./token', '');
|
fs.writeFileSync('./token', '');
|
||||||
console.error('Missing Discord Token, please enter the bot token into the token file');
|
console.error('Missing Discord Token, please enter the bot token into the token file');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const TOKEN = fs.readFileSync('./token').toString();
|
const TOKEN = fs.readFileSync('./token').toString();
|
||||||
|
//discord connections
|
||||||
CLIENT.on('ready', client => {
|
CLIENT.on('ready', client => {
|
||||||
console.log(`Logged in as ${client.user.tag}`);
|
console.log(`Logged in as ${client.user.tag}`);
|
||||||
client.guilds.fetch().then(guilds => (0, discord_1.registerCommands)(TOKEN, client.user.id, guilds.map(g => g.id)));
|
client.guilds.fetch().then(guilds => (0, discord_1.registerCommands)(TOKEN, client.user.id, guilds.map(g => g.id)));
|
||||||
});
|
});
|
||||||
CLIENT.on('interactionCreate', (interaction) => __awaiter(void 0, void 0, void 0, function* () {
|
CLIENT.on('interactionCreate', async (interaction) => {
|
||||||
if (!interaction.isCommand())
|
if (!interaction.isCommand())
|
||||||
return;
|
return;
|
||||||
if (interaction.commandName === 'queue')
|
try {
|
||||||
yield (0, queue_1.createQueue)(interaction);
|
if (interaction.commandName === 'queue')
|
||||||
else if (interaction.commandName === 'join')
|
await (0, queue_1.createQueue)(interaction);
|
||||||
yield (0, queue_1.joinQueue)(interaction);
|
else if (interaction.commandName === 'join')
|
||||||
//else if (interaction.commandName === 'ready')
|
await (0, queue_1.joinQueue)(interaction);
|
||||||
// await readyQueue(interaction);
|
else if (interaction.commandName === 'leave')
|
||||||
else if (interaction.commandName === 'queueinfo')
|
await (0, queue_1.leaveQueue)(interaction);
|
||||||
yield (0, queue_1.queueInfo)(interaction);
|
else if (interaction.commandName === 'ready')
|
||||||
else if (interaction.commandName === 'elo')
|
await (0, queue_1.readyQueue)(interaction);
|
||||||
yield (0, api_1.getPlayerInteraction)(interaction);
|
else if (interaction.commandName === 'cancel')
|
||||||
}));
|
await (0, queue_1.cancelQueue)(interaction);
|
||||||
|
else if (interaction.commandName === 'player')
|
||||||
|
await (0, api_1.getPlayerInteraction)(interaction);
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
if (e instanceof util_1.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);
|
CLIENT.login(TOKEN);
|
||||||
|
|||||||
240
dist/queue.js
vendored
240
dist/queue.js
vendored
@@ -1,73 +1,189 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.queueInfo = exports.joinQueue = exports.createQueue = 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 util_1 = require("./util");
|
||||||
//maps ChannelID to QueueInfo
|
//maps ChannelID to QueueInfo
|
||||||
const QUEUE = new Map();
|
const QUEUE = new Map();
|
||||||
function createQueue(interaction) {
|
/**
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
* get the queueInfo of an interaction
|
||||||
console.log('COMMAND createQueue');
|
* @param interaction
|
||||||
let member = interaction.member;
|
* @throws errorMessage class if it does not exist
|
||||||
if (!(member instanceof discord_js_1.GuildMember)) {
|
* @returns queue info
|
||||||
yield interaction.reply('Unable to retrieve guild member information, please try again');
|
*/
|
||||||
return;
|
function getInfo(interaction) {
|
||||||
}
|
let info = QUEUE.get(interaction.channelId);
|
||||||
let channelId = interaction.channelId;
|
if (!info)
|
||||||
if (QUEUE.has(channelId)) {
|
throw (0, util_1.emsg)('There is not an active queue in this channel, type `/queue` to create one');
|
||||||
yield interaction.reply('There is already an active queue in this channel, type `/join` to join');
|
return info;
|
||||||
return;
|
}
|
||||||
}
|
exports.getInfo = getInfo;
|
||||||
QUEUE.set(channelId, {
|
/**
|
||||||
players: [],
|
* compiles all the get functions above
|
||||||
initiator: member,
|
* @param interaction
|
||||||
teamsize: interaction.options.getInteger('teamsize', true)
|
* @throws if another get function throws
|
||||||
});
|
* @returns object containing each
|
||||||
yield interaction.reply('Queue has been created, type `/join` to join');
|
*/
|
||||||
|
const getAll = (interaction) => ({
|
||||||
|
member: (0, util_1.getMember)(interaction),
|
||||||
|
channel: (0, util_1.getChannel)(interaction),
|
||||||
|
info: getInfo(interaction)
|
||||||
|
});
|
||||||
|
exports.getAll = getAll;
|
||||||
|
/**
|
||||||
|
* checks if the interaction data is already in the queue
|
||||||
|
* @param interaction
|
||||||
|
* @returns boolean
|
||||||
|
*/
|
||||||
|
function queueContains(interaction) {
|
||||||
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
|
if (info.players.map(m => m.id).includes(member.id))
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
exports.queueContains = queueContains;
|
||||||
|
/**
|
||||||
|
* creates the timeout for the queue
|
||||||
|
* @param interaction
|
||||||
|
* @returns time timeout identifier
|
||||||
|
*/
|
||||||
|
function setQueueTimeout(interaction) {
|
||||||
|
let channel = (0, util_1.getChannel)(interaction);
|
||||||
|
return setTimeout(() => {
|
||||||
|
clearQueue(interaction);
|
||||||
|
channel.send('Queue has been reset due to inactivity');
|
||||||
|
}, 5 * 60 * 1000); //5 minutes
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 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;
|
exports.createQueue = createQueue;
|
||||||
function joinQueue(interaction) {
|
/**
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
* joins a queue from an interaction
|
||||||
console.log('COMMAND joinQueue');
|
* @param interaction
|
||||||
let member = interaction.member;
|
* @throws errorMessage class if it cannot be joined
|
||||||
if (!(member instanceof discord_js_1.GuildMember)) {
|
*/
|
||||||
yield interaction.reply('Unable to retrieve guild member information, please try again');
|
async function joinQueue(interaction) {
|
||||||
return;
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
}
|
if (queueContains(interaction))
|
||||||
let channelId = interaction.channelId;
|
throw (0, util_1.emsg)('You are already in the active queue');
|
||||||
let info = QUEUE.get(channelId);
|
info.players.push(member);
|
||||||
if (!info) {
|
clearTimeout(info.timeout);
|
||||||
yield interaction.reply('There is not an active queue in this channel, type `/queue` to create one');
|
info.timeout = setQueueTimeout(interaction);
|
||||||
return;
|
QUEUE.set(interaction.channelId, info);
|
||||||
}
|
sendQueueEmbed(interaction);
|
||||||
info.players.push(member);
|
await interaction.reply('Joined the queue');
|
||||||
QUEUE.set(channelId, info);
|
|
||||||
yield interaction.reply('Joined the queue');
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
exports.joinQueue = joinQueue;
|
exports.joinQueue = joinQueue;
|
||||||
function queueInfo(interaction) {
|
/**
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
* leaves a queue from an interaction
|
||||||
console.log('COMMAND queueInfo');
|
* @param interaction
|
||||||
let channelId = interaction.channelId, info = QUEUE.get(channelId);
|
* @throws errorMessage class if it cannot be left
|
||||||
if (!info) {
|
*/
|
||||||
yield interaction.reply('There is not an active queue in this channel, type `/queue` to create one');
|
async function leaveQueue(interaction) {
|
||||||
return;
|
let { member, info } = (0, exports.getAll)(interaction);
|
||||||
}
|
if (!queueContains(interaction))
|
||||||
yield interaction.reply('```' + `
|
throw (0, util_1.emsg)('You aren\'t in the active queue');
|
||||||
players: ${info.players.map(p => p.user.tag).join('\n ')}
|
info.players.splice(info.players.indexOf(member), 1);
|
||||||
initiator: ${info.initiator.user.tag}
|
clearTimeout(info.timeout);
|
||||||
teamsize: ${info.teamsize}
|
info.timeout = setQueueTimeout(interaction);
|
||||||
` + '```');
|
QUEUE.set(interaction.channelId, info);
|
||||||
});
|
sendQueueEmbed(interaction);
|
||||||
|
await interaction.reply('Left the queue');
|
||||||
}
|
}
|
||||||
exports.queueInfo = queueInfo;
|
exports.leaveQueue = leaveQueue;
|
||||||
|
/**
|
||||||
|
* readys a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be readied
|
||||||
|
*/
|
||||||
|
async function readyQueue(interaction) {
|
||||||
|
let { member, info } = (0, exports.getAll)(interaction), { initiator } = info;
|
||||||
|
if (member.id !== initiator.member.id)
|
||||||
|
throw (0, util_1.emsg)('Only the queue initiator can ready the queue');
|
||||||
|
clearQueue(interaction);
|
||||||
|
if (info.players.filter(m => m.id !== initiator.member.id).length === 0)
|
||||||
|
throw (0, util_1.emsg)('Nobody signed up for the queue, the queue has been reset');
|
||||||
|
//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;
|
||||||
|
/**
|
||||||
|
* readys a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be reset
|
||||||
|
*/
|
||||||
|
async function cancelQueue(interaction) {
|
||||||
|
let { info, member, channel } = (0, exports.getAll)(interaction);
|
||||||
|
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
|
||||||
|
throw (0, util_1.emsg)('You do not have permission to run this command');
|
||||||
|
clearQueue(interaction);
|
||||||
|
await interaction.reply('Queue has been reset');
|
||||||
|
}
|
||||||
|
exports.cancelQueue = cancelQueue;
|
||||||
|
|||||||
66
dist/util.js
vendored
Normal file
66
dist/util.js
vendored
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.getChannel = exports.getMember = exports.emsg = exports.errorMessage = exports.shuffle = void 0;
|
||||||
|
const discord_js_1 = require("discord.js");
|
||||||
|
/**
|
||||||
|
* shuffles an array
|
||||||
|
* https://stackoverflow.com/a/2450976/2856416
|
||||||
|
* @param array an array
|
||||||
|
* @returns an array but shuffled
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
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(msg, ephemeral);
|
||||||
|
exports.emsg = emsg;
|
||||||
|
/**
|
||||||
|
* get the GuildMember of an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be read
|
||||||
|
* @returns member
|
||||||
|
*/
|
||||||
|
function getMember(interaction) {
|
||||||
|
let member = interaction.member;
|
||||||
|
if (!(member instanceof discord_js_1.GuildMember))
|
||||||
|
throw (0, exports.emsg)('Unable to retrieve guild member information, please try again');
|
||||||
|
return member;
|
||||||
|
}
|
||||||
|
exports.getMember = getMember;
|
||||||
|
/**
|
||||||
|
* get the TextChannel of an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be read
|
||||||
|
* @returns member
|
||||||
|
*/
|
||||||
|
function getChannel(interaction) {
|
||||||
|
let channel = interaction.channel;
|
||||||
|
if (!(channel instanceof discord_js_1.TextChannel))
|
||||||
|
throw (0, exports.emsg)('Unable to retrieve text channel information, please try again');
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
exports.getChannel = getChannel;
|
||||||
6776
package-lock.json
generated
6776
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
79
package.json
79
package.json
@@ -1,43 +1,44 @@
|
|||||||
{
|
{
|
||||||
"name": "1800queue",
|
"name": "1800queue-alt",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"start": "node .",
|
"start": "node .",
|
||||||
"watch": "npm-watch",
|
"watch": "npm-watch",
|
||||||
"dev": "npm-watch"
|
"dev": "npm-watch",
|
||||||
},
|
"getname": "echo $npm_package_name"
|
||||||
"watch": {
|
|
||||||
"build": {
|
|
||||||
"patterns": [
|
|
||||||
"src"
|
|
||||||
],
|
|
||||||
"extensions": "ts",
|
|
||||||
"legacyWatch": true
|
|
||||||
},
|
},
|
||||||
"start": {
|
"watch": {
|
||||||
"patterns": [
|
"build": {
|
||||||
"dist"
|
"patterns": [
|
||||||
],
|
"src"
|
||||||
"extensions": "js",
|
],
|
||||||
"legacyWatch": true,
|
"extensions": "ts",
|
||||||
"runOnChangeOnly": true
|
"legacyWatch": true
|
||||||
|
},
|
||||||
|
"start": {
|
||||||
|
"patterns": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"extensions": "js",
|
||||||
|
"legacyWatch": true,
|
||||||
|
"runOnChangeOnly": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"author": "",
|
||||||
|
"license": "MIT",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^17.0.13",
|
||||||
|
"npm-watch": "^0.11.0",
|
||||||
|
"ts-node": "^10.4.0",
|
||||||
|
"typescript": "^4.5.5"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@discordjs/rest": "^0.3.0",
|
||||||
|
"cheerio": "^1.0.0-rc.10",
|
||||||
|
"discord-api-types": "^0.26.1",
|
||||||
|
"discord.js": "^13.6.0"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"author": "",
|
|
||||||
"license": "MIT",
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^17.0.13",
|
|
||||||
"npm-watch": "^0.11.0",
|
|
||||||
"ts-node": "^10.4.0",
|
|
||||||
"typescript": "^4.5.5"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@discordjs/rest": "^0.3.0",
|
|
||||||
"cheerio": "^1.0.0-rc.10",
|
|
||||||
"discord-api-types": "^0.26.1",
|
|
||||||
"discord.js": "^13.6.0"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
18
scripts/mac-linux/install
Executable file
18
scripts/mac-linux/install
Executable file
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
#change to ccurrent directory
|
||||||
|
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
#run
|
||||||
|
npm install
|
||||||
|
|
||||||
|
#discord token
|
||||||
|
[ ! -f "token" ] && touch "token"
|
||||||
|
|
||||||
|
if [ ! -s "token" ]
|
||||||
|
then
|
||||||
|
printf "Enter your discord bot token: "
|
||||||
|
read token
|
||||||
|
printf $token > "token"
|
||||||
|
fi
|
||||||
42
scripts/mac-linux/start
Executable file
42
scripts/mac-linux/start
Executable file
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
#change to current directory
|
||||||
|
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
#colors
|
||||||
|
C1='\033[1;37m'
|
||||||
|
C2='\033[1;33m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
#make log folder
|
||||||
|
if [[ ! -d log ]]
|
||||||
|
then
|
||||||
|
mkdir log
|
||||||
|
fi
|
||||||
|
|
||||||
|
#current file number
|
||||||
|
num=0
|
||||||
|
if [[ -f log/number ]]
|
||||||
|
then
|
||||||
|
num=$(cat log/number)
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo $num > log/number
|
||||||
|
|
||||||
|
#watchdog
|
||||||
|
while true
|
||||||
|
do
|
||||||
|
|
||||||
|
#increment log file number
|
||||||
|
num=$(( num + 1 ))
|
||||||
|
echo $num > log/number
|
||||||
|
|
||||||
|
#run
|
||||||
|
npm start 2> log/$num.err | tee log/$num.out
|
||||||
|
|
||||||
|
#give chance to close program
|
||||||
|
printf "\n\n\n${C1}press ${C2}Control+C${C1} to close${NC}\n\n\n"
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
done
|
||||||
12
scripts/mac-linux/start_screen
Executable file
12
scripts/mac-linux/start_screen
Executable file
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
#change to ccurrent directory
|
||||||
|
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||||
|
|
||||||
|
#start
|
||||||
|
if [[ $(screen -ls | grep $(npm run getname -s)) ]]; then
|
||||||
|
echo "Session already exists"
|
||||||
|
else
|
||||||
|
screen -S $(npm run getname -s) -d -m ./start
|
||||||
|
echo "Created session"
|
||||||
|
fi
|
||||||
12
scripts/mac-linux/start_tmux
Executable file
12
scripts/mac-linux/start_tmux
Executable file
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
#change to ccurrent directory
|
||||||
|
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||||
|
|
||||||
|
#start
|
||||||
|
if [[ $(tmux ls | grep $(npm run getname -s)) ]]; then
|
||||||
|
echo "Session already exists"
|
||||||
|
else
|
||||||
|
tmux new-session -d -s $(npm run getname -s) ./start
|
||||||
|
echo "Created session"
|
||||||
|
fi
|
||||||
16
scripts/windows/install.bat
Normal file
16
scripts/windows/install.bat
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
@echo off
|
||||||
|
|
||||||
|
@REM change to ccurrent directory
|
||||||
|
cd %~f0\..\..\..\
|
||||||
|
|
||||||
|
@REM discord token
|
||||||
|
if not exist "token" copy NUL "token"
|
||||||
|
|
||||||
|
for /f %%i in ("token") do set size=%%~zi
|
||||||
|
if %size% equ 0 (
|
||||||
|
set /p token="Enter your discord bot token: "
|
||||||
|
echo | set /p=%id% > "token"
|
||||||
|
)
|
||||||
|
|
||||||
|
@REM run
|
||||||
|
npm install
|
||||||
28
scripts/windows/start.bat
Normal file
28
scripts/windows/start.bat
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
|
||||||
|
@Rem change to current directory
|
||||||
|
cd %~f0\..\..\..\
|
||||||
|
|
||||||
|
@Rem make log folder
|
||||||
|
if not exist log mkdir log
|
||||||
|
|
||||||
|
@Rem current file number
|
||||||
|
set /A num=0
|
||||||
|
if exist log\number set /p num=<log\number
|
||||||
|
|
||||||
|
echo %num > log\number
|
||||||
|
|
||||||
|
@Rem watchdog
|
||||||
|
:watchdog
|
||||||
|
|
||||||
|
@Rem increment log file number
|
||||||
|
set /A num=num+1
|
||||||
|
echo %num > log\number
|
||||||
|
|
||||||
|
@Rem run
|
||||||
|
powershell "npm start 2> log\%num%.err | tee log\%num%.out"
|
||||||
|
|
||||||
|
@Rem give chance to close program
|
||||||
|
timeout /t 5 /nobreak
|
||||||
|
|
||||||
|
goto watchdog
|
||||||
164
src/api.ts
164
src/api.ts
@@ -1,38 +1,32 @@
|
|||||||
import * as cheerio from 'cheerio';
|
import * as cheerio from 'cheerio';
|
||||||
import { CommandInteraction } from 'discord.js';
|
import { CommandInteraction, MessageEmbed } from 'discord.js';
|
||||||
import { IncomingMessage } from 'http';
|
import { IncomingMessage } from 'http';
|
||||||
import http from 'https';
|
import http from 'https';
|
||||||
|
import { emsg } from './util';
|
||||||
|
|
||||||
//making long regex rather than splitting the string at ":" because regex would be easier to debug than logic in the case the website changes
|
|
||||||
//while names cant have spaces, the name slot in ogtitle could be shown as "No Player Name" which has spaces
|
|
||||||
const uniteApiRegex = {
|
const uniteApiRegex = {
|
||||||
//$1 = name, $2 = id
|
//$1 = name, $2 = id
|
||||||
ogtitle: /Unite API - ([\w\d ]+) \((.*)\)/,
|
ogtitle: /unite api - (.+) \((.*)\)/i,
|
||||||
//$1 = level, $2 = rank, $3 = elo, $4 = battles, $5 = wins, $6 = win rate
|
//$1 = level, $2 = rank, $3 = elo/class (rest is found by splitting each line)
|
||||||
ogdescription: /Pokémon Unite : Lv.(\d+) (\w+) \((\d+)\)\n Battles : (\d+)\n Wins : (\d+)\n Win Rate : (\d+)%/,
|
ogdescription: [ //just the first line
|
||||||
|
/lv\.(\d+) (\w+) \((\d+)\)/i, //master
|
||||||
|
/lv\.(\d+) (\w+): class (\d+)/i //other
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
type uniteApiData = {
|
type uniteApiData = {
|
||||||
name: string,
|
name: string,
|
||||||
id: string,
|
id: string,
|
||||||
|
avatar: string,
|
||||||
|
|
||||||
level: string,
|
level: string,
|
||||||
rank: string,
|
rank: string,
|
||||||
elo: string,
|
class: string|null,
|
||||||
|
elo: string|null,
|
||||||
battles: string,
|
battles: string,
|
||||||
wins: string,
|
wins: string,
|
||||||
winrate: string
|
winrate: string
|
||||||
}
|
}
|
||||||
/*
|
|
||||||
og:title
|
|
||||||
Unite API - IanWhysp (X188GF7)
|
|
||||||
|
|
||||||
og:description
|
|
||||||
Pokémon Unite : Lv.40 Master (1741)
|
|
||||||
Battles : 1089
|
|
||||||
Wins : 576
|
|
||||||
Win Rate : 52%
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* gets the html of the uniteApi page for the player
|
* gets the html of the uniteApi page for the player
|
||||||
@@ -41,7 +35,7 @@ Pokémon Unite : Lv.40 Master (1741)
|
|||||||
*/
|
*/
|
||||||
function getHTML(name: string): Promise<string> {
|
function getHTML(name: string): Promise<string> {
|
||||||
|
|
||||||
name = name.replace(/[^\w\d]/g, '');
|
//name = name.replace(/[^\w\d]/g, '');
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|
||||||
@@ -59,12 +53,11 @@ function getHTML(name: string): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = Buffer.alloc(0);
|
let result = Buffer.alloc(0);
|
||||||
response.on('data', function(chunk) {
|
response.on('data', chunk => {
|
||||||
result = Buffer.concat([result, chunk]);
|
result = Buffer.concat([result, chunk]);
|
||||||
});
|
});
|
||||||
|
|
||||||
response.on('end', function() {
|
response.on('end', () => {
|
||||||
// result has response body buffer
|
|
||||||
resolve(result.toString());
|
resolve(result.toString());
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -80,16 +73,20 @@ function getHTML(name: string): Promise<string> {
|
|||||||
* interprets the html from getHTML()
|
* interprets the html from getHTML()
|
||||||
* @param name name of player
|
* @param name name of player
|
||||||
* @returns player data from site
|
* @returns player data from site
|
||||||
|
* @throws errorMessage class if the request fails
|
||||||
*/
|
*/
|
||||||
function readHTML(html: string): uniteApiData {
|
function readHTML(html: string): uniteApiData {
|
||||||
let metaElems = cheerio.load(html)('meta').toArray(),
|
let $ = cheerio.load(html)
|
||||||
|
let metaElems = $('meta').toArray(),
|
||||||
foundData: uniteApiData = {
|
foundData: uniteApiData = {
|
||||||
name: "",
|
name: "",
|
||||||
id: "",
|
id: "",
|
||||||
|
avatar: "",
|
||||||
|
|
||||||
level: "",
|
level: "",
|
||||||
rank: "",
|
rank: "",
|
||||||
elo: "",
|
elo: null,
|
||||||
|
class: null,
|
||||||
battles: "",
|
battles: "",
|
||||||
wins: "",
|
wins: "",
|
||||||
winrate: ""
|
winrate: ""
|
||||||
@@ -108,18 +105,89 @@ function readHTML(html: string): uniteApiData {
|
|||||||
foundData.id = data[2];
|
foundData.id = data[2];
|
||||||
}
|
}
|
||||||
} else if (attr.property === 'og:description') {
|
} else if (attr.property === 'og:description') {
|
||||||
let data = uniteApiRegex.ogdescription.exec(attr.content);
|
|
||||||
if (data !== null && data.length >= 7) {
|
//all lines
|
||||||
foundData.level = data[1];
|
let lines = attr.content.split('\n').map(l => l.trim()),
|
||||||
foundData.rank = data[2];
|
extraLines: string[] = [];
|
||||||
foundData.elo = data[3];
|
|
||||||
foundData.battles = data[4];
|
//ensure first line is correct
|
||||||
foundData.wins = data[5];
|
while (lines.length && !/pok.mon unite/i.test(lines[0])) {
|
||||||
foundData.winrate = data[6];
|
let line = lines.shift();
|
||||||
|
if (line)
|
||||||
|
extraLines.push(line);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!lines.length)
|
||||||
|
throw emsg('Unable to read data, please try again');
|
||||||
|
|
||||||
|
//bring the first lines removed back into the data
|
||||||
|
lines = [
|
||||||
|
...lines,
|
||||||
|
...extraLines.filter(d => d)
|
||||||
|
];
|
||||||
|
|
||||||
|
//first line
|
||||||
|
{
|
||||||
|
//will be only text after "pokemon unite:"
|
||||||
|
let line = lines[0].split(':').slice(1).join(':').trim();
|
||||||
|
|
||||||
|
let regex = uniteApiRegex.ogdescription;
|
||||||
|
|
||||||
|
if (regex[0].test(line)) { //is master/has elo
|
||||||
|
|
||||||
|
let regexData = line.match(regex[0]);
|
||||||
|
|
||||||
|
if (!regexData || regexData.length < 4)
|
||||||
|
throw emsg('Unable to read data, please try again');
|
||||||
|
|
||||||
|
foundData.level = regexData[1];
|
||||||
|
foundData.rank = regexData[2];
|
||||||
|
foundData.elo = regexData[3];
|
||||||
|
|
||||||
|
} else { //is not master/has a class
|
||||||
|
|
||||||
|
let regexData = line.match(regex[1]);
|
||||||
|
|
||||||
|
if (!regexData || regexData.length < 4)
|
||||||
|
throw emsg('Unable to read data, please try again');
|
||||||
|
|
||||||
|
foundData.level = regexData[1];
|
||||||
|
foundData.rank = regexData[2];
|
||||||
|
foundData.class = regexData[3];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.shift();
|
||||||
|
|
||||||
|
//rest of lines
|
||||||
|
lines.forEach(line => {
|
||||||
|
|
||||||
|
let split = line.split(':').map(l => l.trim()),
|
||||||
|
key = split[0].toLowerCase().replace(/[^\w]/g, ''),
|
||||||
|
value = split[1];
|
||||||
|
|
||||||
|
switch(key) {
|
||||||
|
case 'battles':
|
||||||
|
foundData.battles = value;
|
||||||
|
break;
|
||||||
|
case 'wins':
|
||||||
|
foundData.wins = value;
|
||||||
|
break;
|
||||||
|
case 'winrate':
|
||||||
|
foundData.winrate = value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
});
|
||||||
|
|
||||||
|
foundData.avatar = $('.player-card-image img').attr('src') || "";
|
||||||
|
foundData.avatar = foundData.avatar.replace('../', 'https://uniteapi.dev/');
|
||||||
|
|
||||||
return foundData;
|
return foundData;
|
||||||
|
|
||||||
@@ -149,15 +217,35 @@ export async function getPlayer(name: string): Promise<uniteApiData|null> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPlayerInteraction(interaction: CommandInteraction): Promise<void> {
|
async function sendPlayerEmbed(interaction: CommandInteraction, data: uniteApiData) {
|
||||||
|
|
||||||
|
let embed = new MessageEmbed()
|
||||||
|
.setTitle(`${data.name} (${data.id})`)
|
||||||
|
.setURL(`https://uniteapi.dev/p/${encodeURIComponent(data.name)}`)
|
||||||
|
.setTimestamp()
|
||||||
|
.setThumbnail(data.avatar)
|
||||||
|
.setDescription(`Level ${data.level}
|
||||||
|
${data.rank} ${data.elo ? `(${data.elo})` : `Class ${data.class}`}
|
||||||
|
|
||||||
|
**Battles** ${data.battles}
|
||||||
|
**Wins** ${data.wins}
|
||||||
|
**Win Rate** ${data.winrate}`);
|
||||||
|
|
||||||
|
await interaction.editReply({embeds: [embed]});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* calls getPlayer() with the name from the interaction
|
||||||
|
* @param interaction discord interaction
|
||||||
|
* @throws errorMessage class if the user cannot be found
|
||||||
|
*/
|
||||||
|
export async function getPlayerInteraction(interaction: CommandInteraction) {
|
||||||
let username = interaction.options.getString('username', true);
|
let username = interaction.options.getString('username', true);
|
||||||
interaction.deferReply();
|
await interaction.deferReply();
|
||||||
|
|
||||||
let data = await getPlayer(username);
|
let data = await getPlayer(username);
|
||||||
if (data === null)
|
if (data === null)
|
||||||
await interaction.reply('Unable to find user');
|
throw emsg('Unable to find user');
|
||||||
else
|
else
|
||||||
await interaction.reply('```\n'+JSON.stringify(data, null, 2)+'\n```');
|
sendPlayerEmbed(interaction, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
//await getPlayer('IanWhysp')
|
|
||||||
@@ -1,39 +1,45 @@
|
|||||||
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
|
||||||
const commands = [
|
const commands = [
|
||||||
{
|
{
|
||||||
name: 'queue',
|
name: 'queue',
|
||||||
description: 'creates a queue',
|
description: 'create a queue',
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
type: 4, //INTEGER
|
type: 4, //INTEGER
|
||||||
name: 'teamsize',
|
name: 'teamsize',
|
||||||
description: 'size of each team',
|
description: 'size of each team',
|
||||||
required: true
|
required: true,
|
||||||
|
min_value: 1
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'join',
|
name: 'join',
|
||||||
description: 'joins the active queue'
|
description: 'join the active queue'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'leave',
|
||||||
|
description: 'leave the active queue'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'ready',
|
name: 'ready',
|
||||||
description: 'readys the queue and displays team info'
|
description: 'ready the queue and display team info'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'queueinfo',
|
name: 'cancel',
|
||||||
description: 'gets info of the current queue'
|
description: 'cancels the current queue (must have the Manage Messages permission)'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'elo',
|
name: 'player',
|
||||||
description: 'displays your elo information',
|
description: 'display player information',
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
type: 3, //STRING
|
type: 3, //STRING
|
||||||
name: 'username',
|
name: 'username',
|
||||||
description: 'your in game name',
|
description: 'in game name or UniteApi short link',
|
||||||
required: true
|
required: true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
48
src/index.ts
48
src/index.ts
@@ -3,9 +3,14 @@ import { Client, Intents } from 'discord.js';
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { getPlayerInteraction } from './api';
|
import { getPlayerInteraction } from './api';
|
||||||
import { registerCommands } from './discord';
|
import { registerCommands } from './discord';
|
||||||
import { createQueue, joinQueue, queueInfo } from './queue';
|
import { cancelQueue, createQueue, joinQueue, leaveQueue, readyQueue } from './queue';
|
||||||
|
import { errorMessage } from './util';
|
||||||
const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS] });
|
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')) {
|
if (!fs.existsSync('./token')) {
|
||||||
fs.writeFileSync('./token', '');
|
fs.writeFileSync('./token', '');
|
||||||
console.error('Missing Discord Token, please enter the bot token into the token file');
|
console.error('Missing Discord Token, please enter the bot token into the token file');
|
||||||
@@ -13,6 +18,7 @@ if (!fs.existsSync('./token')) {
|
|||||||
}
|
}
|
||||||
const TOKEN = fs.readFileSync('./token').toString();
|
const TOKEN = fs.readFileSync('./token').toString();
|
||||||
|
|
||||||
|
//discord connections
|
||||||
CLIENT.on('ready', client => {
|
CLIENT.on('ready', client => {
|
||||||
console.log(`Logged in as ${client.user.tag}`);
|
console.log(`Logged in as ${client.user.tag}`);
|
||||||
client.guilds.fetch().then(guilds =>
|
client.guilds.fetch().then(guilds =>
|
||||||
@@ -22,16 +28,36 @@ CLIENT.on('ready', client => {
|
|||||||
CLIENT.on('interactionCreate', async interaction => {
|
CLIENT.on('interactionCreate', async interaction => {
|
||||||
if (!interaction.isCommand()) return;
|
if (!interaction.isCommand()) return;
|
||||||
|
|
||||||
if (interaction.commandName === 'queue')
|
try {
|
||||||
await createQueue(interaction);
|
|
||||||
else if (interaction.commandName === 'join')
|
if (interaction.commandName === 'queue')
|
||||||
await joinQueue(interaction);
|
await createQueue(interaction);
|
||||||
//else if (interaction.commandName === 'ready')
|
else if (interaction.commandName === 'join')
|
||||||
// await readyQueue(interaction);
|
await joinQueue(interaction);
|
||||||
else if (interaction.commandName === 'queueinfo')
|
else if (interaction.commandName === 'leave')
|
||||||
await queueInfo(interaction);
|
await leaveQueue(interaction);
|
||||||
else if (interaction.commandName === 'elo')
|
else if (interaction.commandName === 'ready')
|
||||||
await getPlayerInteraction(interaction);
|
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);
|
CLIENT.login(TOKEN);
|
||||||
|
|||||||
264
src/queue.ts
264
src/queue.ts
@@ -1,86 +1,236 @@
|
|||||||
import { CommandInteraction, GuildMember } from "discord.js";
|
import { CommandInteraction, GuildMember, MessageEmbed } from "discord.js";
|
||||||
|
import { emsg, getChannel, getMember, queueInfo, shuffle } from "./util";
|
||||||
type queueInfo = {
|
|
||||||
players: GuildMember[],
|
|
||||||
initiator: GuildMember,
|
|
||||||
teamsize: number
|
|
||||||
}
|
|
||||||
|
|
||||||
//maps ChannelID to QueueInfo
|
//maps ChannelID to QueueInfo
|
||||||
const QUEUE = new Map<string, queueInfo>();
|
const QUEUE = new Map<string, queueInfo>();
|
||||||
|
|
||||||
export async function createQueue(interaction: CommandInteraction) {
|
/**
|
||||||
|
* get the queueInfo of an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it does not exist
|
||||||
|
* @returns queue info
|
||||||
|
*/
|
||||||
|
export function getInfo(interaction: CommandInteraction): queueInfo {
|
||||||
|
let info = QUEUE.get(interaction.channelId);
|
||||||
|
|
||||||
console.log('COMMAND createQueue')
|
if (!info)
|
||||||
|
throw emsg('There is not an active queue in this channel, type `/queue` to create one');
|
||||||
|
|
||||||
let member = interaction.member;
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
if (!(member instanceof GuildMember)) {
|
/**
|
||||||
await interaction.reply('Unable to retrieve guild member information, please try again');
|
* compiles all the get functions above
|
||||||
return;
|
* @param interaction
|
||||||
}
|
* @throws if another get function throws
|
||||||
|
* @returns object containing each
|
||||||
let channelId = interaction.channelId;
|
*/
|
||||||
|
export const getAll = (interaction: CommandInteraction) => ({
|
||||||
if (QUEUE.has(channelId)) {
|
member: getMember(interaction),
|
||||||
await interaction.reply('There is already an active queue in this channel, type `/join` to join');
|
channel: getChannel(interaction),
|
||||||
return;
|
info: getInfo(interaction)
|
||||||
}
|
|
||||||
|
|
||||||
QUEUE.set(channelId, {
|
|
||||||
players: [],
|
|
||||||
initiator: member,
|
|
||||||
teamsize: interaction.options.getInteger('teamsize', true)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await interaction.reply('Queue has been created, type `/join` to join');
|
/**
|
||||||
|
* checks if the interaction data is already in the queue
|
||||||
|
* @param interaction
|
||||||
|
* @returns boolean
|
||||||
|
*/
|
||||||
|
export function queueContains(interaction: CommandInteraction): boolean {
|
||||||
|
|
||||||
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
|
if (info.players.map(m=>m.id).includes(member.id))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* creates the timeout for the queue
|
||||||
|
* @param interaction
|
||||||
|
* @returns time timeout identifier
|
||||||
|
*/
|
||||||
|
function setQueueTimeout(interaction: CommandInteraction) {
|
||||||
|
let channel = getChannel(interaction);
|
||||||
|
return setTimeout(() => {
|
||||||
|
clearQueue(interaction);
|
||||||
|
channel.send('Queue has been reset due to inactivity');
|
||||||
|
}, 5*60*1000) //5 minutes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* updates the rich embed for the current queue
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function sendQueueEmbed(interaction: CommandInteraction, closed: boolean = false) {
|
||||||
|
let info = getInfo(interaction),
|
||||||
|
origInteraction = info.initiator.interaction;
|
||||||
|
|
||||||
|
let embed = new MessageEmbed()
|
||||||
|
.setTitle('Queue')
|
||||||
|
.setAuthor({
|
||||||
|
name: info.initiator.member.displayName,
|
||||||
|
iconURL: info.initiator.member.displayAvatarURL({dynamic: true})
|
||||||
|
})
|
||||||
|
.addField('Team Size', info.teamsize.toString(), true)
|
||||||
|
.addField('Players Joined', info.players.length.toString(), true)
|
||||||
|
.setFooter({text: closed ? 'queue is finished' : 'type /join'});
|
||||||
|
|
||||||
|
if (origInteraction.deferred || origInteraction.replied)
|
||||||
|
await origInteraction.editReply({embeds: [embed]});
|
||||||
|
else
|
||||||
|
await origInteraction.reply({embeds: [embed]});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function sendTeamsEmbed(interaction: CommandInteraction, teams: GuildMember[][]) {
|
||||||
|
let embed = new MessageEmbed()
|
||||||
|
.setTitle('Teams');
|
||||||
|
|
||||||
|
teams.forEach((team, i) => {
|
||||||
|
team.map(m => m.user.tag);
|
||||||
|
embed.addField(`Team ${i+1}`, team.join('\n'))
|
||||||
|
});
|
||||||
|
|
||||||
|
interaction.reply({embeds: [embed]});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sends the list of teams
|
||||||
|
* @param interaction
|
||||||
|
*/
|
||||||
|
async function clearQueue(interaction: CommandInteraction) {
|
||||||
|
let info = getInfo(interaction);
|
||||||
|
sendQueueEmbed(interaction, true);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
QUEUE.delete(interaction.channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* creates a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be created
|
||||||
|
*/
|
||||||
|
export async function createQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
|
let member = getMember(interaction),
|
||||||
|
{channelId} = interaction,
|
||||||
|
teamsize = interaction.options.getInteger('teamsize', true);
|
||||||
|
|
||||||
|
if (QUEUE.has(channelId))
|
||||||
|
throw emsg('There is already an active queue in this channel, ' + (queueContains(interaction) ? 'and you are already in it' : 'type `/join` to join'));
|
||||||
|
|
||||||
|
QUEUE.set(channelId, {
|
||||||
|
players: [
|
||||||
|
member
|
||||||
|
],
|
||||||
|
initiator: {
|
||||||
|
interaction,
|
||||||
|
member
|
||||||
|
},
|
||||||
|
teamsize: teamsize,
|
||||||
|
timeout: setQueueTimeout(interaction)
|
||||||
|
});
|
||||||
|
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* joins a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be joined
|
||||||
|
*/
|
||||||
export async function joinQueue(interaction: CommandInteraction) {
|
export async function joinQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
console.log('COMMAND joinQueue')
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
let member = interaction.member;
|
if (queueContains(interaction))
|
||||||
|
throw emsg('You are already in the active queue');
|
||||||
if (!(member instanceof GuildMember)) {
|
|
||||||
await interaction.reply('Unable to retrieve guild member information, please try again');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let channelId = interaction.channelId;
|
|
||||||
|
|
||||||
let info = QUEUE.get(channelId);
|
|
||||||
|
|
||||||
if (!info) {
|
|
||||||
await interaction.reply('There is not an active queue in this channel, type `/queue` to create one');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
info.players.push(member);
|
info.players.push(member);
|
||||||
|
clearTimeout(info.timeout);
|
||||||
|
info.timeout = setQueueTimeout(interaction)
|
||||||
|
|
||||||
QUEUE.set(channelId, info);
|
QUEUE.set(interaction.channelId, info);
|
||||||
|
|
||||||
|
sendQueueEmbed(interaction);
|
||||||
await interaction.reply('Joined the queue');
|
await interaction.reply('Joined the queue');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function queueInfo(interaction: CommandInteraction) {
|
/**
|
||||||
|
* leaves a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be left
|
||||||
|
*/
|
||||||
|
export async function leaveQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
console.log('COMMAND queueInfo')
|
let {member, info} = getAll(interaction);
|
||||||
|
|
||||||
let channelId = interaction.channelId,
|
if (!queueContains(interaction))
|
||||||
info = QUEUE.get(channelId);
|
throw emsg('You aren\'t in the active queue');
|
||||||
|
|
||||||
if (!info) {
|
info.players.splice(info.players.indexOf(member), 1);
|
||||||
await interaction.reply('There is not an active queue in this channel, type `/queue` to create one');
|
clearTimeout(info.timeout);
|
||||||
return;
|
info.timeout = setQueueTimeout(interaction)
|
||||||
}
|
|
||||||
|
|
||||||
await interaction.reply('```'+`
|
QUEUE.set(interaction.channelId, info);
|
||||||
players: ${info.players.map(p => p.user.tag).join('\n ')}
|
|
||||||
initiator: ${info.initiator.user.tag}
|
sendQueueEmbed(interaction);
|
||||||
teamsize: ${info.teamsize}
|
await interaction.reply('Left the queue');
|
||||||
`+'```')
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* readys a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be readied
|
||||||
|
*/
|
||||||
|
export async function readyQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
|
let {member, info} = getAll(interaction),
|
||||||
|
{initiator} = info;
|
||||||
|
|
||||||
|
if (member.id !== initiator.member.id)
|
||||||
|
throw emsg('Only the queue initiator can ready the queue');
|
||||||
|
|
||||||
|
clearQueue(interaction);
|
||||||
|
|
||||||
|
if (info.players.filter(m => m.id !== initiator.member.id).length === 0)
|
||||||
|
throw emsg('Nobody signed up for the queue, the queue has been reset');
|
||||||
|
|
||||||
|
//team data
|
||||||
|
let playerlist: GuildMember[] = shuffle(info.players),
|
||||||
|
teams: GuildMember[][] = [];
|
||||||
|
|
||||||
|
//fill team data
|
||||||
|
for (let i = 0; i < playerlist.length; i+= info.teamsize)
|
||||||
|
teams.push(playerlist.slice(i, i+info.teamsize));
|
||||||
|
|
||||||
|
sendTeamsEmbed(interaction, teams);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* readys a queue from an interaction
|
||||||
|
* @param interaction
|
||||||
|
* @throws errorMessage class if it cannot be reset
|
||||||
|
*/
|
||||||
|
export async function cancelQueue(interaction: CommandInteraction) {
|
||||||
|
|
||||||
|
let {info, member, channel} = getAll(interaction);
|
||||||
|
|
||||||
|
if (!member.permissionsIn(channel).has('MANAGE_MESSAGES'))
|
||||||
|
throw emsg('You do not have permission to run this command');
|
||||||
|
|
||||||
|
clearQueue(interaction);
|
||||||
|
|
||||||
|
await interaction.reply('Queue has been reset');
|
||||||
|
|
||||||
}
|
}
|
||||||
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,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "es2016",
|
"target": "es2020",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"rootDir": "./src",
|
"rootDir": "./src",
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
|
|||||||
Reference in New Issue
Block a user