Current section
Files
Jump to
Current section
Files
lib/telegex/plug/presets/commander.ex
defmodule Telegex.Plug.Presets.Commander do
@moduledoc """
Command processing plug-in.
"""
@typedoc "Match results."
@type match_result :: {:match | :nomatch, Telegex.Plug.state()}
defmacro __using__(command) when is_atom(command) do
quote do
use Telegex.Plug
@behaviour Telegex.Plug.Presets.Commander
@command "/#{unquote(command)}"
@impl true
def __preset__, do: :commander
unquote(def_match())
unquote(def_ignore_calls())
@impl true
def call(%{message: %{text: text} = message} = _update, state) do
case match(text, state) do
{:match, state} ->
handle(message, state)
{:nomatch, state} ->
{:ignored, state}
end
end
defoverridable match: 2
end
end
defp def_match do
quote do
@impl true
def match(text, state) do
if text == @command || text == "#{@command}@#{Telegex.Plug.get_usename()}" do
{:match, state}
else
{:nomatch, state}
end
end
end
end
defp def_ignore_calls do
quote do
@impl true
def call(%{message: nil} = _update, state), do: {:ignored, state}
@impl true
def call(%{message: %{text: nil}} = _update, state), do: {:ignored, state}
end
end
@doc """
Match commands.
This function can be automatically generated by `use` this module.
"""
@callback match(text :: String.t(), state :: Telegex.Plug.state()) :: match_result()
@doc """
Handle commands.
"""
@callback handle(message :: Telegex.Model.Message.t(), state :: Telegex.Plug.state()) ::
Telegex.Plug.stateful()
end