Skip to content
Deploying apps6 min read

How to keep a Telegram bot running 24/7

Short answer

A bot started from a terminal stops when the session closes, when it crashes, or when the server restarts, because nothing starts it again. On hosting you have two options: a polling bot that a cron job launches every minute through flock, so it is back within a minute after any stop, or a webhook bot that runs as a web app through Passenger or PHP and needs no permanent process at all.

ArabyHost teamLast updated: ShareWhatsAppXLinkedIn
Contents
  1. Why a bot started from a terminal dies
  2. Webhook or polling
  3. Method 1: polling with cron and flock
  4. Method 2: a webhook on Passenger (Node.js or Python)
  5. Method 3: a PHP webhook on any plan
  6. Monitoring a webhook bot
  7. Troubleshooting
  8. On ArabyHost

On your computer you type python bot.py, the bot runs, and it stops when you close the laptop. On a server the same thing happens, just more slowly: you start it over SSH, close the window, and it dies at once, or at the first error, or at the first server restart. “24/7” means something other than you makes sure the bot always comes back. This guide covers how to choose an approach and build it on hosting without root. The full step-by-step setup for a Python bot is in run a Python Telegram bot on hosting.

Why a bot started from a terminal dies

What happens Result Does nohup help?
Closing the SSH or terminal window A SIGHUP signal ends the process Yes
An unhandled exception in the code The bot exits No
Hitting your account’s memory or process limit The bot is killed No
A server restart for maintenance Every process stops No

So the fix isn’t keeping the bot alive; it’s restarting it automatically whenever it stops, or not needing a permanent process.

Webhook or polling

Polling Webhook
How messages arrive The bot keeps asking Telegram through getUpdates Telegram sends each message to your HTTPS URL
What runs on the server A permanent process A web app that wakes up on request
How it stays up 24/7 A cron job restarts it It doesn’t need to; the web server runs it per message
Needs SSH and background processes A domain or subdomain with SSL
Good for Scheduled jobs, bots that watch something continuously Most bots that answer messages

Never use both with the same token. While a webhook is set, getUpdates fails, and two polling copies give 409 Conflict.

Method 1: polling with cron and flock

The idea: a cron job runs every minute and tries to start the bot. flock holds a lock on a file while the bot runs, so a new attempt exits at once if the bot is up, and if it has stopped the lock is free and the next attempt starts it. The lock is released automatically when the process dies, so no stale PID files fool you.

1. A start script

Create ~/bots/tgbot/start.sh, which loads the token and starts the bot:

#!/bin/bash
cd /home/USER/bots/tgbot || exit 1
set -a; . ./.env; set +a
exec venv/bin/python bot.py
chmod 700 ~/bots/tgbot/start.sh

For a Node.js bot, replace the last line with the Node path from the environment you created in Setup Node.js App, for example exec /home/USER/nodevenv/bots/tgbot/20/bin/node bot.js.

2. The cron job

In Cron Jobs, add a job with the schedule * * * * * and the command:

/usr/bin/flock -n /home/USER/bots/tgbot/bot.lock /home/USER/bots/tgbot/start.sh >> /home/USER/bots/tgbot/bot.log 2>&1

You can build schedules with the cron generator. Within a minute the bot starts. Check:

pgrep -af bot.py
tail -n 20 ~/bots/tgbot/bot.log

3. Deploying a new version

After uploading new code, stop the running copy and the cron job starts the new one within a minute:

pkill -f /home/USER/bots/tgbot/bot.py

4. A heartbeat in the log

Add a job to the bot that writes a line every five minutes, such as heartbeat 2026-11-27 10:05. If the last line is old, the bot is down or stuck. If the log shows the bot starting every minute, it crashes right after starting; read the error just before each start line.

Method 2: a webhook on Passenger (Node.js or Python)

No permanent process and no cron: create an app in Setup Node.js App or Setup Python App on a subdomain such as bot.example.com, and add BOT_TOKEN and WEBHOOK_SECRET under Environment variables. A Node.js and Express example:

const express = require('express');
const app = express();
app.use(express.json());

const { BOT_TOKEN, WEBHOOK_SECRET } = process.env;

