Learning objectives
After reading this article you will be able to:
- Choose between long polling and a webhook for your bot
- Run a bot with python-telegram-bot 22 in polling and webhook mode
- Check that the bot is online and avoid the most common errors
A Telegram bot is a program that receives updates (messages, commands, button clicks) and replies through the Bot API. Unlike a Discord bot, it does not hold an open WebSocket: Telegram delivers updates over HTTP. Your process still has to be running to fetch or receive them, and that is what hosting is for.
Below you create the token, pick how the bot receives updates, run the code and confirm it works. The examples use Python with the python-telegram-bot 22 API; check PyPI for the current release and the minimum Python version it requires.
What does running a Telegram bot 24/7 mean?#
It means a process that keeps running on a machine that does not shut down, and that comes back on its own if it crashes. The bot's code is just a loop that fetches or receives updates and calls your functions. If the process dies, nobody answers.
Running it on your own computer is fine for testing, but the bot goes down when the machine sleeps, reboots or loses connection. For a bot other people use, the usual answer is an always-on server: a VPS, a container or a hosting platform. See what to expect from no-cost options in free bot hosting limits.
How do I create the bot and get the token?#
- Open a chat with @BotFather on Telegram.
- Send
/newbotand answer the prompts (a name and a username ending inbot). - Copy the token it returns. It looks like a number, a colon and a string of characters.
The token authenticates the bot, not your account, and works like a password: whoever has it controls the bot. Telegram's documentation recommends keeping it out of the code, in environment variables or a settings file. If it leaks, revoke it through BotFather. For the concept, read what are environment variables.
Long polling or webhook?#
Telegram offers two ways to deliver updates, and you can only use one at a time:
| Long polling | Webhook | |
|---|---|---|
| Who starts it | The bot asks Telegram (getUpdates) |
Telegram sends a POST to your URL |
| Public URL | Not needed | Required, over HTTPS |
| Ports | Any outbound | 443, 80, 88 or 8443 |
| Setup | None | setWebhook, valid certificate |
| Good for | Getting started, small and medium bots | High volume, server already exposed |
With long polling, getUpdates accepts a timeout in seconds: above zero, the connection stays open until an update arrives instead of polling constantly. The default is 0, which is short polling. Libraries handle this for you.
With a webhook, the URL must be HTTPS. You can set a secret_token of 1 to 256 characters (letters, digits, _ and -), which Telegram sends back in the X-Telegram-Bot-Api-Secret-Token header so you can drop forged requests. The default is up to 40 simultaneous connections (max_connections).
For most bots, start with polling. Move to a webhook if you need volume or already have an HTTPS server.
How do I run a bot with long polling?#
Install the library and create a bot.py file:
pip install "python-telegram-bot>=22,<23"import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("I'm online!")
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()Set BOT_TOKEN in the environment and run python bot.py. run_polling blocks the process and handles shutdown signals. Send /start to the bot: if it answers, the loop works.
The idea is the same in other libraries: aiogram (Python), Telegraf and grammY (Node.js) each have a start method that enters polling.
How do I run it with a webhook?#
Swap run_polling for run_webhook. Install the webhooks extra:
pip install "python-telegram-bot[webhooks]>=22,<23"import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("I'm online via webhook!")
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.run_webhook(
listen="0.0.0.0",
port=int(os.environ.get("PORT", "8080")),
url_path="telegram",
webhook_url=f"{os.environ['PUBLIC_URL']}/telegram",
secret_token=os.environ["WEBHOOK_SECRET"],
)
if __name__ == "__main__":
main()PUBLIC_URL is your server's public HTTPS address (for example https://mybot.example.com). PORT and PUBLIC_URL are just example names. The port in webhook_url must be one Telegram accepts (443, 80, 88 or 8443); if a reverse proxy receives the traffic, the bot can listen on a different local port. The library calls setWebhook on startup and checks the secret_token on every request. To understand the certificate behind that address, see how Let's Encrypt works.
How do I keep the process alive?#
In practice, hosting 24/7 comes down to three guarantees:
- Automatic restart: on a VPS, use
systemdor a process manager such aspm2; on a platform, check whether restarts are included. - Settings outside the code: the token and webhook secret come from the environment, never from the repository.
- Logs: without logs you cannot tell why the bot stopped. Print errors and read the process output.
Telegram keeps pending updates for up to 24 hours. A short outage costs you no messages; one that lasts more than a day does.
How do I know the bot is online?#
- Send a command and see whether it answers.
- Call the Bot API
getMemethod to validate the token (never share that URL, since it contains the token). - With a webhook,
getWebhookInfoshows the registered URL, the number of pending updates and the last delivery error.
What are the common errors?#
- The bot does not answer in webhook mode: the URL is not valid HTTPS, the port is not an allowed one, or the
secret_tokendoes not match. Checklast_error_messageingetWebhookInfo. Conflict: terminated by other getUpdates request: two instances of the same bot are polling. Stop the other one, including the one on your PC.getUpdatesdoes not work: a webhook is active. Remove it withdeleteWebhook.Unauthorized(InvalidTokenin python-telegram-bot): wrong or revoked token. Check the environment variable.- The bot goes offline after a few hours: the process was killed for lack of memory or by an unhandled error. Read the logs.
How to do this on Square Cloud#
On Square Cloud, both modes from this article work without changing the code. With long polling, the bot is a background application: it only makes outbound requests, needs no subdomain and starts at 256 MB of RAM. For a webhook, create a web application with a subdomain: it gets a squareweb.app address with HTTPS, which goes in PUBLIC_URL, and the example above already listens on 0.0.0.0 on the port from the PORT variable, which the platform sets. The public URL uses HTTPS on the standard port, which Telegram accepts, and a web application starts at 512 MB.
The three guarantees for keeping the process alive come with the container. It stays on, with no sleep mode, and automatic restart, on by default for dashboard deploys, brings the bot back when the process exits with an error. If it runs out of memory, the application stops and only comes back when you raise its RAM and start it again. BOT_TOKEN and WEBHOOK_SECRET go in as application environment variables, and real-time logs show why the bot went down. When you deploy, stop the copy running on your PC, or polling goes back to Conflict.
The bot works with python-telegram-bot, aiogram, Telethon, Telegraf or grammY. Hobby costs R$12.49 per month for 1 GB of RAM shared across your applications. See the details on Telegram bot hosting.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
Does a Telegram bot need my computer to stay on?
It needs a process running somewhere. If that is your PC, the bot goes down when it shuts off or loses internet. On an always-on server, the bot keeps answering without depending on your machine.
Do I lose messages if the bot goes offline?
Not right away. Telegram keeps pending updates until the bot fetches them, but never for more than 24 hours. After that, older messages are discarded.
Can I use long polling and a webhook at the same time?
No. While a webhook is set, the getUpdates method does not work. To go back to polling, remove the webhook with deleteWebhook.
Do I need a domain to host a Telegram bot?
Only for a webhook. Long polling needs no public URL, because the bot makes the requests. A webhook needs an HTTPS URL that Telegram can reach.
More in Bots
See all 33 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.