Skip to content

Offer: your first month of web hosting is free on monthly plans. Order by 7 Jan. See plans

HostEthical
All guides

Guides 10 min read ·

How to Host a Telegram Bot 24/7 (Python, systemd, VPS)

Telegram bot hosting free 24/7: why Render, Colab and PythonAnywhere free tiers stop, polling vs webhooks, and a Python bot on a VPS with systemd.

To keep a Telegram bot online 24/7, run it on a server that never sleeps, usually a small Linux VPS, as a systemd service that restarts it whenever it stops. Free platforms don't stay up: as of 15 November 2026, Render's free web services spin down after 15 minutes without incoming traffic, free Google Colab sessions end after 12 hours at most, and PythonAnywhere's free plan has no always-on tasks. Your laptop stops every time it sleeps.

The steps below use python-telegram-bot 22.8, the latest release on PyPI in November 2026, on Ubuntu 24.04. The same approach works for Discord bots.

Why does my bot stop on free hosting?

A bot that uses polling is a program that has to keep running. Most free platforms are built for websites that wake up when someone visits, and they put idle programs to sleep or stop them. Here is what each one does, from its own documentation:

WhereWhat happensOK for a 24/7 polling bot?
Your laptop or PCStops when it sleeps, restarts or loses internet. Telegram's bot tutorial warns that your computer "might not always be online" and suggests a serverFor testing only
Google Colab (free)Notebooks run for 12 hours at most and time out when idle. Colab also bans web services unrelated to interactive notebook workNo
Render free web serviceSpins down after 15 minutes without inbound requests and takes about a minute to wake. Background workers aren't available on the free tierNo. A polling bot gets no inbound requests, so it goes to sleep
PythonAnywhere (free Beginner plan)Restricted outbound internet (HTTP(S) to approved sites only) and no always-on tasks. One always-on task starts with the US$10-a-month Developer planNo
Replit Reserved VMA VM that "never sleeps", aimed at chat bots that must stay connected. From US$15 a month for 0.5 vCPU and 2 GBYes, but it's paid
Linux VPSYour own server, on all the time. You install and look after itYes

Short outages are less serious than they look. The Bot API keeps undelivered updates on Telegram's servers for up to 24 hours, so a bot that restarts within a few minutes picks up the messages it missed. After 24 hours they're gone.

Polling or webhook: which should your Telegram bot use?

Telegram offers two ways to receive messages, and a bot can use only one at a time.

  • Long polling (getUpdates). Your bot keeps asking Telegram for new messages. It needs no domain, no HTTPS and no open port, so it works on any server, but the program must run all the time.
  • Webhook (setWebhook). Telegram sends each update to an HTTPS address you give it. Nothing has to poll, but you need a public HTTPS endpoint that is always reachable.

Telegram's webhook guide lists the requirements, as of November 2026:

  • HTTPS on port 443, 80, 88 or 8443. Other ports don't work.
  • IPv4. Telegram says IPv6 is not supported for webhooks.
  • TLS 1.2 or newer, and a certificate whose name (CN or SAN) matches the address you register.
  • A self-signed certificate is allowed if you upload its public key with setWebhook, and then the IP address can be used as the name.
  • Incoming requests come from 149.154.160.0/20 and 91.108.4.0/22, so your firewall can allow just those.

Set a secret_token when you register the webhook: Telegram then sends it in an X-Telegram-Bot-Api-Secret-Token header, so your code can reject requests that didn't come from Telegram. If you have no domain, either use a self-signed certificate for the server's IP or a publicly trusted certificate for the IP itself, which Let's Encrypt has offered to everyone since January 2026 as six-day certificates. Our guide to SSL certificates for an IP address covers both.

For a personal or small bot on a VPS, polling is simpler and just as reliable. Use a webhook when you already run a web server, or when your host only runs code in response to web requests.

How to host a Telegram bot on a Linux VPS, step by step

These steps assume a fresh Ubuntu 24.04 server that you've already secured; see how to set up a VPS for SSH keys, updates and the firewall. A polling bot needs no open ports.

1. Get a token from BotFather

In Telegram, message @BotFather, send /newbot and follow the prompts. BotFather replies with a token. Telegram's tutorial says to treat it like a password and never share it; you can revoke it in BotFather if it leaks.

2. Create a user and a Python virtual environment

