Merge branch 'dev' of gitlab.libraryofcode.org:engineering/communityrelations into dev

merge-requests/21/merge
Matthew 2021-03-05 22:46:17 -05:00
commit 0961729a1d
No known key found for this signature in database
GPG Key ID: 210AF32ADE3B5C4B
24 changed files with 1137 additions and 1334 deletions

View File

@ -1,47 +1,46 @@
{ {
"settings": { "settings": {
"import/resolver": { "import/resolver": {
"node": { "node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"] "extensions": [".js", ".jsx", ".ts", ".tsx"]
} }
} }
}, },
"env": { "env": {
"es6": true, "es6": true,
"node": true "node": true
}, },
"extends": [ "extends": ["airbnb-base"],
"airbnb-base" "globals": {
], "Atomics": "readonly",
"globals": { "SharedArrayBuffer": "readonly"
"Atomics": "readonly", },
"SharedArrayBuffer": "readonly" "parser": "@typescript-eslint/parser",
}, "parserOptions": {
"parser": "@typescript-eslint/parser", "ecmaVersion": 2020,
"parserOptions": { "sourceType": "module"
"ecmaVersion": 2020, },
"sourceType": "module" "plugins": ["@typescript-eslint"],
}, "rules": {
"plugins": [ "linebreak-style": "off",
"@typescript-eslint" "no-unused-vars": "off",
], "max-len": "off",
"rules": { "import/no-dynamic-require": "off",
"linebreak-style": "off", "global-require": "off",
"no-unused-vars": "off", "class-methods-use-this": "off",
"max-len": "off", "no-restricted-syntax": "off",
"import/no-dynamic-require": "off", "camelcase": "off",
"global-require": "off", "indent": "warn",
"class-methods-use-this":"off", "object-curly-newline": "off",
"no-restricted-syntax": "off", "import/prefer-default-export": "off",
"camelcase": "off", "no-useless-constructor": "off",
"indent": "warn", "@typescript-eslint/no-useless-constructor": 2,
"object-curly-newline": "off", "import/extensions": "off",
"import/prefer-default-export": "off", "no-param-reassign": "off",
"no-useless-constructor": "off", "no-underscore-dangle": "off",
"@typescript-eslint/no-useless-constructor": 2, "keyword-spacing": "off",
"import/extensions": "off", "no-multiple-empty-lines": "off",
"no-param-reassign": "off", "consistent-return": "off"
"no-underscore-dangle": "off" },
}, "ignorePatterns": "**/*.js"
"ignorePatterns": "**/*.js"
} }

1
.gitignore vendored
View File

@ -1,6 +1,5 @@
# Package Management & Libraries # Package Management & Libraries
node_modules node_modules
package-lock.json
# Configuration Files # Configuration Files
config.yaml config.yaml

View File

@ -19,14 +19,14 @@
"@types/jsonwebtoken": "^8.5.0", "@types/jsonwebtoken": "^8.5.0",
"@types/mathjs": "^6.0.7", "@types/mathjs": "^6.0.7",
"@types/mongoose": "^5.7.19", "@types/mongoose": "^5.7.19",
"@types/node": "^14.0.1", "@types/node": "^14.14.25",
"@types/nodemailer": "^6.4.0", "@types/nodemailer": "^6.4.0",
"@types/puppeteer": "^5.4.2", "@types/puppeteer": "^5.4.3",
"@types/signale": "^1.4.1", "@types/signale": "^1.4.1",
"@types/uuid": "^7.0.3", "@types/uuid": "^7.0.3",
"@typescript-eslint/eslint-plugin": "^2.33.0", "@typescript-eslint/eslint-plugin": "^2.33.0",
"@typescript-eslint/parser": "^2.33.0", "@typescript-eslint/parser": "^2.33.0",
"eslint": "^7.0.0", "eslint": "^7.19.0",
"eslint-config-airbnb-base": "^14.1.0", "eslint-config-airbnb-base": "^14.1.0",
"eslint-plugin-import": "^2.20.2", "eslint-plugin-import": "^2.20.2",
"tslib": "^2.1.0", "tslib": "^2.1.0",
@ -36,21 +36,21 @@
"@google-cloud/text-to-speech": "^3.1.2", "@google-cloud/text-to-speech": "^3.1.2",
"ari-client": "^2.2.0", "ari-client": "^2.2.0",
"asterisk-manager": "^0.1.16", "asterisk-manager": "^0.1.16",
"awesome-phonenumber": "^2.41.0", "awesome-phonenumber": "^2.45.0",
"axios": "^0.19.2", "axios": "^0.19.2",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"brain.js": "^2.0.0-beta.2", "brain.js": "^2.0.0-beta.2",
"bull": "^3.18.1", "bull": "^3.20.1",
"cheerio": "^1.0.0-rc.5", "cheerio": "^1.0.0-rc.5",
"cron": "^1.8.2", "cron": "^1.8.2",
"eris": "^0.13.3", "eris": "^0.14.0",
"eris-pagination": "bsian03/eris-pagination", "eris-pagination": "github:bsian03/eris-pagination",
"express": "^4.17.1", "express": "^4.17.1",
"helmet": "^3.22.0", "helmet": "^3.22.0",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"mathjs": "^7.6.0", "mathjs": "^7.6.0",
"moment": "^2.25.3", "moment": "^2.25.3",
"mongoose": "^5.9.13", "mongoose": "^5.11.15",
"nodemailer": "^6.4.8", "nodemailer": "^6.4.8",
"pluris": "^0.2.5", "pluris": "^0.2.5",
"puppeteer": "^5.5.0", "puppeteer": "^5.5.0",

