Skip to content

Commit 2f2507b

Browse files
committed
Ignore old messages middleware
1 parent 8d4d6dd commit 2f2507b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

functions/bot.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { createAuthFailedResponse } from "./lib/json-response/create-auth-failed
55
import { onMessage } from "./server-bot/on-message.ts";
66
import { onCallbackQuery } from "./server-bot/on-callback-query.ts";
77
import { onStart } from "./server-bot/on-start.ts";
8+
import { ignoreOldMessageMiddleware } from "./server-bot/ignore-old-messages-middleware.ts";
89

910
export const onRequestPost: PagesFunction = handleError(
1011
async ({ env, request }) => {
@@ -15,6 +16,7 @@ export const onRequestPost: PagesFunction = handleError(
1516
}
1617

1718
const bot = new Bot(envSafe.BOT_TOKEN);
19+
bot.use(ignoreOldMessageMiddleware);
1820
bot.command("start", onStart);
1921
bot.on("message", onMessage(envSafe));
2022
bot.on("callback_query:data", onCallbackQuery(envSafe));
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Context, NextFunction } from "grammy";
2+
3+
const threshold = 5 * 60; // 5 minutes
4+
export async function ignoreOldMessageMiddleware(
5+
ctx: Context,
6+
next: NextFunction
7+
): Promise<void> {
8+
if (ctx.message) {
9+
if (new Date().getTime() / 1000 - ctx.message.date < threshold) {
10+
await next();
11+
} else {
12+
console.log(
13+
`Ignoring message from ${ctx.from?.id ?? 'Unknown ID'} at ${
14+
ctx.chat?.id ?? 'Unknown Chat ID'
15+
} (${new Date().getTime() / 1000}:${ctx.message.date})`
16+
);
17+
}
18+
} else {
19+
await next();
20+
}
21+
}

0 commit comments

Comments
 (0)