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/keywords'
77 require 'rbot/ircsocket'
79 require 'rbot/botuser'
81 require 'rbot/plugins'
82 # require 'rbot/channel'
83 require 'rbot/message'
84 require 'rbot/language'
86 require 'rbot/registry'
87 require 'rbot/httputil'
91 # Main bot class, which manages the various components, receives messages,
92 # handles them or passes them to plugins, and contains core functionality.
94 # the bot's IrcAuth data
97 # the bot's BotConfig data
100 # the botclass for this bot (determines configdir among other things)
101 attr_reader :botclass
103 # used to perform actions periodically (saves configuration once per minute
107 # bot's Language data
110 # server the bot is connected to
114 # the client personality of the bot
122 # bot's object registry, plugins get an interface to this for persistant
123 # storage (hash interface tied to a bdb file, plugins use Accessors to store
124 # and restore objects in their own namespaces.)
125 attr_reader :registry
127 # bot's plugins. This is an instance of class Plugins
130 # bot's httputil help object, for fetching resources via http. Sets up
131 # proxies etc as defined by the bot configuration/environment
132 attr_reader :httputil
134 # bot User in the client/server connection
137 # bot User in the client/server connection
142 # create a new IrcBot with botclass +botclass+
143 def initialize(botclass, params = {})
144 # BotConfig for the core bot
145 # TODO should we split socket stuff into ircsocket, etc?
146 BotConfig.register BotConfigStringValue.new('server.name',
147 :default => "localhost", :requires_restart => true,
148 :desc => "What server should the bot connect to?",
150 BotConfig.register BotConfigIntegerValue.new('server.port',
151 :default => 6667, :type => :integer, :requires_restart => true,
152 :desc => "What port should the bot connect to?",
153 :validate => Proc.new {|v| v > 0}, :wizard => true)
154 BotConfig.register BotConfigStringValue.new('server.password',
155 :default => false, :requires_restart => true,
156 :desc => "Password for connecting to this server (if required)",
158 BotConfig.register BotConfigStringValue.new('server.bindhost',
159 :default => false, :requires_restart => true,
160 :desc => "Specific local host or IP for the bot to bind to (if required)",
162 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
163 :default => 5, :validate => Proc.new{|v| v >= 0},
164 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
165 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
166 :default => 2.0, :validate => Proc.new{|v| v >= 0},
167 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
168 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
169 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
170 :default => 4, :validate => Proc.new{|v| v >= 0},
171 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
172 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
173 BotConfig.register BotConfigStringValue.new('server.byterate',
174 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
175 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
176 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
177 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
178 :default => 30, :validate => Proc.new{|v| v >= 0},
179 :on_change => Proc.new {|bot, v| bot.start_server_pings},
180 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
182 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
183 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
184 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
185 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
186 :requires_restart => true,
187 :desc => "local user the bot should appear to be", :wizard => true)
188 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
189 :default => [], :wizard => true,
190 :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'")
191 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
193 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
195 BotConfig.register BotConfigIntegerValue.new('core.save_every',
196 :default => 60, :validate => Proc.new{|v| v >= 0},
197 # TODO change timer via on_change proc
198 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
200 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
201 :default => false, :requires_restart => true,
202 :desc => "Should the bot run as a daemon?")
204 BotConfig.register BotConfigStringValue.new('log.file',
205 :default => false, :requires_restart => true,
206 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
207 BotConfig.register BotConfigIntegerValue.new('log.level',
208 :default => 1, :requires_restart => false,
209 :validate => Proc.new { |v| (0..5).include?(v) },
210 :on_change => Proc.new { |bot, v|
213 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
214 BotConfig.register BotConfigIntegerValue.new('log.keep',
215 :default => 1, :requires_restart => true,
216 :validate => Proc.new { |v| v >= 0 },
217 :desc => "How many old console messages logfiles to keep")
218 BotConfig.register BotConfigIntegerValue.new('log.max_size',
219 :default => 10, :requires_restart => true,
220 :validate => Proc.new { |v| v > 0 },
221 :desc => "Maximum console messages logfile size (in megabytes)")
223 @argv = params[:argv]
225 unless FileTest.directory? Config::coredir
226 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
230 unless FileTest.directory? Config::datadir
231 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
235 unless botclass and not botclass.empty?
236 # We want to find a sensible default.
237 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
238 # * On Windows (at least the NT versions) we want to put our stuff in the
239 # Application Data folder.
240 # We don't use any particular O/S detection magic, exploiting the fact that
241 # Etc.getpwuid is nil on Windows
242 if Etc.getpwuid(Process::Sys.geteuid)
243 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
245 if ENV.has_key?('APPDATA')
246 botclass = ENV['APPDATA'].dup
247 botclass.gsub!("\\","/")
252 botclass = File.expand_path(botclass)
253 @botclass = botclass.gsub(/\/$/, "")
255 unless FileTest.directory? botclass
256 log "no #{botclass} directory found, creating from templates.."
257 if FileTest.exist? botclass
258 error "file #{botclass} exists but isn't a directory"
261 FileUtils.cp_r Config::datadir+'/templates', botclass
264 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
265 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
270 @startup_time = Time.new
271 @config = BotConfig.new(self)
273 if @config['core.run_as_daemon']
277 @logfile = @config['log.file']
278 if @logfile.class!=String || @logfile.empty?
279 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
282 # See http://blog.humlab.umu.se/samuel/archives/000107.html
283 # for the backgrounding code
289 rescue NotImplementedError
290 warning "Could not background, fork not supported"
292 warning "Could not background. #{e.inspect}"
295 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
296 log "Redirecting standard input/output/error"
298 STDIN.reopen "/dev/null"
300 # On Windows, there's not such thing as /dev/null
303 def STDOUT.write(str=nil)
305 return str.to_s.length
307 def STDERR.write(str=nil)
308 if str.to_s.match(/:\d+: warning:/)
313 return str.to_s.length
317 # Set the new logfile and loglevel. This must be done after the daemonizing
318 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
319 $logger.datetime_format= $dateformat
320 $logger.level = @config['log.level']
321 $logger.level = $cl_loglevel if $cl_loglevel
322 $logger.level = 0 if $debug
326 @registry = BotRegistry.new self
328 @timer = Timer::Timer.new(1.0) # only need per-second granularity
329 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
333 @httputil = Utils::HttpUtil.new(self)
335 @lang = Language::Language.new(@config['core.language'])
337 # @keywords = Keywords.new(self)
340 @auth = Auth::authmanager
341 @auth.bot_associate(self)
342 # @auth.load("#{botclass}/botusers.yaml")
345 fatal e.backtrace.join("\n")
349 @auth.everyone.set_default_permission("*", true)
351 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
352 @plugins = Plugins::pluginmanager
353 @plugins.bot_associate(self)
354 @plugins.add_botmodule_dir(Config::coredir)
355 @plugins.add_botmodule_dir("#{botclass}/plugins")
356 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
359 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
360 @client = IrcClient.new
361 @server = @client.server
362 @myself = @client.client
363 @myself.nick = @config['irc.nick']
365 # Channels where we are quiet
366 # It's nil when we are not quiet, an empty list when we are quiet
367 # in all channels, a list of channels otherwise
370 @client[:welcome] = proc {|data|
371 irclog "joined server #{@client.server} as #{myself}", "server"
373 @plugins.delegate("connect")
375 @config['irc.join_channels'].each { |c|
376 debug "autojoining channel #{c}"
377 if(c =~ /^(\S+)\s+(\S+)$/i)
384 @client[:isupport] = proc { |data|
385 # TODO this needs to go into rfc2812.rb
386 # Since capabs are two-steps processes, server.supports[:capab]
387 # should be a three-state: nil, [], [....]
388 sendq "CAPAB IDENTIFY-MSG" if @server.supports[:capab]
390 @client[:datastr] = proc { |data|
391 # TODO this needs to go into rfc2812.rb
392 if data[:text] == "IDENTIFY-MSG"
393 @server.capabilities["identify-msg".to_sym] = true
395 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
398 @client[:privmsg] = proc { |data|
399 m = PrivMessage.new(self, @server, data[:source], data[:target], data[:message])
401 # TODO use the new Netmask class
402 # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
406 @plugins.delegate "listen", m
409 @client[:notice] = proc { |data|
410 message = NoticeMessage.new(self, @server, data[:source], data[:target], data[:message])
411 # pass it off to plugins that want to hear everything
412 @plugins.delegate "listen", message
414 @client[:motd] = proc { |data|
415 data[:motd].each_line { |line|
416 irclog "MOTD: #{line}", "server"
419 @client[:nicktaken] = proc { |data|
420 nickchg "#{data[:nick]}_"
421 @plugins.delegate "nicktaken", data[:nick]
423 @client[:badnick] = proc {|data|
424 warning "bad nick (#{data[:nick]})"
426 @client[:ping] = proc {|data|
427 sendq "PONG #{data[:pingid]}"
429 @client[:pong] = proc {|data|
432 @client[:nick] = proc {|data|
433 source = data[:source]
436 m = NickMessage.new(self, @server, source, old, new)
438 debug "my nick is now #{new}"
440 data[:is_on].each { |ch|
441 irclog "@ #{old} is now known as #{new}", ch
443 @plugins.delegate("listen", m)
444 @plugins.delegate("nick", m)
446 @client[:quit] = proc {|data|
447 source = data[:source]
448 message = data[:message]
449 m = QuitMessage.new(self, @server, source, source, message)
450 data[:was_on].each { |ch|
451 irclog "@ Quit: #{source}: #{message}", ch
453 @plugins.delegate("listen", m)
454 @plugins.delegate("quit", m)
456 @client[:mode] = proc {|data|
457 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
459 @client[:join] = proc {|data|
460 m = JoinMessage.new(self, @server, data[:source], data[:channel], data[:message])
463 @plugins.delegate("listen", m)
464 @plugins.delegate("join", m)
466 @client[:part] = proc {|data|
467 m = PartMessage.new(self, @server, data[:source], data[:channel], data[:message])
470 @plugins.delegate("listen", m)
471 @plugins.delegate("part", m)
473 @client[:kick] = proc {|data|
474 m = KickMessage.new(self, @server, data[:source], data[:target], data[:channel],data[:message])
477 @plugins.delegate("listen", m)
478 @plugins.delegate("kick", m)
480 @client[:invite] = proc {|data|
481 if data[:target] == myself
482 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
485 @client[:changetopic] = proc {|data|
486 m = TopicMessage.new(self, @server, data[:source], data[:channel], data[:topic])
489 @plugins.delegate("listen", m)
490 @plugins.delegate("topic", m)
492 @client[:topic] = proc { |data|
493 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
495 @client[:topicinfo] = proc { |data|
496 channel = data[:channel]
497 topic = channel.topic
498 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
499 m = TopicMessage.new(self, @server, data[:source], channel, topic)
501 @plugins.delegate("listen", m)
502 @plugins.delegate("topic", m)
504 @client[:names] = proc { |data|
505 @plugins.delegate "names", data[:channel], data[:users]
507 @client[:unknown] = proc { |data|
508 #debug "UNKNOWN: #{data[:serverstring]}"
509 irclog data[:serverstring], ".unknown"
513 # checks if we should be quiet on a channel
514 def quiet_on?(channel)
515 return false unless @quiet
516 return true if @quiet.empty?
517 return @quiet.include?(channel.to_s)
520 def set_quiet(channel=nil)
522 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
528 def reset_quiet(channel=nil)
530 @quiet.delete_if { |x| x == channel.to_s }
536 # things to do when we receive a signal
538 debug "received #{sig}, queueing quit"
540 debug "interrupted #{$interrupted} times"
545 elsif $interrupted >= 3
551 # connect the bot to IRC
554 trap("SIGINT") { got_sig("SIGINT") }
555 trap("SIGTERM") { got_sig("SIGTERM") }
556 trap("SIGHUP") { got_sig("SIGHUP") }
557 rescue ArgumentError => e
558 debug "failed to trap signals (#{e.inspect}): running on Windows?"
560 debug "failed to trap signals: #{e.inspect}"
563 quit if $interrupted > 0
566 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
568 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
569 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
573 # begin event handling loop
577 quit if $interrupted > 0
581 while @socket.connected?
583 break unless reply = @socket.gets
584 @client.process reply
586 quit if $interrupted > 0
589 # I despair of this. Some of my users get "connection reset by peer"
590 # exceptions that ARENT SocketError's. How am I supposed to handle
595 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
596 error "network exception: #{e.class}: #{e}"
597 debug e.backtrace.join("\n")
598 rescue BDB::Fatal => e
599 fatal "fatal bdb error: #{e.class}: #{e}"
600 fatal e.backtrace.join("\n")
602 # Why restart? DB problems are serious stuff ...
603 # restart("Oops, we seem to have registry problems ...")
606 rescue Exception => e
607 error "non-net exception: #{e.class}: #{e}"
608 error e.backtrace.join("\n")
610 fatal "unexpected exception: #{e.class}: #{e}"
611 fatal e.backtrace.join("\n")
618 if @socket.connected?
625 quit if $interrupted > 0
627 log "waiting to reconnect"
628 sleep @config['server.reconnect_wait']
632 # type:: message type
633 # where:: message target
634 # message:: message text
635 # send message +message+ of type +type+ to target +where+
636 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
637 # relevant say() or notice() methods. This one should be used for IRCd
638 # extensions you want to use in modules.
639 def sendmsg(type, where, message, chan=nil, ring=0)
640 # limit it according to the byterate, splitting the message
641 # taking into consideration the actual message length
642 # and all the extra stuff
643 # TODO allow something to do for commands that produce too many messages
644 # TODO example: math 10**10000
645 left = @socket.bytes_per - type.length - where.to_s.length - 4
647 if(left >= message.length)
648 sendq "#{type} #{where} :#{message}", chan, ring
649 log_sent(type, where, message)
652 line = message.slice!(0, left)
653 lastspace = line.rindex(/\s+/)
655 message = line.slice!(lastspace, line.length) + message
656 message.gsub!(/^\s+/, "")
658 sendq "#{type} #{where} :#{line}", chan, ring
659 log_sent(type, where, line)
660 end while(message.length > 0)
663 # queue an arbitraty message for the server
664 def sendq(message="", chan=nil, ring=0)
666 @socket.queue(message, chan, ring)
669 # send a notice message to channel/nick +where+
670 def notice(where, message, mchan="", mring=-1)
686 message.each_line { |line|
688 next unless(line.length > 0)
689 sendmsg "NOTICE", where, line, chan, ring
693 # say something (PRIVMSG) to channel/nick +where+
694 def say(where, message, mchan="", mring=-1)
710 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
712 next unless(line.length > 0)
713 unless quiet_on?(where)
714 sendmsg "PRIVMSG", where, line, chan, ring
719 # perform a CTCP action with message +message+ to channel/nick +where+
720 def action(where, message, mchan="", mring=-1)
736 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
739 irclog "* #{myself} #{message}", where
741 irclog "* #{myself}[#{where}] #{message}", where
745 # quick way to say "okay" (or equivalent) to +where+
747 say where, @lang.get("okay")
750 # log IRC-related message +message+ to a file determined by +where+.
751 # +where+ can be a channel name, or a nick for private message logging
752 def irclog(message, where="server")
753 message = message.chomp
754 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
755 where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
756 unless(@logs.has_key?(where))
757 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
758 @logs[where].sync = true
760 @logs[where].puts "[#{stamp}] #{message}"
761 #debug "[#{stamp}] <#{where}> #{message}"
764 # set topic of channel +where+ to +topic+
765 def topic(where, topic)
766 sendq "TOPIC #{where} :#{topic}", where, 2
769 # disconnect from the server and cleanup all plugins and modules
770 def shutdown(message = nil)
771 debug "Shutting down ..."
772 ## No we don't restore them ... let everything run through
774 # trap("SIGINT", "DEFAULT")
775 # trap("SIGTERM", "DEFAULT")
776 # trap("SIGHUP", "DEFAULT")
778 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
780 message = @lang.get("quit") if (message.nil? || message.empty?)
781 if @socket.connected?
782 debug "Clearing socket"
784 debug "Sending quit message"
785 @socket.emergency_puts "QUIT :#{message}"
786 debug "Flushing socket"
788 debug "Shutting down socket"
791 debug "Logging quits"
792 @server.channels.each { |ch|
793 irclog "@ quit (#{message})", ch
799 # debug "Closing registries"
801 debug "Cleaning up the db environment"
803 log "rbot quit (#{message})"
806 # message:: optional IRC quit message
807 # quit IRC, shutdown the bot
808 def quit(message=nil)
816 # totally shutdown and respawn the bot
817 def restart(message = false)
818 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
820 sleep @config['server.reconnect_wait']
822 # Note, this fails on Windows
826 # call the save method for bot's config, keywords, auth and all plugins
835 # call the rescan method for the bot's lang, keywords and all plugins
842 # channel:: channel to join
843 # key:: optional channel key if channel is +s
845 def join(channel, key=nil)
847 sendq "JOIN #{channel} :#{key}", channel, 2
849 sendq "JOIN #{channel}", channel, 2
854 def part(channel, message="")
855 sendq "PART #{channel} :#{message}", channel, 2
858 # attempt to change bot's nick to +name+
864 def mode(channel, mode, target)
865 sendq "MODE #{channel} #{mode} #{target}", channel, 2
868 # m:: message asking for help
869 # topic:: optional topic help is requested for
870 # respond to online help requests
872 topic = nil if topic == ""
875 helpstr = "help topics: "
876 helpstr += @plugins.helptopics
877 helpstr += " (help <topic> for more info)"
879 unless(helpstr = @plugins.help(topic))
880 helpstr = "no help for topic #{topic}"
886 # returns a string describing the current status of the bot (uptime etc)
888 secs_up = Time.new - @startup_time
889 uptime = Utils.secs_to_string secs_up
890 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
891 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
894 # we'll ping the server every 30 seconds or so, and expect a response
895 # before the next one come around..
896 def start_server_pings
898 return unless @config['server.ping_timeout'] > 0
899 # we want to respond to a hung server within 30 secs or so
900 @ping_timer = @timer.add(30) {
901 @last_ping = Time.now
902 @socket.queue "PING :rbot"
904 @pong_timer = @timer.add(10) {
905 unless @last_ping.nil?
906 diff = Time.now - @last_ping
907 unless diff < @config['server.ping_timeout']
908 debug "no PONG from server for #{diff} seconds, reconnecting"
912 debug "couldn't shutdown connection (already shutdown?)"
915 raise TimeoutError, "no PONG from server in #{diff} seconds"
921 def stop_server_pings
923 # stop existing timers if running
924 unless @ping_timer.nil?
925 @timer.remove @ping_timer
928 unless @pong_timer.nil?
929 @timer.remove @pong_timer
939 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
941 irclog "* #{m.sourcenick} #{m.message}", m.target
945 irclog "<#{m.sourcenick}> #{m.message}", m.target
947 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
952 # log a message. Internal use only.
953 def log_sent(type, where, message)
958 irclog "-=#{myself}=- #{message}", where
960 irclog "[-=#{where}=-] #{message}", $1
962 irclog "[-=#{where}=-] #{message}", where
967 irclog "<#{myself}> #{message}", where
969 irclog "[msg(#{where})] #{message}", $1
971 irclog "[msg(#{where})] #{message}", where
978 debug "joined channel #{m.channel}"
979 irclog "@ Joined channel #{m.channel}", m.channel
981 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
987 debug "left channel #{m.channel}"
988 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
990 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
996 debug "kicked from channel #{m.channel}"
997 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
999 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1004 if m.source == myself
1005 irclog "@ I set topic \"#{m.topic}\"", m.channel
1007 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel