Skip to content

Commit

Permalink
Ignore old messages middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
kubk committed Dec 19, 2023
1 parent 8d4d6dd commit 2f2507b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions functions/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { createAuthFailedResponse } from "./lib/json-response/create-auth-failed
import { onMessage } from "./server-bot/on-message.ts";
import { onCallbackQuery } from "./server-bot/on-callback-query.ts";
import { onStart } from "./server-bot/on-start.ts";
import { ignoreOldMessageMiddleware } from "./server-bot/ignore-old-messages-middleware.ts";

export const onRequestPost: PagesFunction = handleError(
async ({ env, request }) => {
Expand All @@ -15,6 +16,7 @@ export const onRequestPost: PagesFunction = handleError(
}

const bot = new Bot(envSafe.BOT_TOKEN);
bot.use(ignoreOldMessageMiddleware);
bot.command("start", onStart);
bot.on("message", onMessage(envSafe));
bot.on("callback_query:data", onCallbackQuery(envSafe));
Expand Down
21 changes: 21 additions & 0 deletions functions/server-bot/ignore-old-messages-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Context, NextFunction } from "grammy";

const threshold = 5 * 60; // 5 minutes
export async function ignoreOldMessageMiddleware(
ctx: Context,
next: NextFunction
): Promise<void> {
if (ctx.message) {
if (new Date().getTime() / 1000 - ctx.message.date < threshold) {
await next();
} else {
console.log(
`Ignoring message from ${ctx.from?.id ?? 'Unknown ID'} at ${
ctx.chat?.id ?? 'Unknown Chat ID'
} (${new Date().getTime() / 1000}:${ctx.message.date})`
);
}
} else {
await next();
}
}

0 comments on commit 2f2507b

Please sign in to comment.