]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
DB backend option
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot core
5
6 require 'thread'
7
8 require 'etc'
9 require 'fileutils'
10 require 'logger'
11
12 $debug = false unless $debug
13 $daemonize = false unless $daemonize
14
15 $dateformat = "%Y/%m/%d %H:%M:%S"
16 $logger = Logger.new($stderr)
17 $logger.datetime_format = $dateformat
18 $logger.level = $cl_loglevel if defined? $cl_loglevel
19 $logger.level = 0 if $debug
20
21 $log_queue = Queue.new
22 $log_thread = nil
23
24 require 'pp'
25
26 unless Kernel.respond_to? :pretty_inspect
27   def pretty_inspect
28     PP.pp(self, '')
29   end
30   public :pretty_inspect
31 end
32
33 class Exception
34   def pretty_print(q)
35     q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
36       if self.backtrace and not self.backtrace.empty?
37         q.text "\n"
38         q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
39       end
40     }
41   end
42 end
43
44 class ServerError < RuntimeError
45 end
46
47 def rawlog(level, message=nil, who_pos=1)
48   call_stack = caller
49   if call_stack.length > who_pos
50     who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
51   else
52     who = "(unknown)"
53   end
54   # Output each line. To distinguish between separate messages and multi-line
55   # messages originating at the same time, we blank #{who} after the first message
56   # is output.
57   # Also, we output strings as-is but for other objects we use pretty_inspect
58   case message
59   when String
60     str = message
61   else
62     str = message.pretty_inspect
63   end
64   qmsg = Array.new
65   str.each_line { |l|
66     qmsg.push [level, l.chomp, who]
67     who = ' ' * who.size
68   }
69   $log_queue.push qmsg
70 end
71
72 def halt_logger
73   if $log_thread && $log_thread.alive?
74     $log_queue << nil
75     $log_thread.join
76     $log_thread = nil
77   end
78 end
79
80 END { halt_logger }
81
82 def restart_logger(newlogger = false)
83   halt_logger
84
85   $logger = newlogger if newlogger
86
87   $log_thread = Thread.new do
88     ls = nil
89     while ls = $log_queue.pop
90       ls.each { |l| $logger.add(*l) }
91     end
92   end
93 end
94
95 restart_logger
96
97 def log_session_start
98   $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
99   restart_logger
100 end
101
102 def log_session_end
103   $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
104   $log_queue << nil
105 end
106
107 def debug(message=nil, who_pos=1)
108   rawlog(Logger::Severity::DEBUG, message, who_pos)
109 end
110
111 def log(message=nil, who_pos=1)
112   rawlog(Logger::Severity::INFO, message, who_pos)
113 end
114
115 def warning(message=nil, who_pos=1)
116   rawlog(Logger::Severity::WARN, message, who_pos)
117 end
118
119 def error(message=nil, who_pos=1)
120   rawlog(Logger::Severity::ERROR, message, who_pos)
121 end
122
123 def fatal(message=nil, who_pos=1)
124   rawlog(Logger::Severity::FATAL, message, who_pos)
125 end
126
127 debug "debug test"
128 log "log test"
129 warning "warning test"
130 error "error test"
131 fatal "fatal test"
132
133 # The following global is used for the improved signal handling.
134 $interrupted = 0
135
136 # these first
137 require 'rbot/rbotconfig'
138 begin
139   require 'rubygems'
140 rescue LoadError
141   log "rubygems unavailable"
142 end
143
144 require 'rbot/load-gettext'
145 require 'rbot/config'
146 require 'rbot/config-compat'
147
148 require 'rbot/irc'
149 require 'rbot/rfc2812'
150 require 'rbot/ircsocket'
151 require 'rbot/botuser'
152 require 'rbot/timer'
153 require 'rbot/plugins'
154 require 'rbot/message'
155 require 'rbot/language'
156
157 module Irc
158
159 # Main bot class, which manages the various components, receives messages,
160 # handles them or passes them to plugins, and contains core functionality.
161 class Bot
162   COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
163   SOURCE_URL = "http://ruby-rbot.org"
164   # the bot's Auth data
165   attr_reader :auth
166
167   # the bot's Config data
168   attr_reader :config
169
170   # the botclass for this bot (determines configdir among other things)
171   attr_reader :botclass
172
173   # used to perform actions periodically (saves configuration once per minute
174   # by default)
175   attr_reader :timer
176
177   # synchronize with this mutex while touching permanent data files:
178   # saving, flushing, cleaning up ...
179   attr_reader :save_mutex
180
181   # bot's Language data
182   attr_reader :lang
183
184   # bot's irc socket
185   # TODO multiserver
186   attr_reader :socket
187
188   # bot's object registry, plugins get an interface to this for persistant
189   # storage (hash interface tied to a bdb file, plugins use Accessors to store
190   # and restore objects in their own namespaces.)
191   attr_reader :registry
192
193   # bot's plugins. This is an instance of class Plugins
194   attr_reader :plugins
195
196   # bot's httputil help object, for fetching resources via http. Sets up
197   # proxies etc as defined by the bot configuration/environment
198   attr_accessor :httputil
199
200   # server we are connected to
201   # TODO multiserver
202   def server
203     @client.server
204   end
205
206   # bot User in the client/server connection
207   # TODO multiserver
208   def myself
209     @client.user
210   end
211
212   # bot nick in the client/server connection
213   def nick
214     myself.nick
215   end
216
217   # bot channels in the client/server connection
218   def channels
219     myself.channels
220   end
221
222   # nick wanted by the bot. This defaults to the irc.nick config value,
223   # but may be overridden by a manual !nick command
224   def wanted_nick
225     @wanted_nick || config['irc.nick']
226   end
227
228   # set the nick wanted by the bot
229   def wanted_nick=(wn)
230     if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
231       @wanted_nick = nil
232     else
233       @wanted_nick = wn.to_s.dup
234     end
235   end
236
237
238   # bot inspection
239   # TODO multiserver
240   def inspect
241     ret = self.to_s[0..-2]
242     ret << ' version=' << $version.inspect
243     ret << ' botclass=' << botclass.inspect
244     ret << ' lang="' << lang.language
245     if defined?(GetText)
246       ret << '/' << locale
247     end
248     ret << '"'
249     ret << ' nick=' << nick.inspect
250     ret << ' server='
251     if server
252       ret << (server.to_s + (socket ?
253         ' [' << socket.server_uri.to_s << ']' : '')).inspect
254       unless server.channels.empty?
255         ret << " channels="
256         ret << server.channels.map { |c|
257           "%s%s" % [c.modes_of(nick).map { |m|
258             server.prefix_for_mode(m)
259           }, c.name]
260         }.inspect
261       end
262     else
263       ret << '(none)'
264     end
265     ret << ' plugins=' << plugins.inspect
266     ret << ">"
267   end
268
269
270   # create a new Bot with botclass +botclass+
271   def initialize(botclass, params = {})
272     # Config for the core bot
273     # TODO should we split socket stuff into ircsocket, etc?
274     Config.register Config::ArrayValue.new('server.list',
275       :default => ['irc://localhost'], :wizard => true,
276       :requires_restart => true,
277       :desc => "List of irc servers rbot should try to connect to. Use comma to separate values. Servers are in format 'server.doma.in:port'. If port is not specified, default value (6667) is used.")
278     Config.register Config::BooleanValue.new('server.ssl',
279       :default => false, :requires_restart => true, :wizard => true,
280       :desc => "Use SSL to connect to this server?")
281     Config.register Config::StringValue.new('server.password',
282       :default => false, :requires_restart => true,
283       :desc => "Password for connecting to this server (if required)",
284       :wizard => true)
285     Config.register Config::StringValue.new('server.bindhost',
286       :default => false, :requires_restart => true,
287       :desc => "Specific local host or IP for the bot to bind to (if required)",
288       :wizard => true)
289     Config.register Config::IntegerValue.new('server.reconnect_wait',
290       :default => 5, :validate => Proc.new{|v| v >= 0},
291       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
292     Config.register Config::IntegerValue.new('server.ping_timeout',
293       :default => 30, :validate => Proc.new{|v| v >= 0},
294       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
295     Config.register Config::ArrayValue.new('server.nocolor_modes',
296       :default => ['c'], :wizard => false,
297       :requires_restart => false,
298       :desc => "List of channel modes that require messages to be without colors")
299
300     Config.register Config::StringValue.new('irc.nick', :default => "rbot",
301       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
302       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
303     Config.register Config::StringValue.new('irc.name',
304       :default => "Ruby bot", :requires_restart => true,
305       :desc => "IRC realname the bot should use")
306     Config.register Config::BooleanValue.new('irc.name_copyright',
307       :default => true, :requires_restart => true,
308       :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
309     Config.register Config::StringValue.new('irc.user', :default => "rbot",
310       :requires_restart => true,
311       :desc => "local user the bot should appear to be", :wizard => true)
312     Config.register Config::ArrayValue.new('irc.join_channels',
313       :default => [], :wizard => true,
314       :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'")
315     Config.register Config::ArrayValue.new('irc.ignore_users',
316       :default => [],
317       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
318     Config.register Config::ArrayValue.new('irc.ignore_channels',
319       :default => [],
320       :desc => "Which channels to ignore input in. This is mainly to turn the bot into a logbot that doesn't interact with users in any way (in the specified channels)")
321
322     Config.register Config::IntegerValue.new('core.save_every',
323       :default => 60, :validate => Proc.new{|v| v >= 0},
324       :on_change => Proc.new { |bot, v|
325         if @save_timer
326           if v > 0
327             @timer.reschedule(@save_timer, v)
328             @timer.unblock(@save_timer)
329           else
330             @timer.block(@save_timer)
331           end
332         else
333           if v > 0
334             @save_timer = @timer.add(v) { bot.save }
335           end
336           # Nothing to do when v == 0
337         end
338       },
339       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
340
341     Config.register Config::BooleanValue.new('core.run_as_daemon',
342       :default => false, :requires_restart => true,
343       :desc => "Should the bot run as a daemon?")
344
345     Config.register Config::StringValue.new('log.file',
346       :default => false, :requires_restart => true,
347       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
348     Config.register Config::IntegerValue.new('log.level',
349       :default => 1, :requires_restart => false,
350       :validate => Proc.new { |v| (0..5).include?(v) },
351       :on_change => Proc.new { |bot, v|
352         $logger.level = v
353       },
354       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
355     Config.register Config::IntegerValue.new('log.keep',
356       :default => 1, :requires_restart => true,
357       :validate => Proc.new { |v| v >= 0 },
358       :desc => "How many old console messages logfiles to keep")
359     Config.register Config::IntegerValue.new('log.max_size',
360       :default => 10, :requires_restart => true,
361       :validate => Proc.new { |v| v > 0 },
362       :desc => "Maximum console messages logfile size (in megabytes)")
363
364     Config.register Config::ArrayValue.new('plugins.path',
365       :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
366       :requires_restart => false,
367       :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
368       :desc => "Where the bot should look for plugins. List multiple directories using commas to separate. Use '(default)' for default prepackaged plugins collection, '(default)/contrib' for prepackaged unsupported plugins collection")
369
370     Config.register Config::EnumValue.new('send.newlines',
371       :values => ['split', 'join'], :default => 'split',
372       :on_change => Proc.new { |bot, v|
373         bot.set_default_send_options :newlines => v.to_sym
374       },
375       :desc => "When set to split, messages with embedded newlines will be sent as separate lines. When set to join, newlines will be replaced by the value of join_with")
376     Config.register Config::StringValue.new('send.join_with',
377       :default => ' ',
378       :on_change => Proc.new { |bot, v|
379         bot.set_default_send_options :join_with => v.dup
380       },
381       :desc => "String used to replace newlines when send.newlines is set to join")
382     Config.register Config::IntegerValue.new('send.max_lines',
383       :default => 5,
384       :validate => Proc.new { |v| v >= 0 },
385       :on_change => Proc.new { |bot, v|
386         bot.set_default_send_options :max_lines => v
387       },
388       :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
389     Config.register Config::EnumValue.new('send.overlong',
390       :values => ['split', 'truncate'], :default => 'split',
391       :on_change => Proc.new { |bot, v|
392         bot.set_default_send_options :overlong => v.to_sym
393       },
394       :desc => "When set to split, messages which are too long to fit in a single IRC line are split into multiple lines. When set to truncate, long messages are truncated to fit the IRC line length")
395     Config.register Config::StringValue.new('send.split_at',
396       :default => '\s+',
397       :on_change => Proc.new { |bot, v|
398         bot.set_default_send_options :split_at => Regexp.new(v)
399       },
400       :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
401     Config.register Config::BooleanValue.new('send.purge_split',
402       :default => true,
403       :on_change => Proc.new { |bot, v|
404         bot.set_default_send_options :purge_split => v
405       },
406       :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
407     Config.register Config::StringValue.new('send.truncate_text',
408       :default => "#{Reverse}...#{Reverse}",
409       :on_change => Proc.new { |bot, v|
410         bot.set_default_send_options :truncate_text => v.dup
411       },
412       :desc => "When truncating overlong messages (see send.overlong) or when sending too many lines per message (see send.max_lines) replace the end of the last line with this text")
413     Config.register Config::IntegerValue.new('send.penalty_pct',
414       :default => 100,
415       :validate => Proc.new { |v| v >= 0 },
416       :on_change => Proc.new { |bot, v|
417         bot.socket.penalty_pct = v
418       },
419       :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
420     Config.register Config::StringValue.new('core.db',
421       :default => "bdb",
422       :wizard => true, :default => "bdb",
423       :validate => Proc.new { |v| ["bdb"].include? v },
424       :requires_restart => true,
425       :desc => "DB adaptor to use for storing settings and plugin data. Options are: bdb (Berkeley DB, stable adaptor, but troublesome to install and unmaintained)")
426
427     @argv = params[:argv]
428     @run_dir = params[:run_dir] || Dir.pwd
429
430     unless FileTest.directory? Config::coredir
431       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
432       exit 2
433     end
434
435     unless FileTest.directory? Config::datadir
436       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
437       exit 2
438     end
439
440     unless botclass and not botclass.empty?
441       # We want to find a sensible default.
442       # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
443       # * On Windows (at least the NT versions) we want to put our stuff in the
444       #   Application Data folder.
445       # We don't use any particular O/S detection magic, exploiting the fact that
446       # Etc.getpwuid is nil on Windows
447       if Etc.getpwuid(Process::Sys.geteuid)
448         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
449       else
450         if ENV.has_key?('APPDATA')
451           botclass = ENV['APPDATA'].dup
452           botclass.gsub!("\\","/")
453         end
454       end
455       botclass = File.join(botclass, ".rbot")
456     end
457     botclass = File.expand_path(botclass)
458     @botclass = botclass.gsub(/\/$/, "")
459
460     repopulate_botclass_directory
461
462     registry_dir = File.join(@botclass, 'registry')
463     Dir.mkdir(registry_dir) unless File.exist?(registry_dir)
464     unless FileTest.directory? registry_dir
465       error "registry storage location #{registry_dir} is not a directory"
466       exit 2
467     end
468     save_dir = File.join(@botclass, 'safe_save')
469     Dir.mkdir(save_dir) unless File.exist?(save_dir)
470     unless FileTest.directory? save_dir
471       error "safe save location #{save_dir} is not a directory"
472       exit 2
473     end
474
475     # Time at which the last PING was sent
476     @last_ping = nil
477     # Time at which the last line was RECV'd from the server
478     @last_rec = nil
479
480     @startup_time = Time.new
481
482     begin
483       @config = Config.manager
484       @config.bot_associate(self)
485     rescue Exception => e
486       fatal e
487       log_session_end
488       exit 2
489     end
490
491     if @config['core.run_as_daemon']
492       $daemonize = true
493     end
494     case @config["core.db"]
495       when "bdb"
496         require 'rbot/registry/bdb'
497       else
498         raise _("Unknown DB adaptor: %s") % @config["core.db"]
499     end
500
501     @logfile = @config['log.file']
502     if @logfile.class!=String || @logfile.empty?
503       logfname =  File.basename(botclass).gsub(/^\.+/,'')
504       logfname << ".log"
505       @logfile = File.join(botclass, logfname)
506       debug "Using `#{@logfile}' as debug log"
507     end
508
509     # See http://blog.humlab.umu.se/samuel/archives/000107.html
510     # for the backgrounding code
511     if $daemonize
512       begin
513         exit if fork
514         Process.setsid
515         exit if fork
516       rescue NotImplementedError
517         warning "Could not background, fork not supported"
518       rescue SystemExit
519         exit 0
520       rescue Exception => e
521         warning "Could not background. #{e.pretty_inspect}"
522       end
523       Dir.chdir botclass
524       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
525     end
526
527     logger = Logger.new(@logfile,
528                         @config['log.keep'],
529                         @config['log.max_size']*1024*1024)
530     logger.datetime_format= $dateformat
531     logger.level = @config['log.level']
532     logger.level = $cl_loglevel if defined? $cl_loglevel
533     logger.level = 0 if $debug
534
535     restart_logger(logger)
536
537     log_session_start
538
539     if $daemonize
540       log "Redirecting standard input/output/error"
541       [$stdin, $stdout, $stderr].each do |fd|
542         begin
543           fd.reopen "/dev/null"
544         rescue Errno::ENOENT
545           # On Windows, there's not such thing as /dev/null
546           fd.reopen "NUL"
547         end
548       end
549
550       def $stdout.write(str=nil)
551         log str, 2
552         return str.to_s.size
553       end
554       def $stdout.write(str=nil)
555         if str.to_s.match(/:\d+: warning:/)
556           warning str, 2
557         else
558           error str, 2
559         end
560         return str.to_s.size
561       end
562     end
563
564     File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
565       pf << "#{$$}\n"
566     end
567
568     @registry = Registry.new self
569
570     @timer = Timer.new
571     @save_mutex = Mutex.new
572     if @config['core.save_every'] > 0
573       @save_timer = @timer.add(@config['core.save_every']) { save }
574     else
575       @save_timer = nil
576     end
577     @quit_mutex = Mutex.new
578
579     @plugins = nil
580     @lang = Language.new(self, @config['core.language'])
581
582     begin
583       @auth = Auth::manager
584       @auth.bot_associate(self)
585       # @auth.load("#{botclass}/botusers.yaml")
586     rescue Exception => e
587       fatal e
588       log_session_end
589       exit 2
590     end
591     @auth.everyone.set_default_permission("*", true)
592     @auth.botowner.password= @config['auth.password']
593
594     @plugins = Plugins::manager
595     @plugins.bot_associate(self)
596     setup_plugins_path()
597
598     if @config['server.name']
599         debug "upgrading configuration (server.name => server.list)"
600         srv_uri = 'irc://' + @config['server.name']
601         srv_uri += ":#{@config['server.port']}" if @config['server.port']
602         @config.items['server.list'.to_sym].set_string(srv_uri)
603         @config.delete('server.name'.to_sym)
604         @config.delete('server.port'.to_sym)
605         debug "server.list is now #{@config['server.list'].inspect}"
606     end
607
608     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
609     @client = Client.new
610
611     @plugins.scan
612
613     # Channels where we are quiet
614     # Array of channels names where the bot should be quiet
615     # '*' means all channels
616     #
617     @quiet = Set.new
618     # but we always speak here
619     @not_quiet = Set.new
620
621     # the nick we want, if it's different from the irc.nick config value
622     # (e.g. as set by a !nick command)
623     @wanted_nick = nil
624
625     @client[:welcome] = proc {|data|
626       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
627
628       @plugins.delegate("welcome", m)
629       @plugins.delegate("connect")
630     }
631
632     # TODO the next two @client should go into rfc2812.rb, probably
633     # Since capabs are two-steps processes, server.supports[:capab]
634     # should be a three-state: nil, [], [....]
635     asked_for = { :"identify-msg" => false }
636     @client[:isupport] = proc { |data|
637       if server.supports[:capab] and !asked_for[:"identify-msg"]
638         sendq "CAPAB IDENTIFY-MSG"
639         asked_for[:"identify-msg"] = true
640       end
641     }
642     @client[:datastr] = proc { |data|
643       if data[:text] == "IDENTIFY-MSG"
644         server.capabilities[:"identify-msg"] = true
645       else
646         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
647       end
648     }
649
650     @client[:privmsg] = proc { |data|
651       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
652       # debug "Message source is #{data[:source].inspect}"
653       # debug "Message target is #{data[:target].inspect}"
654       # debug "Bot is #{myself.inspect}"
655
656       @config['irc.ignore_channels'].each { |channel|
657         if m.target.downcase == channel.downcase
658           m.ignored = true
659           break
660         end
661       }
662       @config['irc.ignore_users'].each { |mask|
663         if m.source.matches?(server.new_netmask(mask))
664           m.ignored = true
665           break
666         end
667       } unless m.ignored
668
669       @plugins.irc_delegate('privmsg', m)
670     }
671     @client[:notice] = proc { |data|
672       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
673       # pass it off to plugins that want to hear everything
674       @plugins.irc_delegate "notice", message
675     }
676     @client[:motd] = proc { |data|
677       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
678       @plugins.delegate "motd", m
679     }
680     @client[:nicktaken] = proc { |data|
681       new = "#{data[:nick]}_"
682       nickchg new
683       # If we're setting our nick at connection because our choice was taken,
684       # we have to fix our nick manually, because there will be no NICK message
685       # to inform us that our nick has been changed.
686       if data[:target] == '*'
687         debug "setting my connection nick to #{new}"
688         nick = new
689       end
690       @plugins.delegate "nicktaken", data[:nick]
691     }
692     @client[:badnick] = proc {|data|
693       warning "bad nick (#{data[:nick]})"
694     }
695     @client[:ping] = proc {|data|
696       sendq "PONG #{data[:pingid]}"
697     }
698     @client[:pong] = proc {|data|
699       @last_ping = nil
700     }
701     @client[:nick] = proc {|data|
702       # debug "Message source is #{data[:source].inspect}"
703       # debug "Bot is #{myself.inspect}"
704       source = data[:source]
705       old = data[:oldnick]
706       new = data[:newnick]
707       m = NickMessage.new(self, server, source, old, new)
708       m.is_on = data[:is_on]
709       if source == myself
710         debug "my nick is now #{new}"
711       end
712       @plugins.irc_delegate("nick", m)
713     }
714     @client[:quit] = proc {|data|
715       source = data[:source]
716       message = data[:message]
717       m = QuitMessage.new(self, server, source, source, message)
718       m.was_on = data[:was_on]
719       @plugins.irc_delegate("quit", m)
720     }
721     @client[:mode] = proc {|data|
722       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
723       m.modes = data[:modes]
724       @plugins.delegate "modechange", m
725     }
726     @client[:whois] = proc {|data|
727       source = data[:source]
728       target = server.get_user(data[:whois][:nick])
729       m = WhoisMessage.new(self, server, source, target, data[:whois])
730       @plugins.delegate "whois", m
731     }
732     @client[:join] = proc {|data|
733       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
734       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
735       @plugins.irc_delegate("join", m)
736       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
737     }
738     @client[:part] = proc {|data|
739       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
740       @plugins.irc_delegate("part", m)
741     }
742     @client[:kick] = proc {|data|
743       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
744       @plugins.irc_delegate("kick", m)
745     }
746     @client[:invite] = proc {|data|
747       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
748       @plugins.irc_delegate("invite", m)
749     }
750     @client[:changetopic] = proc {|data|
751       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
752       m.info_or_set = :set
753       @plugins.irc_delegate("topic", m)
754     }
755     # @client[:topic] = proc { |data|
756     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
757     # }
758     @client[:topicinfo] = proc { |data|
759       channel = data[:channel]
760       topic = channel.topic
761       m = TopicMessage.new(self, server, data[:source], channel, topic)
762       m.info_or_set = :info
763       @plugins.irc_delegate("topic", m)
764     }
765     @client[:names] = proc { |data|
766       m = NamesMessage.new(self, server, server, data[:channel])
767       m.users = data[:users]
768       @plugins.delegate "names", m
769     }
770     @client[:banlist] = proc { |data|
771       m = BanlistMessage.new(self, server, server, data[:channel])
772       m.bans = data[:bans]
773       @plugins.delegate "banlist", m
774     }
775     @client[:nosuchtarget] = proc { |data|
776       m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
777       @plugins.delegate "nosuchtarget", m
778     }
779     @client[:error] = proc { |data|
780       raise ServerError, data[:message]
781     }
782     @client[:unknown] = proc { |data|
783       #debug "UNKNOWN: #{data[:serverstring]}"
784       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
785       @plugins.delegate "unknown_message", m
786     }
787
788     set_default_send_options :newlines => @config['send.newlines'].to_sym,
789       :join_with => @config['send.join_with'].dup,
790       :max_lines => @config['send.max_lines'],
791       :overlong => @config['send.overlong'].to_sym,
792       :split_at => Regexp.new(@config['send.split_at']),
793       :purge_split => @config['send.purge_split'],
794       :truncate_text => @config['send.truncate_text'].dup
795
796     trap_sigs
797   end
798
799   def repopulate_botclass_directory
800     template_dir = File.join Config::datadir, 'templates'
801     if FileTest.directory? @botclass
802       # compare the templates dir with the current botclass dir, filling up the
803       # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
804       # :update option, so we have to do it manually.
805       # Note that we use the */** pattern because we don't want to match
806       # keywords.rbot, which gets deleted on load and would therefore be missing
807       # always
808       missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
809       missing.map do |f|
810         dest = File.join(@botclass, f)
811         FileUtils.mkdir_p(File.dirname(dest))
812         FileUtils.cp File.join(template_dir, f), dest
813       end
814     else
815       log "no #{@botclass} directory found, creating from templates..."
816       if FileTest.exist? @botclass
817         error "file #{@botclass} exists but isn't a directory"
818         exit 2
819       end
820       FileUtils.cp_r template_dir, @botclass
821     end
822   end
823
824   # Return a path under the current botclass by joining the mentioned
825   # components. The components are automatically converted to String
826   def path(*components)
827     File.join(@botclass, *(components.map {|c| c.to_s}))
828   end
829
830   def setup_plugins_path
831     plugdir_default = File.join(Config::datadir, 'plugins')
832     plugdir_local = File.join(@botclass, 'plugins')
833     Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
834
835     @plugins.clear_botmodule_dirs
836     @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
837     @plugins.add_core_module_dir(Config::coredir)
838     if FileTest.directory? plugdir_local
839       @plugins.add_plugin_dir(plugdir_local)
840     else
841       warning "local plugin location #{plugdir_local} is not a directory"
842     end
843
844     @config['plugins.path'].each do |_|
845         path = _.sub(/^\(default\)/, plugdir_default)
846         @plugins.add_plugin_dir(path)
847     end
848   end
849
850   def set_default_send_options(opts={})
851     # Default send options for NOTICE and PRIVMSG
852     unless defined? @default_send_options
853       @default_send_options = {
854         :queue_channel => nil,      # use default queue channel
855         :queue_ring => nil,         # use default queue ring
856         :newlines => :split,        # or :join
857         :join_with => ' ',          # by default, use a single space
858         :max_lines => 0,          # maximum number of lines to send with a single command
859         :overlong => :split,        # or :truncate
860         # TODO an array of splitpoints would be preferrable for this option:
861         :split_at => /\s+/,         # by default, split overlong lines at whitespace
862         :purge_split => true,       # should the split string be removed?
863         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
864       }
865     end
866     @default_send_options.update opts unless opts.empty?
867   end
868
869   # checks if we should be quiet on a channel
870   def quiet_on?(channel)
871     ch = channel.downcase
872     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
873   end
874
875   def set_quiet(channel = nil)
876     if channel
877       ch = channel.downcase.dup
878       @not_quiet.delete(ch)
879       @quiet << ch
880     else
881       @quiet.clear
882       @not_quiet.clear
883       @quiet << '*'
884     end
885   end
886
887   def reset_quiet(channel = nil)
888     if channel
889       ch = channel.downcase.dup
890       @quiet.delete(ch)
891       @not_quiet << ch
892     else
893       @quiet.clear
894       @not_quiet.clear
895     end
896   end
897
898   # things to do when we receive a signal
899   def got_sig(sig, func=:quit)
900     debug "received #{sig}, queueing #{func}"
901     # this is not an interruption if we just need to reconnect
902     $interrupted += 1 unless func == :reconnect
903     self.send(func) unless @quit_mutex.locked?
904     debug "interrupted #{$interrupted} times"
905     if $interrupted >= 3
906       debug "drastic!"
907       log_session_end
908       exit 2
909     end
910   end
911
912   # trap signals
913   def trap_sigs
914     begin
915       trap("SIGINT") { got_sig("SIGINT") }
916       trap("SIGTERM") { got_sig("SIGTERM") }
917       trap("SIGHUP") { got_sig("SIGHUP", :restart) }
918       trap("SIGUSR1") { got_sig("SIGUSR1", :reconnect) }
919     rescue ArgumentError => e
920       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
921     rescue Exception => e
922       debug "failed to trap signals: #{e.pretty_inspect}"
923     end
924   end
925
926   # connect the bot to IRC
927   def connect
928     # make sure we don't have any spurious ping checks running
929     # (and initialize the vars if this is the first time we connect)
930     stop_server_pings
931     begin
932       quit if $interrupted > 0
933       @socket.connect
934       @last_rec = Time.now
935     rescue => e
936       raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: #{e}"
937     end
938     quit if $interrupted > 0
939
940     realname = @config['irc.name'].clone || 'Ruby bot'
941     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
942
943     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
944     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
945     quit if $interrupted > 0
946     myself.nick = @config['irc.nick']
947     myself.user = @config['irc.user']
948   end
949
950   # disconnect the bot from IRC, if connected, and then connect (again)
951   def reconnect(message=nil, too_fast=false)
952     # we will wait only if @last_rec was not nil, i.e. if we were connected or
953     # got disconnected by a network error
954     # if someone wants to manually call disconnect() _and_ reconnect(), they
955     # will have to take care of the waiting themselves
956     will_wait = !!@last_rec
957
958     if @socket.connected?
959       disconnect(message)
960     end
961
962     begin
963       if will_wait
964         log "\n\nDisconnected\n\n"
965
966         quit if $interrupted > 0
967
968         log "\n\nWaiting to reconnect\n\n"
969         sleep @config['server.reconnect_wait']
970         sleep 10*@config['server.reconnect_wait'] if too_fast
971       end
972
973       connect
974     rescue Exception => e
975       will_wait = true
976       retry
977     end
978   end
979
980   # begin event handling loop
981   def mainloop
982     while true
983       too_fast = false
984       begin
985         quit_msg = nil
986         reconnect(quit_msg, too_fast)
987         quit if $interrupted > 0
988         while @socket.connected?
989           quit if $interrupted > 0
990
991           # Wait for messages and process them as they arrive. If nothing is
992           # received, we call the ping_server() method that will PING the
993           # server if appropriate, or raise a TimeoutError if no PONG has been
994           # received in the user-chosen timeout since the last PING sent.
995           if @socket.select(1)
996             break unless reply = @socket.gets
997             @last_rec = Time.now
998             @client.process reply
999           else
1000             ping_server
1001           end
1002         end
1003
1004       # I despair of this. Some of my users get "connection reset by peer"
1005       # exceptions that ARENT SocketError's. How am I supposed to handle
1006       # that?
1007       rescue SystemExit
1008         log_session_end
1009         exit 0
1010       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1011         error "network exception: #{e.pretty_inspect}"
1012         quit_msg = e.to_s
1013       rescue ServerError => e
1014         # received an ERROR from the server
1015         quit_msg = "server ERROR: " + e.message
1016         too_fast = e.message.index("reconnect too fast")
1017         retry
1018       rescue BDB::Fatal => e
1019         fatal "fatal bdb error: #{e.pretty_inspect}"
1020         DBTree.stats
1021         # Why restart? DB problems are serious stuff ...
1022         # restart("Oops, we seem to have registry problems ...")
1023         log_session_end
1024         exit 2
1025       rescue Exception => e
1026         error "non-net exception: #{e.pretty_inspect}"
1027         quit_msg = e.to_s
1028       rescue => e
1029         fatal "unexpected exception: #{e.pretty_inspect}"
1030         log_session_end
1031         exit 2
1032       end
1033     end
1034   end
1035
1036   # type:: message type
1037   # where:: message target
1038   # message:: message text
1039   # send message +message+ of type +type+ to target +where+
1040   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1041   # relevant say() or notice() methods. This one should be used for IRCd
1042   # extensions you want to use in modules.
1043   def sendmsg(original_type, original_where, original_message, options={})
1044
1045     # filter message with sendmsg filters
1046     ds = DataStream.new original_message.to_s.dup,
1047       :type => original_type, :dest => original_where,
1048       :options => @default_send_options.merge(options)
1049     filters = filter_names(:sendmsg)
1050     filters.each do |fname|
1051       debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1052       ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1053     end
1054
1055     opts = ds[:options]
1056     type = ds[:type]
1057     where = ds[:dest]
1058     filtered = ds[:text]
1059
1060     # For starters, set up appropriate queue channels and rings
1061     mchan = opts[:queue_channel]
1062     mring = opts[:queue_ring]
1063     if mchan
1064       chan = mchan
1065     else
1066       chan = where
1067     end
1068     if mring
1069       ring = mring
1070     else
1071       case where
1072       when User
1073         ring = 1
1074       else
1075         ring = 2
1076       end
1077     end
1078
1079     multi_line = filtered.gsub(/[\r\n]+/, "\n")
1080
1081     # if target is a channel with nocolor modes, strip colours
1082     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1083       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1084     end
1085
1086     messages = Array.new
1087     case opts[:newlines]
1088     when :join
1089       messages << [multi_line.gsub("\n", opts[:join_with])]
1090     when :split
1091       multi_line.each_line { |line|
1092         line.chomp!
1093         next unless(line.size > 0)
1094         messages << line
1095       }
1096     else
1097       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1098     end
1099
1100     # The IRC protocol requires that each raw message must be not longer
1101     # than 512 characters. From this length with have to subtract the EOL
1102     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1103     # that will be prepended by the server to all of our messages.
1104
1105     # The maximum raw message length we can send is therefore 512 - 2 - 2
1106     # minus the length of our hostmask.
1107
1108     max_len = 508 - myself.fullform.size
1109
1110     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1111     # will have a + or - prepended
1112     if server.capabilities[:"identify-msg"]
1113       max_len -= 1
1114     end
1115
1116     # When splitting the message, we'll be prefixing the following string:
1117     # (e.g. "PRIVMSG #rbot :")
1118     fixed = "#{type} #{where} :"
1119
1120     # And this is what's left
1121     left = max_len - fixed.size
1122
1123     truncate = opts[:truncate_text]
1124     truncate = @default_send_options[:truncate_text] if truncate.size > left
1125     truncate = "" if truncate.size > left
1126
1127     all_lines = messages.map { |line|
1128       if line.size < left
1129         line
1130       else
1131         case opts[:overlong]
1132         when :split
1133           msg = line.dup
1134           sub_lines = Array.new
1135           begin
1136             sub_lines << msg.slice!(0, left)
1137             break if msg.empty?
1138             lastspace = sub_lines.last.rindex(opts[:split_at])
1139             if lastspace
1140               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1141               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1142             end
1143           end until msg.empty?
1144           sub_lines
1145         when :truncate
1146           line.slice(0, left - truncate.size) << truncate
1147         else
1148           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1149         end
1150       end
1151     }.flatten
1152
1153     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1154       lines = all_lines[0...opts[:max_lines]]
1155       new_last = lines.last.slice(0, left - truncate.size) << truncate
1156       lines.last.replace(new_last)
1157     else
1158       lines = all_lines
1159     end
1160
1161     lines.each { |line|
1162       sendq "#{fixed}#{line}", chan, ring
1163       delegate_sent(type, where, line)
1164     }
1165   end
1166
1167   # queue an arbitraty message for the server
1168   def sendq(message="", chan=nil, ring=0)
1169     # temporary
1170     @socket.queue(message, chan, ring)
1171   end
1172
1173   # send a notice message to channel/nick +where+
1174   def notice(where, message, options={})
1175     return if where.kind_of?(Channel) and quiet_on?(where)
1176     sendmsg "NOTICE", where, message, options
1177   end
1178
1179   # say something (PRIVMSG) to channel/nick +where+
1180   def say(where, message, options={})
1181     return if where.kind_of?(Channel) and quiet_on?(where)
1182     sendmsg "PRIVMSG", where, message, options
1183   end
1184
1185   def ctcp_notice(where, command, message, options={})
1186     return if where.kind_of?(Channel) and quiet_on?(where)
1187     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1188   end
1189
1190   def ctcp_say(where, command, message, options={})
1191     return if where.kind_of?(Channel) and quiet_on?(where)
1192     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1193   end
1194
1195   # perform a CTCP action with message +message+ to channel/nick +where+
1196   def action(where, message, options={})
1197     ctcp_say(where, 'ACTION', message, options)
1198   end
1199
1200   # quick way to say "okay" (or equivalent) to +where+
1201   def okay(where)
1202     say where, @lang.get("okay")
1203   end
1204
1205   # set topic of channel +where+ to +topic+
1206   # can also be used to retrieve the topic of channel +where+
1207   # by omitting the last argument
1208   def topic(where, topic=nil)
1209     if topic.nil?
1210       sendq "TOPIC #{where}", where, 2
1211     else
1212       sendq "TOPIC #{where} :#{topic}", where, 2
1213     end
1214   end
1215
1216   def disconnect(message=nil)
1217     message = @lang.get("quit") if (!message || message.empty?)
1218     if @socket.connected?
1219       begin
1220         debug "Clearing socket"
1221         @socket.clearq
1222         debug "Sending quit message"
1223         @socket.emergency_puts "QUIT :#{message}"
1224         debug "Logging quits"
1225         delegate_sent('QUIT', myself, message)
1226         debug "Flushing socket"
1227         @socket.flush
1228       rescue SocketError => e
1229         error "error while disconnecting socket: #{e.pretty_inspect}"
1230       end
1231       debug "Shutting down socket"
1232       @socket.shutdown
1233     end
1234     stop_server_pings
1235     @client.reset
1236   end
1237
1238   # disconnect from the server and cleanup all plugins and modules
1239   def shutdown(message=nil)
1240     @quit_mutex.synchronize do
1241       debug "Shutting down: #{message}"
1242       ## No we don't restore them ... let everything run through
1243       # begin
1244       #   trap("SIGINT", "DEFAULT")
1245       #   trap("SIGTERM", "DEFAULT")
1246       #   trap("SIGHUP", "DEFAULT")
1247       # rescue => e
1248       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1249       # end
1250       debug "\tdisconnecting..."
1251       disconnect(message)
1252       debug "\tstopping timer..."
1253       @timer.stop
1254       debug "\tsaving ..."
1255       save
1256       debug "\tcleaning up ..."
1257       @save_mutex.synchronize do
1258         @plugins.cleanup
1259       end
1260       # debug "\tstopping timers ..."
1261       # @timer.stop
1262       # debug "Closing registries"
1263       # @registry.close
1264       debug "\t\tcleaning up the db environment ..."
1265       DBTree.cleanup_env
1266       log "rbot quit (#{message})"
1267     end
1268   end
1269
1270   # message:: optional IRC quit message
1271   # quit IRC, shutdown the bot
1272   def quit(message=nil)
1273     begin
1274       shutdown(message)
1275     ensure
1276       exit 0
1277     end
1278   end
1279
1280   # totally shutdown and respawn the bot
1281   def restart(message=nil)
1282     message = _("restarting, back in %{wait}...") % {
1283       :wait => @config['server.reconnect_wait']
1284     } if (!message || message.empty?)
1285     shutdown(message)
1286     sleep @config['server.reconnect_wait']
1287     begin
1288       # now we re-exec
1289       # Note, this fails on Windows
1290       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1291       log_session_end
1292       Dir.chdir(@run_dir)
1293       exec($0, *@argv)
1294     rescue Errno::ENOENT
1295       log_session_end
1296       exec("ruby", *(@argv.unshift $0))
1297     rescue Exception => e
1298       $interrupted += 1
1299       raise e
1300     end
1301   end
1302
1303   # call the save method for all of the botmodules
1304   def save
1305     @save_mutex.synchronize do
1306       @plugins.save
1307       DBTree.cleanup_logs
1308     end
1309   end
1310
1311   # call the rescan method for all of the botmodules
1312   def rescan
1313     debug "\tstopping timer..."
1314     @timer.stop
1315     @save_mutex.synchronize do
1316       @lang.rescan
1317       @plugins.rescan
1318     end
1319     @timer.start
1320   end
1321
1322   # channel:: channel to join
1323   # key::     optional channel key if channel is +s
1324   # join a channel
1325   def join(channel, key=nil)
1326     if(key)
1327       sendq "JOIN #{channel} :#{key}", channel, 2
1328     else
1329       sendq "JOIN #{channel}", channel, 2
1330     end
1331   end
1332
1333   # part a channel
1334   def part(channel, message="")
1335     sendq "PART #{channel} :#{message}", channel, 2
1336   end
1337
1338   # attempt to change bot's nick to +name+
1339   def nickchg(name)
1340     sendq "NICK #{name}"
1341   end
1342
1343   # changing mode
1344   def mode(channel, mode, target=nil)
1345     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1346   end
1347
1348   # asking whois
1349   def whois(nick, target=nil)
1350     sendq "WHOIS #{target} #{nick}", nil, 0
1351   end
1352
1353   # kicking a user
1354   def kick(channel, user, msg)
1355     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1356   end
1357
1358   # m::     message asking for help
1359   # topic:: optional topic help is requested for
1360   # respond to online help requests
1361   def help(topic=nil)
1362     topic = nil if topic == ""
1363     case topic
1364     when nil
1365       helpstr = _("help topics: ")
1366       helpstr += @plugins.helptopics
1367       helpstr += _(" (help <topic> for more info)")
1368     else
1369       unless(helpstr = @plugins.help(topic))
1370         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1371       end
1372     end
1373     return helpstr
1374   end
1375
1376   # returns a string describing the current status of the bot (uptime etc)
1377   def status
1378     secs_up = Time.new - @startup_time
1379     uptime = Utils.secs_to_string secs_up
1380     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1381     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1382              {
1383                :up => uptime, :plug => @plugins.length,
1384                :sent => @socket.lines_sent, :recv => @socket.lines_received
1385              })
1386   end
1387
1388   # We want to respond to a hung server in a timely manner. If nothing was received
1389   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1390   # the server. If the PONG is not received within the user-defined timeout, we
1391   # assume we're in ping timeout and act accordingly.
1392   def ping_server
1393     act_timeout = @config['server.ping_timeout']
1394     return if act_timeout <= 0
1395     now = Time.now
1396     if @last_rec && now > @last_rec + act_timeout
1397       if @last_ping.nil?
1398         # No previous PING pending, send a new one
1399         sendq "PING :rbot"
1400         @last_ping = Time.now
1401       else
1402         diff = now - @last_ping
1403         if diff > act_timeout
1404           debug "no PONG from server in #{diff} seconds, reconnecting"
1405           # the actual reconnect is handled in the main loop:
1406           raise TimeoutError, "no PONG from server in #{diff} seconds"
1407         end
1408       end
1409     end
1410   end
1411
1412   def stop_server_pings
1413     # cancel previous PINGs and reset time of last RECV
1414     @last_ping = nil
1415     @last_rec = nil
1416   end
1417
1418   private
1419
1420   # delegate sent messages
1421   def delegate_sent(type, where, message)
1422     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1423     case type
1424       when "NOTICE"
1425         m = NoticeMessage.new(*args)
1426       when "PRIVMSG"
1427         m = PrivMessage.new(*args)
1428       when "QUIT"
1429         m = QuitMessage.new(*args)
1430         m.was_on = myself.channels
1431     end
1432     @plugins.delegate('sent', m)
1433   end
1434
1435 end
1436
1437 end