ruby 2.0.0: changes sigtrapping, fixes ThreadError
[rbot] / 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 db 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 helper 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", "tc"].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), tc (Tokyo Cabinet, new adaptor, fast and furious, but may be not available and contain bugs)")
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
495     case @config["core.db"]
496       when "bdb"
497         require 'rbot/registry/bdb'
498       when "tc"
499         require 'rbot/registry/tc'
500       else
501         raise _("Unknown DB adaptor: %s") % @config["core.db"]
502     end
503
504     @logfile = @config['log.file']
505     if @logfile.class!=String || @logfile.empty?
506       logfname =  File.basename(botclass).gsub(/^\.+/,'')
507       logfname << ".log"
508       @logfile = File.join(botclass, logfname)
509       debug "Using `#{@logfile}' as debug log"
510     end
511
512     # See http://blog.humlab.umu.se/samuel/archives/000107.html
513     # for the backgrounding code
514     if $daemonize
515       begin
516         exit if fork
517         Process.setsid
518         exit if fork
519       rescue NotImplementedError
520         warning "Could not background, fork not supported"
521       rescue SystemExit
522         exit 0
523       rescue Exception => e
524         warning "Could not background. #{e.pretty_inspect}"
525       end
526       Dir.chdir botclass
527       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
528     end
529
530     logger = Logger.new(@logfile,
531                         @config['log.keep'],
532                         @config['log.max_size']*1024*1024)
533     logger.datetime_format= $dateformat
534     logger.level = @config['log.level']
535     logger.level = $cl_loglevel if defined? $cl_loglevel
536     logger.level = 0 if $debug
537
538     restart_logger(logger)
539
540     log_session_start
541
542     if $daemonize
543       log "Redirecting standard input/output/error"
544       [$stdin, $stdout, $stderr].each do |fd|
545         begin
546           fd.reopen "/dev/null"
547         rescue Errno::ENOENT
548           # On Windows, there's not such thing as /dev/null
549           fd.reopen "NUL"
550         end
551       end
552
553       def $stdout.write(str=nil)
554         log str, 2
555         return str.to_s.size
556       end
557       def $stdout.write(str=nil)
558         if str.to_s.match(/:\d+: warning:/)
559           warning str, 2
560         else
561           error str, 2
562         end
563         return str.to_s.size
564       end
565     end
566
567     File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
568       pf << "#{$$}\n"
569     end
570
571     @registry = Registry.new self
572
573     @timer = Timer.new
574     @save_mutex = Mutex.new
575     if @config['core.save_every'] > 0
576       @save_timer = @timer.add(@config['core.save_every']) { save }
577     else
578       @save_timer = nil
579     end
580     @quit_mutex = Mutex.new
581
582     @plugins = nil
583     @lang = Language.new(self, @config['core.language'])
584
585     begin
586       @auth = Auth::manager
587       @auth.bot_associate(self)
588       # @auth.load("#{botclass}/botusers.yaml")
589     rescue Exception => e
590       fatal e
591       log_session_end
592       exit 2
593     end
594     @auth.everyone.set_default_permission("*", true)
595     @auth.botowner.password= @config['auth.password']
596
597     @plugins = Plugins::manager
598     @plugins.bot_associate(self)
599     setup_plugins_path()
600
601     if @config['server.name']
602         debug "upgrading configuration (server.name => server.list)"
603         srv_uri = 'irc://' + @config['server.name']
604         srv_uri += ":#{@config['server.port']}" if @config['server.port']
605         @config.items['server.list'.to_sym].set_string(srv_uri)
606         @config.delete('server.name'.to_sym)
607         @config.delete('server.port'.to_sym)
608         debug "server.list is now #{@config['server.list'].inspect}"
609     end
610
611     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
612     @client = Client.new
613
614     @plugins.scan
615
616     # Channels where we are quiet
617     # Array of channels names where the bot should be quiet
618     # '*' means all channels
619     #
620     @quiet = Set.new
621     # but we always speak here
622     @not_quiet = Set.new
623
624     # the nick we want, if it's different from the irc.nick config value
625     # (e.g. as set by a !nick command)
626     @wanted_nick = nil
627
628     @client[:welcome] = proc {|data|
629       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
630
631       @plugins.delegate("welcome", m)
632       @plugins.delegate("connect")
633     }
634
635     # TODO the next two @client should go into rfc2812.rb, probably
636     # Since capabs are two-steps processes, server.supports[:capab]
637     # should be a three-state: nil, [], [....]
638     asked_for = { :"identify-msg" => false }
639     @client[:isupport] = proc { |data|
640       if server.supports[:capab] and !asked_for[:"identify-msg"]
641         sendq "CAPAB IDENTIFY-MSG"
642         asked_for[:"identify-msg"] = true
643       end
644     }
645     @client[:datastr] = proc { |data|
646       if data[:text] == "IDENTIFY-MSG"
647         server.capabilities[:"identify-msg"] = true
648       else
649         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
650       end
651     }
652
653     @client[:privmsg] = proc { |data|
654       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
655       # debug "Message source is #{data[:source].inspect}"
656       # debug "Message target is #{data[:target].inspect}"
657       # debug "Bot is #{myself.inspect}"
658
659       @config['irc.ignore_channels'].each { |channel|
660         if m.target.downcase == channel.downcase
661           m.ignored = true
662           break
663         end
664       }
665       @config['irc.ignore_users'].each { |mask|
666         if m.source.matches?(server.new_netmask(mask))
667           m.ignored = true
668           break
669         end
670       } unless m.ignored
671
672       @plugins.irc_delegate('privmsg', m)
673     }
674     @client[:notice] = proc { |data|
675       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
676       # pass it off to plugins that want to hear everything
677       @plugins.irc_delegate "notice", message
678     }
679     @client[:motd] = proc { |data|
680       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
681       @plugins.delegate "motd", m
682     }
683     @client[:nicktaken] = proc { |data|
684       new = "#{data[:nick]}_"
685       nickchg new
686       # If we're setting our nick at connection because our choice was taken,
687       # we have to fix our nick manually, because there will be no NICK message
688       # to inform us that our nick has been changed.
689       if data[:target] == '*'
690         debug "setting my connection nick to #{new}"
691         nick = new
692       end
693       @plugins.delegate "nicktaken", data[:nick]
694     }
695     @client[:badnick] = proc {|data|
696       warning "bad nick (#{data[:nick]})"
697     }
698     @client[:ping] = proc {|data|
699       sendq "PONG #{data[:pingid]}"
700     }
701     @client[:pong] = proc {|data|
702       @last_ping = nil
703     }
704     @client[:nick] = proc {|data|
705       # debug "Message source is #{data[:source].inspect}"
706       # debug "Bot is #{myself.inspect}"
707       source = data[:source]
708       old = data[:oldnick]
709       new = data[:newnick]
710       m = NickMessage.new(self, server, source, old, new)
711       m.is_on = data[:is_on]
712       if source == myself
713         debug "my nick is now #{new}"
714       end
715       @plugins.irc_delegate("nick", m)
716     }
717     @client[:quit] = proc {|data|
718       source = data[:source]
719       message = data[:message]
720       m = QuitMessage.new(self, server, source, source, message)
721       m.was_on = data[:was_on]
722       @plugins.irc_delegate("quit", m)
723     }
724     @client[:mode] = proc {|data|
725       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
726       m.modes = data[:modes]
727       @plugins.delegate "modechange", m
728     }
729     @client[:whois] = proc {|data|
730       source = data[:source]
731       target = server.get_user(data[:whois][:nick])
732       m = WhoisMessage.new(self, server, source, target, data[:whois])
733       @plugins.delegate "whois", m
734     }
735     @client[:list] = proc {|data|
736       source = data[:source]
737       m = ListMessage.new(self, server, source, source, data[:list])
738       @plugins.delegate "irclist", m
739     }
740     @client[:join] = proc {|data|
741       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
742       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
743       @plugins.irc_delegate("join", m)
744       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
745     }
746     @client[:part] = proc {|data|
747       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
748       @plugins.irc_delegate("part", m)
749     }
750     @client[:kick] = proc {|data|
751       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
752       @plugins.irc_delegate("kick", m)
753     }
754     @client[:invite] = proc {|data|
755       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
756       @plugins.irc_delegate("invite", m)
757     }
758     @client[:changetopic] = proc {|data|
759       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
760       m.info_or_set = :set
761       @plugins.irc_delegate("topic", m)
762     }
763     # @client[:topic] = proc { |data|
764     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
765     # }
766     @client[:topicinfo] = proc { |data|
767       channel = data[:channel]
768       topic = channel.topic
769       m = TopicMessage.new(self, server, data[:source], channel, topic)
770       m.info_or_set = :info
771       @plugins.irc_delegate("topic", m)
772     }
773     @client[:names] = proc { |data|
774       m = NamesMessage.new(self, server, server, data[:channel])
775       m.users = data[:users]
776       @plugins.delegate "names", m
777     }
778     @client[:banlist] = proc { |data|
779       m = BanlistMessage.new(self, server, server, data[:channel])
780       m.bans = data[:bans]
781       @plugins.delegate "banlist", m
782     }
783     @client[:nosuchtarget] = proc { |data|
784       m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
785       @plugins.delegate "nosuchtarget", m
786     }
787     @client[:error] = proc { |data|
788       raise ServerError, data[:message]
789     }
790     @client[:unknown] = proc { |data|
791       #debug "UNKNOWN: #{data[:serverstring]}"
792       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
793       @plugins.delegate "unknown_message", m
794     }
795
796     set_default_send_options :newlines => @config['send.newlines'].to_sym,
797       :join_with => @config['send.join_with'].dup,
798       :max_lines => @config['send.max_lines'],
799       :overlong => @config['send.overlong'].to_sym,
800       :split_at => Regexp.new(@config['send.split_at']),
801       :purge_split => @config['send.purge_split'],
802       :truncate_text => @config['send.truncate_text'].dup
803
804     @signals = []
805     trap_sigs
806   end
807
808   def repopulate_botclass_directory
809     template_dir = File.join Config::datadir, 'templates'
810     if FileTest.directory? @botclass
811       # compare the templates dir with the current botclass dir, filling up the
812       # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
813       # :update option, so we have to do it manually.
814       # Note that we use the */** pattern because we don't want to match
815       # keywords.rbot, which gets deleted on load and would therefore be missing
816       # always
817       missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
818       missing.map do |f|
819         dest = File.join(@botclass, f)
820         FileUtils.mkdir_p(File.dirname(dest))
821         FileUtils.cp File.join(template_dir, f), dest
822       end
823     else
824       log "no #{@botclass} directory found, creating from templates..."
825       if FileTest.exist? @botclass
826         error "file #{@botclass} exists but isn't a directory"
827         exit 2
828       end
829       FileUtils.cp_r template_dir, @botclass
830     end
831   end
832
833   # Return a path under the current botclass by joining the mentioned
834   # components. The components are automatically converted to String
835   def path(*components)
836     File.join(@botclass, *(components.map {|c| c.to_s}))
837   end
838
839   def setup_plugins_path
840     plugdir_default = File.join(Config::datadir, 'plugins')
841     plugdir_local = File.join(@botclass, 'plugins')
842     Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
843
844     @plugins.clear_botmodule_dirs
845     @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
846     @plugins.add_core_module_dir(Config::coredir)
847     if FileTest.directory? plugdir_local
848       @plugins.add_plugin_dir(plugdir_local)
849     else
850       warning "local plugin location #{plugdir_local} is not a directory"
851     end
852
853     @config['plugins.path'].each do |_|
854         path = _.sub(/^\(default\)/, plugdir_default)
855         @plugins.add_plugin_dir(path)
856     end
857   end
858
859   def set_default_send_options(opts={})
860     # Default send options for NOTICE and PRIVMSG
861     unless defined? @default_send_options
862       @default_send_options = {
863         :queue_channel => nil,      # use default queue channel
864         :queue_ring => nil,         # use default queue ring
865         :newlines => :split,        # or :join
866         :join_with => ' ',          # by default, use a single space
867         :max_lines => 0,          # maximum number of lines to send with a single command
868         :overlong => :split,        # or :truncate
869         # TODO an array of splitpoints would be preferrable for this option:
870         :split_at => /\s+/,         # by default, split overlong lines at whitespace
871         :purge_split => true,       # should the split string be removed?
872         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
873       }
874     end
875     @default_send_options.update opts unless opts.empty?
876   end
877
878   # checks if we should be quiet on a channel
879   def quiet_on?(channel)
880     ch = channel.downcase
881     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
882   end
883
884   def set_quiet(channel = nil)
885     if channel
886       ch = channel.downcase.dup
887       @not_quiet.delete(ch)
888       @quiet << ch
889     else
890       @quiet.clear
891       @not_quiet.clear
892       @quiet << '*'
893     end
894   end
895
896   def reset_quiet(channel = nil)
897     if channel
898       ch = channel.downcase.dup
899       @quiet.delete(ch)
900       @not_quiet << ch
901     else
902       @quiet.clear
903       @not_quiet.clear
904     end
905   end
906
907   # things to do when we receive a signal
908   def handle_sigs
909     while sig = @signals.shift
910       func = case sig
911              when 'SIGHUP'
912                :restart
913              when 'SIGUSR1'
914                :reconnect
915              else
916                :quit
917              end
918       debug "received #{sig}, queueing #{func}"
919       # this is not an interruption if we just need to reconnect
920       $interrupted += 1 unless func == :reconnect
921       self.send(func) unless @quit_mutex.locked?
922       debug "interrupted #{$interrupted} times"
923       if $interrupted >= 3
924         debug "drastic!"
925         log_session_end
926         exit 2
927       end
928     end
929   end
930
931   # trap signals
932   def trap_sigs
933     begin
934       %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
935         trap(sig) { @signals << sig }
936       end
937     rescue ArgumentError => e
938       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
939     rescue Exception => e
940       debug "failed to trap signals: #{e.pretty_inspect}"
941     end
942   end
943
944   # connect the bot to IRC
945   def connect
946     # make sure we don't have any spurious ping checks running
947     # (and initialize the vars if this is the first time we connect)
948     stop_server_pings
949     begin
950       quit if $interrupted > 0
951       @socket.connect
952       @last_rec = Time.now
953     rescue Exception => e
954       uri = @socket.server_uri || '<unknown>'
955       error "failed to connect to IRC server at #{uri}"
956       error e
957       raise
958     end
959     quit if $interrupted > 0
960
961     realname = @config['irc.name'].clone || 'Ruby bot'
962     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
963
964     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
965     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
966     quit if $interrupted > 0
967     myself.nick = @config['irc.nick']
968     myself.user = @config['irc.user']
969   end
970
971   # disconnect the bot from IRC, if connected, and then connect (again)
972   def reconnect(message=nil, too_fast=0)
973     # we will wait only if @last_rec was not nil, i.e. if we were connected or
974     # got disconnected by a network error
975     # if someone wants to manually call disconnect() _and_ reconnect(), they
976     # will have to take care of the waiting themselves
977     will_wait = !!@last_rec
978
979     if @socket.connected?
980       disconnect(message)
981     end
982
983     begin
984       if will_wait
985         log "\n\nDisconnected\n\n"
986
987         quit if $interrupted > 0
988
989         log "\n\nWaiting to reconnect\n\n"
990         sleep @config['server.reconnect_wait']
991         if too_fast > 0
992           tf = too_fast*@config['server.reconnect_wait']
993           tfu = Utils.secs_to_string(tf)
994           log "Will sleep for an extra #{tf}s (#{tfu})"
995           sleep tf
996         end
997       end
998
999       connect
1000     rescue DBFatal => e
1001       fatal "fatal db error: #{e.pretty_inspect}"
1002       DBTree.stats
1003       log_session_end
1004       exit 2
1005     rescue Exception => e
1006       error e
1007       will_wait = true
1008       retry
1009     end
1010   end
1011
1012   # begin event handling loop
1013   def mainloop
1014     while true
1015       too_fast = 0
1016       quit_msg = nil
1017       valid_recv = false # did we receive anything (valid) from the server yet?
1018       begin
1019         handle_sigs
1020         reconnect(quit_msg, too_fast)
1021         quit if $interrupted > 0
1022         valid_recv = false
1023         while @socket.connected?
1024           handle_sigs
1025           quit if $interrupted > 0
1026
1027           # Wait for messages and process them as they arrive. If nothing is
1028           # received, we call the ping_server() method that will PING the
1029           # server if appropriate, or raise a TimeoutError if no PONG has been
1030           # received in the user-chosen timeout since the last PING sent.
1031           if @socket.select(1)
1032             break unless reply = @socket.gets
1033             @last_rec = Time.now
1034             @client.process reply
1035             valid_recv = true
1036             too_fast = 0
1037           else
1038             ping_server
1039           end
1040         end
1041
1042       # I despair of this. Some of my users get "connection reset by peer"
1043       # exceptions that ARENT SocketError's. How am I supposed to handle
1044       # that?
1045       rescue SystemExit
1046         log_session_end
1047         exit 0
1048       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1049         error "network exception: #{e.pretty_inspect}"
1050         quit_msg = e.to_s
1051         too_fast += 10 if valid_recv
1052       rescue ServerMessageParseError => e
1053         # if the bot tried reconnecting too often, we can get forcefully
1054         # disconnected by the server, while still receiving an empty message
1055         # wait at least 10 minutes in this case
1056         if e.message.empty?
1057           oldtf = too_fast
1058           too_fast = [too_fast, 300].max
1059           too_fast*= 2
1060           log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1061         end
1062         quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1063         retry
1064       rescue ServerError => e
1065         quit_msg = "server ERROR: " + e.message
1066         debug quit_msg
1067         idx = e.message.index("connect too fast")
1068         debug "'connect too fast' @ #{idx}"
1069         if idx
1070           oldtf = too_fast
1071           too_fast += (idx+1)*2
1072           log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1073         end
1074         idx = e.message.index(/a(uto)kill/i)
1075         debug "'autokill' @ #{idx}"
1076         if idx
1077           # we got auto-killed. since we don't have an easy way to tell
1078           # if it's permanent or temporary, we just set a rather high
1079           # reconnection timeout
1080           oldtf = too_fast
1081           too_fast += (idx+1)*5
1082           log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1083         end
1084         retry
1085       rescue DBFatal => e
1086         fatal "fatal db error: #{e.pretty_inspect}"
1087         DBTree.stats
1088         # Why restart? DB problems are serious stuff ...
1089         # restart("Oops, we seem to have registry problems ...")
1090         log_session_end
1091         exit 2
1092       rescue Exception => e
1093         error "non-net exception: #{e.pretty_inspect}"
1094         quit_msg = e.to_s
1095       rescue => e
1096         fatal "unexpected exception: #{e.pretty_inspect}"
1097         log_session_end
1098         exit 2
1099       end
1100     end
1101   end
1102
1103   # type:: message type
1104   # where:: message target
1105   # message:: message text
1106   # send message +message+ of type +type+ to target +where+
1107   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1108   # relevant say() or notice() methods. This one should be used for IRCd
1109   # extensions you want to use in modules.
1110   def sendmsg(original_type, original_where, original_message, options={})
1111
1112     # filter message with sendmsg filters
1113     ds = DataStream.new original_message.to_s.dup,
1114       :type => original_type, :dest => original_where,
1115       :options => @default_send_options.merge(options)
1116     filters = filter_names(:sendmsg)
1117     filters.each do |fname|
1118       debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1119       ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1120     end
1121
1122     opts = ds[:options]
1123     type = ds[:type]
1124     where = ds[:dest]
1125     filtered = ds[:text]
1126
1127     # For starters, set up appropriate queue channels and rings
1128     mchan = opts[:queue_channel]
1129     mring = opts[:queue_ring]
1130     if mchan
1131       chan = mchan
1132     else
1133       chan = where
1134     end
1135     if mring
1136       ring = mring
1137     else
1138       case where
1139       when User
1140         ring = 1
1141       else
1142         ring = 2
1143       end
1144     end
1145
1146     multi_line = filtered.gsub(/[\r\n]+/, "\n")
1147
1148     # if target is a channel with nocolor modes, strip colours
1149     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1150       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1151     end
1152
1153     messages = Array.new
1154     case opts[:newlines]
1155     when :join
1156       messages << [multi_line.gsub("\n", opts[:join_with])]
1157     when :split
1158       multi_line.each_line { |line|
1159         line.chomp!
1160         next unless(line.size > 0)
1161         messages << line
1162       }
1163     else
1164       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1165     end
1166
1167     # The IRC protocol requires that each raw message must be not longer
1168     # than 512 characters. From this length with have to subtract the EOL
1169     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1170     # that will be prepended by the server to all of our messages.
1171
1172     # The maximum raw message length we can send is therefore 512 - 2 - 2
1173     # minus the length of our hostmask.
1174
1175     max_len = 508 - myself.fullform.size
1176
1177     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1178     # will have a + or - prepended
1179     if server.capabilities[:"identify-msg"]
1180       max_len -= 1
1181     end
1182
1183     # When splitting the message, we'll be prefixing the following string:
1184     # (e.g. "PRIVMSG #rbot :")
1185     fixed = "#{type} #{where} :"
1186
1187     # And this is what's left
1188     left = max_len - fixed.size
1189
1190     truncate = opts[:truncate_text]
1191     truncate = @default_send_options[:truncate_text] if truncate.size > left
1192     truncate = "" if truncate.size > left
1193
1194     all_lines = messages.map { |line|
1195       if line.size < left
1196         line
1197       else
1198         case opts[:overlong]
1199         when :split
1200           msg = line.dup
1201           sub_lines = Array.new
1202           begin
1203             sub_lines << msg.slice!(0, left)
1204             break if msg.empty?
1205             lastspace = sub_lines.last.rindex(opts[:split_at])
1206             if lastspace
1207               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1208               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1209             end
1210           end until msg.empty?
1211           sub_lines
1212         when :truncate
1213           line.slice(0, left - truncate.size) << truncate
1214         else
1215           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1216         end
1217       end
1218     }.flatten
1219
1220     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1221       lines = all_lines[0...opts[:max_lines]]
1222       new_last = lines.last.slice(0, left - truncate.size) << truncate
1223       lines.last.replace(new_last)
1224     else
1225       lines = all_lines
1226     end
1227
1228     lines.each { |line|
1229       sendq "#{fixed}#{line}", chan, ring
1230       delegate_sent(type, where, line)
1231     }
1232   end
1233
1234   # queue an arbitraty message for the server
1235   def sendq(message="", chan=nil, ring=0)
1236     # temporary
1237     @socket.queue(message, chan, ring)
1238   end
1239
1240   # send a notice message to channel/nick +where+
1241   def notice(where, message, options={})
1242     return if where.kind_of?(Channel) and quiet_on?(where)
1243     sendmsg "NOTICE", where, message, options
1244   end
1245
1246   # say something (PRIVMSG) to channel/nick +where+
1247   def say(where, message, options={})
1248     return if where.kind_of?(Channel) and quiet_on?(where)
1249     sendmsg "PRIVMSG", where, message, options
1250   end
1251
1252   def ctcp_notice(where, command, message, options={})
1253     return if where.kind_of?(Channel) and quiet_on?(where)
1254     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1255   end
1256
1257   def ctcp_say(where, command, message, options={})
1258     return if where.kind_of?(Channel) and quiet_on?(where)
1259     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1260   end
1261
1262   # perform a CTCP action with message +message+ to channel/nick +where+
1263   def action(where, message, options={})
1264     ctcp_say(where, 'ACTION', message, options)
1265   end
1266
1267   # quick way to say "okay" (or equivalent) to +where+
1268   def okay(where)
1269     say where, @lang.get("okay")
1270   end
1271
1272   # set topic of channel +where+ to +topic+
1273   # can also be used to retrieve the topic of channel +where+
1274   # by omitting the last argument
1275   def topic(where, topic=nil)
1276     if topic.nil?
1277       sendq "TOPIC #{where}", where, 2
1278     else
1279       sendq "TOPIC #{where} :#{topic}", where, 2
1280     end
1281   end
1282
1283   def disconnect(message=nil)
1284     message = @lang.get("quit") if (!message || message.empty?)
1285     if @socket.connected?
1286       begin
1287         debug "Clearing socket"
1288         @socket.clearq
1289         debug "Sending quit message"
1290         @socket.emergency_puts "QUIT :#{message}"
1291         debug "Logging quits"
1292         delegate_sent('QUIT', myself, message)
1293         debug "Flushing socket"
1294         @socket.flush
1295       rescue SocketError => e
1296         error "error while disconnecting socket: #{e.pretty_inspect}"
1297       end
1298       debug "Shutting down socket"
1299       @socket.shutdown
1300     end
1301     stop_server_pings
1302     @client.reset
1303   end
1304
1305   # disconnect from the server and cleanup all plugins and modules
1306   def shutdown(message=nil)
1307     @quit_mutex.synchronize do
1308       debug "Shutting down: #{message}"
1309       ## No we don't restore them ... let everything run through
1310       # begin
1311       #   trap("SIGINT", "DEFAULT")
1312       #   trap("SIGTERM", "DEFAULT")
1313       #   trap("SIGHUP", "DEFAULT")
1314       # rescue => e
1315       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1316       # end
1317       debug "\tdisconnecting..."
1318       disconnect(message)
1319       debug "\tstopping timer..."
1320       @timer.stop
1321       debug "\tsaving ..."
1322       save
1323       debug "\tcleaning up ..."
1324       @save_mutex.synchronize do
1325         @plugins.cleanup
1326       end
1327       # debug "\tstopping timers ..."
1328       # @timer.stop
1329       # debug "Closing registries"
1330       # @registry.close
1331       debug "\t\tcleaning up the db environment ..."
1332       DBTree.cleanup_env
1333       log "rbot quit (#{message})"
1334     end
1335   end
1336
1337   # message:: optional IRC quit message
1338   # quit IRC, shutdown the bot
1339   def quit(message=nil)
1340     begin
1341       shutdown(message)
1342     ensure
1343       exit 0
1344     end
1345   end
1346
1347   # totally shutdown and respawn the bot
1348   def restart(message=nil)
1349     message = _("restarting, back in %{wait}...") % {
1350       :wait => @config['server.reconnect_wait']
1351     } if (!message || message.empty?)
1352     shutdown(message)
1353     sleep @config['server.reconnect_wait']
1354     begin
1355       # now we re-exec
1356       # Note, this fails on Windows
1357       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1358       log_session_end
1359       Dir.chdir(@run_dir)
1360       exec($0, *@argv)
1361     rescue Errno::ENOENT
1362       log_session_end
1363       exec("ruby", *(@argv.unshift $0))
1364     rescue Exception => e
1365       $interrupted += 1
1366       raise e
1367     end
1368   end
1369
1370   # call the save method for all of the botmodules
1371   def save
1372     @save_mutex.synchronize do
1373       @plugins.save
1374       DBTree.cleanup_logs
1375     end
1376   end
1377
1378   # call the rescan method for all of the botmodules
1379   def rescan
1380     debug "\tstopping timer..."
1381     @timer.stop
1382     @save_mutex.synchronize do
1383       @lang.rescan
1384       @plugins.rescan
1385     end
1386     @timer.start
1387   end
1388
1389   # channel:: channel to join
1390   # key::     optional channel key if channel is +s
1391   # join a channel
1392   def join(channel, key=nil)
1393     if(key)
1394       sendq "JOIN #{channel} :#{key}", channel, 2
1395     else
1396       sendq "JOIN #{channel}", channel, 2
1397     end
1398   end
1399
1400   # part a channel
1401   def part(channel, message="")
1402     sendq "PART #{channel} :#{message}", channel, 2
1403   end
1404
1405   # attempt to change bot's nick to +name+
1406   def nickchg(name)
1407     sendq "NICK #{name}"
1408   end
1409
1410   # changing mode
1411   def mode(channel, mode, target=nil)
1412     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1413   end
1414
1415   # asking whois
1416   def whois(nick, target=nil)
1417     sendq "WHOIS #{target} #{nick}", nil, 0
1418   end
1419
1420   # kicking a user
1421   def kick(channel, user, msg)
1422     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1423   end
1424
1425   # m::     message asking for help
1426   # topic:: optional topic help is requested for
1427   # respond to online help requests
1428   def help(topic=nil)
1429     topic = nil if topic == ""
1430     case topic
1431     when nil
1432       helpstr = _("help topics: ")
1433       helpstr += @plugins.helptopics
1434       helpstr += _(" (help <topic> for more info)")
1435     else
1436       unless(helpstr = @plugins.help(topic))
1437         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1438       end
1439     end
1440     return helpstr
1441   end
1442
1443   # returns a string describing the current status of the bot (uptime etc)
1444   def status
1445     secs_up = Time.new - @startup_time
1446     uptime = Utils.secs_to_string secs_up
1447     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1448     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1449              {
1450                :up => uptime, :plug => @plugins.length,
1451                :sent => @socket.lines_sent, :recv => @socket.lines_received
1452              })
1453   end
1454
1455   # We want to respond to a hung server in a timely manner. If nothing was received
1456   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1457   # the server. If the PONG is not received within the user-defined timeout, we
1458   # assume we're in ping timeout and act accordingly.
1459   def ping_server
1460     act_timeout = @config['server.ping_timeout']
1461     return if act_timeout <= 0
1462     now = Time.now
1463     if @last_rec && now > @last_rec + act_timeout
1464       if @last_ping.nil?
1465         # No previous PING pending, send a new one
1466         sendq "PING :rbot"
1467         @last_ping = Time.now
1468       else
1469         diff = now - @last_ping
1470         if diff > act_timeout
1471           debug "no PONG from server in #{diff} seconds, reconnecting"
1472           # the actual reconnect is handled in the main loop:
1473           raise TimeoutError, "no PONG from server in #{diff} seconds"
1474         end
1475       end
1476     end
1477   end
1478
1479   def stop_server_pings
1480     # cancel previous PINGs and reset time of last RECV
1481     @last_ping = nil
1482     @last_rec = nil
1483   end
1484
1485   private
1486
1487   # delegate sent messages
1488   def delegate_sent(type, where, message)
1489     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1490     case type
1491       when "NOTICE"
1492         m = NoticeMessage.new(*args)
1493       when "PRIVMSG"
1494         m = PrivMessage.new(*args)
1495       when "QUIT"
1496         m = QuitMessage.new(*args)
1497         m.was_on = myself.channels
1498     end
1499     @plugins.delegate('sent', m)
1500   end
1501
1502 end
1503
1504 end