Ubuntu 24.04 ships Python 3.12, and python-telegram-bot needs 3.10 or newer. Run the bot as its own unprivileged user, not as root:

sudo apt update
sudo apt install -y python3-venv
sudo useradd --system --create-home --home-dir /opt/echobot --shell /usr/sbin/nologin echobot
sudo -u echobot python3 -m venv /opt/echobot/venv
sudo -u echobot /opt/echobot/venv/bin/pip install "python-telegram-bot>=22.8,<23"

The version range keeps you on the 22.x series, so a future major release with breaking changes isn't installed by accident.

3. Save the token where only root can read it

sudo install -m 600 /dev/null /opt/echobot/.env
sudo nano /opt/echobot/.env

BOT_TOKEN=123456789:replace-with-your-token

Only root can read this file. systemd loads it when it starts the bot and passes the token in as an environment variable, so the token never appears in your code.

4. Write a minimal echo bot

Save this as /opt/echobot/bot.py. It's a shortened version of the library's official echo example:

# /opt/echobot/bot.py: replies to /start and echoes any text message
import logging
import os

from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters

logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)  # keeps request URLs, which contain the token, out of the log


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Hi! Send me any text and I'll send it back.")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(update.message.text)


def main() -> None:
    app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
    app.run_polling(allowed_updates=Update.ALL_TYPES)  # long polling: runs until stopped


if __name__ == "__main__":
    main()

Every Bot API request goes to https://api.telegram.org/bot<token>/METHOD, which is why the example turns down the httpx logging: at the default level it would write each request URL, token included, into your logs.

How to keep the bot running 24/7 with systemd

nohup, screen and tmux keep a program alive after you log out, but they don't restart it after a crash or a reboot. systemd does both. Create /etc/systemd/system/echobot.service:

[Unit]
Description=Telegram echo bot
After=network-online.target
Wants=network-online.target

[Service]
User=echobot
WorkingDirectory=/opt/echobot
EnvironmentFile=/opt/echobot/.env
ExecStart=/opt/echobot/venv/bin/python /opt/echobot/bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Then load it, start it now and at every boot, and check that it's running:

sudo systemctl daemon-reload
sudo systemctl enable --now echobot
systemctl status echobot

Send /start to your bot in Telegram and it should answer. According to the systemd documentation, Restart=always restarts the service whether it exited cleanly or not, which suits a bot that should never stop. Restart=on-failure restarts only after an error. RestartSec=5 waits five seconds between attempts instead of the default 100 ms, so a bot that crashes on start-up doesn't hammer Telegram. For timers, crash-loop limits and phone alerts when a bot dies, see our guide to running a Python bot 24/7, written for trading bots but the same for any bot.

How to check logs and update the bot

Everything the bot logs goes to the systemd journal:

sudo journalctl -u echobot -f             # follow live; Ctrl+C to stop watching
sudo journalctl -u echobot -n 100         # the last 100 lines
sudo journalctl -u echobot --since today  # everything since midnight

To change the code or update the library, edit the file (or git pull if you keep the bot in a repository), then restart the service:

sudo nano /opt/echobot/bot.py
sudo -u echobot /opt/echobot/venv/bin/pip install --upgrade "python-telegram-bot>=22.8,<23"
sudo systemctl restart echobot

Two problems come up often:

  • The bot gets no messages after you used a webhook. The Bot API says getUpdates doesn't work while a webhook is set. Remove it with curl "https://api.telegram.org/bot<token>/deleteWebhook" and restart the bot.
  • A "Conflict: terminated by other getUpdates request" error. Developers report this when two copies of the bot poll with the same token, typically a test copy still running on a laptop. Stop the other copy.

To switch this bot to a webhook later, install python-telegram-bot[webhooks] and replace run_polling with run_webhook. Behind nginx with a certificate, it looks like this:

app.run_webhook(
    listen="127.0.0.1",                         # nginx on port 443 forwards here, so any local port works
    port=8080,
    url_path="telegram",
    secret_token=os.environ["WEBHOOK_SECRET"],  # e.g. the output of: openssl rand -hex 32
    webhook_url="https://bot.example.com/telegram",
)

Our TradingView webhook guide shows the nginx and Let's Encrypt set-up for a receiver like this.

Can you host Discord and WhatsApp bots the same way?

Discord

