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
273 @config = BotConfig.configmanager
274 @config.bot_associate(self)
277 fatal e.backtrace.join("\n")
282 if @config['core.run_as_daemon']
286 @logfile = @config['log.file']
287 if @logfile.class!=String || @logfile.empty?
288 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
291 # See http://blog.humlab.umu.se/samuel/archives/000107.html
292 # for the backgrounding code
298 rescue NotImplementedError
299 warning "Could not background, fork not supported"
301 warning "Could not background. #{e.inspect}"
304 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
305 log "Redirecting standard input/output/error"
307 STDIN.reopen "/dev/null"
309 # On Windows, there's not such thing as /dev/null
312 def STDOUT.write(str=nil)
314 return str.to_s.length
316 def STDERR.write(str=nil)
317 if str.to_s.match(/:\d+: warning:/)
322 return str.to_s.length
326 # Set the new logfile and loglevel. This must be done after the daemonizing
327 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
328 $logger.datetime_format= $dateformat
329 $logger.level = @config['log.level']
330 $logger.level = $cl_loglevel if $cl_loglevel
331 $logger.level = 0 if $debug
335 @registry = BotRegistry.new self
337 @timer = Timer::Timer.new(1.0) # only need per-second granularity
338 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
342 @httputil = Utils::HttpUtil.new(self)
344 @lang = Language::Language.new(@config['core.language'])
346 # @keywords = Keywords.new(self)
349 @auth = Auth::authmanager
350 @auth.bot_associate(self)
351 # @auth.load("#{botclass}/botusers.yaml")
354 fatal e.backtrace.join("\n")
358 @auth.everyone.set_default_permission("*", true)
360 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
361 @plugins = Plugins::pluginmanager
362 @plugins.bot_associate(self)
363 @plugins.add_botmodule_dir(Config::coredir)
364 @plugins.add_botmodule_dir("#{botclass}/plugins")
365 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
368 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
369 @client = IrcClient.new
370 @server = @client.server
371 @myself = @client.client
372 @myself.nick = @config['irc.nick']
374 # Channels where we are quiet
375 # It's nil when we are not quiet, an empty list when we are quiet
376 # in all channels, a list of channels otherwise
379 @client[:welcome] = proc {|data|
380 irclog "joined server #{@client.server} as #{myself}", "server"
382 @plugins.delegate("connect")
384 @config['irc.join_channels'].each { |c|
385 debug "autojoining channel #{c}"
386 if(c =~ /^(\S+)\s+(\S+)$/i)
393 @client[:isupport] = proc { |data|
394 # TODO this needs to go into rfc2812.rb
395 # Since capabs are two-steps processes, server.supports[:capab]
396 # should be a three-state: nil, [], [....]
397 sendq "CAPAB IDENTIFY-MSG" if @server.supports[:capab]
399 @client[:datastr] = proc { |data|
400 # TODO this needs to go into rfc2812.rb
401 if data[:text] == "IDENTIFY-MSG"
402 @server.capabilities["identify-msg".to_sym] = true
404 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
407 @client[:privmsg] = proc { |data|
408 m = PrivMessage.new(self, @server, data[:source], data[:target], data[:message])
410 # TODO use the new Netmask class
411 # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
415 @plugins.delegate "listen", m
416 @plugins.privmsg(m) if m.address?
418 @client[:notice] = proc { |data|
419 message = NoticeMessage.new(self, @server, data[:source], data[:target], data[:message])
420 # pass it off to plugins that want to hear everything
421 @plugins.delegate "listen", message
423 @client[:motd] = proc { |data|
424 data[:motd].each_line { |line|
425 irclog "MOTD: #{line}", "server"
428 @client[:nicktaken] = proc { |data|
429 nickchg "#{data[:nick]}_"
430 @plugins.delegate "nicktaken", data[:nick]
432 @client[:badnick] = proc {|data|
433 warning "bad nick (#{data[:nick]})"
435 @client[:ping] = proc {|data|
436 sendq "PONG #{data[:pingid]}"
438 @client[:pong] = proc {|data|
441 @client[:nick] = proc {|data|
442 source = data[:source]
445 m = NickMessage.new(self, @server, source, old, new)
447 debug "my nick is now #{new}"
449 data[:is_on].each { |ch|
450 irclog "@ #{old} is now known as #{new}", ch
452 @plugins.delegate("listen", m)
453 @plugins.delegate("nick", m)
455 @client[:quit] = proc {|data|
456 source = data[:source]
457 message = data[:message]
458 m = QuitMessage.new(self, @server, source, source, message)
459 data[:was_on].each { |ch|
460 irclog "@ Quit: #{source}: #{message}", ch
462 @plugins.delegate("listen", m)
463 @plugins.delegate("quit", m)
465 @client[:mode] = proc {|data|
466 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
468 @client[:join] = proc {|data|
469 m = JoinMessage.new(self, @server, data[:source], data[:channel], data[:message])
472 @plugins.delegate("listen", m)
473 @plugins.delegate("join", m)
475 @client[:part] = proc {|data|
476 m = PartMessage.new(self, @server, data[:source], data[:channel], data[:message])
479 @plugins.delegate("listen", m)
480 @plugins.delegate("part", m)
482 @client[:kick] = proc {|data|
483 m = KickMessage.new(self, @server, data[:source], data[:target], data[:channel],data[:message])
486 @plugins.delegate("listen", m)
487 @plugins.delegate("kick", m)
489 @client[:invite] = proc {|data|
490 if data[:target] == myself
491 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
494 @client[:changetopic] = proc {|data|
495 m = TopicMessage.new(self, @server, data[:source], data[:channel], data[:topic])
498 @plugins.delegate("listen", m)
499 @plugins.delegate("topic", m)
501 @client[:topic] = proc { |data|
502 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
504 @client[:topicinfo] = proc { |data|
505 channel = data[:channel]
506 topic = channel.topic
507 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
508 m = TopicMessage.new(self, @server, data[:source], channel, topic)
510 @plugins.delegate("listen", m)
511 @plugins.delegate("topic", m)
513 @client[:names] = proc { |data|
514 @plugins.delegate "names", data[:channel], data[:users]
516 @client[:unknown] = proc { |data|
517 #debug "UNKNOWN: #{data[:serverstring]}"
518 irclog data[:serverstring], ".unknown"
522 # checks if we should be quiet on a channel
523 def quiet_on?(channel)
524 return false unless @quiet
525 return true if @quiet.empty?
526 return @quiet.include?(channel.to_s)
529 def set_quiet(channel=nil)
531 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
537 def reset_quiet(channel=nil)
539 @quiet.delete_if { |x| x == channel.to_s }
545 # things to do when we receive a signal
547 debug "received #{sig}, queueing quit"
549 debug "interrupted #{$interrupted} times"
554 elsif $interrupted >= 3
560 # connect the bot to IRC
563 trap("SIGINT") { got_sig("SIGINT") }
564 trap("SIGTERM") { got_sig("SIGTERM") }
565 trap("SIGHUP") { got_sig("SIGHUP") }
566 rescue ArgumentError => e
567 debug "failed to trap signals (#{e.inspect}): running on Windows?"
569 debug "failed to trap signals: #{e.inspect}"
572 quit if $interrupted > 0
575 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
577 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
578 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
582 # begin event handling loop
586 quit if $interrupted > 0
590 while @socket.connected?
592 break unless reply = @socket.gets
593 @client.process reply
595 quit if $interrupted > 0
598 # I despair of this. Some of my users get "connection reset by peer"
599 # exceptions that ARENT SocketError's. How am I supposed to handle
604 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
605 error "network exception: #{e.class}: #{e}"
606 debug e.backtrace.join("\n")
607 rescue BDB::Fatal => e
608 fatal "fatal bdb error: #{e.class}: #{e}"
609 fatal e.backtrace.join("\n")
611 # Why restart? DB problems are serious stuff ...
612 # restart("Oops, we seem to have registry problems ...")
615 rescue Exception => e
616 error "non-net exception: #{e.class}: #{e}"
617 error e.backtrace.join("\n")
619 fatal "unexpected exception: #{e.class}: #{e}"
620 fatal e.backtrace.join("\n")
627 if @socket.connected?
634 quit if $interrupted > 0
636 log "waiting to reconnect"
637 sleep @config['server.reconnect_wait']
641 # type:: message type
642 # where:: message target
643 # message:: message text
644 # send message +message+ of type +type+ to target +where+
645 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
646 # relevant say() or notice() methods. This one should be used for IRCd
647 # extensions you want to use in modules.
648 def sendmsg(type, where, message, chan=nil, ring=0)
649 # limit it according to the byterate, splitting the message
650 # taking into consideration the actual message length
651 # and all the extra stuff
652 # TODO allow something to do for commands that produce too many messages
653 # TODO example: math 10**10000
654 left = @socket.bytes_per - type.length - where.to_s.length - 4
656 if(left >= message.length)
657 sendq "#{type} #{where} :#{message}", chan, ring
658 log_sent(type, where, message)
661 line = message.slice!(0, left)
662 lastspace = line.rindex(/\s+/)
664 message = line.slice!(lastspace, line.length) + message
665 message.gsub!(/^\s+/, "")
667 sendq "#{type} #{where} :#{line}", chan, ring
668 log_sent(type, where, line)
669 end while(message.length > 0)
672 # queue an arbitraty message for the server
673 def sendq(message="", chan=nil, ring=0)
675 @socket.queue(message, chan, ring)
678 # send a notice message to channel/nick +where+
679 def notice(where, message, mchan="", mring=-1)
695 message.each_line { |line|
697 next unless(line.length > 0)
698 sendmsg "NOTICE", where, line, chan, ring
702 # say something (PRIVMSG) to channel/nick +where+
703 def say(where, message, mchan="", mring=-1)
719 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
721 next unless(line.length > 0)
722 unless quiet_on?(where)
723 sendmsg "PRIVMSG", where, line, chan, ring
728 # perform a CTCP action with message +message+ to channel/nick +where+
729 def action(where, message, mchan="", mring=-1)
745 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
748 irclog "* #{myself} #{message}", where
750 irclog "* #{myself}[#{where}] #{message}", where
754 # quick way to say "okay" (or equivalent) to +where+
756 say where, @lang.get("okay")
759 # log IRC-related message +message+ to a file determined by +where+.
760 # +where+ can be a channel name, or a nick for private message logging
761 def irclog(message, where="server")
762 message = message.chomp
763 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
764 where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
765 unless(@logs.has_key?(where))
766 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
767 @logs[where].sync = true
769 @logs[where].puts "[#{stamp}] #{message}"
770 #debug "[#{stamp}] <#{where}> #{message}"
773 # set topic of channel +where+ to +topic+
774 def topic(where, topic)
775 sendq "TOPIC #{where} :#{topic}", where, 2
778 # disconnect from the server and cleanup all plugins and modules
779 def shutdown(message = nil)
780 debug "Shutting down ..."
781 ## No we don't restore them ... let everything run through
783 # trap("SIGINT", "DEFAULT")
784 # trap("SIGTERM", "DEFAULT")
785 # trap("SIGHUP", "DEFAULT")
787 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
789 message = @lang.get("quit") if (message.nil? || message.empty?)
790 if @socket.connected?
791 debug "Clearing socket"
793 debug "Sending quit message"
794 @socket.emergency_puts "QUIT :#{message}"
795 debug "Flushing socket"
797 debug "Shutting down socket"
800 debug "Logging quits"
801 @server.channels.each { |ch|
802 irclog "@ quit (#{message})", ch
808 # debug "Closing registries"
810 debug "Cleaning up the db environment"
812 log "rbot quit (#{message})"
815 # message:: optional IRC quit message
816 # quit IRC, shutdown the bot
817 def quit(message=nil)
825 # totally shutdown and respawn the bot
826 def restart(message = false)
827 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
829 sleep @config['server.reconnect_wait']
831 # Note, this fails on Windows
835 # call the save method for bot's config, keywords, auth and all plugins
844 # call the rescan method for the bot's lang, keywords and all plugins
851 # channel:: channel to join
852 # key:: optional channel key if channel is +s
854 def join(channel, key=nil)
856 sendq "JOIN #{channel} :#{key}", channel, 2
858 sendq "JOIN #{channel}", channel, 2
863 def part(channel, message="")
864 sendq "PART #{channel} :#{message}", channel, 2
867 # attempt to change bot's nick to +name+
873 def mode(channel, mode, target)
874 sendq "MODE #{channel} #{mode} #{target}", channel, 2
877 # m:: message asking for help
878 # topic:: optional topic help is requested for
879 # respond to online help requests
881 topic = nil if topic == ""
884 helpstr = "help topics: "
885 helpstr += @plugins.helptopics
886 helpstr += " (help <topic> for more info)"
888 unless(helpstr = @plugins.help(topic))
889 helpstr = "no help for topic #{topic}"
895 # returns a string describing the current status of the bot (uptime etc)
897 secs_up = Time.new - @startup_time
898 uptime = Utils.secs_to_string secs_up
899 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
900 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
903 # we'll ping the server every 30 seconds or so, and expect a response
904 # before the next one come around..
905 def start_server_pings
907 return unless @config['server.ping_timeout'] > 0
908 # we want to respond to a hung server within 30 secs or so
909 @ping_timer = @timer.add(30) {
910 @last_ping = Time.now
911 @socket.queue "PING :rbot"
913 @pong_timer = @timer.add(10) {
914 unless @last_ping.nil?
915 diff = Time.now - @last_ping
916 unless diff < @config['server.ping_timeout']
917 debug "no PONG from server for #{diff} seconds, reconnecting"
921 debug "couldn't shutdown connection (already shutdown?)"
924 raise TimeoutError, "no PONG from server in #{diff} seconds"
930 def stop_server_pings
932 # stop existing timers if running
933 unless @ping_timer.nil?
934 @timer.remove @ping_timer
937 unless @pong_timer.nil?
938 @timer.remove @pong_timer
948 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
950 irclog "* #{m.sourcenick} #{m.message}", m.target
954 irclog "<#{m.sourcenick}> #{m.message}", m.target
956 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
961 # log a message. Internal use only.
962 def log_sent(type, where, message)
967 irclog "-=#{myself}=- #{message}", where
969 irclog "[-=#{where}=-] #{message}", $1
971 irclog "[-=#{where}=-] #{message}", where
976 irclog "<#{myself}> #{message}", where
978 irclog "[msg(#{where})] #{message}", $1
980 irclog "[msg(#{where})] #{message}", where
987 debug "joined channel #{m.channel}"
988 irclog "@ Joined channel #{m.channel}", m.channel
990 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
996 debug "left channel #{m.channel}"
997 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
999 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1005 debug "kicked from channel #{m.channel}"
1006 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1008 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1013 if m.source == myself
1014 irclog "@ I set topic \"#{m.topic}\"", m.channel
1016 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel