Initial commit

merge-requests/1/merge
Matthew 2020-04-14 13:15:33 -04:00
commit bfb7e962c3
No known key found for this signature in database
GPG Key ID: 766BE43AE75F7559
14 changed files with 2117 additions and 0 deletions

44
.eslintrc.json Normal file
View File

@ -0,0 +1,44 @@
{
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"]
}
}
},
"env": {
"es6": true,
"node": true
},
"extends": [
"airbnb-base"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"linebreak-style": "off",
"no-unused-vars": "off",
"max-len": "off",
"import/no-dynamic-require": "off",
"global-require": "off",
"class-methods-use-this":"off",
"no-restricted-syntax": "off",
"camelcase": "off",
"indent": "warn",
"object-curly-newline": "off",
"import/prefer-default-export": "off",
"no-useless-constructor": "off",
"@typescript-eslint/no-useless-constructor": 2,
"import/extensions": "off"
}
}

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
# Package Management & Libraries
node_modules
# Configuration Files
config.yaml
src/config.yaml
build/config.yaml
# Build/Distribution Files
build
dist

7
Makefile Normal file
View File

@ -0,0 +1,7 @@
all: clean build
clean:
@-rm -rf build
build:
tsc -p ./tsconfig.json

25
package.json Normal file
View File

@ -0,0 +1,25 @@
{
"name": "loccommunityrelations",
"version": "1.0.0",
"description": "The official system for handling Community Relations in the LOC Discord server.",
"main": "dist/client.js",
"repository": "https://gitlab.libraryofcode.org/engineering/communityrelations.git",
"author": "Matthew R <matthew@staff.libraryofcode.org>",
"license": "MIT",
"private": false,
"devDependencies": {
"@types/node": "^13.11.0",
"@types/yaml": "^1.2.0",
"@typescript-eslint/eslint-plugin": "^2.27.0",
"@typescript-eslint/parser": "^2.27.0",
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.1.0",
"eslint-plugin-import": "^2.20.2",
"typescript": "^3.8.3"
},
"dependencies": {
"eris": "^0.11.2",
"mongoose": "^5.9.7",
"yaml": "^1.8.3"
}
}

42
src/class/Client.ts Normal file
View File

@ -0,0 +1,42 @@
import eris from 'eris';
import { promises as fs } from 'fs';
import { Collection, Command, Util } from '.';
export default class Client extends eris.Client {
public config: { token: string, prefix: string };
public commands: Collection<Command>;
public util: Util;
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(token: string, options?: eris.ClientOptions) {
super(token, options);
this.commands = new Collection<Command>();
}
public loadPlugins() {
this.util = new Util(this);
}
public async loadEvents() {
const evtFiles = await fs.readdir(`${__dirname}/../events`);
evtFiles.forEach((file) => {
const eventName = file.split('.')[0];
if (file === 'index.js') return;
// eslint-disable-next-line
const event = new (require(`${__dirname}/../events/${file}`).default)(this);
this.on(eventName, (...args) => event.run(...args));
delete require.cache[require.resolve(`${__dirname}/../events/${file}`)];
});
}
public async loadCommands() {
const commandFiles = await fs.readdir(`${__dirname}/../commands`);
commandFiles.forEach((file) => {
// eslint-disable-next-line new-cap
const command: Command = new (require(`${__dirname}/../commands/${file}`).default)(this);
this.commands.add(command.name, command);
});
}
}

153
src/class/Collection.ts Normal file
View File

@ -0,0 +1,153 @@
/**
* Hold a bunch of something
*/
export default class Collection<V> extends Map<string, V> {
baseObject: any
/**
* Creates an instance of Collection
*/
constructor(iterable: any[]|object = null) {
if (iterable && iterable instanceof Array) {
super(iterable);
} else if (iterable && iterable instanceof Object) {
super(Object.entries(iterable));
} else {
super();
}
}
/**
* Map to array
* ```js
* [value, value, value]
* ```
*/
toArray(): V[] {
return [...this.values()];
}
/**
* Map to object
* ```js
* { key: value, key: value, key: value }
* ```
*/
toObject(): object {
const obj: object = {};
for (const [key, value] of this.entries()) {
obj[key] = value;
}
return obj;
}
/**
* Add an object
*
* If baseObject, add only if instance of baseObject
*
* If no baseObject, add
* @param key The key of the object
* @param value The object data
* @param replace Whether to replace an existing object with the same key
* @return The existing or newly created object
*/
add(key: string, value: V, replace: boolean = false): V {
if (this.has(key) && !replace) {
return this.get(key);
}
if (this.baseObject && !(value instanceof this.baseObject)) return null;
this.set(key, value);
return value;
}
/**
* Return the first object to make the function evaluate true
* @param func A function that takes an object and returns something
* @return The first matching object, or `null` if no match
*/
find(func: Function): V {
for (const item of this.values()) {
if (func(item)) return item;
}
return null;
}
/**
* Return an array with the results of applying the given function to each element
* @param callbackfn A function that takes an object and returns something
*/
map<U>(callbackfn: (value?: V, index?: number, array?: V[]) => U): U[] {
const arr = [];
for (const item of this.values()) {
arr.push(callbackfn(item));
}
return arr;
}
/**
* Return all the objects that make the function evaluate true
* @param func A function that takes an object and returns true if it matches
*/
filter(func: Function): V[] {
const arr = [];
for (const item of this.values()) {
if (func(item)) {
arr.push(item);
}
}
return arr;
}
/**
* Test if at least one element passes the test implemented by the provided function. Returns true if yes, or false if not.
* @param func A function that takes an object and returns true if it matches
*/
some(func: Function) {
for (const item of this.values()) {
if (func(item)) {
return true;
}
}
return false;
}
/**
* Update an object
* @param key The key of the object
* @param value The updated object data
*/
update(key: string, value: V) {
return this.add(key, value, true);
}
/**
* Remove an object
* @param key The key of the object
* @returns The removed object, or `null` if nothing was removed
*/
remove(key: string): V {
const item = this.get(key);
if (!item) {
return null;
}
this.delete(key);
return item;
}
/**
* Get a random object from the Collection
* @returns The random object or `null` if empty
*/
random(): V {
if (!this.size) {
return null;
}
return Array.from(this.values())[Math.floor(Math.random() * this.size)];
}
toString() {
return `[Collection<${this.baseObject.name}>]`;
}
}

