|
| 1 | +import type { Message } from "discord.js"; |
| 2 | +import { runQueueCommand, type QueueResult } from "../bot/cli-runner.js"; |
| 3 | +import type { MessageCommandHandler } from "../interfaces/command-handler.js"; |
| 4 | + |
| 5 | +export interface CrawlCommandParseResult { |
| 6 | + isCrawlCommand: boolean; |
| 7 | + seedUrl: string | null; |
| 8 | +} |
| 9 | + |
| 10 | +export interface CrawlCommandHandlerDependencies { |
| 11 | + runQueue?: typeof runQueueCommand; |
| 12 | +} |
| 13 | + |
| 14 | +export class CrawlCommandHandler implements MessageCommandHandler { |
| 15 | + private readonly queue: typeof runQueueCommand; |
| 16 | + |
| 17 | + constructor(dependencies: CrawlCommandHandlerDependencies = {}) { |
| 18 | + this.queue = dependencies.runQueue ?? runQueueCommand; |
| 19 | + } |
| 20 | + |
| 21 | + parse(content: string): CrawlCommandParseResult { |
| 22 | + const isCrawl = /^\s*crawl\s+/i.test(content); |
| 23 | + if (!isCrawl) { |
| 24 | + return { |
| 25 | + isCrawlCommand: false, |
| 26 | + seedUrl: null, |
| 27 | + }; |
| 28 | + } |
| 29 | + |
| 30 | + const match = content.match(/^\s*crawl\s+(https?:\/\/[^\s]+)/i); |
| 31 | + return { |
| 32 | + isCrawlCommand: true, |
| 33 | + seedUrl: match ? match[1] : null, |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + async queueSeed(message: Message, seedUrl: string): Promise<QueueResult> { |
| 38 | + return this.queue(seedUrl, { |
| 39 | + channelId: message.channelId, |
| 40 | + messageId: message.id, |
| 41 | + authorId: message.author.id, |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + async handleMessage(message: Message): Promise<boolean> { |
| 46 | + const parsed = this.parse(message.content); |
| 47 | + if (!parsed.isCrawlCommand) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + if (!parsed.seedUrl) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + await this.queueSeed(message, parsed.seedUrl); |
| 55 | + return true; |
| 56 | + } |
| 57 | +} |
0 commit comments