Telegram bot with Neon Functions, AI Gateway, and Postgres for message storage.
About this template
This template is a minimal Telegram webhook bot on Neon Functions. It verifies Telegram's secret token, sends each text message to a model through Neon AI Gateway, and replies with the answer. It stores the conversation in Postgres and sends the model the last 10 messages of the chat as context.
Create the bot
Open @BotFather, send /newbot, and copy the token.
Generate a webhook secret, which may contain only letters, digits, _, and -:
openssl rand -hex 32
Scaffold and configure
npm i -g neon@latestneon loginneon linkneon functions new telegram-bot
Add both values to .env.local without replacing the Neon values already there:
echo 'TELEGRAM_BOT_TOKEN=<bot token>' >> .env.localecho 'TELEGRAM_WEBHOOK_SECRET=<secret from above>' >> .env.local
Variable
Description
Required
TELEGRAM_BOT_TOKEN
Bot token from @BotFather; used to reply to messages.
Yes
TELEGRAM_WEBHOOK_SECRET
Random secret (letters, digits, _ and -) used to verify that incoming requests are from Telegram.
Yes
Enable AI Gateway on the branch:
neon config add ai-gateway
You can also set aiGateway: true in neon.ts. AI Gateway requires a paid Neon plan with prepaid credits and a project in a supported region. See AI Gateway get started.
neon link writes DATABASE_URL to .env.local. When you open the function URL in a browser or send it a GET request, the function creates the telegram_messages table and its index, then registers the webhook with Telegram so the bot can receive messages. If Telegram rejects the request, for example because the bot token is wrong, the function returns 502 with Telegram's error message. neon deploy prints the function URL.
Deploy
neon deploy --env .env.localneon functions get telegrambot
Try it
Open the bot in Telegram, send /start, then send any text. Follow up with another message to see the bot use the earlier turns.