app.post('/webhook', async (req, res) => {
  if (req.get('X-Telegram-Bot-Api-Secret-Token') !== WEBHOOK_SECRET) return res.sendStatus(403);
  res.sendStatus(200);                       // answer Telegram fast
  const msg = req.body.message;
  if (msg && msg.text) {
    await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: msg.chat.id, text: 'Got it: ' + msg.text }),
    });
  }
});

app.listen(process.env.PORT || 3000);

Then register the URL once from your computer:

curl "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
  -d url=https://bot.example.com/webhook -d secret_token="$WEBHOOK_SECRET"

Passenger may stop the app after a quiet period and start it again with the next message, which then arrives only a second or two late. A Python Flask example is in the Python bot guide.

Method 3: a PHP webhook on any plan

A PHP webhook bot is just a page that receives a POST request, so it runs on regular website plans without SSH. Put the file in a randomly named folder inside public_html, such as public_html/tg-7c2f/hook.php:

<?php
$token  = 'PASTE-TOKEN';           // better: read it from a file outside public_html
$secret = 'PASTE-SECRET';
if (($_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '') !== $secret) {
    http_response_code(403);
    exit;
}
$update = json_decode(file_get_contents('php://input'), true);
$msg = $update['message'] ?? null;
if ($msg && isset($msg['text'])) {
    file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query([
        'chat_id' => $msg['chat']['id'],
        'text'    => 'Got it: ' . $msg['text'],
    ]));
}
echo 'ok';

Register it with the same setWebhook call and the file’s URL. This suits simple reply bots; jobs that take minutes need Method 1.

Monitoring a webhook bot

curl "https://api.telegram.org/bot$BOT_TOKEN/getWebhookInfo"

Look at pending_update_count (undelivered messages) and last_error_message. A certificate error or Wrong response from the webhook: 503 means the problem is on the server, not at Telegram. See webhook not receiving. Telegram accepts webhook URLs only on ports 443, 80, 88 and 8443; plain HTTPS on 443 is simplest.

Troubleshooting

  • The bot runs, then stops after you close the terminal: it wasn’t started from cron. See bot stops after closing the terminal.
  • 409 Conflict: a copy on your computer, or a webhook set while polling. Call deleteWebhook before switching to polling.
  • The cron job starts nothing: a relative path or a script without execute permission. See cron job not running.
  • Messages repeat: your reply to Telegram was slow or an error, so it resent the update. Answer 200 first, then do the work.

On ArabyHost

Polling bots and Node.js or Python webhook apps run on ArabyHost AI/Developer plans: SSH jailed in CageFS, Node.js 20 and 24, Python 3.9 to 3.12, Passenger apps, and background processes kept alive by cron as in Method 1, with a free SSL certificate for the subdomain. The bot runs within your account’s resource limits, and there’s no root or Docker, so a bot built only for Docker should be run as a plain program. To compare options see Telegram bot hosting and free bot hosting; prices are on the pricing page.

FAQ

Can I host a Telegram bot for free 24/7?

A simple webhook bot can run on the free tiers of some serverless platforms, within the request and execution-time limits they publish. A permanent polling bot is different: free tiers usually put it to sleep or cap its hours, so read their terms before relying on one.

Why does my bot stop when I close the terminal or my laptop?

The bot is a child of the terminal session, and closing it sends a hang-up signal to everything started from it. With nohup it survives logout, but it doesn't come back after a crash or a server restart. That's why you need cron or a webhook.

Which is better for a bot, webhook or polling?

A webhook is lighter on hosting because it only runs when a message arrives, and it needs an HTTPS URL. Polling is easier to code and test but is a permanent process. For bots that run scheduled or long jobs, polling with cron is simpler.

How do I know the bot is still running?

For a webhook bot, open getWebhookInfo to see pending updates and the last error. For a polling bot, have it write a line to its log every few minutes and watch the time of the last line.

Useful? Share it with someone who needs it:WhatsAppXLinkedIn

Read next

Ready to put your idea online?

Fast, isolated hosting, support that understands you, and an AI assistant that fixes problems with you.