Skip to content

Instantly share code, notes, and snippets.

@sleepiecappy
Created October 22, 2018 18:31
Show Gist options
  • Save sleepiecappy/f9c38ce47048084b5424ebdba5a118a6 to your computer and use it in GitHub Desktop.
Save sleepiecappy/f9c38ce47048084b5424ebdba5a118a6 to your computer and use it in GitHub Desktop.
not working chat, idk for future reference
defmodule Engag.ChatFeed do
alias :gun, as: Gun
@type message :: {:text, iodata()}
@type channel :: String.t()
def connect(nickname, token) do
with {:ok, conn} <- http(),
{:ok, _protocol} <- Gun.await_up(conn),
_ref <- upgrade(conn),
{:ok, _} <- Gun.await_up(conn)
do
:ok = authenticate(conn, nickname, token)
conn
end
end
@spec authenticate(pid(), String.t(), String.t()) :: :ok
def authenticate(conn, nickname, token) do
Gun.ws_send(conn, message("CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership"))
Gun.ws_send(conn, message("PASS #{token}"))
Gun.ws_send(conn, message("NICK #{nickname}"))
Gun.ws_send(conn, message("USER #{nickname} 8 * :#{nickname}"))
end
@spec join(pid(), channel()) :: :ok
def join(conn, channel) do
Gun.ws_send(conn, message("JOIN ##{channel}"))
end
@spec message(String.t()) :: message()
def message(text) do
{:text, String.to_charlist(text)}
end
defp http() do
Gun.open('irc-ws.chat.twitch.tv', 80)
end
defp upgrade(conn) do
Gun.ws_upgrade(conn, '/')
end
@spec handle(Engag.Handler.t()) :: :ok
def handle(handler) do
receive do
{:gun_upgrade, conn, ref, ["websocket"], _headers} ->
handler.upgraded(conn, ref)
{:gun_response, conn, _, _, status, headers} ->
handler.upgrade_failure(conn, status, headers)
handle(handler)
{:gun_error, conn, _ref, reason} ->
handler.upgrade_failure(conn, "400", reason: reason)
handle(handler)
{:gun_ws, conn, ref, frame} ->
handler.handle_message(conn, ref, frame)
handle(handler)
any ->
IO.puts(any)
after 180_000 ->
IO.puts("Timeout")
:ok
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment