ghorsington vor 4 Jahren
Ursprung
Commit
94d049e62e

+ 0 - 114
bot/src/command_manager.ts

@@ -1,114 +0,0 @@
-import path from "path";
-import fs from "fs";
-import { isCommandSet, ICommand, IBotCommand, ActionType, BotAction } from "./model/command";
-import { getNumberEnums, assertOk } from "./util";
-import { Message } from "discord.js";
-
-interface IDocumentationData {
-    name: string;
-    doc?: string;
-    example?: string;
-    auth: boolean;
-}
-
-type BotEventCollection = { [event in ActionType]: BotAction[] };
-
-export class CommandManager {
-    private commandSets: ICommand[] = [];
-    private botCommands: IBotCommand[] = [];
-    private botEvents: BotEventCollection = getNumberEnums(ActionType).reduce((p, c) => { p[c as ActionType] = []; return p; }, {} as BotEventCollection);
-    private startActions: Array<() => void | Promise<void>> = [];
-
-    constructor(private cmdPath: string) {
-        this.init();
-    }
-
-    private init(): void {
-        const files = fs.readdirSync(this.cmdPath);
-
-        for (const file of files) {
-            const ext = path.extname(file);
-            if (ext != ".js")
-                continue;
-
-            // eslint-disable-next-line @typescript-eslint/no-var-requires
-            this.loadCommand(require(path.resolve(this.cmdPath, file)));
-        }
-    }
-
-    private loadCommand(mod: Record<string, unknown>) {
-        for (const i in mod) {
-            if (!Object.prototype.hasOwnProperty.call(mod, i))
-                continue;
-    
-            const commandClass = mod[i] as unknown;
-            // Ensure this is indeed a command class
-            if (!isCommandSet(commandClass))
-                continue;
-    
-            const cmd = new commandClass();
-            this.commandSets.push(cmd);
-    
-            if (cmd._botCommands)
-                this.botCommands.push(...cmd._botCommands.map(c => ({ ...c, action: c.action.bind(cmd) })));
-    
-            if (cmd._botEvents)
-                for (const [i, event] of Object.entries(cmd._botEvents)) {
-                    this.botEvents[+i as ActionType].push((event as BotAction).bind(cmd));
-                }
-    
-            if (cmd.onStart)
-                this.startActions.push(cmd.onStart.bind(cmd));
-        }
-    }
-
-    get documentation(): IDocumentationData[] {
-        return this.botCommands.filter(m => m.documentation !== undefined).map(m => ({
-            name: m.pattern.toString(),
-            doc: m.documentation?.description,
-            example: m.documentation?.example,
-            auth: m.auth || false
-        }));
-    }
-
-    async onStart(): Promise<void> {
-        for (let i = 0; i < this.startActions.length; i++) {
-            const action = this.startActions[i];
-            const val = action();
-            if (val instanceof Promise)
-                await assertOk(val);
-        }
-    }
-
-    async trigger(type: ActionType, ...params: unknown[]): Promise<boolean> {
-        let actionDone = false;
-        const actions = this.botEvents[type];
-        for (let i = 0; i < actions.length; i++) {
-            const action = actions[i] as (...args: unknown[]) => boolean | Promise<boolean>;
-            const actionResult = action(actionDone, ...params);
-            if (actionResult instanceof Promise)
-                actionDone = (await assertOk(actionResult)) || actionDone;
-            else
-                actionDone = actionResult || actionDone;
-        }
-        return actionDone;
-    }
-
-    runCommand(m: Message, content: string): boolean {
-        const lowerCaseContent = content.toLowerCase();
-        for (const c of this.botCommands) {
-            if (typeof (c.pattern) == "string" && lowerCaseContent.startsWith(c.pattern)) {
-                c.action(m, content);
-                return true;
-            }
-            else if (c.pattern instanceof RegExp) {
-                const result = c.pattern.exec(content);
-                if (result != null) {
-                    c.action(m, content, result);
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-}

+ 0 - 67
bot/src/model/command.ts

@@ -1,67 +0,0 @@
-import { Message } from "discord.js";
-import { EsModuleClass, isModuleClass } from "src/util";
-
-export interface CommandDocumentation {
-    description: string;
-    example: string;
-}
-
-export interface CommandOptions {
-    pattern: string | RegExp;
-    documentation?: CommandDocumentation;
-    auth?: boolean;
-}
-
-export type BotAction = (actionsDone: boolean, m : Message, content: string) => boolean | Promise<boolean>;
-export type BotMessageCommand = (message: Message, strippedContents: string, matches?: RegExpMatchArray) => void;
-
-export interface ICommand {
-    onStart?(): void | Promise<void>;
-    _botCommands?: IBotCommand[];
-    _botEvents?: { [action in ActionType]?: BotAction };
-    BOT_COMMAND?: string;
-}
-
-export interface IBotCommand extends CommandOptions {
-    action : BotMessageCommand;
-}
-
-export const BOT_COMMAND_DESCRIPTOR = "BOT_COMMAND";
-export function CommandSet<T extends {new(...params: unknown[]): unknown}>(base: T): void {
-    base.prototype.BOT_COMMAND = BOT_COMMAND_DESCRIPTOR;
-}
-
-export enum ActionType {
-    MESSAGE,
-    INDIRECT_MENTION,
-    DIRECT_MENTION,
-    POST_MESSAGE
-}
-export function Action(type: ActionType): MethodDecorator {
-    return function<T>(target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): void {
-        const command = target as ICommand;
-        if(!command._botEvents)
-            command._botEvents= {};
-
-        command._botEvents[type] = descriptor.value as BotAction | undefined;
-    };
-}
-
-export function Command(opts: CommandOptions) : MethodDecorator {
-    return function<T>(target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): void {
-        if(!descriptor.value)
-            throw new Error("The decorator value must be initialized!");
-        const command = target as ICommand;
-        if(!command._botCommands)
-            command._botCommands = [];
-
-        command._botCommands.push({
-            action: descriptor.value as unknown as BotMessageCommand,
-            ...opts
-        });
-    };
-}
-
-export function isCommandSet(obj: unknown): obj is EsModuleClass<ICommand> {
-    return isModuleClass<ICommand>(obj) && obj.prototype.BOT_COMMAND == BOT_COMMAND_DESCRIPTOR;
-}

+ 0 - 3
bot/src/plugins/guide.ts

@@ -1,4 +1,3 @@
-import { isAuthorisedAsync } from "../util";
 import { Message } from "discord.js";
 import { getRepository } from "typeorm";
 import { Guide, GuideType, GuideKeyword } from "@shared/db/entity/Guide";
@@ -85,7 +84,6 @@ export class GuideCommands {
         }
     })
     async makeGuide({ message, contents }: ICommandData): Promise<void> {
-        if (!await isAuthorisedAsync(message.member)) return;
         const match = contents as RegExpMatchArray;
         const type = match[1].toLowerCase();
         const name = match[2].trim();
@@ -164,7 +162,6 @@ export class GuideCommands {
         }
     })
     async deleteGuide({ message, contents }: ICommandData): Promise<void> {
-        if (!await isAuthorisedAsync(message.member)) return;
         const match = contents as RegExpMatchArray;
         const type = match[1];
         const keywords = match[2].toLowerCase().split(" ").map(s => s.trim()).filter(s => s.length != 0);

+ 0 - 9
bot/src/plugins/quote.ts

@@ -1,4 +1,3 @@
-import { isAuthorisedAsync } from "../util";
 import { getRepository } from "typeorm";
 import { Quote } from "@shared/db/entity/Quote";
 import { Command, ICommandData, Plugin } from "src/model/plugin";
@@ -24,9 +23,6 @@ export class QuoteCommand {
         }
     })
     async addQuote({ message, contents }: ICommandData): Promise<void> {
-        if (!isAuthorisedAsync(message.member))
-            return;
-
         const result = quotePattern.exec(contents as string);
 
         if (result == null)
@@ -101,11 +97,6 @@ export class QuoteCommand {
         auth: true 
     })
     async listQuotes({ message }: ICommandData): Promise<void> {
-        if (!isAuthorisedAsync(message.member)) {
-            message.reply("to prevent spamming, only bot moderators can view all quotes!");
-            return;
-        }
-
         const repo = getRepository(Quote);
 
         const quotes = await repo.find();

+ 0 - 6
bot/src/plugins/react.ts

@@ -3,7 +3,6 @@ import { getRepository } from "typeorm";
 import { MessageReaction } from "@shared/db/entity/MessageReaction";
 import { KnownUser } from "@shared/db/entity/KnownUser";
 import { ReactionType, ReactionEmote } from "@shared/db/entity/ReactionEmote";
-import { isAuthorisedAsync } from "../util";
 import { Message } from "discord.js";
 import { logger } from "src/logging";
 import { Command, ICommandData, Event, BotEventData, Plugin } from "src/model/plugin";
@@ -38,8 +37,6 @@ export class ReactCommands {
         }
     })
     async addReaction({ message, contents }: ICommandData): Promise<void> {
-        if (!await isAuthorisedAsync(message.member))
-            return;
         const reactContents = pattern.exec(contents as string);
 
         if (reactContents != null) {
@@ -72,9 +69,6 @@ export class ReactCommands {
         } 
     })
     async removeReaction({message, contents}: ICommandData): Promise<void> {
-        if (!await isAuthorisedAsync(message.member))
-            return;
-
         const content = (contents as string).substring("remove reaction to ".length).trim().toLowerCase();
         const repo = getRepository(MessageReaction);
         const result = await repo.delete({ message: content });