aboutsummaryrefslogtreecommitdiff
path: root/lib/command/meme.ex
blob: 50e8769c52c3270a922f1aa6ac19b010bcdfdf18 (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
alias Nosedrum.TextCommand.Predicates
alias Thulani.Command.Util
alias Thulani.Schema.Meme
alias Thulani.Schema.Image
# alias Thulani.Schema.Audio

defmodule Thulani.Command.Meme do
  @behaviour Nosedrum.TextCommand

  @impl true
  def aliases, do: ["meme"]

  @impl true
  def usage, do: ["meme <title:str>"]

  @impl true
  def predicates, do: [&Predicates.guild_only/1]

  @impl true
  def description, do: "post a random meme"

  @impl true
  def command(msg, args) do
    {:ok, meme} =
      Thulani.Repo.transaction(fn ->
        get(args)
        |> Thulani.Repo.one()
        |> Thulani.Repo.preload([:image, :audio, :metadata])
      end)

    meme = post(meme)
    msg |> Util.reply(meme)
  end

  defp get([]), do: Thulani.Meme.random(Thulani.Meme.any())
  defp get([name]), do: Thulani.Meme.by_name(name)

  @spec post(Meme.t()) :: Nostrum.Api.options()
  defp post(%Meme{
         content: content,
         image: image
       }) do
    [content: content] ++ post_image(image)
  end

  defp post_image(%Image{
         filename: filename,
         data: data
       }),
       do: [
         file: %{
           name: filename,
           body: data
         }
       ]

  defp post_image(_x), do: []
end