Current section
Files
Jump to
Current section
Files
lib/mattermost.ex
defmodule Mattermost do
@moduledoc """
Elixir bot framework for Mattermost.
See `Mattermost.Bot` for the full guide, or jump straight in:
## Quickstart
# config/runtime.exs
config :mattermost,
base_url: "https://your-mattermost.com",
token: System.get_env("MM_TOKEN"),
bot_user_id: System.get_env("MM_BOT_USER_ID")
# lib/my_app/bot.ex
defmodule MyApp.Bot do
use Mattermost.Bot
def handle_message(%Mattermost.Post{text: "ping"}, ctx) do
Mattermost.API.reply(ctx, "pong")
end
def handle_command("deploy", env, ctx) do
Mattermost.API.reply(ctx, "Deploying to \#{env}...")
end
end
# lib/my_app/application.ex
children = [MyApp.Bot]
# lib/my_app_web/router.ex
scope "/agent" do
forward "/commands", Mattermost.Plug, handler: MyApp.Bot
end
## Authentication
Uses Personal Access Tokens (PAT).
Generate one in Mattermost under **Profile → Security → Personal Access Tokens**.
"""
use TypedStruct
typedstruct enforce: true do
@typedoc "Mattermost connection config. Build with `Mattermost.new/1` or `Mattermost.from_env/0`."
field(:base_url, String.t())
field(:token, String.t())
field(:bot_user_id, String.t())
end
@doc """
Builds a `%Mattermost{}` config struct from keyword options.
iex> Mattermost.new(
...> base_url: "https://mm.example.com",
...> token: "my-token",
...> bot_user_id: "user123"
...> )
"""
@spec new(keyword()) :: t()
def new(opts), do: struct!(__MODULE__, opts)
@doc """
Builds a `%Mattermost{}` config from the `:mattermost` application environment.
Reads `:base_url`, `:token`, and `:bot_user_id` from `Application.get_env/2`.
# config/runtime.exs
config :mattermost,
base_url: "https://your-mattermost.com",
token: System.get_env("MM_TOKEN"),
bot_user_id: System.get_env("MM_BOT_USER_ID")
"""
@spec from_env() :: t()
def from_env do
new(
base_url: Application.fetch_env!(:mattermost, :base_url),
token: Application.fetch_env!(:mattermost, :token),
bot_user_id: Application.fetch_env!(:mattermost, :bot_user_id)
)
end
end