Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'eventmachine'
- require 'ostruct'
- module IRCClient
- class Message
- attr_reader :client, :raw, :hostmask, :nick, :hostname, :ident, :sender, :command, :rarg, :arguments
- def initialize(client)
- @client = client
- end
- def parse!(line)
- @raw = line
- words = line.chomp.split(" ")
- if words[0][0] == ":"
- @hostmask = words[0][1..-1]
- @nick = @hostmask.split("!", 2).first
- @hostname = @hostmask.split("@", 2).last
- @ident = @hostmask.split("!", 2).last.split("@", 2).first
- @sender = client.find_user(@nick, @ident, @hostname)
- @command = words[1]
- @rarg = words[2..-1].join(" ")
- else
- @sender = @nick = @hostname = @hostmask = @ident = nil
- @command = words[0]
- @rarg = words[1..-1].join(" ")
- end
- @arguments = @rarg.split(" ")
- i = @arguments.find_index {|a| a[0] == ":" }
- @arguments[i..-1] = @arguments[i..-1].join(" ")[1..-1] if i
- end
- end
- def initialize(*args)
- super
- @buffer = BufferedTokenizer.new("\r\n")
- end
- def post_init
- puts "[CLIENT] Registering"
- send_frame "NICK", "Lime"
- send_frame "USER", "lime", "*", "*", ":Lime, the IRC bot"
- puts "[CLIENT] Registered"
- end
- def send_frame(command, *arguments)
- puts "[CLIENT] Sent: #{command} #{arguments.join(" ")}"
- send_data "#{command} #{arguments.join(" ")}\r\n"
- end
- def privmsg(to, msg)
- to = to.nick if to.respond_to?(:nick)
- send_frame "PRIVMSG", to, ":"+msg
- end
- def join(channel)
- send_frame "JOIN", channel
- end
- def receive_data(data)
- @buffer.extract(data).each do |line|
- receive_line(line.chomp)
- end
- rescue StandardError => e
- receive_error(e.to_s)
- close_connection
- return
- end
- def receive_line(line)
- @irc_message = Message.new(self)
- @irc_message.parse!(line)
- puts "[CLIENT] Received: #{@irc_message.raw}"
- case @irc_message.command
- when 'PING'
- send_frame "PONG", @irc_message.rarg
- when 'INVITE'
- join(@irc_message.arguments[1])
- privmsg(@irc_message.arguments[1], "#{@irc_message.nick}: Thanks for inviting me!")
- end
- end
- def receive_error(error)
- puts "[CLIENT] {ERROR} #{error}"
- end
- def unbind
- puts "[CLIENT] Connection lost"
- EventMachine.stop_event_loop
- end
- def find_user(nick, ident=nil, hostname=nil)
- @users ||= {}
- user = @users[nick.downcase]
- return user unless ident || hostname
- if user && user.nick == nick && user.ident == ident && user.hostname == hostname
- return user
- else
- user = OpenStruct.new
- user.nick = nick
- user.ident = ident
- user.hostname = hostname
- @users[nick.downcase] = user
- return user
- end
- end
- end
- EventMachine.run do
- EventMachine.connect("irc.cluenet.org", 6667, IRCClient)
- end
Add Comment
Please, Sign In to add comment