Skip to content

Application & handlers

Application

moonlygram.ext.Application

builder staticmethod

builder() -> 'ApplicationBuilder'

Return a builder for the Application.builder().token(...).build() idiom.

add_handler

add_handler(handler: BaseHandler, group: int = 0) -> None

Register a handler in a group.

Groups run in ascending order; within a group only the first matching handler runs.

add_error_handler

add_error_handler(callback: Callback) -> None

Register a callback to handle exceptions raised during dispatch.

The callback receives (update, context) with the offending exception on context.error. Several may be registered; all run. With none registered the error is logged and processing continues, as before.

initialize async

initialize() -> None

Confirm the token, cache the bot's own user, and load persisted state.

Fails fast on a bad token.

shutdown async

shutdown() -> None

Stop jobs, flush persisted state (if any), and close the HTTP session.

update_persistence async

update_persistence() -> None

Flush bot/chat/user data and conversation state to persistence.

process_update async

process_update(update: Update) -> None

Dispatch one update through the handler groups.

Groups run in ascending order; within a group the first matching handler runs and the rest of that group is skipped. A handler may raise ApplicationHandlerStop to halt all processing; other exceptions are sent to the registered error handlers (or logged) and do not stop the remaining groups. A non-blocking handler (block=False) is run as a background task so later groups are not delayed by it; it cannot halt processing.

start_polling async

start_polling() -> None

Poll getUpdates and dispatch updates until stop() is called.

This is the async primitive; await it directly or gather it with other coroutines. It does not initialize or shut down the bot.

run_polling

run_polling() -> None

Run the bot until interrupted. Blocking; owns and closes the event loop.

feed_webhook_update async

feed_webhook_update(data: dict[str, Any] | Update) -> None

Parse a raw webhook update (or an Update) and dispatch it.

Use this to wire Moonlygram into your own web framework instead of the built-in webhook server.

run_webhook

run_webhook(*, listen: str = '127.0.0.1', port: int = 8443, url_path: str = '', secret_token: Optional[str] = None, webhook_url: Optional[str] = None, allowed_updates: Optional[list[str]] = None) -> None

Run a webhook server until interrupted. Blocking; owns the event loop.

start_webhook async

start_webhook(*, listen: str = '127.0.0.1', port: int = 8443, url_path: str = '', secret_token: Optional[str] = None, webhook_url: Optional[str] = None, allowed_updates: Optional[list[str]] = None) -> None

Serve updates over a webhook until stop() is called.

A minimal HTTP server accepts Telegram's POSTs, validates the request path and optional secret token, and dispatches updates concurrently. If webhook_url is given, setWebhook is called first. This is the async primitive; it does not initialize or shut down the bot.

stop

stop() -> None

Signal the polling loop to finish and unwind.

moonlygram.ext.ApplicationBuilder

Fluent builder mirroring python-telegram-bot's Application.builder().

token

token(token: str) -> 'ApplicationBuilder'

Set the bot token.

base_url

base_url(base_url: str) -> 'ApplicationBuilder'

Override the Bot API base URL (for a local Bot API server).

poll_timeout

poll_timeout(seconds: int) -> 'ApplicationBuilder'

Set the long-polling timeout passed to getUpdates.

allowed_updates

allowed_updates(allowed_updates: list[str]) -> 'ApplicationBuilder'

Limit which update types Telegram sends (see the getUpdates docs).

defaults

defaults(defaults: Defaults) -> 'ApplicationBuilder'

Set default parameter values applied to outgoing Bot API calls.

persistence

persistence(persistence: BasePersistence) -> 'ApplicationBuilder'

Set the persistence backend for bot/chat/user data and conversations.

job_queue

job_queue(job_queue: Optional[JobQueue]) -> 'ApplicationBuilder'

Set the JobQueue, or pass None to disable scheduled jobs.

When left unset, the Application gets a default JobQueue.

rate_limiter

rate_limiter(rate_limiter: Any) -> 'ApplicationBuilder'

Set a BaseRateLimiter to pace outgoing Bot API calls.

arbitrary_callback_data

arbitrary_callback_data(value: bool | int = True) -> 'ApplicationBuilder'

Enable non-string callback_data on inline buttons.

Pass True for the default cache size, an int to set it, or False to disable.

concurrent_updates

concurrent_updates(value: bool | int) -> 'ApplicationBuilder'

Process updates concurrently: True (a default cap), an int cap, or False.

context_types

context_types(context_types: ContextTypes) -> 'ApplicationBuilder'

Set custom types for the context object and its data dictionaries.

post_init

post_init(callback: LifecycleHook) -> 'ApplicationBuilder'

Set a coroutine run after initialize() but before the update loop starts.

It receives the Application; use it to set bot commands, warm caches, or open resources. Runs only under run_polling()/run_webhook().

post_stop

post_stop(callback: LifecycleHook) -> 'ApplicationBuilder'

Set a coroutine run after the update loop stops but before shutdown().

post_shutdown

post_shutdown(callback: LifecycleHook) -> 'ApplicationBuilder'

