Contents
A Telegram bot written with python-telegram-bot or aiogram is usually a script that runs run_polling() forever. On a laptop that works until you close the lid. On hosting you need three things: a process that keeps running after you log out, something that restarts it when it crashes or the server reboots, and logs you can read. On cPanel, nohup and a cron keepalive script provide all three.
Polling or webhook?
| Long polling | Webhook | |
|---|---|---|
| How updates arrive | The bot calls getUpdates in a loop |
Telegram POSTs each update to your HTTPS URL |
| Runs as | A permanent background process | A web app (Passenger) started on demand |
| Needs a public URL | No | Yes, with a valid SSL certificate |
| Best for | Most bots, quick setup | Bots with occasional traffic, or bots built inside a web app |
This guide uses polling, with a webhook alternative at the end.
Prerequisites
- An AI/Developer plan with SSH access.
- A bot token from
@BotFather. - Code that works locally, plus a
requirements.txt(for example containingpython-telegram-bot).
Step by step
1. Create a folder and virtualenv
mkdir -p ~/bots/tgbot && cd ~/bots/tgbot
/opt/alt/python312/bin/python3.12 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r requirements.txt
Upload bot.py and requirements.txt into ~/bots/tgbot first, with Git, SFTP or File Manager. Python 3.9-3.12 are available; use the same version you developed with.
2. Store the token outside the code
printf 'BOT_TOKEN=%s\n' 'PASTE-YOUR-TOKEN-HERE' > ~/bots/tgbot/.env
chmod 600 ~/bots/tgbot/.env
Never commit the token to Git. If it leaks, revoke it in @BotFather with /revoke.
3. A minimal bot.py
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s", level=logging.INFO)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Hello! The bot is running.")
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
if __name__ == "__main__":
main()
4. Test in the foreground
Stop any copy running on your computer, then:
cd ~/bots/tgbot
set -a; . ./.env; set +a
venv/bin/python bot.py
Send /start to the bot, then press Ctrl+C.
5. Write the keepalive script
Save this as ~/bots/tgbot/keepalive.sh. It starts the bot only when no copy is running:
#!/bin/bash
APP="$HOME/bots/tgbot"
cd "$APP" || exit 1
# Already running? Then do nothing.
if pgrep -f "$APP/bot.py" > /dev/null; then
exit 0
fi
set -a
. "$APP/.env"
set +a
nohup "$APP/venv/bin/python" "$APP/bot.py" >> "$APP/bot.log" 2>&1 &
echo "$(date '+%F %T') started PID $!" >> "$APP/keepalive.log"
chmod 700 ~/bots/tgbot/keepalive.sh
~/bots/tgbot/keepalive.sh
The bot is started with its full path, so pgrep -f matches exactly this bot and not another one in your account.
6. Add the cron job
In cPanel open Advanced › Cron Jobs. Under Add New Cron Job, pick Once Per Five Minutes (*/5 * * * *) from Common Settings, and enter the command:
/bin/bash /home/USER/bots/tgbot/keepalive.sh >/dev/null 2>&1
From now on, if the bot crashes or the server restarts, it is back within five minutes. The cron jobs guide explains the schedule syntax.
7. Read logs and deploy updates
tail -f ~/bots/tgbot/bot.log # live output and tracebacks
pkill -f "$HOME/bots/tgbot/bot.py" # stop the bot to load new code
~/bots/tgbot/keepalive.sh # start it again right away
To stop the log growing forever, add a weekly cron job that empties it: 0 4 * * 0 : > /home/USER/bots/tgbot/bot.log.
Alternative: a webhook through Passenger
If you prefer no permanent process, create a Flask app in Setup Python App on a subdomain such as bot.example.com. Set the startup file to passenger_wsgi.py, and add BOT_TOKEN and WEBHOOK_SECRET under Environment variables:
import os
import requests
from flask import Flask, abort, request
TOKEN = os.environ["BOT_TOKEN"]
SECRET = os.environ["WEBHOOK_SECRET"]
application = Flask(__name__)
@application.post("/webhook")
def webhook():
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != SECRET:
abort(403)
message = (request.get_json(silent=True) or {}).get("message") or {}
if "text" in message:
requests.post(
f"https://api.telegram.org/bot{TOKEN}/sendMessage",
json={"chat_id": message["chat"]["id"], "text": "Got it: " + message["text"]},
timeout=10,
)
return "ok"
Register it once (and don’t run a polling copy alongside it):
curl "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
-d url=https://bot.example.com/webhook -d secret_token="$WEBHOOK_SECRET"
Troubleshooting
409 Conflict: terminated by other getUpdates request: two copies are polling. Count them withpgrep -af bot.py, and check your computer. After switching from a webhook, runcurl "https://api.telegram.org/bot$BOT_TOKEN/deleteWebhook". See Telegram 409 Conflict.ModuleNotFoundError: No module named 'telegram': the bot ran with the system Python instead ofvenv/bin/python, or a file in your folder is namedtelegram.pyand hides the library.KeyError: 'BOT_TOKEN': the.envfile wasn’t loaded. Cron doesn’t read.bashrc, which is why the script loads.envitself.- The bot stops and keepalive.log shows frequent restarts: read the end of
bot.log. An unhandled exception or your account’s memory limit is the usual cause. - The cron job never starts the bot: use full paths, check the script’s permissions, and see cron job not running.
On ArabyHost
Telegram bots run on the AI/Developer plans: SSH jailed in CageFS, Python 3.9-3.12 and Node.js 20 and 24, background workers kept alive with cron as shown above, and Passenger apps through Setup Python App for webhooks, with free SSL issued automatically for the webhook subdomain. The bot shares your account’s own resource limits (LVE), so keep heavy work such as AI model calls on external APIs; there is no GPU, no Docker and no root access. Read Telegram bot hosting for which plan fits, or run a Discord bot with the same method.
FAQ
Can I run a Telegram bot on ordinary shared hosting?
A polling bot is a process that never stops, so it needs SSH and permission to run background processes. On ArabyHost that is the AI/Developer plans; shared plans serve websites only.
Should I use polling or a webhook?
Polling is simpler: one process asks Telegram for updates and needs no public URL. A webhook needs an HTTPS address and a web app, but no permanent process. Pick one; using both at once causes 409 Conflict.
Why does my bot answer twice or show 409 Conflict?
Two copies are running with the same token, often one on your computer and one on the server, or a webhook is still set. Stop the extra copy, call deleteWebhook if you use polling, and keep the cron keepalive check in place so it never starts a second copy.