summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/seen_plugin.ex
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--lib/lsg_irc/seen_plugin.ex58
1 files changed, 58 insertions, 0 deletions
diff --git a/lib/lsg_irc/seen_plugin.ex b/lib/lsg_irc/seen_plugin.ex
new file mode 100644
index 0000000..8b2178f
--- /dev/null
+++ b/lib/lsg_irc/seen_plugin.ex
@@ -0,0 +1,58 @@
+defmodule LSG.IRC.SeenPlugin do
+ @moduledoc """
+ # seen
+
+ * **!seen `<nick>`**
+ """
+
+ def irc_doc, do: @moduledoc
+ def start_link() do
+ GenServer.start_link(__MODULE__, [])
+ end
+
+ def init([]) do
+ {:ok, _} = Registry.register(IRC.PubSub, "triggers", [])
+ {:ok, _} = Registry.register(IRC.PubSub, "message", [])
+ dets_filename = (LSG.data_path() <> "/seen.dets") |> String.to_charlist()
+ {:ok, dets} = :dets.open_file(dets_filename, [])
+ {:ok, %{dets: dets}}
+ end
+
+ def handle_info({:irc, :trigger, "seen", m = %IRC.Message{trigger: %IRC.Trigger{type: :bang, args: [nick]}}}, state) do
+ witness(m, state)
+ m.replyfun.(last_seen(m.channel, nick, state))
+ {:noreply, state}
+ end
+
+ def handle_info({:irc, :trigger, _, m}, state) do
+ witness(m, state)
+ {:noreply, state}
+ end
+
+ def handle_info({:irc, :text, m}, state) do
+ witness(m, state)
+ {:noreply, state}
+ end
+
+ defp witness(%IRC.Message{channel: channel, text: text, sender: %{nick: nick}}, %{dets: dets}) do
+ :dets.insert(dets, {{channel, nick}, DateTime.utc_now(), text})
+ :ok
+ end
+
+ defp last_seen(channel, nick, %{dets: dets}) do
+ case :dets.lookup(dets, {channel, nick}) do
+ [{_, date, text}] ->
+ diff = round(DateTime.diff(DateTime.utc_now(), date)/60)
+ cond do
+ diff >= 30 ->
+ duration = Timex.Duration.from_minutes(diff)
+ format = Timex.Format.Duration.Formatter.lformat(duration, "fr", :humanized)
+ "#{nick} a parlé pour la dernière fois il y a #{format}: “#{text}”"
+ true -> "#{nick} est là..."
+ end
+ [] ->
+ "je ne connais pas de #{nick}"
+ end
+ end
+
+end