Nanfeng

Notes on software development, code, and curious ideas

Forwarding Telegram Bot Messages to a Server

After releasing a Telegram Mini App, we wanted to capture feedback that users might send directly to the bot. The bot listens for text messages and forwards them to our server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Bot } from "https://deno.land/x/grammy@v1.25.0/mod.ts";

const TOKEN = '';
const serverUrl = 'https://example.com/api/feedback';
const bot = new Bot(TOKEN);

bot.on('message:text', async (ctx) => {
const payload = {
uid: ctx.message.chat.id,
message: ctx.message.text,
};

try {
const response = await fetch(serverUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log('Server response:', await response.json());
} catch (error) {
console.error('Failed to forward message:', error);
}
});

bot.start();

Authenticate the server endpoint, validate input, rate-limit requests, and avoid logging sensitive message content unnecessarily.

+