Class: Ircmad::IRCClient

Inherits:
Object
  • Object
show all
Includes:
Configurable
Defined in:
lib/ircmad/irc_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Configurable

#config, #set

Constructor Details

#initialize(&block) ⇒ IRCClient

Returns a new instance of IRCClient.



6
7
8
9
10
# File 'lib/ircmad/irc_client.rb', line 6

def initialize(&block)
  instance_eval(&block) if block_given?

  Ircmad.post_channel.subscribe(&on_post)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(action, *args, &block) ⇒ Object



85
86
87
# File 'lib/ircmad/irc_client.rb', line 85

def method_missing(action, *args, &block)
  client.send(action.to_s, *args, &block)
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



3
4
5
# File 'lib/ircmad/irc_client.rb', line 3

def client
  @client
end

Instance Method Details

#close_clientObject



74
75
76
77
78
79
80
81
82
83
# File 'lib/ircmad/irc_client.rb', line 74

def close_client
  # oh...
  if @client
    socket = @client.instance_variable_get(:@socket)
    if socket.respond_to?(:closed?) && !socket.closed?
      socket.close
    end
    @client = nil
  end
end

#on_postObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ircmad/irc_client.rb', line 47

def on_post
  proc { |msg|
    m = begin
     JSON.parse(msg, :symbolize_names => true)
    rescue JSON::ParserError
      puts "#{msg} is invalid json"
    end

    if m && client
      m[:type] ||= 'privmsg'

      case m[:type].downcase
      when 'privmsg'
        client.privmsg m[:to], ":#{m[:body]}"
      when 'list'
        client.list m[:to]
      when 'names'
        client.names m[:to]
      when 'join'
        client.join m[:to] if m[:to]
      end
    end
  }
end

#run!Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ircmad/irc_client.rb', line 12

def run!
  self.client ||= Zircon.new config

  first_join = true
  client.on_join do |message|
    if first_join
      first_join = false
      config[:channel_list].each { |channel| client.join channel }
    else
      Ircmad.get_channel << message
    end
  end
  client.on_privmsg { |msg| Ircmad.get_channel << msg }
  client.on_numericreply { |msg| Ircmad.get_channel << msg }
  client.run!
rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE => e
  puts "#{e}\nRetry Now!"
  close_client
  sleep 1
  retry
rescue ArgumentError
  msg = $!.message
  if /Invalid message:.*/ =~ msg
    retry
  else
    puts 'Unexpected Error!'
    puts msg
    exit!
  end
rescue => e
  puts 'Unexpected Error!'
  puts e
  exit!
end