View File

@ -76,7 +76,6 @@ export default class Report extends Route {
return res.status(403).json({ code: this.constants.codes.PERMISSION_DENIED, message: this.constants.messages.PERMISSION_DENIED }); return res.status(403).json({ code: this.constants.codes.PERMISSION_DENIED, message: this.constants.messages.PERMISSION_DENIED });
} }
const flags = []; const flags = [];
if (mem.user.publicFlags) { if (mem.user.publicFlags) {
if ((mem.user.publicFlags & (1 << 0)) === 1 << 0) flags.push('DISCORD_EMPLOYEE'); if ((mem.user.publicFlags & (1 << 0)) === 1 << 0) flags.push('DISCORD_EMPLOYEE');
@ -325,7 +324,6 @@ export default class Report extends Route {
array.push(data); array.push(data);
} }
return res.status(200).json({ return res.status(200).json({
code: this.constants.codes.SUCCESS, code: this.constants.codes.SUCCESS,
message: { message: {
@ -408,7 +406,6 @@ export default class Report extends Route {
else if (member.cloudServices > 10) cloudServicesScore = 10; else if (member.cloudServices > 10) cloudServicesScore = 10;
else cloudServicesScore = Math.round(member.cloudServices); else cloudServicesScore = Math.round(member.cloudServices);
return res.status(200).json({ return res.status(200).json({
code: this.constants.codes.SUCCESS, code: this.constants.codes.SUCCESS,
message: { message: {
@ -587,11 +584,11 @@ export default class Report extends Route {
name?: string, name?: string,
department?: string, department?: string,
date?: Date, date?: Date,
}> jwt.verify(req.query.code.toString(), this.server.client.config.internalKey); }>jwt.verify(req.query.code.toString(), this.server.client.config.internalKey);
} catch { } catch {
return res.status(401).json({ code: this.constants.codes.UNAUTHORIZED, message: this.constants.messages.UNAUTHORIZED }); return res.status(401).json({ code: this.constants.codes.UNAUTHORIZED, message: this.constants.messages.UNAUTHORIZED });
} }
const chan = <TextChannel> this.server.client.guilds.get(this.constants.discord.SERVER_ID).channels.get(offer.channelID); const chan = <TextChannel>this.server.client.guilds.get(this.constants.discord.SERVER_ID).channels.get(offer.channelID);
await chan.createMessage(`__**PRE-APPROVED OFFER ACCEPTED**__\n<@${offer.staffID}>`); await chan.createMessage(`__**PRE-APPROVED OFFER ACCEPTED**__\n<@${offer.staffID}>`);
const message = await chan.getMessage(offer.messageID); const message = await chan.getMessage(offer.messageID);
const args = []; const args = [];

View File

@ -1,35 +0,0 @@
/* eslint-disable no-bitwise */
import { Member, Message, User } from 'eris';
import { randomBytes } from 'crypto';
import moment, { unitOfTime } from 'moment';
import { Client, Moderation, RichEmbed } from '.';
import { Moderation as ModerationModel, ModerationInterface } from '../models';
import { moderation as channels } from '../configs/channels.json';
export default class AutoMod extends Moderation {
public client: Client;
public list: Set<string>
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(client: Client) {
super(client);
this.list = new Set();
}
public run(message: Message, member: Member) {
/*
try {
if (member)
}
*/
}
public warn(message: Message, member: Member) {
/*
try {
await message.channel.createMessage(`__**`)
}
*/
}
}

View File

@ -1,133 +1,133 @@
import Stripe from 'stripe'; import Stripe from 'stripe';
import eris from 'eris'; import eris from 'eris';
import pluris from 'pluris'; import pluris from 'pluris';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { promises as fs } from 'fs'; import { promises as fs } from 'fs';
import { Collection, Command, LocalStorage, Queue, Util, ServerManagement, Event } from '.'; import { Collection, Command, LocalStorage, Queue, Util, ServerManagement, Event } from '.';
import { import {
Customer, CustomerInterface, Customer, CustomerInterface,
CustomerPortal, CustomerPortalInterface, CustomerPortal, CustomerPortalInterface,
File, FileInterface, File, FileInterface,
Inquiry, InquiryInterface, Inquiry, InquiryInterface,
Member, MemberInterface, Member, MemberInterface,
Merchant, MerchantInterface, Merchant, MerchantInterface,
Moderation, ModerationInterface, Moderation, ModerationInterface,
NNTrainingData, NNTrainingDataInterface, NNTrainingData, NNTrainingDataInterface,
Note, NoteInterface, Note, NoteInterface,
PagerNumber, PagerNumberInterface, PagerNumber, PagerNumberInterface,
Promo, PromoInterface, Promo, PromoInterface,
Rank, RankInterface, Rank, RankInterface,
Redirect, RedirectInterface, Redirect, RedirectInterface,
Score, ScoreInterface, Score, ScoreInterface,
ScoreHistorical, ScoreHistoricalInterface, ScoreHistorical, ScoreHistoricalInterface,
Staff, StaffInterface, Staff, StaffInterface,
Stat, StatInterface, Stat, StatInterface,
} from '../models'; } from '../models';
import { Config } from '../../types'; // eslint-disable-line import { Config } from '../../types'; // eslint-disable-line
pluris(eris); pluris(eris);
export default class Client extends eris.Client { export default class Client extends eris.Client {
public config: Config; public config: Config;
public commands: Collection<Command>; public commands: Collection<Command>;
public events: Collection<Event>; public events: Collection<Event>;
public intervals: Collection<NodeJS.Timeout>; public intervals: Collection<NodeJS.Timeout>;
public util: Util; public util: Util;
public serverManagement: ServerManagement; public serverManagement: ServerManagement;
public queue: Queue; public queue: Queue;
public stripe: Stripe; public stripe: Stripe;
public db: { Customer: mongoose.Model<CustomerInterface>, CustomerPortal: mongoose.Model<CustomerPortalInterface>, File: mongoose.Model<FileInterface>, Inquiry: mongoose.Model<InquiryInterface>, Member: mongoose.Model<MemberInterface>, Merchant: mongoose.Model<MerchantInterface>, Moderation: mongoose.Model<ModerationInterface>, NNTrainingData: mongoose.Model<NNTrainingDataInterface>, Note: mongoose.Model<NoteInterface>, PagerNumber: mongoose.Model<PagerNumberInterface>, Promo: mongoose.Model<PromoInterface>, Rank: mongoose.Model<RankInterface>, Redirect: mongoose.Model<RedirectInterface>, Score: mongoose.Model<ScoreInterface>, ScoreHistorical: mongoose.Model<ScoreHistoricalInterface>, Staff: mongoose.Model<StaffInterface>, Stat: mongoose.Model<StatInterface>, local: { muted: LocalStorage } }; public db: { Customer: mongoose.Model<CustomerInterface>, CustomerPortal: mongoose.Model<CustomerPortalInterface>, File: mongoose.Model<FileInterface>, Inquiry: mongoose.Model<InquiryInterface>, Member: mongoose.Model<MemberInterface>, Merchant: mongoose.Model<MerchantInterface>, Moderation: mongoose.Model<ModerationInterface>, NNTrainingData: mongoose.Model<NNTrainingDataInterface>, Note: mongoose.Model<NoteInterface>, PagerNumber: mongoose.Model<PagerNumberInterface>, Promo: mongoose.Model<PromoInterface>, Rank: mongoose.Model<RankInterface>, Redirect: mongoose.Model<RedirectInterface>, Score: mongoose.Model<ScoreInterface>, ScoreHistorical: mongoose.Model<ScoreHistoricalInterface>, Staff: mongoose.Model<StaffInterface>, Stat: mongoose.Model<StatInterface>, local: { muted: LocalStorage } };
constructor(token: string, options?: eris.ClientOptions) { constructor(token: string, options?: eris.ClientOptions) {
super(token, options); super(token, options);
this.commands = new Collection<Command>(); this.commands = new Collection<Command>();
this.events = new Collection<Event>(); this.events = new Collection<Event>();
this.intervals = new Collection<NodeJS.Timeout>(); this.intervals = new Collection<NodeJS.Timeout>();
this.queue = new Queue(this); this.queue = new Queue(this);
this.db = { Customer, CustomerPortal, File, Inquiry, Member, Merchant, Moderation, NNTrainingData, Note, PagerNumber, Promo, Rank, Redirect, Score, ScoreHistorical, Staff, Stat, local: { muted: new LocalStorage('muted') } }; this.db = { Customer, CustomerPortal, File, Inquiry, Member, Merchant, Moderation, NNTrainingData, Note, PagerNumber, Promo, Rank, Redirect, Score, ScoreHistorical, Staff, Stat, local: { muted: new LocalStorage('muted') } };
} }
get report() { get report() {
return this.util.report; return this.util.report;
} }
get pbx() { get pbx() {
return this.util.pbx; return this.util.pbx;
} }
public async loadDatabase() { public async loadDatabase() {
await mongoose.connect(this.config.mongoDB, { useNewUrlParser: true, useUnifiedTopology: true, poolSize: 50 }); await mongoose.connect(this.config.mongoDB, { useNewUrlParser: true, useUnifiedTopology: true, poolSize: 50 });
const statMessages = await this.db.Stat.findOne({ name: 'messages' }); const statMessages = await this.db.Stat.findOne({ name: 'messages' });
const statCommands = await this.db.Stat.findOne({ name: 'commands' }); const statCommands = await this.db.Stat.findOne({ name: 'commands' });
const statPages = await this.db.Stat.findOne({ name: 'pages' }); const statPages = await this.db.Stat.findOne({ name: 'pages' });
const statRequests = await this.db.Stat.findOne({ name: 'requests' }); const statRequests = await this.db.Stat.findOne({ name: 'requests' });
if (!statMessages) { if (!statMessages) {
await (new this.db.Stat({ name: 'messages', value: 0 }).save()); await (new this.db.Stat({ name: 'messages', value: 0 }).save());
} }
if (!statCommands) { if (!statCommands) {
await (new this.db.Stat({ name: 'commands', value: 0 }).save()); await (new this.db.Stat({ name: 'commands', value: 0 }).save());
} }
if (!statPages) { if (!statPages) {
await (new this.db.Stat({ name: 'pages', value: 0 }).save()); await (new this.db.Stat({ name: 'pages', value: 0 }).save());
} }
if (!statRequests) { if (!statRequests) {
await (new this.db.Stat({ name: 'requests', value: 0 }).save()); await (new this.db.Stat({ name: 'requests', value: 0 }).save());
} }
} }
public loadPlugins() { public loadPlugins() {
this.util = new Util(this); this.util = new Util(this);
this.serverManagement = new ServerManagement(this); this.serverManagement = new ServerManagement(this);
this.stripe = new Stripe(this.config.stripeKey, { apiVersion: null, typescript: true }); this.stripe = new Stripe(this.config.stripeKey, { apiVersion: null, typescript: true });
} }
public async loadIntervals() { public async loadIntervals() {
const intervalFiles = await fs.readdir(`${__dirname}/../intervals`); const intervalFiles = await fs.readdir(`${__dirname}/../intervals`);
intervalFiles.forEach((file) => { intervalFiles.forEach((file) => {
const intervalName = file.split('.')[0]; const intervalName = file.split('.')[0];
if (file === 'index.js') return; if (file === 'index.js') return;
const interval: NodeJS.Timeout = (require(`${__dirname}/../intervals/${file}`).default)(this); const interval: NodeJS.Timeout = (require(`${__dirname}/../intervals/${file}`).default)(this);
this.intervals.add(intervalName, interval); this.intervals.add(intervalName, interval);
this.util.signale.success(`Successfully loaded interval: ${intervalName}`); this.util.signale.success(`Successfully loaded interval: ${intervalName}`);
}); });
} }
public async loadEvents(eventFiles: { [s: string]: typeof Event; } | ArrayLike<typeof Event>) { public async loadEvents(eventFiles: { [s: string]: typeof Event; } | ArrayLike<typeof Event>) {
const evtFiles = Object.entries<typeof Event>(eventFiles); const evtFiles = Object.entries<typeof Event>(eventFiles);
for (const [name, Ev] of evtFiles) { for (const [name, Ev] of evtFiles) {
const event = new Ev(this); const event = new Ev(this);
this.events.add(event.event, event); this.events.add(event.event, event);
this.on(event.event, event.run); this.on(event.event, event.run);
this.util.signale.success(`Successfully loaded event: ${name}`); this.util.signale.success(`Successfully loaded event: ${name}`);
delete require.cache[require.resolve(`${__dirname}/../events/${name}`)]; delete require.cache[require.resolve(`${__dirname}/../events/${name}`)];
} }
} }
public async loadCommands(commandFiles: { [s: string]: typeof Command; } | ArrayLike<typeof Command>) { public async loadCommands(commandFiles: { [s: string]: typeof Command; } | ArrayLike<typeof Command>) {
const cmdFiles = Object.values<typeof Command>(commandFiles); const cmdFiles = Object.values<typeof Command>(commandFiles);
for (const Cmd of cmdFiles) { for (const Cmd of cmdFiles) {
const command = new Cmd(this); const command = new Cmd(this);
if (command.subcmds.length) { if (command.subcmds.length) {
command.subcmds.forEach((C) => { command.subcmds.forEach((C) => {
const cmd: Command = new C(this); const cmd: Command = new C(this);
command.subcommands.add(cmd.name, cmd); command.subcommands.add(cmd.name, cmd);
this.util.signale.success(`Successfully loaded subcommand ${cmd.name} under ${command.name}`); this.util.signale.success(`Successfully loaded subcommand ${cmd.name} under ${command.name}`);
}); });
} }
delete command.subcmds; delete command.subcmds;
this.commands.add(command.name, command); this.commands.add(command.name, command);
this.util.signale.success(`Successfully loaded command: ${command.name}`); this.util.signale.success(`Successfully loaded command: ${command.name}`);
} }
} }
} }

View File

@ -1,9 +1,10 @@
/* eslint-disable no-constant-condition */ /* eslint-disable no-constant-condition */
import { promises as fs, accessSync, constants, writeFileSync } from 'fs'; import { promises as fs, accessSync, constants, writeFileSync } from 'fs';
import { promisify } from 'util'; import { promisify } from 'util';
import { join } from 'path';
import { gzip, gzipSync, unzip } from 'zlib'; import { gzip, gzipSync, unzip } from 'zlib';
type JSONData = [{key: string, value: any}?]; type JSONData = [{ key: string, value: any }?];
/** /**
@ -18,7 +19,7 @@ export default class LocalStorage {
private locked: boolean = false; private locked: boolean = false;
constructor(dbName: string, dir = `${__dirname}/../../localstorage`) { constructor(dbName: string, dir = `${__dirname}/../../localstorage`) {
this.storagePath = `${dir}/${dbName}.json.gz`; this.storagePath = join(__dirname, '../../localstorage') || dir;
this.init(); this.init();
} }
@ -42,7 +43,7 @@ export default class LocalStorage {
*/ */
static async compress(data: string): Promise<Buffer> { static async compress(data: string): Promise<Buffer> {
const func = promisify(gzip); const func = promisify(gzip);
const comp = <Buffer> await func(data); const comp = <Buffer>await func(data);
return comp; return comp;
} }
@ -57,7 +58,7 @@ export default class LocalStorage {
*/ */
static async decompress(data: Buffer): Promise<string> { static async decompress(data: Buffer): Promise<string> {
const func = promisify(unzip); const func = promisify(unzip);
const uncomp = <Buffer> await func(data); const uncomp = <Buffer>await func(data);
return uncomp.toString(); return uncomp.toString();
} }
@ -91,7 +92,7 @@ export default class LocalStorage {
* await LocalStorage.get<type>('data-key'); * await LocalStorage.get<type>('data-key');
* @param key The key for the data entry. * @param key The key for the data entry.
*/ */
public async getMany<T>(key: string): Promise<{key: string, value: T}[]> { public async getMany<T>(key: string): Promise<{ key: string, value: T }[]> {
while (true) { while (true) {
if (!this.locked) break; if (!this.locked) break;
} }

View File

@ -56,6 +56,7 @@ export default class Server {
public init() { public init() {
if (this.parse) { if (this.parse) {
this.app.use(bodyParser.json()); this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: true }));
} }
this.app.set('trust proxy', 'loopback'); this.app.set('trust proxy', 'loopback');
this.app.use(helmet({ this.app.use(helmet({

View File

@ -115,7 +115,6 @@ export default class Util {
return `${(bytes / 1024 ** i).toFixed(2)} ${sizes[i]}`; return `${(bytes / 1024 ** i).toFixed(2)} ${sizes[i]}`;
} }
public async exec(command: string, _options: childProcess.ExecOptions = {}): Promise<string> { public async exec(command: string, _options: childProcess.ExecOptions = {}): Promise<string> {
const ex = promisify(childProcess.exec); const ex = promisify(childProcess.exec);
try { try {
@ -148,7 +147,7 @@ export default class Util {
* @param query Command input * @param query Command input
* @param message Only used to check for errors * @param message Only used to check for errors
*/ */
public resolveCommand(query: string | string[], message?: Message): Promise<{cmd: Command, args: string[] }> { public resolveCommand(query: string | string[], message?: Message): Promise<{ cmd: Command, args: string[] }> {
try { try {
let resolvedCommand: Command; let resolvedCommand: Command;
if (typeof query === 'string') query = query.split(' '); if (typeof query === 'string') query = query.split(' ');
@ -238,7 +237,7 @@ export default class Util {
public splitFields(fields: { name: string, value: string, inline?: boolean }[]): { name: string, value: string, inline?: boolean }[][] { public splitFields(fields: { name: string, value: string, inline?: boolean }[]): { name: string, value: string, inline?: boolean }[][] {
let index = 0; let index = 0;
const array: {name: string, value: string, inline?: boolean}[][] = [[]]; const array: { name: string, value: string, inline?: boolean }[][] = [[]];
while (fields.length) { while (fields.length) {
if (array[index].length >= 25) { index += 1; array[index] = []; } if (array[index].length >= 25) { index += 1; array[index] = []; }
array[index].push(fields[0]); fields.shift(); array[index].push(fields[0]); fields.shift();

View File

@ -38,7 +38,7 @@ export default class Apply extends Command {
validation: (member: Member) => member.roles.includes('546457886440685578'), validation: (member: Member) => member.roles.includes('546457886440685578'),
func: async (client: Client, ...data: any[]) => { func: async (client: Client, ...data: any[]) => {
const member = await client.guilds.get(client.config.guildID).getRESTMember(data[0]); const member = await client.guilds.get(client.config.guildID).getRESTMember(data[0]);
const ax = <AxiosStatic> require('axios'); const ax = <AxiosStatic>require('axios');
await ax({ await ax({
method: 'get', method: 'get',
url: `https://api.cloud.libraryofcode.org/wh/t2?userID=${member.id}&auth=${client.config.internalKey}`, url: `https://api.cloud.libraryofcode.org/wh/t2?userID=${member.id}&auth=${client.config.internalKey}`,

View File

@ -23,7 +23,7 @@ export default class Billing_T3 extends Command {
emailAddress?: string, emailAddress?: string,
tier?: number, tier?: number,
supportKey?: string, supportKey?: string,
}> (await axios.get(`https://api.cloud.libraryofcode.org/wh/info?id=${message.author.id}&authorization=${this.client.config.internalKey}`)).data; }>(await axios.get(`https://api.cloud.libraryofcode.org/wh/info?id=${message.author.id}&authorization=${this.client.config.internalKey}`)).data;
if (!response.found) return this.error(message.channel, 'CS Account not found.'); if (!response.found) return this.error(message.channel, 'CS Account not found.');
const customer = await this.client.db.Customer.findOne({ userID: message.author.id }); const customer = await this.client.db.Customer.findOne({ userID: message.author.id });

View File

@ -180,7 +180,7 @@ export default class Page extends Command {
await this.client.util.transporter.sendMail({ await this.client.util.transporter.sendMail({
from: '"LOC Paging System" <internal@libraryofcode.org>', from: '"LOC Paging System" <internal@libraryofcode.org>',
to: email, to: email,
subject: `PAGE FROM ${recipientNumber}`, subject: `PAGE FROM ${senderNumber}`,
html: `<h1>Page</h1>${options?.emergencyNumber ? `<h2>[SEN#${options.emergencyNumber}]` : ''}<strong>Recipient PN:</strong> ${recipientNumber}<br><strong>Sender PN:</strong> ${senderNumber} (${sender ? `${sender.username}#${sender.discriminator}` : ''})<br><strong>Initial Command:</strong> https://discordapp.com/channels/${this.mainGuild.id}/${message.channel.id}/${message.id} (<#${message.channel.id}>)<br><br><strong>Pager Code:</strong> ${code} (${this.local.codeDict.get(code)})${txt ? `<br><strong>Message:</strong> ${txt}` : ''}`, html: `<h1>Page</h1>${options?.emergencyNumber ? `<h2>[SEN#${options.emergencyNumber}]` : ''}<strong>Recipient PN:</strong> ${recipientNumber}<br><strong>Sender PN:</strong> ${senderNumber} (${sender ? `${sender.username}#${sender.discriminator}` : ''})<br><strong>Initial Command:</strong> https://discordapp.com/channels/${this.mainGuild.id}/${message.channel.id}/${message.id} (<#${message.channel.id}>)<br><br><strong>Pager Code:</strong> ${code} (${this.local.codeDict.get(code)})${txt ? `<br><strong>Message:</strong> ${txt}` : ''}`,
}); });
} }

21
src/commands/profile.ts Normal file
View File

@ -0,0 +1,21 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Profile extends Command {
constructor(client: Client) {
super(client);
this.name = 'profile';
this.description = 'Manages your profile on CR';
this.usage = 'profile <bio/github/gitlab> <new value>';
this.permissions = 0;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
if (!await this.client.db.Member.exists({ userID: message.author.id })) {
await this.client.db.Member.create({ userID: message.author.id });
}
this.error(message.channel, `Please specify a valid option to change. Choose from \`github\`, \`bio\` and \`gitlab\`. You can view your profile with \`${this.client.config.prefix}whois\`.`);
}
}

View File

@ -0,0 +1,30 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Profile_Bio extends Command {
constructor(client: Client) {
super(client);
this.name = 'bio';
this.description = 'Updates your bio on your profile.';
this.usage = `${this.client.config.prefix}bio <new bio>`;
this.permissions = 0;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
if (!await this.client.db.Member.exists({ userID: message.author.id })) {
await this.client.db.Member.create({ userID: message.author.id });
}
if (!args[0]) return this.error(message.channel, 'No new bio content was provided.');
const bio = args.join(' ');
if (bio.length >= 256) return this.error(message.channel, 'Bio too long. It must be less than or equal to 256 characters.');
const member = await this.client.db.Member.findOne({ userID: message.author.id });
await member.updateOne({
additional: {
...member.additional,
bio,
},
});
}
}

View File

@ -0,0 +1,38 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Profile_GitHub extends Command {
constructor(client: Client) {
super(client);
this.name = 'github';
this.description = 'Updates your GitHub information on your profile.';
this.usage = `${this.client.config.prefix}github <GitHub profile URL>`;
this.permissions = 0;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
if (!await this.client.db.Member.exists({ userID: message.author.id })) {
await this.client.db.Member.create({ userID: message.author.id });
}
if (!args[0]) return this.error(message.channel, 'No GitHub profile URL was provided.');
const urlRegex = new RegExp(
'^(https?:\\/\\/)?'
+ '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'
+ '((\\d{1,3}\\.){3}\\d{1,3}))'
+ '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'
+ '(\\?[;&a-z\\d%_.~+=-]*)?'
+ '(\\#[-a-z\\d_]*)?$',
'i',
);
if (!urlRegex.test(args[0]) || !args[0].startsWith('https://github.com/')) return this.error(message.channel, 'Invalid GitHub profile URL.');
const member = await this.client.db.Member.findOne({ userID: message.author.id });
await member.updateOne({
additional: {
...member.additional,
github: args[0],
},
});
}
}

View File

@ -0,0 +1,38 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Profile_GitLab extends Command {
constructor(client: Client) {
super(client);
this.name = 'gitlab';
this.description = 'Updates your GitLab information on your profile.';
this.usage = `${this.client.config.prefix}gitlab <GitLab profile URL>`;
this.permissions = 0;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
if (!await this.client.db.Member.exists({ userID: message.author.id })) {
await this.client.db.Member.create({ userID: message.author.id });
}
if (!args[0]) return this.error(message.channel, 'No GitLab profile URL was provided.');
const urlRegex = new RegExp(
'^(https?:\\/\\/)?'
+ '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'
+ '((\\d{1,3}\\.){3}\\d{1,3}))'
+ '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'
+ '(\\?[;&a-z\\d%_.~+=-]*)?'
+ '(\\#[-a-z\\d_]*)?$',
'i',
);
if (!urlRegex.test(args[0]) || !args[0].startsWith('https://gitlab.com/')) return this.error(message.channel, 'Invalid GitLab profile URL.');
const member = await this.client.db.Member.findOne({ userID: message.author.id });
await member.updateOne({
additional: {
...member.additional,
gitlab: args[0],
},
});
}
}

29
src/commands/setnick.ts Normal file
View File

@ -0,0 +1,29 @@
import { Message } from 'eris';
import { Client, Command } from '../class';
export default class Setnick extends Command {
constructor(client: Client) {
super(client);
this.name = 'setnick';
this.description = 'Changes the nickname of a member';
this.usage = 'setnick <member> [new nickname]';
this.permissions = 2;
this.guildOnly = true;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
try {
if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
const member = this.client.util.resolveMember(args[0], this.mainGuild);
if (!member) return this.error(message.channel, 'Cannot find user.');
let nickname = args.slice(1).join(' ');
if (args.length === 1) nickname = null;
if (nickname?.length > 32) return this.error(message.channel, 'New nickname may not be more than 32 characters long.');
await member.edit({ nick: nickname });
return this.success(message.channel, `Updated the nickname of ${member.user.username}#${member.user.discriminator}.`);
} catch (err) {
return this.client.util.handleError(err, message, this, false);
}
}
}

View File

@ -56,14 +56,15 @@ export default class Whois extends Command {
if (ackResolve?.extension) { if (ackResolve?.extension) {
description += `☎️ ${ackResolve.extension}\n`; description += `☎️ ${ackResolve.extension}\n`;
} }
if (ackResolve?.gitlab) { const memberProfile = await this.client.db.Member.findOne({ userID: message.author.id });
description += `${emotes.gitlab} ${ackResolve.gitlab}\n`; if (memberProfile?.additional?.gitlab) {
description += `${emotes.gitlab} ${memberProfile?.additional.gitlab}\n`;
} }
if (ackResolve?.github) { if (memberProfile?.additional?.github) {
description += `${emotes.github} ${ackResolve.github}\n`; description += `${emotes.github} ${memberProfile?.additional.github}\n`;
} }
if (ackResolve?.bio) { if (memberProfile?.additional?.bio) {
description += `${emotes.bio} *${ackResolve.bio}*\n`; description += `${emotes.bio} *${memberProfile?.additional.bio}*\n`;
} }
description += `\n<@${member.id}>`; description += `\n<@${member.id}>`;
embed.setDescription(description); embed.setDescription(description);

View File

@ -71,7 +71,7 @@ async function setupDepartmentCodes(client: Client): Promise<void> {
function logNewPager(client: Client, num: string, member: Member): void { function logNewPager(client: Client, num: string, member: Member): void {
client.util.signale.log(`Pager Number '${num}' created for '${member.user.username}#${member.user.discriminator}'.`); client.util.signale.log(`Pager Number '${num}' created for '${member.user.username}#${member.user.discriminator}'.`);
const channel = <TextableChannel> client.guilds.get(client.config.guildID).channels.get('722636436716781619'); const channel = <TextableChannel>client.guilds.get(client.config.guildID).channels.get('722636436716781619');
channel.createMessage(`__**'${member.user.username}#${member.user.discriminator}' assigned to pager number '${num}'.**__`); channel.createMessage(`__**'${member.user.username}#${member.user.discriminator}' assigned to pager number '${num}'.**__`);
} }

View File

@ -4,6 +4,7 @@
import sdNotify from 'sd-notify'; import sdNotify from 'sd-notify';
import { parse } from 'yaml'; import { parse } from 'yaml';
import { promises as fs } from 'fs'; import { promises as fs } from 'fs';
import { join } from 'path';
import { Client } from './class'; import { Client } from './class';
import * as eventFiles from './events'; import * as eventFiles from './events';
import * as commandFiles from './commands'; import * as commandFiles from './commands';
@ -14,7 +15,7 @@ async function main(): Promise<void> {
sdNotify.ready(); sdNotify.ready();
sdNotify.startWatchdogMode(2500); sdNotify.startWatchdogMode(2500);
} }
const read = await fs.readFile('../config.yaml', 'utf8'); const read = await fs.readFile(join(__dirname, '../config.yaml'), 'utf8');
const config: Config = parse(read); const config: Config = parse(read);
const client = new Client(config.token, { defaultImageFormat: 'png', restMode: true, intents: ['guildBans', 'guildEmojis', 'guildInvites', 'guildMembers', 'guildMessageReactions', 'guildMessages', 'guildPresences', 'guildWebhooks', 'guilds', 'directMessages'] }); const client = new Client(config.token, { defaultImageFormat: 'png', restMode: true, intents: ['guildBans', 'guildEmojis', 'guildInvites', 'guildMembers', 'guildMessageReactions', 'guildMessages', 'guildPresences', 'guildWebhooks', 'guilds', 'directMessages'] });
client.config = config; client.config = config;

View File

@ -5,6 +5,9 @@ export interface MemberInterface extends Document {
additional: { additional: {
langs: ['js', 'py', 'rb', 'ts', 'rs', 'go', 'cfam', 'csharp', 'swift', 'java', 'kt', 'asm'], langs: ['js', 'py', 'rb', 'ts', 'rs', 'go', 'cfam', 'csharp', 'swift', 'java', 'kt', 'asm'],
operatingSystems: ['arch', 'deb', 'cent', 'fedora', 'manjaro', 'mdarwin', 'redhat', 'ubuntu', 'win'], operatingSystems: ['arch', 'deb', 'cent', 'fedora', 'manjaro', 'mdarwin', 'redhat', 'ubuntu', 'win'],
github: string,
gitlab: string,
bio: string,
}, },
bio: string, bio: string,
} }
@ -14,6 +17,9 @@ const Member: Schema = new Schema({
additional: { additional: {
langs: Array, langs: Array,
operatingSystems: Array, operatingSystems: Array,
github: String,
gitlab: String,
bio: String,
}, },
bio: String, bio: String,
}); });

View File

@ -7,9 +7,6 @@ export interface StaffInterface extends Document {
dept: string, dept: string,
pn: string[], pn: string[],
emailAddress: string, emailAddress: string,
gitlab: string,
github: string,
bio: string,
extension: string, extension: string,
acknowledgements: string[], acknowledgements: string[],
additionalRoles: string[] additionalRoles: string[]
@ -22,9 +19,6 @@ const Staff: Schema = new Schema({
dept: String, dept: String,
pn: Array, pn: Array,
emailAddress: String, emailAddress: String,
gitlab: String,
github: String,
bio: String,
extension: String, extension: String,
acknowledgements: Array, acknowledgements: Array,
additionalRoles: Array, additionalRoles: Array,

View File

@ -1,17 +1,17 @@
export { default as Customer, CustomerInterface } from './Customer'; export { default as Customer, CustomerInterface } from './Customer';
export { default as CustomerPortal, CustomerPortalInterface } from './CustomerPortal'; export { default as CustomerPortal, CustomerPortalInterface } from './CustomerPortal';
export { default as File, FileInterface } from './File'; export { default as File, FileInterface } from './File';
export { default as Inquiry, InquiryInterface, InqType } from './Inquiry'; export { default as Inquiry, InquiryInterface, InqType } from './Inquiry';
export { default as Member, MemberInterface } from './Member'; export { default as Member, MemberInterface } from './Member';
export { default as Merchant, MerchantInterface } from './Merchant'; export { default as Merchant, MerchantInterface } from './Merchant';
export { default as Moderation, ModerationInterface } from './Moderation'; export { default as Moderation, ModerationInterface } from './Moderation';
export { default as NNTrainingData, NNTrainingDataInterface } from './NNTrainingData'; export { default as NNTrainingData, NNTrainingDataInterface } from './NNTrainingData';
export { default as Note, NoteInterface } from './Note'; export { default as Note, NoteInterface } from './Note';
export { default as PagerNumber, PagerNumberInterface, PagerNumberRaw } from './PagerNumber'; export { default as PagerNumber, PagerNumberInterface, PagerNumberRaw } from './PagerNumber';
export { default as Promo, PromoInterface } from './Promo'; export { default as Promo, PromoInterface } from './Promo';
export { default as Rank, RankInterface } from './Rank'; export { default as Rank, RankInterface } from './Rank';
export { default as Redirect, RedirectInterface, RedirectRaw } from './Redirect'; export { default as Redirect, RedirectInterface, RedirectRaw } from './Redirect';
export { default as Score, ScoreInterface, ScoreInterfaceRaw } from './Score'; export { default as Score, ScoreInterface, ScoreInterfaceRaw } from './Score';
export { default as ScoreHistorical, ScoreHistoricalInterface } from './ScoreHistorical'; export { default as ScoreHistorical, ScoreHistoricalInterface } from './ScoreHistorical';
export { default as Staff, StaffInterface } from './Staff'; export { default as Staff, StaffInterface } from './Staff';
export { default as Stat, StatInterface } from './Stat'; export { default as Stat, StatInterface } from './Stat';

1814
yarn.lock

File diff suppressed because it is too large Load Diff