Last active
August 29, 2015 14:07
-
-
Save benjamintanweihao/ee7d7f0b76c74a3aff13 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule Exile.Bot do | |
| use GenServer | |
| @nick "exile-bot" | |
| @timeout 10_000 | |
| def start_link(host, port, chan, nick \\ @nick) do | |
| GenServer.start_link(__MODULE__, %{host: host, port: port, chan: chan, nick: nick, sock: nil}, timeout: @timeout) | |
| end | |
| def join_channel(pid) do | |
| GenServer.call(pid, :join_channel) | |
| end | |
| def listen(pid) do | |
| GenServer.cast(pid, :listen) | |
| end | |
| def handle_call(:join_channel, _from, state) do | |
| {:ok, sock} = Socket.TCP.connect(state.host, state.port, packet: :line) | |
| sock |> Socket.Stream.send!("NICK #{state.nick}\r\n") | |
| sock |> Socket.Stream.send!("USER #{state.nick} #{state.host} #{state.nick} #{state.nick}\r\n") | |
| sock |> Socket.Stream.send!("JOIN #{state.chan}\r\n") | |
| state = %{state | sock: sock} | |
| {:reply, state, state} | |
| end | |
| def handle_cast(:listen, state) do | |
| {:noreply, state, 0} | |
| end | |
| def handle_info(:timeout, state) do | |
| do_listen(state) | |
| { :noreply, state } | |
| end | |
| def do_listen(state) do | |
| case state.sock |> Socket.Stream.recv! do | |
| data when is_binary(data)-> | |
| IO.puts data | |
| nil -> | |
| :ok | |
| end | |
| do_listen(state) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment