Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
erl_crash.dump
*.ez
/rel/
/.elixir_ls/
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ log you into matrix.org and you can play around with your bot.

The package can be installed as:

1. Add bender to your list of dependencies in `mix.exs`:
1. Add bender to your list of dependencies in `mix.exs`:

def deps do
[{:bender, git: "https://github.com/DylanGriffith/bender.git"}]
end
def deps do
[{:bender, git: "https://github.com/DylanGriffith/bender.git"}]
end

2. Ensure bender is started before your application:
2. Ensure bender is started before your application:

def application do
[applications: [:bender]]
end
def application do
[applications: [:bender]]
end
3 changes: 3 additions & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ use Mix.Config
config :bender,
command_prefix: "bender",
matrix_home_server: "matrix.org",
matrix_home_server_protocol: "https",
matrix_home_server_port: "443",
matrix_user: "bender",
matrix_password: "bender",
commands: [Bender.Commands.Echo, Bender.Commands.Ping],
event_reactions: [],
room_names: ["#bender:matrix.org"]

#
Expand Down
20 changes: 15 additions & 5 deletions lib/bender.ex
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
defmodule Bender do
use Application

# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false

home_server = Application.get_env(:bender, :matrix_home_server)
home_server_protocol = Application.get_env(:bender, :matrix_home_server_protocol, "https")
home_server_port = Application.get_env(:bender, :matrix_home_server_port, "443")
user = Application.get_env(:bender, :matrix_user)
password = Application.get_env(:bender, :matrix_password)
room_names = Application.get_env(:bender, :room_names)
commands = Application.get_env(:bender, :commands)
event_reactions = Application.get_env(:bender, :event_reactions)

children = [
worker(Bender.Bot, [%Matrix.Config{home_server: home_server, user: user, password: password}, room_names, commands]),
worker(Bender.Bot, [
%Matrix.Config{
home_server: home_server,
user: user,
password: password,
home_server_protocol: home_server_protocol,
home_server_port: home_server_port
},
room_names,
commands,
event_reactions
])
]

# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Bender.Supervisor]
Supervisor.start_link(children, opts)
end
Expand Down
109 changes: 80 additions & 29 deletions lib/bender/bot.ex
Original file line number Diff line number Diff line change
@@ -1,66 +1,117 @@
defmodule Bender.Bot do
use GenServer

def start_link(config = %Matrix.Config{}, room_names, commands) do
GenServer.start_link(__MODULE__, [config, room_names, commands], name: __MODULE__)
require Logger

def start_link(config = %Matrix.Config{}, room_names, commands, event_reactions) do
config |> IO.inspect()

GenServer.start_link(__MODULE__, [config, room_names, commands, event_reactions],
name: __MODULE__
)
|> IO.inspect()
end

def init([config = %Matrix.Config{}, room_names, commands]) do
event_manager = setup_event_manager(commands)
def init([config = %Matrix.Config{}, room_names, commands, event_reactions]) do
event_manager = setup_event_manager(commands, event_reactions)

# Login
session = Matrix.Client.login!(config)
session = Matrix.Client.login!(config) |> IO.inspect()

Logger.debug(fn -> "Login Result (Session): #{inspect(session, pretty: true)}" end)

# Join Rooms
rooms = Enum.map room_names, fn(room_name) ->
Matrix.Client.join!(session, room_name)
end
rooms =
Enum.map(room_names, fn room_name ->
Matrix.Client.join!(session, room_name)
end)

Logger.debug(fn -> "Rooms: #{inspect(rooms, pretty: true)}" end)

# Trigger first poll for events
GenServer.cast(self, :poll_matrix)
{:ok, %{session: session, rooms: rooms, event_manager: event_manager, from: nil, commands: commands}}
GenServer.cast(self(), :poll_matrix)

{:ok,
%{
session: session,
rooms: rooms,
event_manager: event_manager,
from: nil,
commands: commands,
event_reactions: event_reactions
}}
end

def handle_cast(:poll_matrix, state = %{session: session = %Matrix.Session{}, event_manager: event_manager, from: from}) do
# this call primarily exists to allow an optional eval command to modify the
# bot during runtime
def handle_call({:set_state, new_state}, _from, state),
do: {:reply, {state, new_state}, new_state}

def handle_call(:get_state, _from, state), do: {:reply, state, state}

def handle_cast(
:poll_matrix,
state = %{session: session = %Matrix.Session{}, event_manager: event_manager, from: from}
) do
# Get latest events
events = Matrix.Client.events!(session, from)

state = Dict.put state, :from, events.endd
state = Map.put(state, :from, events.endd)

