7 $debug = false unless $debug
8 $daemonize = false unless $daemonize
10 $dateformat = "%Y/%m/%d %H:%M:%S"
11 $logger = Logger.new($stderr)
12 $logger.datetime_format = $dateformat
13 $logger.level = $cl_loglevel if $cl_loglevel
14 $logger.level = 0 if $debug
16 def rawlog(level, message=nil, who_pos=1)
18 if call_stack.length > who_pos
19 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
23 # Output each line. To distinguish between separate messages and multi-line
24 # messages originating at the same time, we blank #{who} after the first message
26 message.to_s.each_line { |l|
27 $logger.add(level, l.chomp, who)
33 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
37 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
40 def debug(message=nil, who_pos=1)
41 rawlog(Logger::Severity::DEBUG, message, who_pos)
44 def log(message=nil, who_pos=1)
45 rawlog(Logger::Severity::INFO, message, who_pos)
48 def warning(message=nil, who_pos=1)
49 rawlog(Logger::Severity::WARN, message, who_pos)
52 def error(message=nil, who_pos=1)
53 rawlog(Logger::Severity::ERROR, message, who_pos)
56 def fatal(message=nil, who_pos=1)
57 rawlog(Logger::Severity::FATAL, message, who_pos)
62 warning "warning test"
66 # The following global is used for the improved signal handling.
70 require 'rbot/rbotconfig'
75 require 'rbot/rfc2812'
76 require 'rbot/ircsocket'
77 require 'rbot/botuser'
79 require 'rbot/plugins'
80 # require 'rbot/channel'
81 require 'rbot/message'
82 require 'rbot/language'
84 require 'rbot/registry'
85 require 'rbot/httputil'
89 # Main bot class, which manages the various components, receives messages,
90 # handles them or passes them to plugins, and contains core functionality.
92 # the bot's IrcAuth data
95 # the bot's BotConfig data
98 # the botclass for this bot (determines configdir among other things)
101 # used to perform actions periodically (saves configuration once per minute
105 # synchronize with this mutex while touching permanent data files:
106 # saving, flushing, cleaning up ...
107 attr_reader :save_mutex
109 # bot's Language data
116 # bot's object registry, plugins get an interface to this for persistant
117 # storage (hash interface tied to a bdb file, plugins use Accessors to store
118 # and restore objects in their own namespaces.)
119 attr_reader :registry
121 # bot's plugins. This is an instance of class Plugins
124 # bot's httputil help object, for fetching resources via http. Sets up
125 # proxies etc as defined by the bot configuration/environment
126 attr_reader :httputil
128 # server we are connected to
134 # bot User in the client/server connection
140 # bot User in the client/server connection
145 # create a new IrcBot with botclass +botclass+
146 def initialize(botclass, params = {})
147 # BotConfig for the core bot
148 # TODO should we split socket stuff into ircsocket, etc?
149 BotConfig.register BotConfigStringValue.new('server.name',
150 :default => "localhost", :requires_restart => true,
151 :desc => "What server should the bot connect to?",
153 BotConfig.register BotConfigIntegerValue.new('server.port',
154 :default => 6667, :type => :integer, :requires_restart => true,
155 :desc => "What port should the bot connect to?",
156 :validate => Proc.new {|v| v > 0}, :wizard => true)
157 BotConfig.register BotConfigStringValue.new('server.password',
158 :default => false, :requires_restart => true,
159 :desc => "Password for connecting to this server (if required)",
161 BotConfig.register BotConfigStringValue.new('server.bindhost',
162 :default => false, :requires_restart => true,
163 :desc => "Specific local host or IP for the bot to bind to (if required)",
165 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
166 :default => 5, :validate => Proc.new{|v| v >= 0},
167 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
168 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
169 :default => 2.0, :validate => Proc.new{|v| v >= 0},
170 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
171 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
172 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
173 :default => 4, :validate => Proc.new{|v| v >= 0},
174 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
175 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
176 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
177 :default => 30, :validate => Proc.new{|v| v >= 0},
178 :on_change => Proc.new {|bot, v| bot.start_server_pings},
179 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
181 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
182 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
183 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
184 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
185 :requires_restart => true,
186 :desc => "local user the bot should appear to be", :wizard => true)
187 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
188 :default => [], :wizard => true,
189 :desc => "What channels the bot should always join at startup. List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'")
190 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
192 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
194 BotConfig.register BotConfigIntegerValue.new('core.save_every',
195 :default => 60, :validate => Proc.new{|v| v >= 0},
196 # TODO change timer via on_change proc
197 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
199 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
200 :default => false, :requires_restart => true,
201 :desc => "Should the bot run as a daemon?")
203 BotConfig.register BotConfigStringValue.new('log.file',
204 :default => false, :requires_restart => true,
205 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
206 BotConfig.register BotConfigIntegerValue.new('log.level',
207 :default => 1, :requires_restart => false,
208 :validate => Proc.new { |v| (0..5).include?(v) },
209 :on_change => Proc.new { |bot, v|
212 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
213 BotConfig.register BotConfigIntegerValue.new('log.keep',
214 :default => 1, :requires_restart => true,
215 :validate => Proc.new { |v| v >= 0 },
216 :desc => "How many old console messages logfiles to keep")
217 BotConfig.register BotConfigIntegerValue.new('log.max_size',
218 :default => 10, :requires_restart => true,
219 :validate => Proc.new { |v| v > 0 },
220 :desc => "Maximum console messages logfile size (in megabytes)")
222 @argv = params[:argv]
224 unless FileTest.directory? Config::coredir
225 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
229 unless FileTest.directory? Config::datadir
230 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
234 unless botclass and not botclass.empty?
235 # We want to find a sensible default.
236 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
237 # * On Windows (at least the NT versions) we want to put our stuff in the
238 # Application Data folder.
239 # We don't use any particular O/S detection magic, exploiting the fact that
240 # Etc.getpwuid is nil on Windows
241 if Etc.getpwuid(Process::Sys.geteuid)
242 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
244 if ENV.has_key?('APPDATA')
245 botclass = ENV['APPDATA'].dup
246 botclass.gsub!("\\","/")
251 botclass = File.expand_path(botclass)
252 @botclass = botclass.gsub(/\/$/, "")
254 unless FileTest.directory? botclass
255 log "no #{botclass} directory found, creating from templates.."
256 if FileTest.exist? botclass
257 error "file #{botclass} exists but isn't a directory"
260 FileUtils.cp_r Config::datadir+'/templates', botclass
263 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
264 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
265 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
266 Utils.set_safe_save_dir("#{botclass}/safe_save")
271 @startup_time = Time.new
274 @config = BotConfig.configmanager
275 @config.bot_associate(self)
278 fatal e.backtrace.join("\n")
283 if @config['core.run_as_daemon']
287 @logfile = @config['log.file']
288 if @logfile.class!=String || @logfile.empty?
289 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
292 # See http://blog.humlab.umu.se/samuel/archives/000107.html
293 # for the backgrounding code
299 rescue NotImplementedError
300 warning "Could not background, fork not supported"
302 warning "Could not background. #{e.inspect}"
305 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
306 log "Redirecting standard input/output/error"
308 STDIN.reopen "/dev/null"
310 # On Windows, there's not such thing as /dev/null
313 def STDOUT.write(str=nil)
315 return str.to_s.length
317 def STDERR.write(str=nil)
318 if str.to_s.match(/:\d+: warning:/)
323 return str.to_s.length
327 # Set the new logfile and loglevel. This must be done after the daemonizing
328 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
329 $logger.datetime_format= $dateformat
330 $logger.level = @config['log.level']
331 $logger.level = $cl_loglevel if $cl_loglevel
332 $logger.level = 0 if $debug
336 @registry = BotRegistry.new self
338 @timer = Timer::Timer.new(1.0) # only need per-second granularity
339 @save_mutex = Mutex.new
340 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
341 @quit_mutex = Mutex.new
345 @httputil = Utils::HttpUtil.new(self)
348 @lang = Language::Language.new(self, @config['core.language'])
351 @auth = Auth::authmanager
352 @auth.bot_associate(self)
353 # @auth.load("#{botclass}/botusers.yaml")
356 fatal e.backtrace.join("\n")
360 @auth.everyone.set_default_permission("*", true)
361 @auth.botowner.password= @config['auth.password']
363 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
364 @plugins = Plugins::pluginmanager
365 @plugins.bot_associate(self)
366 @plugins.add_botmodule_dir(Config::coredir)
367 @plugins.add_botmodule_dir("#{botclass}/plugins")
368 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
371 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
372 @client = IrcClient.new
373 myself.nick = @config['irc.nick']
375 # Channels where we are quiet
376 # It's nil when we are not quiet, an empty list when we are quiet
377 # in all channels, a list of channels otherwise
380 @client[:welcome] = proc {|data|
381 irclog "joined server #{@client.server} as #{myself}", "server"
383 @plugins.delegate("connect")
385 @config['irc.join_channels'].each { |c|
386 debug "autojoining channel #{c}"
387 if(c =~ /^(\S+)\s+(\S+)$/i)
394 @client[:isupport] = proc { |data|
395 # TODO this needs to go into rfc2812.rb
396 # Since capabs are two-steps processes, server.supports[:capab]
397 # should be a three-state: nil, [], [....]
398 sendq "CAPAB IDENTIFY-MSG" if server.supports[:capab]
400 @client[:datastr] = proc { |data|
401 # TODO this needs to go into rfc2812.rb
402 if data[:text] == "IDENTIFY-MSG"
403 server.capabilities["identify-msg".to_sym] = true
405 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
408 @client[:privmsg] = proc { |data|
409 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
410 # debug "Message source is #{data[:source].inspect}"
411 # debug "Message target is #{data[:target].inspect}"
412 # debug "Bot is #{myself.inspect}"
414 # TODO use the new Netmask class
415 # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
419 @plugins.delegate "listen", m
420 @plugins.privmsg(m) if m.address?
422 @client[:notice] = proc { |data|
423 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
424 # pass it off to plugins that want to hear everything
425 @plugins.delegate "listen", message
427 @client[:motd] = proc { |data|
428 data[:motd].each_line { |line|
429 irclog "MOTD: #{line}", "server"
432 @client[:nicktaken] = proc { |data|
433 nickchg "#{data[:nick]}_"
434 @plugins.delegate "nicktaken", data[:nick]
436 @client[:badnick] = proc {|data|
437 warning "bad nick (#{data[:nick]})"
439 @client[:ping] = proc {|data|
440 sendq "PONG #{data[:pingid]}"
442 @client[:pong] = proc {|data|
445 @client[:nick] = proc {|data|
446 source = data[:source]
449 m = NickMessage.new(self, server, source, old, new)
451 debug "my nick is now #{new}"
453 data[:is_on].each { |ch|
454 irclog "@ #{old} is now known as #{new}", ch
456 @plugins.delegate("listen", m)
457 @plugins.delegate("nick", m)
459 @client[:quit] = proc {|data|
460 source = data[:source]
461 message = data[:message]
462 m = QuitMessage.new(self, server, source, source, message)
463 data[:was_on].each { |ch|
464 irclog "@ Quit: #{source}: #{message}", ch
466 @plugins.delegate("listen", m)
467 @plugins.delegate("quit", m)
469 @client[:mode] = proc {|data|
470 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
472 @client[:join] = proc {|data|
473 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
476 @plugins.delegate("listen", m)
477 @plugins.delegate("join", m)
479 @client[:part] = proc {|data|
480 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
483 @plugins.delegate("listen", m)
484 @plugins.delegate("part", m)
486 @client[:kick] = proc {|data|
487 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
490 @plugins.delegate("listen", m)
491 @plugins.delegate("kick", m)
493 @client[:invite] = proc {|data|
494 if data[:target] == myself
495 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
498 @client[:changetopic] = proc {|data|
499 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
502 @plugins.delegate("listen", m)
503 @plugins.delegate("topic", m)
505 @client[:topic] = proc { |data|
506 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
508 @client[:topicinfo] = proc { |data|
509 channel = data[:channel]
510 topic = channel.topic
511 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
512 m = TopicMessage.new(self, server, data[:source], channel, topic)
514 @plugins.delegate("listen", m)
515 @plugins.delegate("topic", m)
517 @client[:names] = proc { |data|
518 @plugins.delegate "names", data[:channel], data[:users]
520 @client[:unknown] = proc { |data|
521 #debug "UNKNOWN: #{data[:serverstring]}"
522 irclog data[:serverstring], ".unknown"
526 # checks if we should be quiet on a channel
527 def quiet_on?(channel)
528 return false unless @quiet
529 return true if @quiet.empty?
530 return @quiet.include?(channel.to_s)
533 def set_quiet(channel=nil)
535 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
541 def reset_quiet(channel=nil)
543 @quiet.delete_if { |x| x == channel.to_s }
549 # things to do when we receive a signal
551 debug "received #{sig}, queueing quit"
553 quit unless @quit_mutex.locked?
554 debug "interrupted #{$interrupted} times"
562 # connect the bot to IRC
565 trap("SIGINT") { got_sig("SIGINT") }
566 trap("SIGTERM") { got_sig("SIGTERM") }
567 trap("SIGHUP") { got_sig("SIGHUP") }
568 rescue ArgumentError => e
569 debug "failed to trap signals (#{e.inspect}): running on Windows?"
571 debug "failed to trap signals: #{e.inspect}"
574 quit if $interrupted > 0
577 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
579 quit if $interrupted > 0
580 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
581 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
582 quit if $interrupted > 0
586 # begin event handling loop
590 quit if $interrupted > 0
594 while @socket.connected?
595 quit if $interrupted > 0
597 break unless reply = @socket.gets
598 @client.process reply
602 # I despair of this. Some of my users get "connection reset by peer"
603 # exceptions that ARENT SocketError's. How am I supposed to handle
608 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
609 error "network exception: #{e.class}: #{e}"
610 debug e.backtrace.join("\n")
611 rescue BDB::Fatal => e
612 fatal "fatal bdb error: #{e.class}: #{e}"
613 fatal e.backtrace.join("\n")
615 # Why restart? DB problems are serious stuff ...
616 # restart("Oops, we seem to have registry problems ...")
619 rescue Exception => e
620 error "non-net exception: #{e.class}: #{e}"
621 error e.backtrace.join("\n")
623 fatal "unexpected exception: #{e.class}: #{e}"
624 fatal e.backtrace.join("\n")
631 if @socket.connected?
638 quit if $interrupted > 0
640 log "waiting to reconnect"
641 sleep @config['server.reconnect_wait']
645 # type:: message type
646 # where:: message target
647 # message:: message text
648 # send message +message+ of type +type+ to target +where+
649 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
650 # relevant say() or notice() methods. This one should be used for IRCd
651 # extensions you want to use in modules.
652 def sendmsg(type, where, message, chan=nil, ring=0)
653 # Split the message so that each line sent is not longher than 400 bytes
654 # TODO allow something to do for commands that produce too many messages
655 # TODO example: math 10**10000
656 # TODO try to use the maximum line length allowed by the server, if there is
657 # a way to know what it is
658 left = 400 - type.length - where.to_s.length - 3
660 if(left >= message.length)
661 sendq "#{type} #{where} :#{message}", chan, ring
662 log_sent(type, where, message)
665 line = message.slice!(0, left)
666 lastspace = line.rindex(/\s+/)
668 message = line.slice!(lastspace, line.length) + message
669 message.gsub!(/^\s+/, "")
671 sendq "#{type} #{where} :#{line}", chan, ring
672 log_sent(type, where, line)
673 end while(message.length > 0)
676 # queue an arbitraty message for the server
677 def sendq(message="", chan=nil, ring=0)
679 @socket.queue(message, chan, ring)
682 # send a notice message to channel/nick +where+
683 def notice(where, message, mchan="", mring=-1)
699 message.each_line { |line|
701 next unless(line.length > 0)
702 sendmsg "NOTICE", where, line, chan, ring
706 # say something (PRIVMSG) to channel/nick +where+
707 def say(where, message, mchan="", mring=-1)
723 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
725 next unless(line.length > 0)
726 unless quiet_on?(where)
727 sendmsg "PRIVMSG", where, line, chan, ring
732 # perform a CTCP action with message +message+ to channel/nick +where+
733 def action(where, message, mchan="", mring=-1)
749 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
752 irclog "* #{myself} #{message}", where
754 irclog "* #{myself}[#{where}] #{message}", where
758 # quick way to say "okay" (or equivalent) to +where+
760 say where, @lang.get("okay")
763 # log IRC-related message +message+ to a file determined by +where+.
764 # +where+ can be a channel name, or a nick for private message logging
765 def irclog(message, where="server")
766 message = message.chomp
767 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
768 where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
769 unless(@logs.has_key?(where))
770 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
771 @logs[where].sync = true
773 @logs[where].puts "[#{stamp}] #{message}"
774 #debug "[#{stamp}] <#{where}> #{message}"
777 # set topic of channel +where+ to +topic+
778 def topic(where, topic)
779 sendq "TOPIC #{where} :#{topic}", where, 2
782 # disconnect from the server and cleanup all plugins and modules
783 def shutdown(message = nil)
784 @quit_mutex.synchronize do
785 debug "Shutting down ..."
786 ## No we don't restore them ... let everything run through
788 # trap("SIGINT", "DEFAULT")
789 # trap("SIGTERM", "DEFAULT")
790 # trap("SIGHUP", "DEFAULT")
792 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
794 message = @lang.get("quit") if (message.nil? || message.empty?)
795 if @socket.connected?
796 debug "Clearing socket"
798 debug "Sending quit message"
799 @socket.emergency_puts "QUIT :#{message}"
800 debug "Flushing socket"
802 debug "Shutting down socket"
805 debug "Logging quits"
806 server.channels.each { |ch|
807 irclog "@ quit (#{message})", ch
812 @save_mutex.synchronize do
815 # debug "Closing registries"
817 debug "Cleaning up the db environment"
819 log "rbot quit (#{message})"
823 # message:: optional IRC quit message
824 # quit IRC, shutdown the bot
825 def quit(message=nil)
833 # totally shutdown and respawn the bot
834 def restart(message = false)
835 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
837 sleep @config['server.reconnect_wait']
839 # Note, this fails on Windows
843 # call the save method for all of the botmodules
845 @save_mutex.synchronize do
851 # call the rescan method for all of the botmodules
853 @save_mutex.synchronize do
859 # channel:: channel to join
860 # key:: optional channel key if channel is +s
862 def join(channel, key=nil)
864 sendq "JOIN #{channel} :#{key}", channel, 2
866 sendq "JOIN #{channel}", channel, 2
871 def part(channel, message="")
872 sendq "PART #{channel} :#{message}", channel, 2
875 # attempt to change bot's nick to +name+
881 def mode(channel, mode, target)
882 sendq "MODE #{channel} #{mode} #{target}", channel, 2
886 def kick(channel, user, msg)
887 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
890 # m:: message asking for help
891 # topic:: optional topic help is requested for
892 # respond to online help requests
894 topic = nil if topic == ""
897 helpstr = "help topics: "
898 helpstr += @plugins.helptopics
899 helpstr += " (help <topic> for more info)"
901 unless(helpstr = @plugins.help(topic))
902 helpstr = "no help for topic #{topic}"
908 # returns a string describing the current status of the bot (uptime etc)
910 secs_up = Time.new - @startup_time
911 uptime = Utils.secs_to_string secs_up
912 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
913 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
916 # we'll ping the server every 30 seconds or so, and expect a response
917 # before the next one come around..
918 def start_server_pings
920 return unless @config['server.ping_timeout'] > 0
921 # we want to respond to a hung server within 30 secs or so
922 @ping_timer = @timer.add(30) {
923 @last_ping = Time.now
924 @socket.queue "PING :rbot"
926 @pong_timer = @timer.add(10) {
927 unless @last_ping.nil?
928 diff = Time.now - @last_ping
929 unless diff < @config['server.ping_timeout']
930 debug "no PONG from server for #{diff} seconds, reconnecting"
934 debug "couldn't shutdown connection (already shutdown?)"
937 raise TimeoutError, "no PONG from server in #{diff} seconds"
943 def stop_server_pings
945 # stop existing timers if running
946 unless @ping_timer.nil?
947 @timer.remove @ping_timer
950 unless @pong_timer.nil?
951 @timer.remove @pong_timer
961 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
963 irclog "* #{m.sourcenick} #{m.message}", m.target
967 irclog "<#{m.sourcenick}> #{m.message}", m.target
969 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
974 # log a message. Internal use only.
975 def log_sent(type, where, message)
980 irclog "-=#{myself}=- #{message}", where
982 irclog "[-=#{where}=-] #{message}", where
987 irclog "<#{myself}> #{message}", where
989 irclog "[msg(#{where})] #{message}", where
996 debug "joined channel #{m.channel}"
997 irclog "@ Joined channel #{m.channel}", m.channel
999 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1005 debug "left channel #{m.channel}"
1006 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1008 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1014 debug "kicked from channel #{m.channel}"
1015 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1017 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1022 if m.source == myself
1023 irclog "@ I set topic \"#{m.topic}\"", m.channel
1025 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel