Archived
0
0
Fork 0

Compare commits

..

5 commits

32 changed files with 1625 additions and 6925 deletions

132
.eslintrc Normal file
View file

@ -0,0 +1,132 @@
{
"root": true,
"env": {
"es2021": true,
"node": true,
"commonjs": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2021,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint",
"unicorn",
"header"
],
"rules": {
// Base Eslint Rules
"indent": [
"error",
"tab",
{
"SwitchCase": 1,
"CallExpression": {
"arguments": 1
}
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"eol-last": [
"error",
"always"
],
"object-curly-spacing": [
"error",
"always"
],
"default-case": "error",
"comma-dangle": [
"error",
"always-multiline"
],
"no-case-declarations": "off",
"camelcase": "off",
"keyword-spacing": "error",
"spaced-comment": [
"error",
"always"
],
"no-var": "error",
"eqeqeq": "error",
"no-eq-null": "error",
"arrow-parens": [
"error",
"always"
],
// TypeScript Rules
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "class",
"format": [
"PascalCase"
]
},
{
"selector": "classProperty",
"modifiers": [
"private"
],
"format": [
"camelCase"
],
"leadingUnderscore": "require"
},
{
"selector": "interface",
"format": null,
"custom": {
"regex": "^I",
"match": true
}
},
{
"selector": "enum",
"format": null,
"custom": {
"regex": "^E",
"match": true
}
}
],
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/explicit-member-accessibility": [
"error",
{
"accessibility": "explicit"
}
],
"@typescript-eslint/explicit-function-return-type": "error",
// Unicorn Rules
"unicorn/filename-case": [
"error",
{
"case": "camelCase"
}
],
// Header rules
"header/header": [
2,
"license-header.txt"
]
},
"reportUnusedDisableDirectives": true
}

1
.husky/.gitignore vendored
View file

@ -1 +0,0 @@
_

View file

@ -2,4 +2,3 @@
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged
yarn test

2
.nvmrc
View file

@ -1 +1 @@
lts/fermium
lts/gallium

7
.nycrc
View file

@ -1,7 +0,0 @@
{
"extends": "@istanbuljs/nyc-config-typescript",
"all": true,
"check-coverage": true,
"include": ["src/lib/**/*.ts"],
"reporter": ["html", "text"]
}

File diff suppressed because one or more lines are too long

View file

@ -3,11 +3,9 @@ nmMode: hardlinks-local
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs
spec: "@yarnpkg/plugin-typescript"
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: "@yarnpkg/plugin-workspace-tools"
- path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs
spec: "@yarnpkg/plugin-typescript"
yarnPath: .yarn/releases/yarn-3.1.0.cjs

View file

@ -1 +0,0 @@
UwU

View file

@ -1,13 +1,12 @@
{
"token": "",
"logLevel": "",
"prefix": "",
"owner": "",
"db": {
"host": "",
"port": "0000",
"user": "",
"password": "",
"database": ""
}
},
"logLevel": "",
"ownerId": "",
"token": "",
}

View file

@ -1,3 +0,0 @@
{
"logLevel": "verbose"
}

View file

@ -1,31 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
exports.shorthands = undefined;
exports.up = (pgm) => {
pgm.createTable('settings', {
id: {
type: 'varchar(20)',
},
locale: {
type: 'varchar(10)',
default: 'en-US',
notNull: true,
},
});
};

View file

