Skip to content

Errors

Exception hierarchy for Moonlygram.

Every exception raised by the library derives from MoonlygramError, so except MoonlygramError catches all of them. The two branches below it are APIError (Telegram replied with ok: false, so there is an error_code) and NetworkError (the request never produced a reply — a transport failure).

Telegram's HTTP status codes map to named APIError subclasses so callers can branch on the kind of failure without inspecting error_code by hand::

try:
    await bot.send_message(chat_id, text)
except Forbidden:
    ...  # the bot was blocked or kicked
except BadRequest:
    ...  # malformed request

MoonlygramError

Bases: Exception

Base class for every error Moonlygram raises.

InvalidToken

Bases: MoonlygramError

The bot token is missing or malformed before any request was made.

NetworkError

Bases: MoonlygramError

The request failed at the transport layer, with no reply from Telegram.

Wraps the underlying httpx error (connection refused, DNS failure, a dropped connection); the original is available as __cause__.

TimedOut

Bases: NetworkError

The request did not complete before the timeout elapsed.

APIError

Bases: MoonlygramError

Telegram replied with ok: false.

Exposes the response fields so callers can branch on error_code. Named subclasses cover the common HTTP status codes.

BadRequest

Bases: APIError

400 — the request was malformed or referred to something that is gone.

Unauthorized

Bases: APIError

401 — the bot token is missing, malformed, or revoked.

Forbidden

Bases: APIError

403 — the bot lacks rights for the action (blocked, kicked, no admin).

NotFound

Bases: APIError

404 — the method or resource does not exist.

Conflict

Bases: APIError

409 — conflicting state, e.g. polling while a webhook is set.

FloodWait

Bases: APIError

429 — you're being rate-limited and must wait retry_after seconds.

ChatMigrated

Bases: APIError

The group migrated to a supergroup with id migrate_to_chat_id.

Telegram returns this as a 400; resend to the new id.

error_from_response

error_from_response(error_code: int, description: str, method: str, parameters: Optional[dict[str, Any]] = None) -> APIError

Build the most specific APIError for an ok: false response.

Used by the Session to turn {error_code, description, parameters} into a named exception. retry_after and migrate_to_chat_id, when present in parameters, win over the plain status-code mapping.