Move more stuff from other places into Omnibot.Core

* Present rooms are tracked by Omnibot.Core now, instead of
  Omnibot.State
* Channel synchronization is done through Omnibot.Core instead of
  Omnibot.Irc
* Add Omnibot.Module.on_init/1 callback, which returns a "state" value
  for the module to keep track of. By default, the state is nil.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2020-06-13 18:45:02 -04:00
parent 91cdd9cae8
commit 4000528d81
4 changed files with 59 additions and 70 deletions

View File

@@ -2,42 +2,71 @@ defmodule Omnibot.Core do
use Omnibot.Module
alias Omnibot.State
@impl true
def on_join(irc, channel, nick) do
cfg = State.cfg()
if nick == cfg.nick do
State.add_channel(channel)
add_channel(channel)
# Sync if we join a channel we shouldn't be in
if !Enum.member?(State.all_channels(), channel),
do: Irc.sync_channels(irc)
do: sync_channels(irc)
end
end
@impl true
def on_part(irc, channel, nick) do
cfg = State.cfg()
if nick == cfg.nick do
State.remove_channel(channel)
remove_channel(channel)
# Sync if we join a channel we forcibly part a channel we shouldn't leave
if Enum.member?(State.all_channels(), channel),
do: Irc.sync_channels(irc)
do: sync_channels(irc)
end
end
@impl true
def on_kick(irc, channel, _nick, target) do
cfg = State.cfg()
if target == cfg.nick do
State.remove_channel(channel)
remove_channel(channel)
# Generally, being kicked is not intentionally leaving a channel, so always sync here
Irc.sync_channels(irc)
sync_channels(irc)
end
end
@impl true
def on_msg(irc, msg) do
case String.upcase(msg.command) do
"001" -> Irc.sync_channels(irc)
"001" -> sync_channels(irc)
"PING" -> Irc.send_msg(irc, "PONG", msg.params)
_ -> route_msg(irc, msg)
end
end
@impl true
def on_init(_cfg) do
MapSet.new()
end
defp sync_channels(irc) do
desired = MapSet.new(State.all_channels())
present = state()
to_join = MapSet.difference(desired, present)
|> MapSet.to_list()
to_part = MapSet.difference(present, desired)
|> MapSet.to_list()
Enum.each(to_join, fn channel -> Irc.join(irc, channel) end)
Enum.each(to_part, fn channel -> Irc.part(irc, channel) end)
end
defp add_channel(channel) do
update_state(fn state -> MapSet.put(state, channel) end)
end
defp remove_channel(channel) do
update_state(fn state -> MapSet.delete(state, channel) end)
end
end