aboutsummaryrefslogtreecommitdiff
path: root/lib/consumer.ex
blob: 406ddeb235213915657e4f1f090db6e2245e0604 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require Logger

defmodule Thulani.DiscordConsumer do
  use Nostrum.Consumer

  @spec handle_event(Nostrum.Consumer.message_create()) :: nil

  def handle_event({
        :MESSAGE_CREATE,
        msg,
        _ws_state
      }) do
    unless msg.author.bot do
      case Nosedrum.TextCommand.Invoker.Split.handle_message(msg) do
        {:error, {:unknown_subcommand, name, :known, known}} ->
          Logger.error("unknown subcommand", name: name, known: known)

        {:error, other} ->
          Logger.error("unknown error", data: other)

        {:ok, data} ->
          Logger.info("handled command ok", data: data)

        other ->
          Logger.warning("unhandled textcommand case", result: other)
      end
    end
  end

  def handle_event({
        :READY,
        data,
        _ws_state
      }) do
    Logger.info("bot ready", data: data)

    commands()
    |> Stream.flat_map(fn command_mod ->
      apply(command_mod, :aliases, [])
      |> Stream.zip(Stream.cycle([command_mod]))
    end)
    |> Stream.each(fn {name, mod} ->
      :ok = Nosedrum.TextCommand.Storage.ETS.add_command([name], mod)
      Logger.info("registered command", command_name: name, mod: mod)
    end)
    |> Stream.run()
  end

  def handle_event(_event), do: :noop

  defp commands,
    do: [
      Thulani.Command.Meme,
      Thulani.Command.AddMeme
    ]
end