Packages

Elixir bot framework for Mattermost

Current section

Files

Jump to
mattermost lib mattermost plug.ex
Raw

lib/mattermost/plug.ex

defmodule Mattermost.Plug do
@moduledoc """
A plug for receiving Mattermost slash command webhooks.
Mount this inside your Phoenix router. The `:handler` option is the module
implementing `Mattermost.Bot`.
# lib/my_app_web/router.ex
scope "/agent" do
forward "/commands", Mattermost.Plug, handler: MyApp.Bot
end
Then in Mattermost, set each slash command's Request URL to:
https://your-domain.com/agent/commands/TRIGGER_WORD
The last path segment becomes the `command` argument in `handle_command/3`.
Mattermost POSTs form-encoded params: `text`, `channel_id`, `user_id`,
`user_name`, `team_id`, etc.
"""
@behaviour Plug
import Plug.Conn
require Logger
@impl Plug
def init(opts), do: opts
@impl Plug
def call(conn, opts) do
handler = Keyword.fetch!(opts, :handler)
conn = Plug.Parsers.call(conn, Plug.Parsers.init(parsers: [:urlencoded], pass: ["*/*"]))
params = conn.body_params
command = List.last(conn.path_info)
text = params["text"] || ""
channel_id = params["channel_id"]
user_id = params["user_id"]
Logger.debug("[Mattermost.Plug] /#{command} from user #{user_id}")
ctx = %Mattermost.Context{
config: Mattermost.from_env(),
channel_id: channel_id,
user_id: user_id,
post: nil
}
safe_dispatch(handler, command, text, ctx)
conn
|> put_resp_content_type("application/json")
|> send_resp(200, "{}")
end
defp safe_dispatch(handler, command, text, ctx) do
handler.handle_command(command, text, ctx)
rescue
error ->
Logger.error("[Mattermost.Plug] Error in #{handler}.handle_command/3: #{inspect(error)}")
end
end