From f36fe4426a2c0f430d3133d91859a7a884ec3586 Mon Sep 17 00:00:00 2001 From: Davide Grilli Date: Sun, 18 Jan 2026 15:08:40 +0100 Subject: [PATCH] Commit iniziale --- Dockerfile | 10 +++++ README.md | 56 ++++++++++++++++++++++++ docker-compose.yml | 9 ++++ main.py | 104 +++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + 5 files changed, 180 insertions(+) create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 main.py create mode 100644 requirements.txt diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..20f55b7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.11-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY main.py . + +CMD ["python", "-u", "main.py"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6df38b5 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# Telegram IP Bot + +Bot Telegram minimalista per recuperare l'indirizzo IP pubblico del server. + +## Setup + +### 1. Ottieni il Token del Bot + +1. Apri Telegram e cerca [@BotFather](https://t.me/botfather) +2. Crea un nuovo bot con `/newbot` +3. Copia il token fornito (formato: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`) + +### 2. Configura le Variabili d'Ambiente + +```bash +cp .env.example .env +nano .env +``` + +Inserisci il tuo token nel file `.env`: +``` +BOT_TOKEN=il_tuo_token_qui +``` + +### 3. Avvia il Bot + +```bash +docker compose up -d --build +``` + +### 4. Usa il Bot + +Apri Telegram, cerca il tuo bot e invia `/start` o `/ip`. + +## Comandi + +```bash +# Ferma il bot +docker compose down + +# Riavvia il bot +docker compose restart + +# Visualizza i log +docker compose logs -f telegram-bot + +# Verifica stato +docker compose ps +``` + +## Note + +- Il bot si riavvia automaticamente in caso di crash o reboot del sistema +- Il token è protetto: `.env` è escluso da Git +- Architettura: Python 3.11 + Docker + requests +- Dipendenza unica: `requests==2.31.0` \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d2aecc7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,9 @@ +services: + telegram-bot: + build: . + container_name: telegram-bot + restart: unless-stopped + env_file: + - .env + environment: + - PYTHONUNBUFFERED=1 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..7ae2eaa --- /dev/null +++ b/main.py @@ -0,0 +1,104 @@ +import requests +import time +import os + +# CONFIGURAZIONE +BOT_TOKEN = os.getenv("BOT_TOKEN") +BASE_URL = f"https://api.telegram.org/bot{BOT_TOKEN}" + +# Funzione per ottenere l'IP pubblico +def get_public_ip(): + try: + response = requests.get("https://ifconfig.me") + response.raise_for_status() + return response.text.strip() + except requests.exceptions.RequestException: + return None + +# Funzione per ottenere aggiornamenti +def get_updates(offset=None): + url = f"{BASE_URL}/getUpdates" + params = {"offset": offset} if offset else {} + try: + response = requests.get(url, params=params) + response.raise_for_status() + return response.json() + except requests.exceptions.RequestException: + return None + +# Funzione per configurare i comandi del bot +def set_bot_commands(): + url = f"{BASE_URL}/setMyCommands" + commands = [ + {"command": "ip", "description": "Mostra l'indirizzo IP pubblico"} + ] + payload = {"commands": commands} + try: + response = requests.post(url, json=payload) + response.raise_for_status() + except requests.exceptions.RequestException: + pass + +# Funzione per inviare messaggi +def send_telegram_message(chat_id, message, keyboard=None): + url = f"{BASE_URL}/sendMessage" + payload = {"chat_id": chat_id, "text": message} + if keyboard: + payload["reply_markup"] = keyboard + try: + response = requests.post(url, json=payload) + response.raise_for_status() + return response.json().get("result", {}).get("message_id") + except requests.exceptions.RequestException: + return None + +# Funzione per processare comandi +def process_command(chat_id, text): + # Tastiera persistente con il pulsante /ip + keyboard = { + "keyboard": [[{"text": "/ip"}]], + "resize_keyboard": True, + "persistent": True + } + + if text == "/ip": + ip_address = get_public_ip() + if ip_address: + message = f"IP pubblico: {ip_address}" + else: + message = "Errore nel recupero dell'IP pubblico." + send_telegram_message(chat_id, message, keyboard) + elif text == "/start": + send_telegram_message(chat_id, "Bot attivo. Usa /ip per ottenere l'indirizzo IP pubblico.", keyboard) + else: + send_telegram_message(chat_id, "Comando non riconosciuto.", keyboard) + +# Funzione principale del bot +def main(): + # Configura i comandi del bot all'avvio + set_bot_commands() + + last_update_id = None + while True: + try: + updates = get_updates(last_update_id + 1 if last_update_id else None) + if updates and updates.get("ok"): + for update in updates["result"]: + update_id = update["update_id"] + message = update.get("message") + + if message: + chat_id = message["chat"]["id"] + text = message.get("text", "") + process_command(chat_id, text) + + last_update_id = update_id + time.sleep(2) + except KeyboardInterrupt: + break + except Exception: + time.sleep(5) + +# Avvia il bot +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..077c95d --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests==2.31.0 \ No newline at end of file