diff options
author | href <href@random.sh> | 2018-02-10 21:40:22 +0100 |
---|---|---|
committer | href <href@random.sh> | 2018-02-10 21:40:22 +0100 |
commit | 935a36eecc0faea60236101e11bc9f7cf1872686 (patch) | |
tree | b7b4358dee2eb3fc60681852f62c750ae8c05cb9 /lib/lsg_irc/youtube_handler.ex | |
parent | sse / embedded player (diff) |
update
Diffstat (limited to 'lib/lsg_irc/youtube_handler.ex')
-rw-r--r-- | lib/lsg_irc/youtube_handler.ex | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/lsg_irc/youtube_handler.ex b/lib/lsg_irc/youtube_handler.ex new file mode 100644 index 0000000..769f220 --- /dev/null +++ b/lib/lsg_irc/youtube_handler.ex @@ -0,0 +1,77 @@ +defmodule LSG.IRC.YouTubeHandler do + require Logger + + @moduledoc """ + # youtube + + !youtube <recherche> + !yt <recherche> + cherche sur youtube (seulement le premier résultat). + """ + + defstruct client: nil, dets: nil + + def irc_doc, do: @moduledoc + + def start_link(client) do + GenServer.start_link(__MODULE__, [client]) + end + + def init([client]) do + ExIRC.Client.add_handler(client, self()) + {:ok, %__MODULE__{client: client}} + end + + def handle_info({:received, "!youtube " <> query, sender, chan}, state) do + irc_search(query, chan, state) + {:noreply, state} + end + + def handle_info({:received, "!yt " <> query, sender, chan}, state) do + irc_search(query, chan, state) + {:noreply, state} + end + + def handle_info(info, state) do + {:noreply, state} + end + + defp irc_search(query, chan, state) do + case search(query) do + {:ok, %{"items" => [item | _]}} -> + title = get_in(item, ["snippet", "title"]) + url = "https://youtube.com/watch?v=" <> get_in(item, ["id", "videoId"]) + msg = "#{title} — #{url}" + ExIRC.Client.msg(state.client, :privmsg, chan, msg) + {:error, error} -> + ExIRC.Client.msg(state.client, :privmsg, chan, "Erreur YouTube: "<>error) + _ -> + nil + end + end + + defp search(query) do + query = query + |> String.strip + key = Application.get_env(:lsg, __MODULE__)[:api_key] + params = %{ + "key" => key, + "maxResults" => 1, + "part" => "snippet", + "safeSearch" => "none", + "type" => "video", + "q" => query, + } + url = "https://www.googleapis.com/youtube/v3/search" + case HTTPoison.get(url, [], params: params) do + {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> Jason.decode(body) + {:ok, %HTTPoison.Response{status_code: 400, body: body}} -> + Logger.error "YouTube HTTP 400: #{inspect body}" + {:error, "http 400"} + error -> + Logger.error "YouTube http error: #{inspect error}" + :error + end + end + +end |