Build a
Telegram Bot with
Node.js on Container Apps
Create a Telegram webhook bot with inline buttons that scales to zero when idle, complete with a starter kit ready to deploy
On this page
- What you need
- Webhook vs Long Polling
- Create the bot with BotFather
- Write the starter bot
- Test locally before deploying
- Push to
GitHub and prepare variables
- Deploy on Container Apps
- Step 1: Source
- Step 2: Configuration
- Step 3: Review & deploy
- Register the webhook and test in
Telegram
- Costs and the free quota
- Bonus: add a protected Notify API for server alerts
- Common problems
- Update the bot and redeploy
- Where to go next
- Frequently asked questions
You can build and run your own Telegram bot from a single Node.js file and a short Dockerfile on XVer Container Apps, giving you an automatic HTTPS webhook URL that scales to zero when nobody is chatting. There is no always-on server to maintain and no SSL certificate to renew yourself.
By the end, sending /start opens a 3-button menu, /ping returns the current Bangkok time, /id prints your chat_id, and an optional /api/notify route lets your servers or cron jobs push Telegram alerts with curl.
What you need#
- A working
Telegram bot with buttons handling
/start,/ping,/idand/help - An HTTPS webhook checking a secret token on every request and scaling to zero when idle
- A private Notify API ready to receive alerts from your servers or
n8n workflows
Before you start
You do not need Docker installed on your machine, because XVer can build the image straight from your GitHub repository.
Webhook vs Long Polling#
A Telegram bot can receive updates in two ways: Webhook (Telegram sends an HTTPS POST to your URL whenever a message arrives) or Long Polling (your process keeps calling getUpdates in a loop).
- A user sends a command or taps a button, such as
/startinTelegram
Telegram sends an HTTPS POST with
X-Telegram-Bot-Api-Secret-Tokento/webhook- Container Apps wakes an instance if it has scaled to 0
- The bot checks the secret token and replies 200 right away
- The bot calls the Bot API to send the message or answer the button tap
On Request-based Container Apps, Webhook is the right fit because instances run only while handling requests and scale back to 0 when quiet. Long Polling needs an always-on connection, which fits Min replicas 1 or a Cloud Server better.
Min replicas 0Recommended
No requests means no running instances and no vCPU or memory charge. The first message after a quiet period waits briefly for an instance to start (cold start). Suits personal bots, team alert bots and shop bots with bursty traffic.
Min replicas 1 or more
An instance stays warm all the time, avoiding cold starts from scaling to 0. You pay for vCPU and memory every second it runs. Suits bots that must answer every message immediately around the clock.
Create the bot with BotFather#
Telegram handles bot creation inside chat through @BotFather, its official bot.
- Open a chat with
@BotFather. Search for@BotFatherinTelegram and verify the blue checkmark.
- Create a new bot. Send
/newbot, enter a display name, then pick a username ending inbot, such asmy_shop_helper_bot. - Save the Bot Token. BotFather replies with an HTTP API token formatted like
123456789:AAH.... Copy it somewhere safe. - Register the command menu (recommended). Send
/setcommands, choose your bot, and paste the list below so users get autocomplete and a menu button in chat.
start - Open the main menu with buttons
ping - Check bot latency and Bangkok time
id - Show the Chat ID of this chat
help - List all available commandsWrite the starter bot#
You can download the complete starter kit (.zip) and unzip it right away, or create a folder named telegram-bot with the four files below.
- telegram-bot/
- server.js
- package.json
- Dockerfile
- test.mjs
The starter uses only built-in Node.js 24 modules (node:http, node:crypto and fetch), so there is no npm install step, keeping the container image small and cold starts fast.
import { timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
const port = Number(process.env.PORT) || 8080;
const token = process.env.TELEGRAM_BOT_TOKEN;
const secret = process.env.TELEGRAM_WEBHOOK_SECRET;
if (!token || !secret) {
console.error('missing TELEGRAM_BOT_TOKEN or TELEGRAM_WEBHOOK_SECRET');
process.exit(1);
}
function safeEqual(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
return bufA.length === bufB.length && timingSafeEqual(bufA, bufB);
}
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 1024 * 1024) throw new Error('body too large');
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function tg(method, payload) {
const res = await fetch(`https://api.telegram.org/bot${token}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10_000),
});
console.log(method, 'status', res.status);
if (!res.ok) console.error(await res.text());
return res.ok;
}
function bangkokTime() {
return new Intl.DateTimeFormat('en-GB', {
timeZone: 'Asia/Bangkok',
dateStyle: 'medium',
timeStyle: 'medium',
}).format(new Date());
}
// Edit the commands and inline buttons here
const menuKeyboard = {
inline_keyboard: [
[
{ text: 'Opening hours', callback_data: 'hours' },
{ text: 'Show Chat ID', callback_data: 'chatid' },
],
[{ text: 'Bot status', callback_data: 'status' }],
],
};
function buildReply(text, chat, from) {
const cmd = text.trim().split(/\s+/)[0].toLowerCase().replace(/@[\w]+$/, '');
const name = from?.first_name || 'there';
if (cmd === '/start') {
return {
text: `Hello ${name}. Pick an option below or send /help to see all commands.`,
reply_markup: menuKeyboard,
};
}
if (cmd === '/help') {
return {
text: [
'Available commands:',
'/start - Open the main menu',
'/ping - Check latency and Bangkok time',
'/id - Show your Chat ID and username',
'/help - Show this list',
].join('\n'),
};
}
if (cmd === '/ping') {
return { text: `pong (${bangkokTime()} Asia/Bangkok)` };
}
if (cmd === '/id') {
const user = from?.username ? `@${from.username}` : 'none';
return { text: `Chat ID: ${chat.id}\nType: ${chat.type}\nUsername: ${user}` };
}
return { text: `You wrote: ${text.slice(0, 500)}\n\nSend /help to see available commands.` };
}
async function handleCallback(query) {
// Acknowledge the button tap immediately so Telegram clears the loading spinner
await tg('answerCallbackQuery', { callback_query_id: query.id });
const chatId = query.message?.chat?.id;
if (!chatId) return;
if (query.data === 'hours') {
await tg('sendMessage', { chat_id: chatId, text: 'Open every day, 10:00 to 20:00 (Asia/Bangkok).' });
} else if (query.data === 'chatid') {
const user = query.from?.username ? `@${query.from.username}` : 'none';
await tg('sendMessage', { chat_id: chatId, text: `Chat ID: ${chatId}\nUsername: ${user}` });
} else if (query.data === 'status') {
const up = Math.floor(process.uptime());
await tg('sendMessage', { chat_id: chatId, text: `Bot online\nTime: ${bangkokTime()} Asia/Bangkok\nUptime: ${up}s` });
}
}
async function handleUpdate(update) {
if (update.callback_query) return handleCallback(update.callback_query);
if (update.message?.text && update.message.chat?.id) {
const reply = buildReply(update.message.text, update.message.chat, update.message.from);
await tg('sendMessage', { chat_id: update.message.chat.id, ...reply });
}
}
function send(res, status, data) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
}
const pending = new Set();
const server = createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && pathname === '/') return send(res, 200, { ok: true });
if (req.method !== 'POST' || pathname !== '/webhook') return send(res, 404, { error: 'not found' });
if (!safeEqual(req.headers['x-telegram-bot-api-secret-token'], secret)) {
console.warn('rejected: bad secret token');
return send(res, 401, { error: 'unauthorized' });
}
const rawBody = await readBody(req);
const update = JSON.parse(rawBody.toString('utf8'));
console.log('accepted update', update.update_id ?? 'unknown');
send(res, 200, { ok: true }); // Acknowledge first, process asynchronously
const job = handleUpdate(update).catch(console.error).finally(() => pending.delete(job));
pending.add(job);
} catch (err) {
console.error(err.message);
if (!res.headersSent) send(res, 400, { error: 'bad request' });
}
});
server.listen(port, '0.0.0.0', () => console.log(`listening on ${port}`));
// Wait for in-flight Telegram replies to finish before exiting on SIGTERM
process.on('SIGTERM', () => {
server.close(async () => {
await Promise.allSettled(pending);
process.exit(0);
});
});Three design choices in this file matter most.
Check the Secret Token with timingSafeEqual
When you register a secret_token, Telegram includes X-Telegram-Bot-Api-Secret-Token on every webhook request. Comparing with timingSafeEqual runs in constant time so callers cannot guess the secret from timing differences.
Return 200 first, process asynchronously
Responding 200 immediately prevents Telegram from retrying the same update while your bot talks back to the Bot API. The SIGTERM handler drains pending jobs before the container stops.
Call answerCallbackQuery on button taps
If you skip answerCallbackQuery, Telegram leaves a loading spinner on the inline button for several seconds. Calling it first keeps button presses snappy.
Next, add package.json and Dockerfile in the same folder.
{
"name": "telegram-bot",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "node server.js",
"test": "node test.mjs"
},
"engines": {
"node": ">=24"
}
}FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package.json server.js ./
USER node
EXPOSE 8080
CMD ["node", "server.js"]The server listens on PORT, defaulting to 8080, which matches the default Container port on XVer, and runs as the non-root node user.
Test locally before deploying#
Create test.mjs to start server.js with a random secret token and verify the health route, valid token, wrong token, missing token and malformed JSON without needing a real Bot Token. It works on Windows,
macOS and
Linux.
import { spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
const secret = randomBytes(16).toString('hex');
const port = '8090';
const base = `http://127.0.0.1:${port}`;
const app = spawn(process.execPath, ['server.js'], {
env: {
...process.env,
PORT: port,
TELEGRAM_BOT_TOKEN: '000000:local-test',
TELEGRAM_WEBHOOK_SECRET: secret,
},
stdio: ['ignore', 'pipe', 'inherit'],
});
await new Promise((resolve, reject) => {
app.stdout.once('data', resolve);
app.once('exit', () => reject(new Error('server.js stopped')));
});
let failed = 0;
async function check(name, want, path, opts = {}) {
const res = await fetch(base + path, opts);
const ok = res.status === want;
if (!ok) failed += 1;
console.log(ok ? 'PASS' : 'FAIL', res.status, name);
}
const body = JSON.stringify({ update_id: 1 });
try {
await check('health check', 200, '/');
await check('valid secret token', 200, '/webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-telegram-bot-api-secret-token': secret },
body,
});
await check('wrong secret token', 401, '/webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-telegram-bot-api-secret-token': 'wrong' },
body,
});
await check('missing secret token', 401, '/webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
await check('invalid JSON', 400, '/webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-telegram-bot-api-secret-token': secret },
body: '{bad-json',
});
} finally {
app.kill();
}
if (failed > 0) process.exit(1);Run the test inside the telegram-bot folder.
node test.mjsLines showing rejected: bad secret token and a JSON parse error appear in between, confirming that invalid requests are blocked.
PASS 200 health check
PASS 200 valid secret token
PASS 401 wrong secret token
PASS 401 missing secret token
PASS 400 invalid JSONPush to
GitHub and prepare variables#
Create an empty GitHub repository named telegram-bot (private is fine), then generate a random WEBHOOK_SECRET. Telegram allows 1 to 256 characters using A-Z, a-z, 0-9, _ and -.
node -e "console.log(require('node:crypto').randomBytes(24).toString('hex'))"Fill in the fields below so every command on this page updates automatically. Come back for SERVICE_URL after deployment completes.
Type your own values and the commands on this page follow
Push the four files to GitHub.
git init -b main
git add server.js package.json Dockerfile test.mjs
git commit -m "Telegram bot starter"
git remote add origin https://github.com/GITHUB_USER/telegram-bot.git
git push -u origin mainDeploy on Container Apps#
Sign in at my.xver.cloud and open Container Apps. If this is your first time, click Activate Container Apps, then click Deployment. The wizard has three steps: Source, Configuration and Review & deploy.