Yes, and a Discord bot needs a persistent process even more than a Telegram one. Discord's Gateway documentation describes a persistent WebSocket connection, and your bot must keep sending heartbeats or Discord closes it. Install discord.py (2.7.1 on PyPI as of November 2026) in a virtual environment, and use the same kind of systemd unit with a different ExecStart. Reading message text needs the privileged Message Content intent: switch it on for your bot in the Developer Portal, then set intents.message_content = True in code. The exception is a bot that only answers slash commands: Discord can send those to an Interactions Endpoint URL over HTTPS instead, and you must reply within 3 seconds.

WhatsApp

The official way to automate WhatsApp is Meta's WhatsApp Business Platform (Cloud API). You need a Meta business portfolio and a business phone number, and incoming messages reach your server by webhook. Meta's webhook documentation requires a valid TLS certificate and doesn't accept self-signed ones. Libraries that drive a personal WhatsApp account through WhatsApp Web are a different matter: WhatsApp's Terms of Service forbid "bulk messaging, auto-messaging, auto-dialing" and accessing the service through unauthorised automated means, so using them puts that number at risk of a ban.

VPS or web hosting: where should your bot live?

If your bot polls, connects to Discord's Gateway, or runs timers and background jobs, it needs a process that never stops, and that means a VPS. A simple bot barely uses the CPU, so even a small server can run several bots, each with its own systemd unit, alongside a database or a website.

HostEthical web hosting runs Python apps and gives every site a free SSL certificate, so a webhook-only bot written as a small Python web app can work there once your domain points to it, as long as it handles each update within the web request. It isn't the place for anything that has to keep running between requests. For those, use a VPS.

Keep your bot online around the clock. VPS Starter gives you 4 vCPU, 8 GB RAM, 100 GB SSD, full root and a dedicated IPv4 in Mumbai or Germany, from ₹860 a month, or about ₹774.17 a month when billed yearly. See Cloud VPS →

Our Cloud VPS is unmanaged KVM with full root access, starting at ₹860 a month, or about ₹774.17 a month when billed yearly. You can choose Mumbai, for a small monthly location fee, or Germany. Snapshots, a firewall and a web console are in the dashboard, and you pay by UPI or binance Pay (USDT). If you're comparing prices, our cheap VPS hosting guide lists what to check before you buy, and our guide to free VPS options in India covers Oracle's Always Free tier and the cloud trials.

Frequently asked questions

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

Not reliably. As of November 2026, Render's free web services sleep after 15 minutes without incoming requests, free Google Colab sessions end after 12 hours at most, and PythonAnywhere's free plan has no always-on tasks. Oracle Cloud's Always Free tier can run a bot if you can get a server, but capacity in India is scarce and idle servers can be reclaimed. A small paid VPS is the dependable option.

Should my Telegram bot use polling or a webhook?

Polling with getUpdates is simplest: the bot keeps asking Telegram for new messages, so it needs no domain, HTTPS or open port, but the program must run all the time. A webhook makes Telegram send each update to your HTTPS address, which suits bots that already sit behind a web server. A bot can use only one method at a time, and getUpdates stops working while a webhook is set.

Which ports does a Telegram bot webhook need?

Telegram sends webhook updates only to HTTPS on port 443, 80, 88 or 8443, over IPv4, with TLS 1.2 or newer. The certificate name must match the address you register. A self-signed certificate works if you upload its public key with setWebhook, and the server's IP address can then be used instead of a domain. Telegram's webhook requests come from 149.154.160.0/20 and 91.108.4.0/22.

How do I keep a Python bot running after I close SSH?

Run it as a systemd service instead of using nohup, screen or tmux. A unit file whose ExecStart points at your virtual environment's Python, with Restart=always and WantedBy=multi-user.target, makes systemd start the bot at boot and restart it whenever it stops. Enable it with sudo systemctl enable --now and the service name, and read its output with journalctl -u and the service name.

Can I run a Discord or WhatsApp bot the same way?

A Discord bot, yes: it holds a persistent WebSocket connection to Discord's Gateway, so it needs a process that never stops, and the same systemd set-up works. For WhatsApp, the official route is Meta's WhatsApp Business Platform Cloud API, which delivers messages to your HTTPS webhook. Unofficial libraries that automate a personal number go against WhatsApp's terms and put the number at risk of a ban.