Class: CampfireBot::Bot

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/bot.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBot

Returns a new instance of Bot.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/bot.rb', line 25

def initialize
  if BOT_ENVIRONMENT.nil?
    puts "you must specify a BOT_ENVIRONMENT"
    exit 1
  end
  @timeouts = 0
  @config   = YAML::load(ERB.new(File.read("#{BOT_ROOT}/config.yml")).result)[BOT_ENVIRONMENT]
  @rooms    = {}
  @root_logger = Logging.logger["CampfireBot"]
  @log = Logging.logger[self]

  log_dir = @config['log_dir']
  Dir.mkdir(log_dir) unless Dir.exists? log_dir

  # TODO much of this should be configurable per environment
  @root_logger.add_appenders Logging.appenders.rolling_file("#{log_dir}/#{BOT_ENVIRONMENT}.log", 
                        :layout => Logging.layouts.pattern(:pattern => "%d | %-6l | %-12c | %m\n"),
                        :age => 'daily', 
                        :keep => 7)
  @root_logger.level = @config['log_level'] rescue :info
end

Instance Attribute Details

#campfireObject (readonly)

FIXME - these will be invalid if disconnected. handle this.



23
24
25
# File 'lib/bot.rb', line 23

def campfire
  @campfire
end

#configObject (readonly)

FIXME - these will be invalid if disconnected. handle this.



23
24
25
# File 'lib/bot.rb', line 23

def config
  @config
end

#logObject (readonly)

FIXME - these will be invalid if disconnected. handle this.



23
24
25
# File 'lib/bot.rb', line 23

def log
  @log
end

#roomsObject (readonly)

FIXME - these will be invalid if disconnected. handle this.



23
24
25
# File 'lib/bot.rb', line 23

def rooms
  @rooms
end

Instance Method Details

#connectObject



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bot.rb', line 47

def connect
  load_plugins unless !@config['enable_plugins']
  begin
    join_rooms
  rescue Errno::ENETUNREACH, SocketError => e
    @log.fatal "We had trouble connecting to the network: #{e.class}: #{e.message}"
    abort "We had trouble connecting to the network: #{e.class}: #{e.message}"
  rescue Exception => e
    @log.fatal "Unhandled exception while joining rooms: #{e.class}: #{e.message} \n #{$!.backtrace.join("\n")}"
    abort "Unhandled exception while joining rooms: #{e.class}: #{e.message} \n #{$!.backtrace.join("\n")}"
  end  
end

#run(interval = 5) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/bot.rb', line 60

def run(interval = 5)
  catch(:stop_listening) do
    trap('INT') { throw :stop_listening }
    trap('TERM') { throw :stop_listening }

    # since room#listen blocks, stick it in its own thread
    @rooms.each_pair do |room_name, room|
      Thread.new do
        begin
          room.listen(:timeout => 8) do |raw_msg|
            handle_message(CampfireBot::Message.new(raw_msg.merge({:room => room})))
          end
        rescue Exception => e 
          trace = e.backtrace.join("\n")
          abort "something went wrong! #{e.message}\n #{trace}"
        end
      end
    end

    loop do
      begin
        @rooms.each_pair do |room_name, room|

          # I assume if we reach here, all the network-related activity has occured successfully
          # and that we're outside of the retry-cycle
          @timeouts = 0

          # Here's how I want it to look
          # @room.listen.each { |m| EventHandler.handle_message(m) }
          # EventHanlder.handle_time(optional_arg = Time.now)

          # Run time-oriented events
          Plugin.registered_intervals.each  do |handler| 
            begin
              handler.run(CampfireBot::Message.new(:room => room))
            rescue
              @log.error "error running #{handler.inspect}: #{$!.class}: #{$!.message} \n #{$!.backtrace.join("\n")}"
            end
          end

          Plugin.registered_times.each_with_index  do |handler, index| 
            begin
              Plugin.registered_times.delete_at(index) if handler.run
            rescue
              @log.error "error running #{handler.inspect}: #{$!.class}: #{$!.message}, \n #{$!.backtrace.join("\n")}"
            end
          end

        end
        STDOUT.flush
        sleep interval
      rescue Timeout::Error => e
        if @timeouts < 5
          sleep(5 * @timeouts)
          @timeouts += 1
          retry
        else
          raise e.message
        end
      end
    end
  end

  # Leave the room so users won't be under the false impression that the bot is still running.
  @rooms.each_value.map(&:leave)
end