Step 1: Source#
Enter a Service name such as my-telegram-bot and choose Request-based as the Pricing model so the container can scale to 0. The pricing model cannot be changed later; changing it requires creating a new container.


GitHub repository
- Choose
GitHub repository and click Connect GitHub to grant the GitHub App access to
telegram-bot. - Pick the Owner and Repository, and set Branch to
main. - Keep Dockerfile path as
Dockerfile, then click Preview Dockerfile to confirm it can be read.
This option is available when you own the project in XVer.
Container image
If you prefer to build and push your own image to Docker Hub or GHCR, choose Container image and enter the image name and Image tag. Add a Registry credential first for private images.
Always target --platform linux/amd64, especially on an Apple Silicon Mac, and run docker login ghcr.io beforehand. The username in the image path must be lowercase.
docker build --platform linux/amd64 -t ghcr.io/GITHUB_USER/telegram-bot:1.0.0 .
docker push ghcr.io/GITHUB_USER/telegram-bot:1.0.0When the push finishes, the final line prints digest: sha256:....
To keep the image in Thailand with XVer instead, see how to push to Artifact Registry and run it on Container Apps.
Step 2: Configuration#
Size the container modestly for Node.js and keep Min replicas at 0.


| Field | Value | Note |
|---|---|---|
| Container port | 8080 | Matches server.js default |
| CPU (m) | 250 | Equals 0.25 vCPU. Change from the 1000 default |
| Memory (MB) | 512 | 0.5 GiB, plenty for |
| Request timeout (s) | 30 | The bot replies 200 immediately |
| Request concurrency | 50 | Default works well |
| Min replicas | 0 | Enables scale-to-zero |
| Max replicas | 1 | Keeps costs predictable while starting out |
Scroll to Environment variables, click Add variable twice, and enter the two required keys.


