summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/calc_plugin.ex
blob: 6e4e30c1e810f9c6dec41d2edb91f24fc20b1398 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
defmodule LSG.IRC.CalcPlugin do
  @moduledoc """
  # calc

  * **!calc `<expression>`**: évalue l'expression mathématique `<expression>`.
  """

  def irc_doc, do: @moduledoc

  def start_link() do
    GenServer.start_link(__MODULE__, [])
  end

  def init(_) do
    {:ok, _} = Registry.register(IRC.PubSub, "trigger:calc", [])
    {:ok, nil}
  end

  def handle_info({:irc, :trigger, "calc", message = %IRC.Message{trigger: %IRC.Trigger{type: :bang, args: expr_list}}}, state) do
    expr = Enum.join(expr_list, " ")
    result = try do
      case Abacus.eval(expr) do
        {:ok, result} -> result
        error -> inspect(error)
      end
    rescue
      error -> "#{error.message}"
    end
    message.replyfun.("#{message.sender.nick}: #{expr} = #{result}")
    {:noreply, state}
  end

  def handle_info(msg, state) do
    {:noreply, state}
  end

end