Logger.debug(fn -> "Matrix Events: #{inspect(events, pretty: true)}" end)

# Dispatch events
Enum.each(events.events, fn event ->
GenEvent.notify(
event_manager,
{:matrix_event, {session, event}}
)
end)

# Extract commands
command_events = (events.events
|> Enum.reject(fn (e) -> e.user && e.user.user_id == session.user_id end)
|> Enum.filter(fn (e) -> e.type == "m.room.message" end)
|> Enum.filter(fn (e) -> e.content.msg_type == "m.text" end)
|> Enum.map(fn (e) -> {Bender.Parser.try_parse(e.content.body), e} end)
|> Enum.filter(fn ({c, _e}) -> !is_nil(c) end))
command_events =
events.events
|> Enum.reject(fn e -> e.user && e.user.user_id == session.user_id end)
|> Enum.filter(fn e -> e.type == "m.room.message" end)
|> Enum.filter(fn e -> e.content.msg_type == "m.text" end)
|> Enum.map(fn e -> {Bender.Parser.try_parse(e.content.body), e} end)
|> Enum.filter(fn {c, _e} -> !is_nil(c) end)

# Dispatch commands
Enum.each command_events, fn ({command, event}) ->
GenEvent.notify(event_manager, {command, %{session: session, room: event.room, author: event.user}})
end
Enum.each(command_events, fn {command, event} ->
GenEvent.notify(
event_manager,
{command, %{session: session, room: event.room, author: event.user}}
)
end)

# Poll again for events
GenServer.cast(self, :poll_matrix)
GenServer.cast(self(), :poll_matrix)

{:noreply, state}
end

def handle_info({:gen_event_EXIT, _, _}, state = %{commands: commands}) do
state = Dict.put(state, :event_manager, setup_event_manager(commands))
def handle_info(
{:gen_event_EXIT, _, _},
state = %{commands: commands, event_reactions: event_reactions}
) do
state = Map.put(state, :event_manager, setup_event_manager(commands, event_reactions))
{:noreply, state}
end

def setup_event_manager(commands) do
def setup_event_manager(commands, event_reactions) do
# Start the GenEvent manager
{:ok, event_manager} = GenEvent.start_link
{:ok, event_manager} = GenEvent.start_link()

Process.monitor(event_manager)

Enum.each commands, fn(c) ->
:ok = GenEvent.add_mon_handler(event_manager, c, self)
end
Enum.each(commands, fn c ->
:ok = GenEvent.add_mon_handler(event_manager, c, self())
end)

Enum.each(event_reactions, fn er ->
:ok = GenEvent.add_mon_handler(event_manager, er, self())
end)

event_manager
end
Expand Down
6 changes: 4 additions & 2 deletions lib/bender/command.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ defmodule Bender.Command do

defmacro __before_compile__(_env) do
quote do

if Module.get_attribute(__MODULE__, :usage) && Module.get_attribute(__MODULE__, :short_description) do
if Module.get_attribute(__MODULE__, :usage) &&
Module.get_attribute(__MODULE__, :short_description) do
def handle_event({{:command, "help", ""}, meta}, parent) do
message = get_help_message(@usage, @short_description)

if message do
respond(message, meta)
end

{:ok, parent}
end
end
Expand Down
24 changes: 24 additions & 0 deletions lib/bender/event_reaction.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
defmodule Bender.EventReaction do
defmacro __using__(_opts) do
quote do
@before_compile unquote(__MODULE__)
use GenEvent

def respond(message, {session, %{room: room}}) do
Matrix.Client.post!(session, room, message)
end
end
end

defmacro __before_compile__(_env) do
quote do
def handle_event(_, parent) do
{:ok, parent}
end

def get_help_message(description) do
"#{inspect(__MODULE__)}: #{description}"
end
end
end
end
15 changes: 14 additions & 1 deletion lib/bender/parser.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
defmodule Bender.Parser do
require Logger

def try_parse(message, command_prefix \\ Application.get_env(:bender, :command_prefix)) do
match = Regex.named_captures(~r/^\s*@?#{command_prefix}:?\s+(?<command>[\w-]+)\s*(?<message>.*)/i, message)
match =
Regex.named_captures(
~r/^#{command_prefix}:?\s*(?<command>[\w-]+)\s*(?<message>.*)/sim,
message
)

Logger.debug(fn ->
"Bender.Parser.try_parse() - Event ({msg, regex_match}): #{
inspect({message, match}, pretty: true)
}"
end)

if match && match["command"] do
{:command, match["command"], match["message"]}
else
Expand Down
Loading