Crea un bot in Python

Questa guida scrive un bot che pubblica su Bluesky con atproto, l’SDK Python della community. Richiede Python 3.9 o successivo.

1. Crea una password per app

Accedi a Bluesky come il bot, poi apri Impostazioni → Privacy e sicurezza → Password per app e creane una. Un bot accede con una password per app, mai con la password principale dell’account.

2. Prepara il progetto

bash
mkdir my-bot && cd my-bot
python -m venv .venv
source .venv/bin/activate
pip install atproto

Tieni le credenziali fuori dal codice:

bash
export BLUESKY_HANDLE="weather.bluesky.bot"
export BLUESKY_APP_PASSWORD="xxxx-xxxx-xxxx-xxxx"

3. Scrivi il bot

bot.py
# bot.py: pubblica una volta come il bot. Eseguilo con `python bot.py`.
import os

from atproto import Client, client_utils

# L’account del bot stesso, con accesso tramite una password per app
# (Impostazioni > Privacy e sicurezza > Password per app),
# mai con la sua password principale.
handle = os.environ.get("BLUESKY_HANDLE")
password = os.environ.get("BLUESKY_APP_PASSWORD")
if not handle or not password:
    raise SystemExit("Set BLUESKY_HANDLE and BLUESKY_APP_PASSWORD.")

client = Client()
client.login(handle, password)

# TextBuilder rende cliccabili il link e l’hashtag.
text = (
    client_utils.TextBuilder()
    .text("Today: sunny, 21°C. Forecast at ")
    .link("example.com", "https://example.com")
    .text(" ")
    .tag("#weather", "weather")
)

post = client.send_post(text)
print(f"Posted {post.uri}")

Cosa fa:

  • Client() comunica con https://bsky.social per impostazione predefinita. Per un server self-hosted, passa il suo URL: Client("https://pds.example.com").
  • login apre una sessione con l’handle e la password per app.
  • TextBuilder costruisce il testo e i facet che rendono cliccabili il link e l’hashtag.
  • send_post crea il post; il suo uri è l’indirizzo at:// del post.

4. Eseguilo

bash
python bot.py

Passi successivi

Usa l’Esploratore di repository per vedere i record pubblici scritti dal tuo bot: collezioni, singoli record JSON e CID, direttamente dal suo PDS, senza accedere.