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