diff --git a/src/handlers/balabola.ts b/src/handlers/balabola.ts index df0f529..385a584 100644 --- a/src/handlers/balabola.ts +++ b/src/handlers/balabola.ts @@ -38,8 +38,23 @@ const balabolaMessage = `Выбери стилизацию ответа: const BALABOLA_INTROS = [0, 24, 25, 11, 6, 8, 9]; -filter.hear(/^(?:продолжи)\s(.*)?$/i, async ctx => { - if (ctx.isChat) return; +const spammers = new Map(); + +filter.use((ctx, next) => { + if (spammers.has(ctx.senderId) && spammers.get(ctx.senderId)! > Date.now()) { + return ctx.reply('отказ', { disable_mentions: true }); + } + + spammers.set(ctx.senderId, Date.now() + 5000); + return next(); +}); + +filter.hear(/^(?:продолжи)\s(.*)?$/i, async (ctx, next) => { + if (ctx.isChat) { + ctx.text = `пр 1 ${ctx.$match[1]}`; + return next(); + } + await ctx.send(balabolaMessage, { keyboard: selectStyleKeyboard(ctx) }); @@ -56,6 +71,7 @@ filter.hear(/^(?:пр)\s(1|2|3|4|5|6|7)\s(.*)?$/i, async ctx => { filter.use(async ctx => { if (ctx.isChat) return; + await ctx.send('генерирую!!'); const result = await throttledBalabola(() => balabola(ctx.text!, 0)); await ctx.send(result); diff --git a/src/utilities/throttledQueue.ts b/src/utilities/throttledQueue.ts index 11a0365..162f2b2 100644 --- a/src/utilities/throttledQueue.ts +++ b/src/utilities/throttledQueue.ts @@ -7,24 +7,30 @@ export function throttledQueue( interval = interval / maxRequestsPerInterval; maxRequestsPerInterval = 1; } + const queue: Array<() => Promise> = []; let lastIntervalStart = 0; let numRequestsPerInterval = 0; let timeout: NodeJS.Timeout | undefined; + const dequeue = () => { const intervalEnd = lastIntervalStart + interval; const now = Date.now(); + if (now < intervalEnd) { timeout !== undefined && clearTimeout(timeout); timeout = setTimeout(dequeue, intervalEnd - now); return; } + lastIntervalStart = now; numRequestsPerInterval = 0; + for (const callback of queue.splice(0, maxRequestsPerInterval)) { numRequestsPerInterval++; void callback(); } + if (queue.length) { timeout = setTimeout(dequeue, interval); } else { @@ -35,11 +41,14 @@ export function throttledQueue( return (fn: () => Promise | Return): Promise => new Promise( (resolve, reject) => { const callback = () => Promise.resolve().then(fn).then(resolve).catch(reject); + const now = Date.now(); + if (timeout === undefined && (now - lastIntervalStart) > interval) { lastIntervalStart = now; numRequestsPerInterval = 0; } + if (numRequestsPerInterval++ < maxRequestsPerInterval) { void callback(); } else {