Skip to content

Instantly share code, notes, and snippets.

@dnet
Last active February 22, 2018 15:16
Show Gist options
  • Save dnet/4714364 to your computer and use it in GitHub Desktop.
Save dnet/4714364 to your computer and use it in GitHub Desktop.
YouTube title plugin for Erlang IRCbot
% depends: https://github.com/talentdeficit/jsx
-module(youtube).
-export([ircmain/1, ircproc/1, reload/2]).
-define(API_KEY, "GetYourOwnApiKeyFromGoogle").
query_gdata_feed(VID) ->
URL = "https://www.googleapis.com/youtube/v3/videos?part=snippet&"
"fields=items/snippet(channelTitle,title)&key=" ?API_KEY "&id=" ++ VID,
{ok, {_, _, JSON}} = httpc:request(get,
{URL, [{"User-Agent", "dehat-youtube"}]}, [], [{body_format, binary}]),
JSON.
get_title_for_vid(VID) ->
JSON = query_gdata_feed(VID),
[Item] = maps:get(<<"items">>, jsx:decode(JSON, [return_maps])),
Snip = maps:get(<<"snippet">>, Item),
[$[, maps:get(<<"channelTitle">>, Snip), "] ", maps:get(<<"title">>, Snip)].
recognize_url(Input) ->
{match, [VID]} = re:run(Input,
"(?:youtu.be/|youtube\\.com/.*v=)([a-zA-Z0-9\-_]+)",
[{capture, all_but_first, list}]),
"YouTube title: " ++ get_title_for_vid(VID).
ircmain(Contact) ->
Pid = spawn(?MODULE, ircproc, [Contact]),
Contact ! {subscribe, Pid},
Pid.
reload(Contact, Pid) ->
Pid ! reloaded,
ircproc(Contact).
ircproc(Contact) ->
receive
quit -> quit;
{incoming, Data} ->
S = binary_to_list(Data),
case string:str(S, "youtu") of
0 -> nop;
_ -> spawn(fun() ->
Contact ! {announce, recognize_url(S)} end)
end,
ircproc(Contact);
{ident, Pid} ->
Pid ! {ident, "youtube"},
ircproc(Contact);
{reload, Pid} ->
?MODULE:reload(Contact, Pid);
_ -> ircproc(Contact)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment