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