summaryrefslogtreecommitdiff
path: root/lib/plugins/untappd.ex
blob: 5a4c070b6a2744b64bc2b1c75330c8379b5afc40 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
defmodule Nola.Plugins.Untappd do
  def irc_doc() do
    """
    # [Untappd](https://untappd.com)

    * `!beer <beer name>` Information about the first beer matching `<beer name>`
    * `?beer <beer name>` List the 10 firsts beer matching `<beer name>`

    _Note_: The best way to search is always "Brewery Name + Beer Name", such as "Dogfish 60 Minute".

    Link your Untappd account to the bot (for automated checkins on [alcoolog](#alcoolog), ...) with the `enable-untappd` command, in private.
    """
  end

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

  def init(_) do
    {:ok, _} = Registry.register(Nola.PubSub, "trigger:beer", plugin: __MODULE__)
    {:ok, %{}}
  end

  def handle_info(
        {:irc, :trigger, _, m = %Nola.Message{trigger: %{type: :bang, args: args}}},
        state
      ) do
    case Untappd.search_beer(Enum.join(args, " "), limit: 1) do
      {:ok, %{"response" => %{"beers" => %{"count" => count, "items" => [result | _]}}}} ->
        %{"beer" => beer, "brewery" => brewery} = result

        description =
          Map.get(beer, "beer_description")
          |> String.replace("\n", " ")
          |> String.replace("\r", " ")
          |> String.trim()

        beer_s =
          "#{Map.get(brewery, "brewery_name")}: #{Map.get(beer, "beer_name")} - #{Map.get(beer, "beer_abv")}°"

        city = get_in(brewery, ["location", "brewery_city"])

        location =
          [Map.get(brewery, "brewery_type"), city, Map.get(brewery, "country_name")]
          |> Enum.filter(fn x -> x end)
          |> Enum.join(", ")

        extra = "#{Map.get(beer, "beer_style")} - IBU: #{Map.get(beer, "beer_ibu")} - #{location}"
        m.replyfun.([beer_s, extra, description])

      err ->
        m.replyfun.("Error")
    end

    {:noreply, state}
  end

  def handle_info(
        {:irc, :trigger, _, m = %Nola.Message{trigger: %{type: :query, args: args}}},
        state
      ) do
    case Untappd.search_beer(Enum.join(args, " ")) do
      {:ok, %{"response" => %{"beers" => %{"count" => count, "items" => results}}}} ->
        beers =
          for %{"beer" => beer, "brewery" => brewery} <- results do
            "#{Map.get(brewery, "brewery_name")}: #{Map.get(beer, "beer_name")} - #{Map.get(beer, "beer_abv")}°"
          end
          |> Enum.intersperse(", ")
          |> Enum.join("")

        m.replyfun.("#{count}. #{beers}")

      err ->
        m.replyfun.("Error")
    end

    {:noreply, state}
  end

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