64
src/class/Command.ts Normal file
View File

@ -0,0 +1,64 @@
import { Member, Message } from 'eris';
import { Client } from '.';
export default class Command {
public client: Client;
/**
* The name of the command
*/
public name: string;
/**
* The description for the command.
*/
public description: string;
/**
* The aliases for the command.
*/
public aliases: string[];
/**
* - **0:** Everyone
* - **1:** Associates Team+
* - **2:** Sheriff+
* - **3:** Faculty Marshals+
* - **4:** Marshal Generals of Engineering
*/
public permissions: number;
/**
* Determines if the command is only available in server.
*/
public guildOnly: boolean;
/**
* Determines if the command is enabled or not.
*/
public enabled: boolean;
public run(message: Message, args: string[]): Promise<any> { return Promise.resolve(); }
constructor(client: Client) {
this.client = client;
}
public checkPermissions(member: Member): boolean {
if (member.id === '278620217221971968' || member.id === '253600545972027394') return true;
switch (this.permissions) {
case 0:
return true;
case 1:
return member.roles.some((r) => ['662163685439045632', '455972169449734144', '453689940140883988'].includes(r));
case 2:
return member.roles.some((r) => ['662163685439045632', '455972169449734144'].includes(r));
case 3:
return member.roles.some((r) => ['662163685439045632'].includes(r));
case 4:
return member.id === '278620217221971968' || member.id === '253600545972027394';
default:
return false;
}
}
}

39
src/class/Util.ts Normal file
View File

@ -0,0 +1,39 @@
// import { Message } from 'eris';
import { Client, Command } from '.';
export default class Util {
public client: Client;
constructor(client: Client) {
this.client = client;
}
get emojis() {
return {
SUCCESS: '<:modSuccess:578750988907970567>',
LOADING: '<a:modloading:588607353935364106>',
ERROR: '<:modError:578750737920688128>',
};
}
/**
* Resolves a command
* @param query Command input
* @param message Only used to check for errors
*/
public resolveCommand(query: string | string[]): Promise<{cmd: Command, args: string[] }> {
try {
// let resolvedCommand: Command;
// eslint-disable-next-line no-param-reassign
if (typeof query === 'string') query = query.split(' ');
const commands = this.client.commands.toArray();
const resolvedCommand = commands.find((c) => c.name === query[0].toLowerCase() || c.aliases.includes(query[0].toLowerCase()));
if (!resolvedCommand) return Promise.resolve(null);
query.shift();
return Promise.resolve({ cmd: resolvedCommand, args: query });
} catch (error) {
return Promise.reject(error);
}
}
}

4
src/class/index.ts Normal file
View File

@ -0,0 +1,4 @@
export { default as Client } from './Client';
export { default as Collection } from './Collection';
export { default as Command } from './Command';
export { default as Util } from './Util';

18
src/commands/ping.ts Normal file
View File

@ -0,0 +1,18 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Ping extends Command {
constructor(client: Client) {
super(client);
this.name = 'ping';
this.description = 'Pings the bot';
this.permissions = 0;
this.enabled = true;
}
public async run(message: Message) {
const clientStart: number = Date.now();
const msg: Message = await message.channel.createMessage('🏓 Pong!');
msg.edit(`🏓 Pong!\nClient: \`${Date.now() - clientStart}ms\`\nResponse: \`${msg.createdAt - message.createdAt}ms\``);
}
}

View File

@ -0,0 +1,22 @@
/* eslint-disable no-useless-return */
import { Message, TextChannel } from 'eris';
import { Client } from '../class';
export default class {
public client: Client;
constructor(client: Client) {
this.client = client;
}
public async run(message: Message) {
if (message.author.bot) return;
if (message.content.indexOf(this.client.config.prefix) !== 0) return;
const noPrefix: string[] = message.content.slice(this.client.config.prefix.length).trim().split(/ +/g);
const resolved = await this.client.util.resolveCommand(noPrefix);
if (!resolved) return;
if (resolved.cmd.guildOnly && !(message.channel instanceof TextChannel)) return;
if (!resolved.cmd.enabled) { message.channel.createMessage(`***${this.client.util.emojis.ERROR} This command has been disabled***`); return; }
await resolved.cmd.run(message, resolved.args);
}
}

16
src/main.ts Normal file
View File

@ -0,0 +1,16 @@
import { parse } from 'yaml';
import { promises as fs } from 'fs';
import { Client } from './class';
async function main(): Promise<void> {
const read = await fs.readFile('../config.yaml', 'utf8');
const config: { token: string, prefix: string } = parse(read);
const client = new Client(config.token);
client.config = config;
client.loadPlugins();
await client.loadEvents();
await client.loadCommands();
client.connect();
}
main();

64
tsconfig.json Normal file
View File

@ -0,0 +1,64 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": false, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": false, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"resolveJsonModule": true,
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}

1608
yarn.lock Normal file

File diff suppressed because it is too large Load Diff