aboutsummaryrefslogtreecommitdiff
path: root/irc.rb
diff options
context:
space:
mode:
authorDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2014-04-19 20:22:05 -0700
committerDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2014-04-19 20:22:05 -0700
commited09327eac899b9d5a1f782616747ca13c4806b1 (patch)
tree68be5f276ef3789d8db5f7253c1060a2d0e712ac /irc.rb
parent6d4f0b1a3c82a983edd7ccba6dee5a7c79a8c941 (diff)
downloaddinobot-ed09327eac899b9d5a1f782616747ca13c4806b1.tar.gz
dinobot-ed09327eac899b9d5a1f782616747ca13c4806b1.tar.xz
Move protocol functionality to separate file.
Diffstat (limited to 'irc.rb')
-rw-r--r--irc.rb85
1 files changed, 85 insertions, 0 deletions
diff --git a/irc.rb b/irc.rb
new file mode 100644
index 0000000..835694e
--- /dev/null
+++ b/irc.rb
@@ -0,0 +1,85 @@
+require 'socket'
+
+module Dinobot
+ class IRC
+ def initialize(server, port, nick, pass=nil)
+ @server = server
+ @port = port
+ @nick = nick
+ @pass = pass
+
+ @socket = nil
+ end
+
+ def connect
+ log :info, "Connecting to #{@server}:#{@port}."
+
+ @socket = TCPSocket.new(@server, @port)
+
+ puts "PASS #{@pass}" if @pass
+ puts "NICK #{@nick}"
+ puts "USER #{@nick} 0 * :#{@nick}"
+ end
+
+ def disconnect
+ @socket.close
+ end
+
+ def connected?
+ !(@socket.nil? || @socket.closed?)
+ end
+
+ def gets
+ str = @socket.gets
+
+ log :in, str.inspect
+
+ str
+ end
+
+ def puts(str)
+ log :out, str.inspect
+
+ @socket.puts str
+ end
+
+ def join(channel)
+ puts "JOIN #{channel}"
+ end
+
+ def part(channel)
+ puts "PART #{channel}"
+ end
+
+ def privmsg(channel, message)
+ puts "PRIVMSG #{channel} :#{message}"
+ end
+
+ def pong(message)
+ puts "PONG #{message}"
+ end
+
+ private
+
+ def log(type, *lines)
+ str = lines.join("\n")
+
+ case type
+ when :in
+ prefix = "\e[32m<<\e[0m "
+ when :out
+ prefix = "\e[36m>>\e[0m "
+ when :error
+ prefix = "\e[31m!!\e[0m "
+ when :info
+ prefix = "\e[33m==\e[0m "
+ when :indent
+ prefix = ' '
+ else
+ raise "unknown type specified -- #{type}"
+ end
+
+ Kernel.puts str.gsub(/^/, prefix)
+ end
+ end
+end