Last active
May 20, 2024 17:03
-
-
Save vrcca/2eb98c33acacc4644590acce480b939e to your computer and use it in GitHub Desktop.
A simple IRC client in Elixir with no dependencies
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 IRC do | |
use GenServer | |
def connect(host, port, nick) do | |
GenServer.start_link(__MODULE__, %{host: host, port: port, nick: nick}) | |
end | |
def init(opts) do | |
{:ok, socket} = connect_and_identify!(opts.host, opts.port, opts.nick) | |
{:ok, Map.put(opts, :socket, socket)} | |
end | |
defp connect_and_identify!(host, port, nick) do | |
{:ok, socket} = :gen_tcp.connect(~c"#{host}", port, [:binary, packet: :line, active: true]) | |
send!(socket, "USER #{nick} 8 * :#{nick}") | |
send!(socket, "NICK #{nick}") | |
{:ok, socket} | |
end | |
def send_msg(client, msg) do | |
GenServer.cast(client, {:send, msg}) | |
end | |
def handle_cast({:send, msg}, state) do | |
send!(state.socket, msg) | |
{:noreply, state} | |
end | |
defp send!(socket, text) do | |
:ok = :gen_tcp.send(socket, ~c"#{text}\n") | |
IO.puts(text) | |
end | |
def handle_info({:tcp, _tcp_socket, text}, opts) do | |
if String.starts_with?(text, "PING "), do: send!(opts.socket, "PONG") | |
IO.puts(text) | |
{:noreply, opts} | |
end | |
end | |
{:ok, client} = IRC.connect("irc.libera.chat", 6665, "awesome_elixir") | |
IRC.send_msg(client, "JOIN #emacs") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment