Torna al blog

Creare un bot Telegram con Python in 10 minuti

I bot Telegram sono uno strumento fantastico per automazioni, notifiche e piccoli esperimenti. E la cosa migliore? Si possono creare in pochissimo tempo con Python!

📚 Cosa ti serve

  • Python 3.6+ installato
  • Un account Telegram
  • 5 minuti di tempo (e uno spritz 🍸)

🤖 Passo 1: Crea il bot su Telegram

  1. Apri Telegram e cerca @BotFather
  2. Invia il comando /newbot
  3. Scegli un nome per il bot (es. MioPrimoBot)
  4. Scegli un username (deve finire in "bot", es. mio_primo_bot)
  5. BotFather ti darà un token tipo: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Salva questo token – ti servirà tra un attimo!

📦 Passo 2: Installa la libreria

Apri il terminale e installa python-telegram-bot (la libreria più usata):

pip install python-telegram-bot

⚡ Passo 3: Il codice base

Crea un file bot.py e incolla questo codice:

import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# Token del bot (sostituisci con il tuo!)
TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"

# Abilita logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

# Comando /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Ciao! Sono un bot creato con Python 🐍\n"
        "Prova i comandi:\n"
        "/help - per vedere cosa so fare\n"
        "/spritz - la ricetta segreta"
    )

# Comando /help
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "So fare queste cose:\n"
        "• /start - messaggio di benvenuto\n"
        "• /help - questo messaggio\n"
        "• /spritz - ricetta spritz\n"
        "• /codice - motto del developer"
    )

# Comando /spritz
async def spritz(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "🍸 Ricetta dello spritz perfetto:\n"
        "3 parti Prosecco\n"
        "2 parti Aperol\n"
        "1 parte soda\n"
        "Ghiaccio, arancia e oliva\n"
        "Mescola e buon aperitivo!"
    )

# Comando /codice
async def codice(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("💻 Il buon codice è come una buona ricetta: equilibrato, pulito e va condiviso!")

# Avvio del bot
def main():
    app = Application.builder().token(TOKEN).build()
    
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("help", help_command))
    app.add_handler(CommandHandler("spritz", spritz))
    app.add_handler(CommandHandler("codice", codice))
    
    print("🤖 Bot avviato! Premi Ctrl+C per fermarlo")
    app.run_polling()

if __name__ == "__main__":
    main()

🚀 Passo 4: Avvia il bot

Nel terminale, esegui:

python bot.py

Ora apri Telegram, cerca il tuo bot (l'username che hai scelto) e invia /start! 🎉

💡 Idee per espandere il bot

  • Webhook: collega il bot a un sito per ricevere notifiche
  • Bot che fa foto: integra con API come NASA o meteo
  • Bot admin: gestisci un gruppo (benvenuti, ban, mute)
  • Bot reminder: che ti ricorda di fare una pausa ogni ora

📌 Suggerimenti

  • Metti il token in una variabile d'ambiente, non hardcoded!
  • Usa python-telegram-bot v20+ (asincrono) – è più moderno
  • Per bot complessi, dividi il codice in moduli
  • Pubblica il bot su un server (es. PythonAnywhere, Heroku) così resta sempre acceso

🤖 Ora tocca a te: cosa ci costruirai? 🐍

#python #telegram #bot #hackerolspritz #coding