@ -15,10 +15,8 @@
"private": true,
"scripts": {
"clean": "rimraf dist",
"compile:dev": "tsc",
"compile:prod": "rollup -c --compact",
"commit": "commit",
"coverage": "NODE_CONFIG_ENV=tests nyc yarn run test",
"compile": "tsc",
"commit": "cz",
"lint": "eslint --format=pretty src/**/*.ts",
"lint:save": "eslint --format=pretty --save src/**/*.ts",
"migrate": "node-pg-migrate",
@ -26,33 +24,25 @@
"release:alpha": "standard-version --prelease alpha -s",
"release:beta": "standard-version --prelease beta -s",
"release:full": "standard-version -s",
"run:dev": "NODE_CONFIG_ENV=dev node dist/src/index.js",
"run:dev": "NODE_CONFIG_ENV=dev node dist/index.js",
"run:prod": "NODE_CONFIG_ENV=production node dist/index.js",
"test": "NODE_CONFIG_ENV=tests mocha -r ts-node/register -r tsconfig-paths/register tests/**/*.test.ts",
"watch:bot": "NODE_CONFIG_ENV=dev nodemon dist/src/index.js",
"watch:rollup": "rollup -c --compact --watch",
"watch:bot": "NODE_CONFIG_ENV=dev nodemon dist/index.js",
"watch:tsc": "tsc --watch"
},
"dependencies": {
"@discordjs/opus": "^0.6.0",
"@discordjs/voice": "^0.7.2",
"@discordjs/rest": "^0.1.0-canary.0",
"@neonjs/framework": "^1.1.1",
"bufferutil": "^4.0.5",
"chalk": "^4.1.2",
"config": "^3.3.6",
"discord.js": "^13.3.0",
"erlpack": "^0.1.3",
"ffmpeg-static": "^4.4.0",
"discord-api-types": "^0.24.0",
"figlet": "^1.5.2",
"gradient-string": "^1.2.0",
"i18next": "^21.3.3",
"i18next-fluent": "^2.0.0",
"i18next": "^21.4.0",
"i18next-fs-backend": "^1.1.1",
"jsonschema": "^1.4.0",
"luxon": "^2.0.2",
"module-alias": "^2.2.2",
"node-pg-migrate": "^6.0.0",
"pg": "^8.7.1",
"sodium": "^3.0.2",
"sql-template-strings": "^2.2.2",
"terminal-link": "^3.0.0",
"tslib": "^2.3.1",
@ -62,125 +52,37 @@
"zlib-sync": "^0.1.7"
},
"devDependencies": {
"@commitlint/cli": "^13.2.1",
"@commitlint/config-conventional": "^13.2.0",
"@commitlint/prompt-cli": "^13.2.1",
"@istanbuljs/nyc-config-typescript": "^1.0.1",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-strip": "^2.1.0",
"@rollup/plugin-typescript": "^8.3.0",
"@types/chai": "^4.2.22",
"@commitlint/cli": "^14.1.0",
"@commitlint/config-conventional": "^14.1.0",
"@commitlint/cz-commitlint": "^14.1.0",
"@types/config": "^0.0.40",
"@types/eslint": "^7.28.2",
"@types/figlet": "^1.5.4",
"@types/gradient-string": "^1.1.2",
"@types/i18next-fs-backend": "^1.1.2",
"@types/inquirer": "^8.1.3",
"@types/luxon": "^2.0.5",
"@types/mocha": "^8.2.3",
"@types/module-alias": "^2.0.1",
"@types/node": "^16.11.6",
"@types/pg": "^8.6.1",
"@types/rimraf": "^3.0.2",
"@types/rollup-plugin-progress": "^1.1.1",
"@types/rollup-plugin-size-snapshot": "^0.10.1",
"@types/sinon": "^10.0.6",
"@types/source-map-support": "^0.5.4",
"@typescript-eslint/eslint-plugin": "^5.2.0",
"@typescript-eslint/parser": "^5.2.0",
"@typescript-eslint/typescript-estree": "^5.2.0",
"chai": "^4.3.4",
"@typescript-eslint/eslint-plugin": "^5.3.0",
"@typescript-eslint/parser": "^5.3.0",
"@typescript-eslint/typescript-estree": "^5.3.0",
"commitizen": "^4.2.4",
"eslint": "^8.1.0",
"eslint-formatter-pretty": "^4.1.0",
"eslint-plugin-header": "^3.1.1",
"eslint-plugin-unicorn": "^38.0.0",
"husky": "^7.0.4",
"i18next-chained-backend": "^3.0.2",
"inquirer": "^8.2.0",
"lint-staged": "^11.2.6",
"mocha": "^9.1.3",
"nodemon": "^2.0.14",
"nyc": "^15.1.0",
"rimraf": "^3.0.2",
"rollup": "^2.58.3",
"rollup-plugin-analyzer": "^4.0.0",
"rollup-plugin-multi-input": "^1.3.1",
"rollup-plugin-progress": "^1.1.2",
"rollup-plugin-size-snapshot": "^0.12.0",
"rollup-plugin-sizes": "^1.0.4",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-visualizer": "^5.5.2",
"sinon": "^11.1.2",
"source-map-support": "^0.5.20",
"standard-version": "^9.3.2",
"ts-node": "^10.4.0",
"ts-sql-plugin": "^0.10.0",
"tsconfig-paths": "^3.11.0",
"typescript-eslint-language-service": "^4.1.5"
},
"eslintConfig": {
"root": true,
"env": {
"es2021": true,
"node": true,
"commonjs": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2021,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint",
"header"
],
"rules": {
"indent": [
"error",
"tab",
{
"SwitchCase": 1,
"CallExpression": {
"arguments": 1
}
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"eol-last": [
"error",
"always"
],
"object-curly-spacing": [
"error",
"always"
],
"default-case": "error",
"comma-dangle": [
"error",
"always-multiline"
],
"header/header": [
2,
"license-header.txt"
],
"no-case-declarations": "off",
"@typescript-eslint/no-non-null-assertion": "off"
},
"reportUnusedDisableDirectives": true
},
"lint-staged": {
"src/**/*": [
"yarn lint"
@ -191,6 +93,11 @@
"@commitlint/config-conventional"
]
},
"config": {
"commitizen": {
"path": "@commitlint/cz-commitlint"
}
},
"standard-version": {
"types": [
{
@ -203,11 +110,5 @@
}
]
},
"_moduleAliases": {
"@": "dist",
"@src": "dist/src",
"@lib": "dist/src/lib",
"@utils": "dist/src/lib/utils/",
"@structures": "dist/src/lib/structures"
}
"packageManager": "yarn@3.1.0"
}

View file

@ -1,38 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import multiInput from 'rollup-plugin-multi-input';
import progress from 'rollup-plugin-progress';
import analyze from 'rollup-plugin-analyzer';
export default {
input: ['src/index.ts', 'src/commands/**/*.ts'],
output: {
dir: 'dist',
format: 'cjs',
},
plugins: [
typescript({ module: 'ESNext', include: ['src/**/*.ts', '*.json'] }),
json({ compact: true, preferConst: true }),
terser(),
multiInput(),
progress(),
analyze(),
],
};

View file

@ -1,102 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import Command from '@structures/command';
import { ECommandRunIn, IGuildSettings } from '@utils/types';
import { query } from '@utils/utils';
import type { Client, Message } from 'discord.js';
import i18next from 'i18next';
import SQL from 'sql-template-strings';
export default class extends Command {
public constructor(client: Client, file: string) {
super(client, file, {
shortDescription: i18next.t('commands:settings.shortDescription'),
extendedDescription: i18next.t('commands:settings.extendedDescription'),
usage: 'set locale en-US',
runIn: ECommandRunIn.Server,
args: [
{
name: 'action',
acceptedValues: [ 'set', 'get', 'reset' ],
description: i18next.t('commands:settings.actionArg'),
},
{
name: 'setting',
description: i18next.t('commands:settings.settingArg'),
},
{
name: 'value',
description: i18next.t('commands:settings.valueArg'),
optional: true,
goToEnd: true,
},
],
});
}
public async run(message: Message, action: string, setting: string, value: string): Promise<void> {
switch(action) {
case 'set':
await this.setSetting(message, setting, value);
break;
case 'get':
break;
case 'reset':
break;
default:
break;
}
}
private async setSetting(message: Message, setting: string, value: string): Promise<void> {
let findGuild = await query<IGuildSettings>(SQL`SELECT *
FROM bot.public.settings
WHERE id = ${message.guild?.id}`);
if(findGuild && findGuild.rowCount === 0) {
await query(SQL`INSERT INTO bot.public.settings (id)
VALUES (${message.guild?.id})`);
findGuild = await query<IGuildSettings>(SQL`SELECT *
FROM bot.public.settings
WHERE id = ${message.guild?.id}`);
}
switch(setting) {
case 'locale':
case 'language':
if(findGuild) {
const guildSettings = findGuild.rows[0]!;
if(guildSettings.locale === value)
await message.reply(i18next.t('commands:settings.localeAlreadySet', { locale: guildSettings.locale }));
else {
await query(SQL`UPDATE bot.public.settings
SET locale=${value}
WHERE id = ${message.guild?.id}`);
await message.channel.send(i18next.t('commands:settings.localeSuccessfullySet', { locale: value }));
}
}
break;
case 'get':
break;
case 'reset':
break;
default:
break;
}
}
}

View file

@ -1,201 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import Command from '@structures/command';
import { capitalize } from '@utils/utils';
import config from 'config';
import { Client, Message, MessageButton, MessageEmbed, MessageSelectMenu, MessageSelectOptionData } from 'discord.js';
import i18next from 'i18next';
export default class extends Command {
public constructor(client: Client, file: string) {
super(client, file, {
shortDescription: i18next.t('commands:help.shortDescription'),
extendedDescription: i18next.t('commands:help.extendedDescription'),
usage: 'vm',
args: [
{
name: 'command',
description: i18next.t('commands:help.commandArg'),
optional: true,
},
],
});
}
public async run(message: Message, command: string): Promise<void> {
if(!command) {
const commandGroups: { name: string; embed: MessageEmbed, commands: Command[] }[] = [];
const categories: string[] = [];
this.client.commands.forEach((command) => {
const findCommand = commandGroups.find((val) => val.name === command.options.group);
if(findCommand) {
findCommand.commands.push(command);
} else {
commandGroups.push({
name: command.options.group!,
embed: new MessageEmbed(),
commands: [ command ],
});
categories.push(command.options.group!);
}
});
commandGroups.forEach((val, index) => {
val.embed = new MessageEmbed();
val.embed.setAuthor(i18next.t('commands:help.embedName'));
val.embed.setTitle(capitalize(val.name));
val.embed.setColor(message.member?.roles.highest.color ?? 0xFFFFFF);
val.embed.setFooter(`Page ${index + 1}/${commandGroups.length}`);
val.embed.setTimestamp();
val.commands.forEach((command) => {
val.embed.addField(`${config.get('prefix')}${command.options.name}`, command.options.shortDescription ?? i18next.t('commands:generic.noShortDescription').toUpperCase(), false);
});
});
const dropDownOptions: MessageSelectOptionData[] = [];
let currentPage = 0;
const nextCategoryBtn = new MessageButton();
nextCategoryBtn.setCustomID('nextCategoryBtn');
nextCategoryBtn.setLabel(i18next.t('commands:help.nextCategoryBtn'));
nextCategoryBtn.setStyle('PRIMARY');
const previousCategoryBtn = new MessageButton();
previousCategoryBtn.setCustomID('previousCategoryBtn');
previousCategoryBtn.setLabel(i18next.t('commands:help.previousCategoryBtn'));
previousCategoryBtn.setStyle('SECONDARY');
previousCategoryBtn.setDisabled(true);
const chooseHelpCategory = new MessageSelectMenu();
chooseHelpCategory.setCustomID('chooseHelpCategory');
chooseHelpCategory.setPlaceholder(i18next.t('commands:help.categoryPlaceholder'));
for(const category of categories) {
dropDownOptions.push({ label: capitalize(category), value: category });
}
chooseHelpCategory.addOptions(dropDownOptions);
const helpMsg = await message.channel.send({
content: i18next.t('commands:help.helpScreenBtnHelp'),
embeds: [ commandGroups[0]!.embed ],
components: [ [ previousCategoryBtn, nextCategoryBtn ], [ chooseHelpCategory ] ],
});
const buttonCollector = helpMsg.channel.createMessageComponentInteractionCollector({ time: 60000 });
buttonCollector.on('collect', async (interaction) => {
if(interaction.customID === 'nextCategoryBtn') {
currentPage++;
if(currentPage + 1 === commandGroups.length) {
nextCategoryBtn.setDisabled(true);
previousCategoryBtn.setDisabled(false);
}
if(currentPage + 1 !== commandGroups.length) {
nextCategoryBtn.setDisabled(false);
previousCategoryBtn.setDisabled(false);
}
await interaction.update({
content: i18next.t('commands:help.helpScreenBtnHelp'),
embeds: [ commandGroups[currentPage]!.embed ],
components: [ [ previousCategoryBtn, nextCategoryBtn ], [ chooseHelpCategory ] ],
});
} else if(interaction.customID === 'previousCategoryBtn') {
currentPage--;
if(currentPage + 1 !== commandGroups.length) {
nextCategoryBtn.setDisabled(false);
previousCategoryBtn.setDisabled(false);
}
if(currentPage === 0) {
previousCategoryBtn.setDisabled(true);
nextCategoryBtn.setDisabled(false);
}
await interaction.update({
content: i18next.t('commands:help.helpScreenBtnHelp'),
embeds: [ commandGroups[currentPage]!.embed ],
components: [ [ previousCategoryBtn, nextCategoryBtn ], [ chooseHelpCategory ] ],
});
} else if(interaction.customID === 'chooseHelpCategory') {
currentPage = categories.indexOf(interaction.values[0]);
if(currentPage === 0) {
previousCategoryBtn.setDisabled(true);
nextCategoryBtn.setDisabled(false);
}
if(currentPage + 1 !== commandGroups.length) {
nextCategoryBtn.setDisabled(false);
previousCategoryBtn.setDisabled(false);
}
if(currentPage + 1 === commandGroups.length) {
nextCategoryBtn.setDisabled(true);
previousCategoryBtn.setDisabled(false);
}
await interaction.update({
content: i18next.t('commands:help.helpScreenBtnHelp'),
embeds: [ commandGroups[currentPage]!.embed ],
components: [ [ previousCategoryBtn, nextCategoryBtn ], [ chooseHelpCategory ] ],
});
}
});
buttonCollector.on('end', async () => {
nextCategoryBtn.setDisabled(true);
previousCategoryBtn.setDisabled(true);
await helpMsg.edit({
content: i18next.t('commands:help.helpTimedOut'),
embeds: [ commandGroups[currentPage]!.embed ],
components: [],
});
});
} else {
const findCommand = this.client.commands.find((cmd) => cmd.options.name === command);
if(findCommand) {
const commandEmbed = new MessageEmbed();
commandEmbed.setAuthor(i18next.t('commands:help.embedName'));
commandEmbed.setTitle(capitalize(findCommand.options.name!));
commandEmbed.setColor(message.member?.roles.highest.color ?? 0xFFFFFF);
commandEmbed.setTimestamp();
commandEmbed.setDescription(i18next.t('commands:help.commandDescription', {
name: findCommand.options.name,
category: capitalize(findCommand.options.group!),
description: findCommand.options.extendedDescription ?? i18next.t('commands:generic.noExtendedDescription'),
usage: findCommand.options.usage ? `!${findCommand.options.name} ${findCommand.options.usage}` : i18next.t('commands:generic.noUsage'),
}));
await message.channel.send({ embeds: [ commandEmbed ] });
} else {
await message.reply(i18next.t('commands:help.unknownCommand'));
}
}
}
}

View file

@ -14,41 +14,55 @@
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import Command from '@structures/command';
import type { Client, Message } from 'discord.js';
import i18next from 'i18next';
import { Command } from '@neonjs/framework';
import type { CacheType, Client, CommandInteraction } from 'discord.js';
import { transpile } from 'typescript';
import { NodeVM } from 'vm2';
export default class extends Command {
public constructor(client: Client, file: string) {
super(client, file, {
shortDescription: i18next.t('commands:vm.shortDescription'),
extendedDescription: i18next.t('commands:vm.extendedDescription'),
usage: 'js const test = \'test\'; return test;',
args: [
{
name: 'language',
acceptedValues: [ 'js', 'javascript', 'ts', 'typescript' ],
description: i18next.t('commands:vm.languageArg'),
description: 'The language to use',
type: 'STRING',
required: true,
choices: [
{
name: 'javascript',
value: 'javascript',
},
{
name: 'typescript',
value: 'typescript',
},
],
},
{
name: 'code',
goToEnd: true,
description: i18next.t('commands:vm.codeArg'),
description: 'The code to run',
type: 'STRING',
required: true,
},
],
cooldown: 5,
extendedDescription: 'Runs Vanilla JavaScript/TypeScript code direct from Discord in a secure VM',
group: 'utils',
name: 'vm',
shortDescription: 'Runs JavaScript/TypeScript code direct from Discord.',
usage: 'js const test = \'test\'; return test;',
});
}
public async run(message: Message, vmLang: string, ...codeArray: string[]): Promise<void> {
const code = codeArray.join(' ');
public async run(interaction: CommandInteraction<CacheType>): Promise<void> {
const code = interaction.options.getString('code', true);
const javascriptVM = new NodeVM({ eval: false, timeout: 1000, wasm: false, console: 'off' });
const vmLang = interaction.options.getString('language', true);
switch (vmLang.toLowerCase()) {
case 'js':
case 'javascript':
await message.channel.send(i18next.t('commands:vm.computing', { language: 'JavaScript' }));
await interaction.reply('Computing JavaScript Code...');
try {
let returnVal: string;
@ -57,14 +71,13 @@ export default class extends Command {
else
returnVal = await javascriptVM.run(`(() => {${code}})()`);
await message.channel.send(`\`\`\`js\n${returnVal}\`\`\``);
await interaction.editReply(`\`\`\`\n${returnVal}\`\`\``);
} catch (err) {
await message.reply(i18next.t('commands:vm.error', { error: err.message, language: 'JavaScript' }));
await interaction.editReply(`An error has occurred! \`\`\`${(err as Error).message}\`\`\``);
}
break;
case 'ts':
case 'typescript':
await message.channel.send(i18next.t('commands:vm.computing', { language: 'TypeScript' }));
await interaction.reply('Computing TypeScript Code...');
try {
const jsCode = transpile(code);
@ -75,13 +88,13 @@ export default class extends Command {
else
returnVal = await javascriptVM.run(`(() => {${jsCode}}()`);
await message.channel.send(`\`\`\`js\n${returnVal}\`\`\``);
await interaction.editReply(`\`\`\`\n${returnVal}\`\`\``);
} catch (err) {
await message.reply(i18next.t('commands:vm.error', { error: err.message, language: 'TypeScript' }));
await interaction.editReply(`An error has occurred! \`\`\`${(err as Error).message}\`\`\``);
}
break;
default:
await message.reply(i18next.t('commands:vm.unknown'));
await interaction.reply('This should not happen tf');
}
}
}

View file

@ -14,145 +14,30 @@
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import 'module-alias/register';
import '@utils/augments';
import ArgonClient from '@lib/ArgonClient';
import { Defaults } from '@utils/defaults';
import { debug, error, fatal, info, verbose } from '@utils/logger';
import { ECommandRunIn, ELoggingScope } from '@utils/types';
import { connectToDB, walkDir } from '@utils/utils';
import chalk from 'chalk';
import { NeonClient } from '@neonjs/framework';
import config from 'config';
import { Collection } from 'discord.js';
import figlet from 'figlet';
import gradient from 'gradient-string';
import i18next from 'i18next';
import Backend from 'i18next-chained-backend';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import Fluent from 'i18next-fluent';
import FSBackend from 'i18next-fs-backend';
import { Validator } from 'jsonschema';
import { DateTime } from 'luxon';
import process from 'process';
import { connectToDB } from './lib/utils/utils';
const commandCooldowns: Collection<string, Collection<string, number>> = new Collection();
let isBotReady = false;
info('Starting bot... Please wait!', ELoggingScope.Startup);
debug('Checking config JSON schema', ELoggingScope.Startup);
const mergedConfig = config.util.extendDeep(Defaults.config, config.util.loadFileConfigs(`${process.cwd()}/config`));
const schemaValidator = new Validator();
const validate = schemaValidator.validate(mergedConfig, Defaults.configSchema);
if(validate.valid) {
debug('Config matches JSON schema', ELoggingScope.Startup);
} else {
// Manually send fatal message in case someone messes up the logLevel config
const message = `Found some errors with the config! Please check errors below.\n${validate.errors}`;
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
console.log(chalk`{grey (${date})} {magenta.bold ${ELoggingScope.Startup}} {red.bold.underline [FATAL]}: {red.underline ${val}}`);
const client = new NeonClient(config.get('ownerId'), {
intents: ['GUILDS'],
});
process.exit(1);
}
figlet('Argon Bot', (err, data) => {
if(err) error(`Figlet encountered an error!\n${err.message}`);
if (err) client.logger.error(`Figlet encountered an error!\n${err.message}`);
info(gradient.rainbow.multiline(`\n${data}`), ELoggingScope.Startup);
});
const client = new ArgonClient({
intents: [ 'GUILDS', 'GUILD_MESSAGES', 'DIRECT_MESSAGES' ],
partials: [ 'CHANNEL' ],
});
client.on('message', async (msg) => {
if(!isBotReady) return;
if(msg.author.bot) return;
if(!msg.content.startsWith(config.get('prefix'))) return;
const args = msg.content.slice((config.get('prefix') as string).length).trim().split(/ +/);
const command = args.shift()!.toLowerCase();
const findCommand = client.commands.find((com) => com.options.name === command);
if(!findCommand) return;
msg.channel.startTyping();
if(findCommand.options.ownerOnly && msg.author.id !== config.get('owner')) {
await msg.reply(i18next.t('commands:errors.ownerOnly'));
msg.channel.stopTyping();
return;
}
if((findCommand.options.runIn === ECommandRunIn.DM) && msg.channel.type !== 'dm') {
await msg.reply(i18next.t('commands:errors.dmsOnly'));
msg.channel.stopTyping();
return;
}
if((findCommand.options.runIn === ECommandRunIn.Server) && msg.channel.type !== 'text') {
await msg.reply(i18next.t('commands:errors.serverOnly'));
msg.channel.stopTyping();
return;
}
if(msg.author.id !== config.get('owner')) {
if(!commandCooldowns.has(findCommand.options.name!)) {
commandCooldowns.set(findCommand.options.name!, new Collection());
}
const now = Date.now();
const timestamps = commandCooldowns.get(findCommand.options.name!);
const cooldownAmount = findCommand.options.cooldown! * 1000;
if(timestamps!.has(msg.author.id)) {
const expirationTime = timestamps!.get(msg.author.id)! + cooldownAmount;
if(now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
await msg.reply(i18next.t('commands:errors.cooldownError', {
time: timeLeft.toFixed(1),
command: findCommand.options.name,
}));
msg.channel.stopTyping();
return;
}
}
timestamps!.set(msg.author.id, now);
setTimeout(() => timestamps!.delete(msg.author.id), cooldownAmount);
}
try {
info(`Command ${findCommand.options.name} is being ran in ${msg.guild ? msg.guild.name : 'DMs'} by ${msg.author.username}`, ELoggingScope.Command);
await findCommand.run(msg, ...args);
info(`Finished running ${findCommand.options.name} in ${msg.guild ? msg.guild.name : `${msg.author.username} DMs`}`, ELoggingScope.Command);
msg.channel.stopTyping();
} catch(e) {
error(`An error has occurred while running ${findCommand.options.name}!\n${e.message}`, ELoggingScope.Command);
await msg.reply(i18next.t('commands:errors.runError', { error: e.message }));
msg.channel.stopTyping();
}
client.logger.info(gradient.rainbow.multiline(`\n${data}`));
});
client.on('ready', async () => {
info('Loading translations...', ELoggingScope.Startup);
client.logger.info('Loading translations...');
await i18next.use(Fluent).use(Backend).init({
supportedLngs: [ 'en-US', 'owo' ],
await i18next.use(Backend).init({
supportedLngs: ['en-US'],
lng: 'en-US',
fallbackLng: 'en-US',
defaultNS: 'common',
@ -168,45 +53,13 @@ client.on('ready', async () => {
},
});
info('Finished loading translations.', ELoggingScope.Startup);
client.logger.info('Finished loading translations');
info('Loading commands...', ELoggingScope.Command);
try {
const files = await walkDir(`${__dirname}/commands`);
files?.forEach((file) => {
if(file.endsWith('js')) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fileCommand = require(file);
const command = new fileCommand['default'](client, file);
client.commands.set(command.options.name, command);
debug(`Loaded command ${command.options.name}`, ELoggingScope.Command);
}
});
info(`Finished loading commands! Found ${client.commands.size} commands.`, ELoggingScope.Command);
} catch(err) {
console.log(err);
fatal(`An error has occurred while attempting to load command files! Please see error below\n${err.message}`, ELoggingScope.Command);
}
info('Creating Database Pool...', ELoggingScope.Database);
client.logger.info('Creating Database Pool...');
await connectToDB(config.get('db'));
info('Finished creating Database Pool', ELoggingScope.Database);
client.logger.info('Finished creating Database Pool');
info('Bot is ready!', ELoggingScope.Startup);
debug(`Total number of Servers: ${client.guilds.cache.size}`, ELoggingScope.Startup);
debug(`Total number of Users: ${client.users.cache.size}`, ELoggingScope.Startup);
isBotReady = true;
});
client.on('raw', (payload) => {
verbose(JSON.stringify(payload, null, 2), ELoggingScope.Payload);
client.logger.info('Bot is ready!');
});
client.login(config.get('token'));

View file

@ -1,28 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import type Command from '@structures/command';
import { Client, ClientOptions, Collection } from 'discord.js';
export default class extends Client {
public commands: Collection<string, Command>;
public constructor(options: ClientOptions) {
super(options);
this.commands = new Collection<string, Command>();
}
}

View file

@ -1,16 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/

View file

@ -1,41 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import type { ICommandOptions } from '@utils/types';
import config from 'config';
import type { Client, Message } from 'discord.js';
import path from 'path';
export default abstract class Command {
public readonly client: Client;
public readonly file: string;
public readonly options: ICommandOptions;
protected constructor(client: Client, file: string, options?: ICommandOptions) {
this.client = client;
this.file = file;
const defaultOptions: ICommandOptions = {
name: path.basename(this.file, path.extname(this.file)),
group: path.basename(path.dirname(this.file)) === 'commands' ? '' : path.basename(path.dirname(this.file)),
cooldown: 5,
};
this.options = config.util.extendDeep(defaultOptions, options);
}
public abstract run(message: Message, ...args: string[]): Promise<void> | void;
}

View file

@ -1,23 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import type Command from '@structures/command';
declare module 'discord.js' {
interface Client{
commands: Collection<string, Command>;
}
}

View file

@ -1,79 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
export const Defaults = {
config: {
logLevel: 'info',
},
configSchema: {
required: [ 'token', 'logLevel', 'prefix', 'owner', 'db' ],
type: 'object',
properties: {
token: {
$id: '#/properties/token',
type: 'string',
},
logLevel: {
$id: '#/properties/logLevel',
type: 'string',
enum: [
'verbose',
'debug',
'info',
'warn',
'error',
'fatal',
],
},
prefix: {
$id: '#/properties/prefix',
type: 'string',
},
owner: {
$id: '#/properties/owner',
type: 'string',
},
db: {
$id: '#/properties/db',
type: 'object',
required: [ 'host', 'port', 'user', 'password', 'database' ],
properties: {
host: {
$id: '#/properties/db/host',
type: 'string',
},
port: {
$id: '#/properties/db/port',
type: 'string',
},
user: {
$id: '#/properties/db/user',
type: 'string',
},
password: {
$id: '#/properties/db/password',
type: 'string',
},
database: {
$id: '#/properties/db/database',
type: 'string',
},
},
},
},
additionalProperties: false,
},
};

View file

@ -1,147 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import chalk from 'chalk';
import config from 'config';
import { DateTime } from 'luxon';
import type { ELoggingScope } from './types';
let verboseLevel = false;
let debugLevel = false;
let infoLevel = false;
let warnLevel = false;
let errorLevel = false;
let fatalLevel = false;
switch((config.get('logLevel') as string).toLowerCase()) {
case 'verbose':
verboseLevel = true;
debugLevel = true;
infoLevel = true;
warnLevel = true;
errorLevel = true;
fatalLevel = true;
break;
case 'debug':
debugLevel = true;
infoLevel = true;
warnLevel = true;
errorLevel = true;
fatalLevel = true;
break;
case 'info':
infoLevel = true;
warnLevel = true;
errorLevel = true;
fatalLevel = true;
break;
case 'warn':
warnLevel = true;
errorLevel = true;
fatalLevel = true;
break;
case 'error':
errorLevel = true;
fatalLevel = true;
break;
case 'fatal':
fatalLevel = true;
break;
default:
break;
}
export function verbose(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(verboseLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {white.bold [VERBOSE]}: {white ${val}}`);
else
console.log(chalk`{grey (${date})} {white.bold [VERBOSE]}: {white ${val}}`);
});
}
export function debug(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(debugLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {blue.bold [DEBUG]}: {blue ${val}}`);
else
console.log(chalk`{grey (${date})} {blue.bold [DEBUG]}: {blue ${val}}`);
});
}
export function info(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(infoLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {green.bold [INFO]}: {green ${val}}`);
else
console.log(chalk`{grey (${date})} {green.bold [INFO]}: {green ${val}}`);
});
}
export function warn(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(warnLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {yellow.bold [WARN]}: {yellow ${val}}`);
else
console.log(chalk`{grey (${date})} {yellow.bold [WARN]}: {yellow ${val}}`);
});
}
export function error(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(errorLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {bold.underline.rgb(255, 165, 0) [ERROR]}: {underline.rgb(255, 165, 0) ${val}}`);
else
console.log(chalk`{grey (${date})} {bold.underline.rgb(255, 165, 0) [ERROR]}: {underline.rgb(255, 165, 0) ${val}}`);
});
}
export function fatal(message: string, scope?: ELoggingScope): void {
const date = DateTime.now().toLocal().setLocale(Intl.DateTimeFormat().resolvedOptions().locale).toFormat('yyyy-LL-dd HH:mm:ss');
const splitMultiline = message.split('\n');
splitMultiline.forEach((val) => {
if(fatalLevel)
if(scope)
console.log(chalk`{grey (${date})} {magenta.bold ${scope}} {red.bold.underline [FATAL]}: {red.underline ${val}}`);
else
console.log(chalk`{grey (${date})} {red.bold.underline [FATAL]}: {red.underline ${val}}`);
});
if(config.util.getEnv('NODE_CONFIG_ENV') !== 'tests')
process.exit(1);
}

View file

@ -1,57 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
//Enums
export enum ELoggingScope {
Startup = 'STARTUP',
Command = 'COMMAND',
Payload = 'PAYLOAD',
Query = 'QUERY',
Database = 'DATABASE',
}
export enum ECommandRunIn {
DM,
Server,
Both,
}
// Interfaces
export interface ICommandOptions {
name?: string;
group?: string;
shortDescription?: string;
extendedDescription?: string;
usage?: string;
ownerOnly?: boolean;
cooldown?: number;
runIn?: ECommandRunIn;
args?: {
name: string;
description?: string;
acceptedValues?: string[];
goToEnd?: boolean;
optional?: boolean;
}[];
}
export interface IGuildSettings {
id: string,
locale: string;
}
// Type Aliases

View file

@ -14,88 +14,45 @@
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import { error, info } from '@utils/logger';
import { ELoggingScope } from '@utils/types';
import fs from 'fs';
import path from 'path';
import Logger from '@neonjs/framework/dist/lib/utils/logger';
import pg, { QueryResult } from 'pg';
import type { SQLStatement } from 'sql-template-strings';
let pool: pg.Pool;
export const walkDir = async (dir: string): Promise<string[]> => {
let results: string[] = [];
return new Promise((resolve, reject) => {
fs.readdir(dir, (err, list) => {
if(err) return reject(err);
let pending = list.length;
if(!pending) return resolve(results);
list.forEach((file) => {
file = path.resolve(dir, file);
fs.stat(file, async (err, stat) => {
if(err) return reject(err);
if(stat && stat.isDirectory()) {
try {
const dir = await walkDir(file);
results = results.concat(dir as unknown as string);
if(!--pending) resolve(results);
} catch(err) {
reject(err);
}
} else {
results.push(file);
if(!--pending) resolve(results);
}
});
});
});
});
};
export const capitalize = (string: string): string => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
const logger = new Logger();
export const connectToDB = async (connectionData: pg.PoolConfig): Promise<void> => {
pool = new pg.Pool(connectionData);
pool.on('connect', () => {
info('Connected to the Postgres Database!', ELoggingScope.Database);
logger.info('Connected to the Postgres Database!');
});
pool.on('error', (err) => {
error(`An error has occurred with node-postgres!\n${err.message}`, ELoggingScope.Database);
logger.error(`An error has occurred with pg!\n${err.message}`);
});
};
export const query = async <t>(query: SQLStatement): Promise<QueryResult<t> | void> => {
if(!pool) return error('Attempted to query to the Database when a connection has not been made yet... Discarding' +
' request.', ELoggingScope.Query);
if (!pool) return logger.error('Attempted to query to the Database when a connection has not been made yet... Discarding request.');
else {
const client = await pool.connect();
try {
info('BEGIN', ELoggingScope.Query);
logger.info('DB: BEGIN');
await client.query('BEGIN');
info(query.text, ELoggingScope.Query);
logger.info(query.text);
const result = await client.query<t>(query);
info('COMMIT', ELoggingScope.Query);
logger.info('DB: COMMIT');
await client.query('COMMIT');
return result;
} catch (e) {
error(`An error has occurred while attempting to query "${query}"... Rolling back changes`, ELoggingScope.Database);
info('ROLLBACK', ELoggingScope.Query);
logger.error(`An error has occurred while attempting to query "${query}"... Rolling back changes`);
logger.info('DB: ROLLBACK');
await client.query('ROLLBACK');
throw e;

View file

@ -1,147 +0,0 @@
/*
* This file is part of ArgonBot
*
* ArgonBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ArgonBot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ArgonBot. If not, see <https: //www.gnu.org/licenses/>.
*/
import { describe, it, beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import * as sinon from 'sinon';
import { verbose, debug, info, warn, error, fatal } from '@utils/logger';
import { ELoggingScope } from '@utils/types';
describe('verbose()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
verbose('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
verbose('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});
describe('debug()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
debug('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
debug('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});
describe('info()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
info('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
info('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});
describe('warn()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
warn('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
warn('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});
describe('error()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
error('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
error('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});
describe('fatal()', () => {
let spy: sinon.SinonStub<[message?: any, ...optionalParams: any[]], void>;
beforeEach(() => {
spy = sinon.stub(console, 'log');
});
it('check message is being logged', () => {
fatal('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch('Test Message')).to.be.true;
});
it('check if Logging Scopes are being logged', () => {
fatal('Test Message', ELoggingScope.Command);
expect(spy.calledWithMatch(/COMMAND/)).to.be.true;
});
afterEach(() => {
spy.restore();
});
});

View file

@ -1,46 +0,0 @@
{
"vm": {
"shortDescription": "Runs code in a safe sandbox for testing",
"extendedDescription": "Runs code in a secure and safe sandbox for prototyping & testing code while preventing access to the system",
"languageArg": "The language to use (JavaScript/TypeScript)",
"codeArg": "The code to run in the VM",
"computing": "Computing { $language } code... Please wait!",
"error": "An error has occurred while executing { $language } code!\n```\n{ $error }\n```",
"unknown": "Unknown language given!"
},
"help": {
"shortDescription": "Shows help menu",
"extendedDescription": "Shows an advanced help menu for commands to show usage",
"commandArg": "The command to see",
"unknownCommand": "Unknown command given!",
"embedName": "Help Menu!",
"helpScreenBtnHelp": "Press the \"Forward\" or \"Back\" Button to move categories! Or alternatively, you can select the category you want on the dropdown menu.",
"nextCategoryBtn": "Next Category",
"previousCategoryBtn": "Previous Category",
"helpTimedOut": "Timed Out",
"commandDescription": "Name: `{ $name }`\nCategory: `{ $category }`\nDescription: `{ $description }`\nUsage: `{ $usage }`",
"categoryPlaceholder": "Choose a category!"
},
"settings": {
"shortDescription": "Changes the current server settings",
"extendedDescription": "Changes the current server settings for better server customization",
"actionArg": "What action you want to take",
"settingArg": "What setting you want to view/set\nOr optionally, you can put 'help' if you are unsure what to do with that action",
"valueArg": "The value you want to set (This is ignored if you are only getting/resetting a setting).",
"localeAlreadySet": "The language of the bot in this server is already set to { $locale }!",
"localeSuccessfullySet": "The language of the bot has been successfully set to { $locale }!"
},
"errors": {
"ownerOnly": "Only the bot owner can run this command!",
"dmsOnly": "You can only run this command in DMs!",
"serverOnly": "You can only run this command in a server!",
"runError": "I'm sorry but an error has occurred while running this command! Please file an issue to https://code.relms.dev/Relms/ArgonBot!\n```{ $error }```",
"cooldownError": "Please wait { $time } more second(s) before reusing the `{ $command }` command."
},
"generic": {
"noShortDescription": "No short description given!",
"noExtendedDescription": "No extended description given!",
"noArgsDescription": "No description for { $arg } has been given!",
"noUsage": "No usage given!"
}
}

View file

@ -1 +0,0 @@
{}

View file

@ -1,37 +0,0 @@
{
"vm": {
"shortDescription": "Wuns code in a safe sandbox fow testing",
"extendedDescription": "Wuns code in a secuwe and safe sandbox fow pwototyping & testing code whiwe pweventing access to the system",
"languageArg": "The wanguage to use (JavaScript/TypeScript)",
"codeArg": "The code to wun in the VM",
"computing": "Computing { $language } code... Pwease wait owo",
"error": "An ewwow has occuwwed whiwe executing { $language } code!\n```\n{ $error }\n```",
"unknown": "Unknyown wanguage given owo"
},
"help": {
"shortDescription": "Shows hewp menyu",
"extendedDescription": "Shows an advanced hewp menyu fow commands to show usage",
"commandArg": "The command to see",
"unknownCommand": "Unknyown command given (・`ω´・)",
"embedName": "Hewp Menyu (・`ω´・)",
"helpScreenBtnHelp": "Pwess the \"Fowwawd\" ow \"Back\" Button to muv categowies owo. Ow awtewnyativewy, you can sewect the categowy you want on the dwopdown menyu.",
"nextCategoryBtn": "Nyext Categowy",
"previousCategoryBtn": "Pwevious Categowy",
"helpTimedOut": "Timed Out",
"commandDescription": "Nyame: `{ $name }`\nCategowy: `{ $category }`\nDescwiption: `{ $description }`\nUsage: `{ $usage }`",
"categoryPlaceholder": "Choose a categowy (・`ω´・)"
},
"errors": {
"ownerOnly": "Onwy the bot ownyew can wun this command ^w^",
"dmsOnly": "You can onwy wun this command in DMs owo",
"serverOnly": "You can onwy wun this command in a sewvew owo",
"runError": "I'm sowwy but an ewwow has occuwwed whiwe wunnying this command ;;w;; Pwease fiwe an issue to https://code.relms.dev/Relms/ArgonBot!\n```{ $error }```",
"cooldownError": "Pwease wait { $time } mowe second(s) befowe weusing the `{ $command }` command."
},
"generic": {
"noShortDescription": "Nyo showt descwiption given >w<",
"noExtendedDescription": "Nyo extended descwiption given ^w^",
"noArgsDescription": "Nyo descwiption fow { $arg } has been given UwU",
"noUsage": "Nyo usage given ;;w;;"
}
}

View file

@ -1 +0,0 @@
{}

View file

@ -1,20 +1,14 @@
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"composite": true,
"downlevelIteration": true,
"importHelpers": true,
"incremental": true,
"declaration": true,
"lib": [
"ESNext",
"ES2021",
"DOM"
],
"module": "CommonJS",
"outDir": "dist",
"tsBuildInfoFile": "dist/.tsbuildinfo",
"removeComments": true,
"target": "ESNext",
"removeComments": false,
"target": "ES2021",
"alwaysStrict": true,
"noImplicitAny": true,
"noImplicitThis": true,
@ -45,56 +39,10 @@
"newLine": "lf",
"noEmitOnError": false,
"preserveConstEnums": true,
"resolveJsonModule": true,
"traceResolution": false,
"inlineSourceMap": true,
"inlineSources": true,
"baseUrl": ".",
"moduleResolution": "Node",
"plugins": [
{
"name": "typescript-eslint-language-service"
},
{
"name": "ts-sql-plugin",
"mock": "0",
"cost_pattern": "/\\(cost=\\d+\\.?\\d*\\.\\.(\\d+\\.?\\d*)/",
"error_cost": null,
"warn_cost": null,
"info_cost": null,
"schema_command": "pg"
}
],
"paths": {
"@/*": [
"*"
],
"@/src": [
"src/*"
],
"@lib/*": [
"src/lib/*"
],
"@utils/*": [
"src/lib/utils/*"
],
"@structures/*": [
"src/lib/structures/*"
]
}
},
"watchOptions": {
"watchFile": "useFsEvents",
"watchDirectory": "useFsEvents",
"fallbackPolling": "dynamicpriority",
"synchronousWatchDirectory": true,
"excludeDirectories": [
"node_modules",
"dist"
]
"moduleResolution": "Node"
},
"include": [
"src/**/*.ts",
"*.json"
"src/**/*.ts"
]
}

6845
yarn.lock

File diff suppressed because it is too large Load diff