Per un piccolo bot Telegram su un VPS conviene partire dal long polling: non servono dominio, certificato né porte aperte. Eseguite il bot come servizio systemd (o sotto supervisord) con riavvio automatico e tenete il token in un file .env con permessi 600. Passate a un webhook dietro nginx, che controlla l’header X-Telegram-Bot-Api-Secret-Token, quando avete più bot o vi serve la consegna istantanea. 1 GB di RAM basta: sul nostro banco di test un bot con aiogram 3.31 usava 168-170 MB, uno con python-telegram-bot 22.8 45 MB.
Come abbiamo testato
- Banco di test RichHost, un container isolato con 2 vCPU / 8 GB, Ubuntu 24.04, Python 3.12.3, nginx 1.24, PHP 8.3-FPM. Ottobre 2026. Non sono server di produzione RichHost.
- api.telegram.org non è raggiungibile dal container (il proxy risponde 403), quindi abbiamo scritto un’imitazione locale della Bot API su aiohttp: getMe, getUpdates, setWebhook, deleteWebhook, getWebhookInfo e sendMessage, con risposte JSON nel formato della documentazione ufficiale. I testi di errore nei log vengono dall’imitazione; le regole di Telegram dalla documentazione (verificata il 25.10.2026, Bot API 10.3).
- Librerie da pip: aiogram 3.31.0 (aiohttp 3.14.5, pydantic 2.13.5), python-telegram-bot 22.8 (httpx 0.28.1), supervisor 4.3.0. L’indirizzo dell’API del bot è stato sostituito tramite
TelegramAPIServer.from_base()ebase_url(). - La memoria è il VmRSS di
/proc/PID/statusa riposo e dopo 1000 messaggi da 50 chat. I crash sono stati simulati conkill -9, con un comando che chiamaos._exit(1)e con un token non valido. - Nel container systemd non è in esecuzione (il PID 1 non è systemd), quindi il file di unità è stato solo controllato con
systemd-analyze verify; il vero test di riavvio è stato fatto sotto supervisord.
$ curl -sS -m 15 https://api.telegram.org/
curl: (56) CONNECT tunnel failed, response 403
Long polling o webhook: cosa ha mostrato il test
In modalità long polling il bot chiama getUpdates con un timeout, e Telegram tiene aperta la richiesta finché non arriva un messaggio. Nei log si vede una richiesta che ha atteso 12 secondi ed è tornata nello stesso millisecondo in cui è arrivato il messaggio, mentre una richiesta vuota si è chiusa dopo esattamente 30 secondi. La risposta è partita 6 ms dopo il messaggio in arrivo (rete locale, senza latenza verso i server di Telegram).
Il bot di test rispondeva in ucraino, per questo le righe di log contengono testo ucraino.
14:28:54.963 MOCK inject update_id=1 text='/start'
14:28:54.963 MOCK getUpdates offset=0 timeout=30 -> 1 update(s) after 0.82 s
14:28:54.977 MOCK sendMessage chat_id=555001 text='Привіт! Я працюю на VPS.'
14:29:06.975 MOCK inject update_id=2 text='друге повідомлення'
14:29:06.975 MOCK getUpdates offset=2 timeout=30 -> 1 update(s) after 12.00 s
14:29:06.981 MOCK sendMessage chat_id=555001 text='друге повідомлення'
14:29:36.989 MOCK getUpdates offset=3 timeout=30 -> 0 update(s) after 30.01 s
La trappola principale del polling sono due copie del bot con lo stesso token, per esempio un avvio manuale accanto al servizio. Il getUpdates più recente interrompe quello precedente, ed entrambe le copie continuano a ricevere l’errore 409:
ERROR aiogram.dispatcher: Failed to fetch updates - TelegramConflictError: Telegram server says
- Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
WARNING aiogram.dispatcher: Sleep for 1.000000 seconds and try again... (tryings = 0, bot id = 123456789)
In modalità webhook Telegram invia un POST al vostro indirizzo HTTPS. La documentazione dice chiaramente che getUpdates non funziona finché è impostato un webhook in uscita, quindi un bot in polling deve prima chiamare deleteWebhook (aiogram e python-telegram-bot lo fanno all’avvio). Abbiamo provato anche un certificato autofirmato: senza caricarlo in setWebhook la consegna falliva con un errore di verifica del certificato; dopo il caricamento gli aggiornamenti arrivavano in 6-8 ms attraverso nginx con TLS.
14:30:38.314 MOCK setWebhook url=https://bot.example.test:8443/tg secret=yes cert=no
14:30:39.373 MOCK webhook POST update_id=1 failed (... [SSL: CERTIFICATE_VERIFY_FAILED] ...), retry #1
# WEBHOOK_CERT set, the self-signed cert.pem is uploaded with setWebhook:
14:31:13.755 MOCK setWebhook url=https://bot.example.test:8443/tg secret=yes cert=uploaded
14:31:14.627 MOCK webhook POST update_id=1 -> 200 in 8.3 ms
14:31:14.937 MOCK webhook POST update_id=2 -> 200 in 6.8 ms
14:31:15.248 MOCK webhook POST update_id=3 -> 200 in 5.9 ms
$ curl -s http://127.0.0.1:18281/bot<TOKEN>/getWebhookInfo
{"ok": true, "result": {"url": "https://bot.example.test:8443/tg", "has_custom_certificate": true,
"pending_update_count": 0, "max_connections": 40}}
$ curl -s http://127.0.0.1:18281/bot<TOKEN>/getUpdates
{"ok": false, "error_code": 409, "description": "Conflict: can't use getUpdates method while webhook
is active; use deleteWebhook to delete the webhook first"}
| Criterio | Long polling | Webhook |
|---|---|---|
| Dominio e certificato | non servono | servono (Let’s Encrypt o autofirmato) |
| Porte in ingresso | nessuna | 443, 80, 88 o 8443 |
| Processo del bot | sempre attivo | sempre attivo (Python) o una richiesta per aggiornamento (PHP) |
| Più bot su un server | ognuno tiene la propria richiesta | un solo nginx, percorsi diversi |
| Errore tipico | 409: due copie del bot | 403/401: secret sbagliato, errore TLS |
| Quando sceglierlo | per iniziare, un bot, nessun dominio | più bot, hosting condiviso, serverless |
Quanta memoria serve davvero a un bot
La cosa che ci ha sorpreso di più è la differenza tra le librerie. Un bot echo con aiogram 3.31.0 usava 168 MB subito dopo l’avvio e 170 MB dopo mille messaggi; lo stesso bot con python-telegram-bot 22.8 usava 44-45 MB. Quasi tutto è dovuto agli import: un interprete Python nudo occupa 8 MB, dopo import aiohttp e import pydantic 38 MB, e dopo from aiogram import Bot, Dispatcher 165 MB. Anche l’avvio è diverso: dal lancio al primo getUpdates aiogram ha impiegato 3,2-3,3 s, python-telegram-bot 0,3-0,4 s (tre esecuzioni ciascuno). La memoria dipende molto dalla versione: nel nostro test l’import di aiogram 3.22.0 occupava 108 MB, quindi misurate la vostra build invece di fidarvi dei numeri altrui.

$ grep VmRSS /proc/$(supervisorctl pid tgbot)/status
VmRSS: 172072 kB # aiogram 3.31.0, polling, idle
VmRSS: 174368 kB # the same process after 1000 messages from 50 chats
$ grep VmRSS /proc/$(cat ptb.pid)/status
VmRSS: 45632 kB # python-telegram-bot 22.8, after 1000 messages
$ ps -o rss,cmd -C supervisord
RSS CMD
20976 .../venv/bin/python3.12 ./venv/bin/supervisord -c supervisord.conf
Cosa significa per il dimensionamento: il bot in sé sta in 50-200 MB; il resto va al sistema operativo, a nginx e a un eventuale database (che qui non abbiamo misurato). Un VPS da 1 GB basta per uno-tre bot di questo tipo, 512 MB sono pochi per aiogram con un database. Cos’altro controllare oltre alla memoria è spiegato in come scegliere un VPS.
Utente, venv e token in .env
La configurazione di base del server (aggiornamenti, chiavi SSH, firewall) è nella nostra guida per configurare un VPS Ubuntu 24.04; qui ci occupiamo solo del bot. Il bot gira come utente di sistema dedicato senza shell di login, con le dipendenze in un ambiente virtuale bloccato su una versione esatta:
sudo useradd --system --create-home --home-dir /opt/tgbot --shell /usr/sbin/nologin tgbot
sudo -u tgbot python3 -m venv /opt/tgbot/venv
sudo -u tgbot /opt/tgbot/venv/bin/pip install aiogram==3.31.0
sudo -u tgbot sh -c '/opt/tgbot/venv/bin/pip freeze > /opt/tgbot/requirements.txt'
sudo -u tgbot touch /opt/tgbot/.env && sudo chmod 600 /opt/tgbot/.env
openssl rand -hex 32 # WEBHOOK_SECRET: only A-Z a-z 0-9 _ - are allowed
Il file .env viene letto sia da systemd (EnvironmentFile) sia dalla shell (. ./.env nel comando di supervisord), quindi scrivete i valori senza virgolette, spazi né variabili: così entrambi li leggono allo stesso modo. Aggiungete .env a .gitignore. Se usate python-telegram-bot, disattivate i log INFO di httpx: abbiamo verificato che a livello INFO la libreria registra l’URL completo della richiesta, token compreso.
# /opt/tgbot/.env owner tgbot, chmod 600, listed in .gitignore
BOT_TOKEN=123456789:AA-your-token-from-BotFather
BOT_MODE=polling
# webhook mode only:
WEBHOOK_URL=https://bot.example.com/tg
WEBHOOK_SECRET=paste-output-of-openssl-rand-hex-32
LISTEN_PORT=8081
Codice del bot: un solo file per entrambe le modalità
Questo è esattamente il file che abbiamo eseguito sul banco in modalità polling e webhook. TG_API_BASE serve solo per il test con l’imitazione locale; non impostatela su un server reale. Se il bot gira in Docker, la policy restart sostituisce systemd: vedete Docker e Compose su un VPS.
import asyncio, logging, os, sys
from aiogram import Bot, Dispatcher, F
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
from aiogram.filters import CommandStart
from aiogram.types import FSInputFile, Message
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
from aiohttp import web
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s",
level=logging.INFO, stream=sys.stdout)
TOKEN = os.environ["BOT_TOKEN"]
MODE = os.environ.get("BOT_MODE", "polling")
API_BASE = os.environ.get("TG_API_BASE") # empty = api.telegram.org (we used a local mock)
dp = Dispatcher()
@dp.message(CommandStart())
async def start(m: Message):
await m.answer("Hi! I am running on a VPS.")
@dp.message(F.text)
async def echo(m: Message):
await m.answer(m.text)
def make_bot():
s = AiohttpSession(api=TelegramAPIServer.from_base(API_BASE)) if API_BASE else None
return Bot(TOKEN, session=s)
async def polling():
bot = make_bot()
await bot.delete_webhook() # getUpdates does not work while a webhook is set
await dp.start_polling(bot, polling_timeout=30)
async def on_startup(bot: Bot):
cert = os.environ.get("WEBHOOK_CERT") # only for a self-signed certificate
await bot.set_webhook(os.environ["WEBHOOK_URL"], secret_token=os.environ["WEBHOOK_SECRET"],
certificate=FSInputFile(cert) if cert else None)
def webhook():
bot = make_bot()
dp.startup.register(on_startup)
app = web.Application()
SimpleRequestHandler(dispatcher=dp, bot=bot,
secret_token=os.environ["WEBHOOK_SECRET"]).register(app, path="/tg")
setup_application(app, dp, bot=bot)
web.run_app(app, host="127.0.0.1", port=int(os.environ.get("LISTEN_PORT", "8081")))
if __name__ == "__main__":
webhook() if MODE == "webhook" else asyncio.run(polling())
L’unità systemd e cosa ha mostrato systemd-analyze
Rispetto al solito esempio abbiamo aggiunto due cose. MemoryMax=300M limita il bot con un margine sopra i 170 MB misurati, così una perdita di memoria non può prendersi tutto il server. StartLimitBurst=5 entro 60 secondi ferma i riavvii infiniti se il bot muore subito dopo l’avvio, per esempio per un token non valido.
# /etc/systemd/system/tgbot.service
[Unit]
Description=Telegram bot (aiogram)
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=tgbot
Group=tgbot
WorkingDirectory=/opt/tgbot
EnvironmentFile=/opt/tgbot/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/tgbot/venv/bin/python /opt/tgbot/bot.py
Restart=on-failure
RestartSec=3
TimeoutStopSec=15
MemoryMax=300M
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/tgbot/data
[Install]
WantedBy=multi-user.target
$ systemd-analyze --version | head -1
systemd 255 (255.4-1ubuntu8.15)
$ systemd-analyze verify ./tgbot.service # before the venv exists
tgbot.service: Command /opt/tgbot/venv/bin/python is not executable: No such file or directory
$ systemd-analyze verify ./tgbot-bench.service; echo "exit=$?" # same unit, bench paths
exit=0
$ systemd-analyze verify ./broken.service # deliberate typos
broken.service:3: Failed to parse service restart specifier, ignoring: sometimes
broken.service:4: Invalid memory limit '300X', ignoring: Invalid argument
systemd-analyze verify rileva un binario ExecStart mancante e valori non validi, ma segnala gli errori di sintassi come avvisi con codice di uscita 0: leggete l’output, non solo il codice di uscita. Eseguitelo dopo aver creato il venv, poi sudo systemctl daemon-reload e sudo systemctl enable --now tgbot. Log: journalctl -u tgbot -f.
supervisord: riavvio dopo un crash, testato
Dove systemd non c’è (container, alcune immagini cloud), supervisord fa lo stesso lavoro. L’exec nel comando è importante: senza di esso SIGTERM arriva alla shell invece che a Python, e il bot non si chiude in modo pulito.
; /etc/supervisor/conf.d/tgbot.conf
[program:tgbot]
command=/bin/sh -c 'set -a; . /opt/tgbot/.env; set +a; exec /opt/tgbot/venv/bin/python /opt/tgbot/bot.py'
directory=/opt/tgbot
user=tgbot
autostart=true
autorestart=true
startsecs=5
startretries=3
stopsignal=TERM
stopwaitsecs=10
environment=PYTHONUNBUFFERED="1"
stdout_logfile=/var/log/tgbot/bot.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
redirect_stderr=true
Risultato del test: dopo kill -9 supervisord ha avviato una nuova copia entro 1 s, il bot era pronto 4,3 s dopo il crash e un messaggio inviato durante il fermo non è andato perso. Telegram conserva gli aggiornamenti non letti fino a 24 ore, e il bot lo ha ricevuto al getUpdates successivo. Con un token non valido supervisord si è arreso dopo quattro tentativi e ha messo il programma nello stato FATAL senza altri riavvii; deve avvisarvi il monitoraggio del server, altrimenti il bot resta muto finché qualcuno non se ne accorge.
$ kill -9 20912 # 14:33:53.144
14:33:53,153 WARN exited: tgbot (terminated by SIGKILL; not expected)
14:33:54,156 INFO spawned: 'tgbot' with pid 20968
14:33:57,447 INFO tgbot: mode=polling pid=20968 (bot log)
14:33:57.461 MOCK sendMessage chat_id=555005 text='повідомлення під час падіння' (mock log)
14:33:59,468 INFO success: tgbot entered RUNNING state, process has stayed up for > than 5 seconds (startsecs)
# /crash command -> os._exit(1)
14:34:01,308 WARN exited: tgbot (exit status 1; not expected)
14:34:02,310 INFO spawned: 'tgbot' with pid 20999
# BOT_TOKEN=broken-token -> TokenValidationError on every start
14:34:33,802 WARN exited: tgbot (exit status 1; not expected)
...
14:34:51,939 WARN exited: tgbot (exit status 1; not expected)
14:34:52,940 INFO gave up: tgbot entered FATAL state, too many start retries too quickly
Webhook dietro nginx con controllo del secret_token
Passate secret_token a setWebhook (da 1 a 256 caratteri, solo A-Z, a-z, 0-9, _ e -) e Telegram lo aggiungerà all’header X-Telegram-Bot-Api-Secret-Token di ogni richiesta. Controllate l’header già in nginx, così le richieste estranee non arrivano mai a Python. L’installazione di nginx è spiegata in installare LEMP su Ubuntu 24.04; il certificato lo rilascia certbot, vedete anche certificato SSL su hosting condiviso.
# /etc/nginx/conf.d/tgbot-secret.conf (http level, chmod 640)
map_hash_bucket_size 128; # a 64-character secret does not fit the default bucket of 64
map $http_x_telegram_bot_api_secret_token $tg_secret_ok {
default 0;
"your-64-hex-secret" 1;
}
La riga map_hash_bucket_size non è decorativa: con un secret di 64 caratteri generato da openssl rand -hex 32 nginx 1.24 senza di essa si rifiutava di partire.
$ nginx -t
nginx: [emerg] could not build map_hash, you should increase map_hash_bucket_size: 64
server {
listen 443 ssl; # Telegram: 443, 80, 88 or 8443 only
server_name bot.example.com;
ssl_certificate /etc/letsencrypt/live/bot.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/bot.example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location = /tg {
if ($tg_secret_ok = 0) { return 403; }
limit_except POST { deny all; }
client_max_body_size 1m;
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 60s;
}
location / { return 404; }
}
Sul banco gli stessi blocchi location giravano sulla porta 18443 con un certificato autofirmato. Un secret sbagliato o assente viene respinto da nginx con 403, anche un GET riceve 403, gli altri percorsi 404, e TLS 1.1 viene rifiutato. aiogram è la seconda linea di difesa: aggirando nginx, una richiesta con il secret sbagliato riceveva 401.
no header: 403
wrong secret: 403
GET + secret: 403
POST + secret: 200
other path: 404
TLS 1.1: 000 exit=35 # handshake refused, only TLS 1.2/1.3 allowed
# aiogram's own check when nginx is bypassed:
$ curl -s -w ' %{http_code}' -XPOST -H 'X-Telegram-Bot-Api-Secret-Token: wrong' http://127.0.0.1:18282/tg
Unauthorized 401
Potete anche consentire /tg solo da 149.154.160.0/20 e 91.108.4.0/22, le reti da cui Telegram invia i webhook secondo la sua documentazione. Telegram avverte che questi intervalli possono cambiare, quindi il secret resta la protezione principale.
Regole ufficiali di Telegram da conoscere
| Regola | Cosa dice la documentazione | Fonte |
|---|---|---|
| Porte del webhook | solo 443, 80, 88 e 8443 | Bot API, setWebhook |
| HTTPS e TLS | l’URL del webhook deve essere HTTPS, sono supportati TLS 1.2 e successivi, IPv6 non è supportato per i webhook | Guida ai webhook |
| Certificato autofirmato | caricare il certificato pubblico come file nel parametro certificate; il CN deve corrispondere al dominio o all’IP | Guida ai webhook |
| getUpdates e webhook | getUpdates non funziona finché è impostato un webhook in uscita | Bot API, getUpdates |
| Conservazione degli aggiornamenti | gli aggiornamenti non letti vengono conservati al massimo 24 ore | Bot API |
| Limiti di invio | non più di 1 messaggio al secondo in una chat, fino a 20 al minuto in un gruppo, circa 30 al secondo per gli invii di massa (fino a 1000 con le trasmissioni a pagamento) | FAQ sui bot |
| max_connections | da 1 a 100, predefinito 40 | Bot API, setWebhook |
Verificato il 25.10.2026; l’ultima voce del changelog è la Bot API 10.3 del 24 agosto 2026.
VPS, serverless o webhook PHP su hosting condiviso
Un webhook non ha bisogno di un processo residente: ogni aggiornamento è una normale richiesta HTTP. Per questo un semplice bot PHP può funzionare anche su un hosting condiviso. La documentazione permette di rispondere a un webhook con una chiamata di metodo direttamente nella risposta: restituite un JSON con un campo method e Telegram lo esegue, senza alcuna richiesta in uscita dal vostro server. Il rovescio della medaglia: non potete sapere se quella chiamata è andata a buon fine.
<?php
// Telegram webhook on shared hosting: one update = one HTTP request, no resident process
$cfg = require __DIR__ . '/../config.php'; // outside public_html: ['secret' => '...']
$got = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if (!hash_equals($cfg['secret'], $got)) {
http_response_code(403);
exit;
}
$update = json_decode(file_get_contents('php://input'), true);
$msg = $update['message'] ?? null;
if (!$msg || !isset($msg['text'])) { // sticker, photo...: just confirm with 200
http_response_code(200);
exit;
}
$text = $msg['text'] === '/start' ? 'Hi! I am answering from PHP.' : $msg['text'];
// reply inside the webhook response: Telegram calls the method itself
header('Content-Type: application/json');
echo json_encode(['method' => 'sendMessage', 'chat_id' => $msg['chat']['id'], 'text' => $text],
JSON_UNESCAPED_UNICODE);
$ curl -i -XPOST -H "X-Telegram-Bot-Api-Secret-Token: $S" -d "$UPDATE" https://bot.example.test:18443/php-hook
HTTP/1.1 200 OK
Content-Type: application/json
{"method":"sendMessage","chat_id":42,"text":"curl test"}
# PHP check alone (nginx check off): wrong secret 403, no secret 403, correct 200, sticker 200
14:33:07.613 MOCK webhook POST update_id=6 -> 200 in 3.4 ms
14:33:07.613 MOCK sendMessage chat_id=555004 text='Привіт! Я відповідаю з PHP.'
php-hook incl. TLS handshake, n=100: min 3.3 ms, median 4.1 ms, p95 5.2 ms, max 8.4 ms
Sul banco (nginx + PHP 8.3-FPM) l’handler ha risposto in 4,1 ms di mediana TLS compreso, e il controllo con hash_equals respingeva le richieste estranee anche senza il controllo in nginx. Questo conta su un hosting condiviso, dove la configurazione del web server non è vostra. Un handler del genere richiede PHP e HTTPS sulla porta 443: i piani di hosting condiviso RichHost a partire da A3 a 8 $ al mese includono SSL Let’s Encrypt gratuito. Abbiamo testato questo codice sul banco di test, non sui server di produzione RichHost.
| Situazione | Scelta | Perché |
|---|---|---|
| Bot in Python o Node, attività in background, code | VPS, polling o webhook | serve un processo residente, 50-200 MB di RAM per bot |
| Più bot su un server | VPS, webhook dietro un solo nginx | una porta 443, percorsi diversi, nessun 409 tra copie |
| Bot semplice: risposte, moduli, notifiche | webhook PHP su hosting condiviso | nessun processo da sorvegliare, l’SSL c’è già |
| Richieste rare, nessuna voglia di gestire un server | funzione serverless con webhook | si paga a chiamata, ma il polling è impossibile e capitano avvii a freddo |
| Invii di massa | VPS con coda | il limite di circa 30 messaggi al secondo va distribuito nel tempo |
Se state ancora scegliendo tra hosting condiviso e server, confrontate i formati in quale tipo di hosting serve al vostro sito.
Errori comuni
| Sintomo | Causa | Soluzione |
|---|---|---|
| 409 Conflict: terminated by other getUpdates request | due copie del bot con un solo token | systemctl status tgbot, pgrep -af bot.py, tenerne una sola |
| 409 Conflict: can’t use getUpdates method while webhook is active | è ancora impostato un vecchio webhook | deleteWebhook prima del polling |
| getWebhookInfo: pending_update_count continua a crescere | TLS, porta sbagliata o 403 da nginx | controllare last_error_message e l’access.log di nginx |
| nginx: could not build map_hash | secret lungo in una map | map_hash_bucket_size 128; |
| il bot si riavvia in loop | errore all’avvio (token, import) | journalctl -u tgbot -n 50, StartLimitBurst o startretries |
| token nei log | httpx a livello INFO | livello WARNING per il logger httpx, revocare il token in @BotFather |
Domande frequenti
Quanta RAM serve a un bot Telegram?
Sul nostro banco il processo in sé usava 45 MB (python-telegram-bot 22.8) o 168-170 MB (aiogram 3.31.0). Aggiungete la memoria per il sistema operativo e un database: un VPS da 1 GB è il minimo pratico per uno-tre bot.
Si perdono messaggi quando il bot si riavvia?
No, purché il fermo duri meno di 24 ore: Telegram conserva gli aggiornamenti non letti e il bot li riceve all’avvio. Nel nostro test un messaggio inviato durante il crash è stato gestito 4,3 s dopo.
Posso usare un webhook sulla porta 8080?
No, Telegram invia i webhook solo alle porte 443, 80, 88 e 8443. Il bot può ascoltare su qualsiasi porta locale, per esempio 8081, mentre nginx accetta le richieste sulla 443 e le inoltra.
systemd o supervisord?
Su un normale VPS Ubuntu, systemd: è già presente, con journal e limiti di risorse. supervisord è comodo nei container e ovunque systemd non sia disponibile; da solo usa circa 20 MB.