| NAME | value |
|---|---|
TELEGRAM_BOT_TOKEN |
Paste the Bot Token from @BotFather |
TELEGRAM_WEBHOOK_SECRET |
Paste the random secret you generated (must match setWebhook) |
Do not add PORT, and make sure there are no quotes or extra spaces around your values.
Step 3: Review & deploy#
Check CPU, Memory and Replicas in the summary, accept the terms, and click Deploy container. Watch build progress on the Builds tab until the status turns ready.
Open the Overview tab and copy the Default URL. It already has HTTPS enabled (ending in .apps.xver.dev on production containers). Paste the hostname into the SERVICE_URL field above.


Verify the health endpoint and confirm /webhook rejects a bad token before registering with Telegram.
curl -i https://SERVICE_URL/
curl -i -X POST https://SERVICE_URL/webhook \
-H 'Content-Type: application/json' \
-H 'x-telegram-bot-api-secret-token: wrong' \
-d '{"update_id":1}'Register the webhook and test in
Telegram#
Call Telegram's setWebhook method to point updates at https://SERVICE_URL/webhook with your secret_token.
curl -s -X POST "https://api.telegram.org/botBOT_TOKEN/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url":"https://SERVICE_URL/webhook","secret_token":"WEBHOOK_SECRET"}'Confirm the active configuration with getWebhookInfo, which is also the quickest diagnostic tool if the bot ever stops replying.
curl -s "https://api.telegram.org/botBOT_TOKEN/getWebhookInfo"Check that url matches your service, pending_update_count is 0, and last_error_message is absent. Then open your bot in Telegram and test it.
- Send
/startand tap Opening hours, Show Chat ID and Bot status. - Send
/pingto seepongwith the currentAsia/Bangkoktimestamp. - Send
/idto record yourChat IDfor notifications.
Costs and the free quota#
Each container includes a monthly free quota of 180,000 vCPU-seconds, 360,000 GiB-seconds and 1,000,000 HTTP requests, reset on the 1st of every month.
Example workload: one instance at 0.25 vCPU and 0.5 GiB running 150 hours a month and handling 300,000 requests.
| Item | Calculation | Used | Free quota |
|---|---|---|---|
| vCPU | 0.25 × 150 × 3,600 | 135,000 vCPU-seconds | 180,000 |
| Memory | 0.5 × 150 × 3,600 | 270,000 GiB-seconds | 360,000 |
| Requests | Counted as received | 300,000 | 1,000,000 |
At this size, vCPU, memory and requests total ฿0 after the free quota. Find the free ceiling by dividing the vCPU-second quota by 0.25 ÷ 3,600 and the GiB-second quota by 0.5 ÷ 3,600, then taking the smaller number.
| Case | Effect on cost |
|---|---|
| Two instances running together for one hour | Counts as two instance-hours |
| Idle warm time before scaling down to 0 | May be counted too, so bots messaged steadily all day consume more hours than pure request execution time |
| Exceeding the free quota | You pay only for the excess of each metric, deducted from account credit |
| Min replicas 1 for 30 days (720 hours) | Uses 648,000 vCPU-seconds and 1,296,000 GiB-seconds, totaling ฿74.88 |
| Block Storage and outbound network traffic | Excluded from this table; volumes have no free quota |
Track live usage on the Free quota and Cost cards on the container page and keep your credit topped up. A container is removed if credit runs out and the 24-hour grace period expires.
Bonus: add a protected Notify API for server alerts#
The same container can accept HTTP alerts from backup scripts, cron jobs or n8n workflows and forward them straight to your Telegram chat or group.
- Add an environment variable named
NOTIFY_API_KEY(at least 24 random characters) on the container's Settings tab. - Read
const notifyKey = process.env.NOTIFY_API_KEY;near the top ofserver.jsand insert this route right before the/webhookcheck.
if (req.method === 'POST' && pathname === '/api/notify') {
if (!notifyKey || !safeEqual(req.headers['x-notify-key'], notifyKey)) {
return send(res, 401, { error: 'unauthorized' });
}
const { chat_id, text } = JSON.parse((await readBody(req)).toString('utf8'));
if (!chat_id || typeof text !== 'string' || !text.trim()) {
return send(res, 400, { error: 'missing chat_id or text' });
}
const ok = await tg('sendMessage', { chat_id, text: text.slice(0, 4000) });
return send(res, ok ? 200 : 502, { ok });
}Push to GitHub, click Rebuild, and send a test alert using the chat_id you retrieved with /id.
curl -X POST "https://SERVICE_URL/api/notify" \
-H "Content-Type: application/json" \
-H "x-notify-key: YOUR_NOTIFY_API_KEY" \
-d '{"chat_id":123456789,"text":"Nightly database backup completed"}'Common problems#
The Logs tab streams output only while an instance is running. Send one message to your bot to wake it, then click Start.
Build and deploy issues on XVer
IssueBuild failed
Usually a missing Dockerfile or wrong branch name. Check the Builds tab logs and verify the Branch and Dockerfile path.
IssueDeploy failed with missing TELEGRAM_...
One or both environment variables are missing. Open the Settings tab, add TELEGRAM_BOT_TOKEN and TELEGRAM_WEBHOOK_SECRET, and click Save changes.
IssueDeploy failed even though the server started
Port mismatch. Make sure Container port is set to 8080.
Issueexec format error in logs
The container image was not built for linux/amd64. Rebuild and push with --platform linux/amd64.
Webhook and Telegram reply issues
IssuesetWebhook says wrong secret token
secret_token must be 1 to 256 characters using only A-Z, a-z, 0-9, _ and -, with no spaces or other symbols.
IssuegetWebhookInfo shows last_error_message: Wrong response from the webhook: 401
The WEBHOOK_SECRET sent to setWebhook does not match TELEGRAM_WEBHOOK_SECRET in Container Apps. Double-check both values and run setWebhook again.
IssuegetWebhookInfo shows 404 Not Found
/webhook is missing from the end of the URL passed to setWebhook.
IssueWebhook returns 200 but the bot stays silent
Check the Logs tab. sendMessage status 401 means TELEGRAM_BOT_TOKEN is wrong or revoked; 400 prints the exact Telegram error details on the next line.
IssueInline button keeps spinning after tap
answerCallbackQuery was skipped or failed before running. Check the container logs while tapping the button.
Update the bot and redeploy#
Whenever you edit buildReply or menuKeyboard, run the local test, push to GitHub, and click Rebuild on the container page.
node test.mjs
git commit -am "Add new command"
git pushThe new version must pass the GET / health check before traffic shifts over.
Where to go next#
Extend your Telegram bot
- Store customer or order records
Connect to a database on a VPS; read how to choose a VPS size and secure an
Ubuntu server while keeping scale-to-zero on the bot.
- Connect no-code automations
Pair the bot with
n8n on a VPS to integrate Google Sheets, email or AI models.
- Store files on the container
Attach storage on the Volumes tab (note: this pins the container to 1 instance, disables scale-to-zero, and bills volume storage continuously).
- Use your own domain
Add it on the Domains tab, configure DNS as shown, then call
setWebhookwith the new URL.- Build a
LINE bot with the same pattern
Unsure whether a workload belongs on Container Apps or a VM? Compare Container Apps and daily and hourly Cloud Servers.
Frequently asked questions#
Can I really run a
Telegram bot for free on Container Apps?
Yes, as long as your vCPU-seconds, GiB-seconds and HTTP requests stay within each container's monthly free quota. The example of 0.25 vCPU, 0.5 GiB, 150 hours and 300,000 requests fits inside it, and Telegram itself charges nothing per message.
Why use a webhook instead of Long Polling on Container Apps?
Request-based containers wake only when an HTTP request arrives and scale back to 0 when idle. Long Polling holds an open connection continuously and does not fit scale-to-zero.
Is setting secret_token in setWebhook really necessary?
Yes. Your /webhook endpoint is reachable on the public internet. Setting secret_token lets your server verify the X-Telegram-Bot-Api-Secret-Token header and reject forged requests immediately.
Can I write the bot in
Python or Go instead of
Node.js?
Yes. Container Apps runs any language packaged as a linux/amd64 Docker image that serves HTTP on your configured Container port.
Why does my bot ignore regular messages inside a
Telegram group?
Telegram enables Group Privacy by default, so bots in groups only see slash commands and direct mentions. To let the bot read all group messages, send /setprivacy to @BotFather and choose Disable.
Start by customizing the three inline buttons in menuKeyboard for your team or shop, then add one new command at a time as real requests come in.