Nadia.Dispatcher (nadia v1.3.0)

View Source

Lightweight dispatch helpers for incoming Telegram updates.

The behaviour-first path dispatches a parsed update to a module implementing Nadia.Handler:

Nadia.Dispatcher.dispatch(update, MyApp.Bot, client: client)

For small bots or tests, an ordered route list can match commands, message text, callback data, and fallback updates without a macro DSL:

routes = [
  {:command, "start", &MyApp.Bot.start/1},
  {:text, ~r/^echo\s+(.+)/, &MyApp.Bot.echo/2},
  {:callback, {:prefix, "confirm:"}, &MyApp.Bot.confirm/1},
  {:fallback, &MyApp.Bot.fallback/1}
]

Nadia.Dispatcher.dispatch(update, routes)

dispatch/3 returns the handler or route action result unchanged. If the handler or action raises, the exception bubbles to the caller.

Summary

Functions

Dispatches an update or context to a handler module or ordered route list.

Matches callback query data.

Matches a message command such as /start or /start arg.

Matches the effective message text.

Types

action()

@type action() ::
  (Nadia.Context.t() -> term())
  | (Nadia.Context.t(), map() -> term())
  | {module(), atom()}

dispatchable()

@type dispatchable() :: Nadia.Model.Update.t() | Nadia.Context.t()

route()

@type route() ::
  {:command, binary() | Regex.t(), action()}
  | {:text, binary() | Regex.t(), action()}
  | {:callback, binary() | {:prefix, binary()} | Regex.t(), action()}
  | {:fallback, action()}

Functions

dispatch(update_or_context, handler_or_routes, client_or_opts \\ [])

@spec dispatch(
  dispatchable(),
  module() | [route()],
  keyword() | map() | Nadia.Client.t() | nil
) ::
  term()

Dispatches an update or context to a handler module or ordered route list.

When dispatching a %Nadia.Model.Update{}, the third argument is passed to Nadia.Context.new/2, so %Nadia.Client{} values and client: client options are preserved in the context.

match_callback(update_or_context, pattern)

@spec match_callback(dispatchable(), binary() | {:prefix, binary()} | Regex.t()) ::
  {:ok, map()} | :nomatch

Matches callback query data.

String matchers require exact data equality. {:prefix, value} matchers keep common callback namespaces like "confirm:" concise. Regex matchers return captures in the match metadata.

match_command(update_or_context, command, opts \\ [])

@spec match_command(dispatchable(), binary() | Regex.t(), keyword() | map()) ::
  {:ok, map()} | :nomatch

Matches a message command such as /start or /start arg.

String matchers compare the command name without the leading slash and without any @botname suffix. Commands with a bot suffix match only when :bot_username is provided and matches that suffix. Regex matchers run against the normalized command name.

match_text(update_or_context, pattern)

@spec match_text(dispatchable(), binary() | Regex.t()) :: {:ok, map()} | :nomatch

Matches the effective message text.

String matchers require exact text equality. Regex matchers return captures in the match metadata.