Created
January 1, 2011 15:48
-
-
Save snicol/761817 to your computer and use it in GitHub Desktop.
Ruby IRC Client. Very basic. No support for IRC commands, yet... Will expand into a full repo/app.
This file contains 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
require 'socket' | |
include Socket::Constants | |
class Client | |
def initialize(settings, channel) | |
@settings = settings | |
@channel = channel | |
@connection = TCPSocket.open(@settings['server'], @settings['port']) | |
send("NICK #{@settings['name']}") | |
send("USER #{@settings['name']} localhost * :#{@settings['name']}") | |
puts "Connecting..." | |
end | |
def send(a) | |
@connection.puts a | |
end | |
def basic_parse(msg) | |
# sends ping reply to tell the server connection is alive | |
if msg.match(/^PING :(.*)$/) | |
send("PONG #{$~[1]}") | |
end | |
# if message from another user, parse to have user: message pretty stuff | |
if msg.match(/^:(.*)!(.*) PRIVMSG (.*) :(.*) :(.*)$/) | |
puts "#{$~[1]}: #{$~[4]} :#{$~[5]}" | |
new_line | |
elsif msg.match(/^:(.*)!(.*) PRIVMSG (.*) :(.*)$/) | |
puts "#{$~[1]}: #{$~[4]}" | |
new_line | |
end | |
# waits for a line with the user authed by NICK | |
if msg.match(/^:(.*) (.*) #{@settings['name']} :(.*)$/) | |
send("JOIN #{@channel}") | |
print("#{msg}") | |
if $~[2] == "266" | |
print("Connected to #{@channel} \n--> ") | |
end | |
end | |
end | |
def input_stdin! | |
if input = STDIN.gets | |
unless input.match(/^PRIVMSG(.*)$/) | |
if input.match(/^JOIN (.*)$/) | |
send("JOIN #{$~[1]}") | |
elsif input.match(/^NAMES$/) | |
send("NAMES") | |
else | |
send("PRIVMSG #{@channel} :#{input}") | |
new_line | |
end | |
end | |
end | |
end | |
def output_stdout! | |
msg = @connection.gets | |
basic_parse(msg) | |
end | |
def new_line | |
print("--> ") | |
end | |
def run | |
until @connection.eof? do | |
inou = select([@connection, STDIN], nil, nil, nil) | |
next if !inou | |
for s in inou[0] | |
Thread.abort_on_exception = true | |
stdin_thread = Thread.new do | |
if s = STDIN | |
input_stdin! | |
end | |
end | |
Thread.abort_on_exception = true | |
stdout_thread = Thread.new do | |
if s = @connection | |
output_stdout! | |
end | |
end | |
end | |
end | |
end | |
end | |
settings = { | |
"name" => "scott_cli", | |
"server" => "irc.weareinfinite.net", | |
"port" => 6667 | |
} | |
channel = "#test" | |
client = Client.new(settings, channel) | |
client.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
beautiful!