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