Set a coroutine run after shutdown() completes.

build

build() -> Application

Construct the Application from the configured settings.

Context

moonlygram.ext.CallbackContext

Per-update context handed to every handler callback.

Carries the Bot, any command arguments parsed by the handler, and three dictionaries for sharing state across handlers: bot_data is shared by all updates, while chat_data and user_data are scoped to the update's chat and sender. Inside an error handler, error holds the exception that was raised. Inside a job callback, job holds the running Job.

moonlygram.ext.ContextTypes

Pluggable types for the context object and its data dictionaries.

Pass an instance to the builder's context_types(...) to swap in a CallbackContext subclass, or to make bot_data/chat_data/user_data something other than plain dicts (any zero-argument callable returning a mapping). The Application uses these factories when it creates per-update contexts and when it allocates the data stores.

Handlers

moonlygram.ext.CommandHandler

Bases: BaseHandler

Run the callback when a message starts with /name or /name@botusername.

Pass a single command name or a list of names; context.args holds the whitespace-separated tokens that follow the command.

moonlygram.ext.MessageHandler

Bases: BaseHandler

Run the callback when a message passes the given filter.

moonlygram.ext.CallbackQueryHandler

Bases: BaseHandler

Run the callback on a callback query, optionally filtered by its data.

If pattern is given, the query's data must match it (re.search).

moonlygram.ext.ConversationHandler

Bases: BaseHandler

A per-conversation state machine layered over other handlers.

entry_points start a conversation; afterwards the update is routed to the handlers registered for the current state. A child callback's return value drives the transition: a state value moves there, ConversationHandler.END ends the conversation, and None keeps the current state. Conversations are keyed by (chat_id, user_id) by default; per_chat / per_user drop a dimension and per_message adds the message the update concerns (for keyboard-only flows).

conversation_timeout ends a conversation after that many seconds of inactivity, using a lightweight asyncio timer (no JobQueue dependency). When nested inside another ConversationHandler, map_to_parent maps a child return value to a parent state, ending the child and handing control back.

moonlygram.ext.TypeHandler

Bases: BaseHandler

Run the callback for every update, optionally narrowed by a predicate.

moonlygram.ext.PrefixHandler

Bases: BaseHandler

Run the callback when a message starts with a prefix plus command, e.g. !help.

Pass one or more prefixes and command names; context.args holds the tokens after the command.

Job queue, persistence, rate limiting

moonlygram.ext.JobQueue

Schedules Jobs against an Application's event loop.

set_application

set_application(application: 'Application') -> None

Attach the Application whose bot and data the jobs see.

jobs

jobs() -> list[Job]

Return the currently scheduled jobs.

get_jobs_by_name

get_jobs_by_name(name: str) -> list[Job]

Return scheduled jobs with the given name.

start

start() -> None

Launch any jobs scheduled before the queue was running.

stop async

stop() -> None

Cancel all jobs and wait for their tasks to unwind.

run_once

run_once(callback: JobCallback, when: TimeSpec, *, data: Any = None, name: Optional[str] = None, chat_id: Optional[int] = None, user_id: Optional[int] = None) -> Job

Run callback once after when (seconds, timedelta, or absolute datetime).

run_repeating

run_repeating(callback: JobCallback, interval: Union[float, timedelta], *, first: Optional[TimeSpec] = None, data: Any = None, name: Optional[str] = None, chat_id: Optional[int] = None, user_id: Optional[int] = None) -> Job

Run callback every interval, the first time after first (default interval).

run_daily

run_daily(callback: JobCallback, time: time, *, data: Any = None, name: Optional[str] = None, chat_id: Optional[int] = None, user_id: Optional[int] = None) -> Job

Run callback every day at the given local time.

run_monthly

run_monthly(callback: JobCallback, when: time, day: int, *, data: Any = None, name: Optional[str] = None, chat_id: Optional[int] = None, user_id: Optional[int] = None) -> Job

Run callback on the given day of every month at the given local time.

Months without that day (e.g. day 31 in February) are skipped.

moonlygram.ext.BasePersistence

Interface for loading and flushing Application state.

moonlygram.ext.AIORateLimiter

Bases: BaseRateLimiter

A token-bucket-style limiter: a global cap plus a per-chat cap.

Rates are expressed as max_rate calls per time_period seconds; the limiter spaces calls evenly to honour them. On a FloodWait it waits the requested time and retries, up to max_retries.

moonlygram.ext.CallbackDataCache

A bounded token-to-object store for arbitrary callback data.

put

put(obj: Any) -> str

Store an object and return the token that stands in for it.

get

get(token: str) -> Any

Return the object for a token (marking it recently used), or _MISSING.

process_keyboard

process_keyboard(markup: Any) -> Any

Rewrite non-string callback_data in an inline keyboard to tokens.

Other markup types, and buttons whose callback_data is already a string, are returned untouched. A rewritten keyboard is a fresh object, so the caller's original markup is never mutated.

process_callback_query

process_callback_query(query: Any) -> None

Swap a query's token data back to the stored object, in place.