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