Class: Imouto::Irc

Inherits:
Object
  • Object
show all
Includes:
IrcCommands
Defined in:
lib/irc.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from IrcCommands

#channel_mode, #invite, #join, #kick, #mode, #notice, #part, #privmsg, #quit, #topic

Constructor Details

#initialize(connection, user) ⇒ Irc

Returns a new instance of Irc.



43
44
45
46
47
48
49
50
# File 'lib/irc.rb', line 43

def initialize(connection, user)
  @connection = Connection.new
  connection.each { |k, v| @connection[k] = v; }
  @user = User.new
  user.each { |k, v| @user[k] = v; }
  @connection_state = Enum.new([:not_connected, :connecting, :connected, :failed], :not_connected)
  self
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



40
41
42
# File 'lib/irc.rb', line 40

def connection
  @connection
end

#connection_stateObject (readonly)

Returns the value of attribute connection_state.



40
41
42
# File 'lib/irc.rb', line 40

def connection_state
  @connection_state
end

#userObject (readonly)

Returns the value of attribute user.



40
41
42
# File 'lib/irc.rb', line 40

def user
  @user
end

Instance Method Details

#raw(msg) ⇒ Object

see irc_commands.rb



59
60
61
# File 'lib/irc.rb', line 59

def raw(msg)
  @socket.puts msg
end

#readObject

Yields PRIVMSGs and handles PINGs as well as setup operations



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/irc.rb', line 91

def read
  until @socket.eof?
    msg = @socket.gets
    if msg.start_with? 'PING'
      raw "PONG #{msg[6..-1]}"
      next
    end
    if  msg.include? 'PRIVMSG'
      m = msg.chomp.match(/:(?<nick>.*)!(?<mask>.*) PRIVMSG (?<target>.*) :(?<message>.*)$/)
      yield m
    end
    if (@connection_state.selected == :connecting) && (msg =~ /:(.*) 376 #{@user.nick} :(.*)$/)
      setup
      @connection_state.set(:connected)
      next
    end
  end
end

#setupObject

Stuff to do when the connection is successfully established



53
54
55
56
# File 'lib/irc.rb', line 53

def setup
  join @connection.channels
  self
end

#startObject

Starts an IRC-connection. Chainable,- you probably want to do irc.start.read {|msg| …}



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/irc.rb', line 65

def start
  begin
    Timeout.timeout(@connection.connect_timeout) {
      @socket = TCPSocket.new(@connection.server, @connection.port)
      raw "PASS #{@user.password}"
      raw "NICK #{@user.nick}"
      raw "USER #{@user.username} 0 * :#{@user.realname}"
    }
  rescue Timeout::Error
    @connection_state.set(:failed)
    puts 'Timeout! Aborting.'
    return false
  rescue SocketError => e
    @connection_state.set(:failed)
    puts "Network error: #{e}"
    return false
  rescue => e
    @connection_state.set(:failed)
    puts "General exception: #{e}"
    return false
  end
  @connection_state.set(:connecting)
  self
end