A Telegram bot gets its messages in one of two ways: it asks Telegram for new updates in a loop, called long polling, or Telegram posts each update to an HTTPS URL, called a webhook. Hosting the bot means keeping one of those running, and the choice decides how the service looks. On Modelence a polling bot is a worker with no port that never runs twice, and a webhook bot is a web service with a health route and the environment's HTTPS URL. Both are a few lines in modelence.config.json, run as containers on AWS in the region you pick out of 17 and can use managed Redis, PostgreSQL or MongoDB for their data.
This guide uses grammY, which has about ten times the npm downloads of Telegraf, the next library, and gets regular releases. The example is a to-do bot with /add, /list and /done, whose lists live in Redis. You'll run it with polling, add a webhook entry point next to it and deploy whichever fits. If your bot already runs on your machine, Choose long polling or a webhook and the config sections are the parts to read.
Telegram bot on Modelence at a glance
- Library
- grammY 1.48, the most downloaded Telegram bot library on npm, written in TypeScript
- Long polling
- node polling.js as a worker with no health check and recreate rollouts, so only one copy asks for updates
- Webhook
- node webhook.js as a web service, with an HTTP health check on /health and the environment's HTTPS URL
- Webhook security
- Telegram sends a secret token in a header on every request, and grammY rejects requests without it
- Sessions
- Per-chat data in managed Redis through grammY's storage adapter, with PostgreSQL and MongoDB adapters too
- Missed updates
- Telegram keeps updates for up to 24 hours, so a bot picks up messages sent while a deploy was running
Before you start
- Node.js 18 or newer and npm
- A Telegram account, to create bots with @BotFather
- A Modelence account, which you can create for free
Create the bot
Open a chat with @BotFather in Telegram, send /newbot and choose a name and a username ending in bot. BotFather replies with a token such as 123456789:AA..., which the code reads from TELEGRAM_BOT_TOKEN. Create a second bot the same way for testing. Running your laptop against the production token would take updates away from the deployed bot, and starting polling also removes a production webhook.
Then create the project and install grammY:
mkdir todo-bot && cd todo-bot
npm init -y
npm pkg set type=module
npm install grammy
bot.js holds everything the bot does and nothing about how updates arrive, so the polling and webhook entry points below share it. ctx.match is the text after the command, the session middleware gives each chat its own ctx.session object, and bot.catch logs an update that fails while the bot carries on with the next one. Sessions stay in memory for now, and Add a database moves them to Redis.
import { Bot, session } from 'grammy';
export const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN);
// One task list per chat, kept in memory until the next section moves it to Redis.
bot.use(session({ initial: () => ({ tasks: [] }) }));
bot.command('start', (ctx) =>
ctx.reply('Add a task with /add, see them with /list and finish one with /done and its number.'),
);
bot.command('add', async (ctx) => {
const task = ctx.match.trim();
if (!task) return ctx.reply('Write the task after the command, like /add renew the domain');
ctx.session.tasks.push(task);
await ctx.reply(`Added. ${ctx.session.tasks.length} on the list.`);
});
bot.command('list', (ctx) => {
const { tasks } = ctx.session;
return ctx.reply(tasks.length ? tasks.map((task, i) => `${i + 1}. ${task}`).join('\n') : 'Nothing to do.');
});
bot.command('done', async (ctx) => {
const index = Number(ctx.match) - 1;
if (!Number.isInteger(index) || index < 0 || index >= ctx.session.tasks.length) {
return ctx.reply('Send /done with a task number from /list.');
}
const [task] = ctx.session.tasks.splice(index, 1);
await ctx.reply(`Done: ${task}`);
});
// Logs a failed update instead of stopping the bot.
bot.catch((error) => {
console.error(`Update ${error.ctx.update.update_id} failed`, error.error);
});Receive updates with long polling
polling.js starts the loop that asks Telegram for updates. bot.start() first removes any webhook set for the bot, since Telegram allows only one of the two, and then keeps a getUpdates request open until something arrives. On SIGTERM, bot.stop() lets the current batch finish and the loop ends.
Add scripts for it to package.json:
"scripts": {
"start": "node polling.js",
"dev": "node --watch polling.js"
}
Then run the test bot and send it /start in Telegram:
TELEGRAM_BOT_TOKEN=<test bot token> npm run dev
The terminal prints @<username> is polling for updates. A wrong token stops it with GrammyError: Call to 'getMe' failed! (401: Unauthorized).
import { bot } from './bot.js';
// On SIGTERM, finish the current batch of updates and stop asking Telegram for more.
process.once('SIGTERM', () => bot.stop());
await bot.start({
onStart: (me) => console.log(`@${me.username} is polling for updates`),
});
process.exit(0);Receive updates with a webhook
webhook.js is the other entry point: an Express server that Telegram posts updates to. Install Express with npm install express, then add the file. When it starts, it:
- calls
bot.init(), which checks the token withgetMe, so a bad token stops the process before it passes a health check, - answers
/healthfor the platform's health check, - hands
POST /telegramto grammY'swebhookCallback, which answers 401 to any request whoseX-Telegram-Bot-Api-Secret-Tokenheader doesn't matchTELEGRAM_WEBHOOK_SECRET, - registers its own address with
setWebhook, built fromSITE_URL, the environment's public URL that Modelence provides, together with the secret.
Locally there's no SITE_URL, so the server skips the registration and you can try the route by posting a JSON update to it with the secret header.
import express from 'express';
import { webhookCallback } from 'grammy';
import { bot } from './bot.js';
const secretToken = process.env.TELEGRAM_WEBHOOK_SECRET;
// Calls getMe, so a wrong token stops the process before it takes traffic.
await bot.init();
const app = express();
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.post('/telegram', express.json(), webhookCallback(bot, 'express', { secretToken }));
// SITE_URL is the environment's public URL, which Modelence provides.
if (process.env.SITE_URL) {
await bot.api.setWebhook(new URL('/telegram', process.env.SITE_URL).href, { secret_token: secretToken });
}
const port = Number(process.env.PORT) || 3000;
app.listen(port, '0.0.0.0', (error) => {
if (error) {
throw error;
}
console.log(`@${bot.botInfo.username} is listening for updates on port ${port}`);
});Choose long polling or a webhook
grammY's docs suggest long polling unless you have a reason to use a webhook, and on a host that keeps the process running, polling is the simpler setup. A webhook pays off when you'd rather have Telegram push updates to a URL, for example to serve the bot next to a web app or spread updates across several containers.
| Long polling | Webhook | |
|---|---|---|
| How updates arrive | The bot asks Telegram in a loop | Telegram posts each update over HTTPS |
| Service on Modelence | Worker: no health check, recreate rollout | Web service: health check on /health |
| Public URL | Not needed, and can be detached | The environment's URL or your own domain |
| Copies | Exactly one | One or more behind the load balancer |
The bot code is the same either way, since only the entry point changes. Deploy with polling first, and move to the webhook later by switching the start command and config.
Add a database
- MongoDB
MONGODB_URI - Postgres
DATABASE_URL - Redis
REDIS_URL
Sessions in memory vanish when the container is replaced, and with a webhook spread over two containers, each would keep its own copy. grammY's storage adapters keep sessions in a database instead, and its session middleware loads and saves ctx.session for each update without other changes to the commands. Modelence creates managed Redis, PostgreSQL and MongoDB in the bot's region and passes their connection strings as variables.
Redis fits session data well. Install the adapter and a client:
npm install @grammyjs/storage-redis ioredis
Then pass the adapter to session in bot.js. REDIS_URL comes from the cache resource in the config below. For PostgreSQL or MongoDB, the @grammyjs/storage-psql and @grammyjs/storage-mongodb adapters plug into the same storage option.
import { RedisAdapter } from '@grammyjs/storage-redis';
import { Bot, session } from 'grammy';
import IORedis from 'ioredis';
export const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN);
const redis = new IORedis(process.env.REDIS_URL);
// One task list per chat, stored in Redis so every container and every deploy sees it.
bot.use(
session({
initial: () => ({ tasks: [] }),
storage: new RedisAdapter({ instance: redis }),
}),
);
// The commands and bot.catch stay as they were.Describe the polling bot in modelence.config.json
For long polling, the bot is one service that runs node polling.js. "healthCheck": { "type": "none" } tells Modelence the bot listens on no port, and "rollout": "recreate" stops the old container before the new one starts, so two loops never ask Telegram for updates together. Updates sent during that short gap wait on Telegram's side and arrive once the new container starts polling. The file also creates the Redis cache and declares the token as a secret:
{
"$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
"resources": {
"bot": {
"type": "service",
"image": "node-22-slim",
"build": { "commands": ["npm ci"] },
"start": { "commands": ["node polling.js"] },
"healthCheck": { "type": "none" },
"rollout": "recreate"
},
"cache": { "type": "redis" }
},
"env": {
"TELEGRAM_BOT_TOKEN": { "type": "secret" },
"REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
}
}Or describe the webhook bot
For a webhook, start node webhook.js and check /health over HTTP instead. The default rollout, which starts new containers before stopping old ones, works here, since Telegram posts each update to one URL and any container can answer it. Generate the webhook secret with openssl rand -hex 32 and paste it when the deploy asks for TELEGRAM_WEBHOOK_SECRET.
{
"$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
"resources": {
"bot": {
"type": "service",
"image": "node-22-slim",
"build": { "commands": ["npm ci"] },
"start": { "commands": ["node webhook.js"] },
"healthCheck": { "type": "http", "path": "/health" }
},
"cache": { "type": "redis" }
},
"env": {
"TELEGRAM_BOT_TOKEN": { "type": "secret" },
"TELEGRAM_WEBHOOK_SECRET": { "type": "secret" },
"REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
}
}Adjust the config for your project
- With TypeScript, add
npm run buildafternpm ciin the build commands and start the compiled entry point, such asnode dist/polling.js. - Without Redis, remove
cacheandREDIS_URL. For PostgreSQL, add"main-db": { "type": "postgres" }and aDATABASE_URLvariable with"resource": "main-db". - A bot written with python-telegram-bot, aiogram or another language's library runs from its own Dockerfile: set
"dockerfile": "Dockerfile"on the service. A polling bot keeps the health check at none and the rollout at recreate, and a webhook bot adds"ports"with the port it listens on. See Dockerfile services. - Several bots can live in one app, each as its own service with its own token variable.
Check the build locally
Run the build and start commands with the test bot and a local Redis. @<username> is polling for updates means the token works and Redis is reachable, and /add followed by a restart and /list shows the task survived:
npm ci
TELEGRAM_BOT_TOKEN=<test bot token> REDIS_URL=redis://localhost:6379 node polling.jsDeploy
Deploy from the project directory:
npx modelence@latest deploy
You sign in through the browser and choose or create the organization, app and environment, then paste the production bot's token for TELEGRAM_BOT_TOKEN. On an environment's first deploy you also pick the AWS region for the bot and its Redis. The command uploads the project and streams the build until the bot runs, and the environment's Logs page shows the startup line.
A polling bot needs no address, so detach the environment's URL under Domains in the dashboard. A webhook bot keeps it and registers https://<app>-<environment>.cloud.modelence.app/telegram with Telegram on startup. To confirm, open https://api.telegram.org/bot<token>/getWebhookInfo, which shows the URL, the number of pending updates and the last delivery error, if any. Use the sandbox environment with the test bot's token to try changes before they reach production.
Deploy from your coding agent
In Claude Code, Cursor or Codex, paste Deploy using https://modelence.com/skill.md in the bot's project. The agent reads which entry point you use, writes the matching config, checks the build and deploys, stopping when it needs you to sign in or paste a token.
Production readiness
Poll from one place only
Telegram lets one getUpdates request run per bot at a time. When a second poller starts with the same token, one of them fails with 409 Conflict: terminated by other getUpdates request, and updates go to whichever asked last. Keep a polling bot at one container with the recreate rollout, run local work against the test bot, and stop any old host before deploying.
Check the webhook secret
Anyone who learns the webhook URL could post fake updates to it. The secretToken option of webhookCallback compares Telegram's header with TELEGRAM_WEBHOOK_SECRET and answers 401 when it differs, so keep the secret set in every environment, and change it by updating the variable and redeploying, since the bot sends it to Telegram again with setWebhook on startup.
Answer webhooks within ten seconds
grammY's webhook handler waits up to 10 seconds for the bot to handle an update and then throws, and Telegram sends an update again when it doesn't get a successful answer, so a slow handler can run twice. Reply to the user first and do slow work, such as calling an AI model or generating a file, after the reply or in a separate worker service. A polling bot has no such deadline, which is one more reason to start with polling.
Handle busy bots
A polling bot handles updates one after another by default. For a bot in busy groups, @grammyjs/runner processes updates in parallel, and its sequentialize middleware keeps updates from one chat in order. Webhooks spread load across containers, and Telegram opens up to 40 connections at once by default, a number setWebhook accepts as max_connections.
Watch the logs
The Logs page shows the startup line after every deploy and each failure that bot.catch writes with its update ID. For a webhook bot, the last_error_message field in getWebhookInfo is the other place to look when messages stop arriving. Traces and metrics come from a telemetry resource with OpenTelemetry, set up as in Deploy setup.
Modelence vs Railway, Render and Cloudflare Workers for Telegram bots
People hosting a Telegram bot most often weigh Railway, Render and Cloudflare Workers, which grammY's own docs cover with a guide. Each supports one or both ways of receiving updates. The details below are from each platform's own pricing pages and docs, read in November 2026.
| Platform | Polling | Webhook | Pricing |
|---|---|---|---|
| Modelence | Worker service with recreate rollouts | Web service with a health check and HTTPS URL | Free plan, then from $20 a month with $20 of usage included |
| Railway | A service with no public domain | A service with a generated domain | Free plan with $1 of usage a month after a trial; Hobby $5 and Pro $20 a month |
| Render | Background worker, with no free tier | Web service; free ones spin down after 15 minutes without inbound traffic | Free web services, and workers from $7 a month for 0.5 CPU and 512 MB |
| Cloudflare Workers | Not used, since Workers answer requests | grammY's webhookCallback in a Worker | Free with 100,000 requests a day, or Workers Paid from $5 a month |
Cloudflare Workers suit a webhook bot with light, quick handlers, with Cloudflare's storage for sessions. Railway and Render run either mode as long-lived processes. Modelence runs either mode with managed Redis, PostgreSQL and MongoDB next to the bot, a sandbox environment for the test bot and room to add a web app or worker as more services in the same file. For more on Render, see Render alternatives.
Next steps
Frequently asked questions
How do I host a Telegram bot 24/7?
Run the bot as a long-lived process on a host that restarts it on new versions and keeps it up between them. On Modelence a polling bot is a service with no health check and a recreate rollout, deployed with npx modelence@latest deploy, and it keeps polling in a container on AWS. Telegram holds updates for up to 24 hours, so nothing sent during a deploy is lost.
Should my Telegram bot use long polling or a webhook?
Start with long polling. It needs no public URL and no request deadline, and grammY's docs recommend it unless you have a reason not to. Choose a webhook when the bot should share a web service with an app, run on several containers, or run on a platform that only answers HTTP requests. The bot code stays the same, and only the entry point and config change.
What does "409 Conflict: terminated by other getUpdates request" mean?
Two processes are polling with the same bot token, often a laptop and a server, or an old host still running after a move. Telegram ends one request when the other starts, so each copy sees some updates and errors on the rest. Stop the extra process, give local testing its own bot, and run the deployed bot as a single container with a rollout that stops the old one first.
Can I host a Telegram bot for free?
You can build and try the bot on Modelence's free plan. A bot that people use every day fits the Starter plan, which is $20 a month with the same $20 included as cloud usage, enough for a small bot running around the clock, and adds managed Redis and PostgreSQL for its sessions.
Can I deploy a python-telegram-bot or aiogram bot?
Yes. A Python bot runs on Modelence from a Dockerfile that installs its requirements and starts the bot. For polling, set the health check to none and the rollout to recreate. For a webhook, list the port the bot listens on and use an HTTP health check, and the rest of this guide applies unchanged.
What URL should I give Telegram for the webhook?
Use the environment's HTTPS address with the webhook path, such as https://<app>-<environment>.cloud.modelence.app/telegram, or the same path on your own domain. Telegram only delivers to HTTPS URLs on ports 443, 80, 88 or 8443, and the Modelence URL is HTTPS on 443. The bot in this guide registers the URL itself from the SITE_URL variable on every start, so you never call setWebhook by hand.
Which Node.js library should I use for a Telegram bot?
grammY is the most used today, with about 16 million npm downloads a month against about 1.5 million for Telegraf and about 1.1 million for node-telegram-bot-api, and it is written in TypeScript with regular releases. Telegraf's last release was in February 2024. Hosting works the same for all of them, since each supports long polling and webhooks.