14 $debug = false unless $debug
15 $daemonize = false unless $daemonize
17 $dateformat = "%Y/%m/%d %H:%M:%S"
18 $logger = Logger.new($stderr)
19 $logger.datetime_format = $dateformat
20 $logger.level = $cl_loglevel if defined? $cl_loglevel
21 $logger.level = 0 if $debug
22 $logger_stderr = $logger
24 $log_queue = Queue.new
29 unless Kernel.respond_to? :pretty_inspect
33 public :pretty_inspect
38 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
39 if self.backtrace and not self.backtrace.empty?
41 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
47 class ServerError < RuntimeError
50 def rawlog(level, message=nil, who_pos=1)
52 if call_stack.length > who_pos
53 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
57 # Output each line. To distinguish between separate messages and multi-line
58 # messages originating at the same time, we blank #{who} after the first message
60 # Also, we output strings as-is but for other objects we use pretty_inspect
61 message = message.kind_of?(String) ? message : (message.pretty_inspect rescue '?')
63 message.each_line { |l|
64 qmsg.push [level, l.chomp, who]
67 if level >= Logger::Severity::WARN and not $daemonize
69 $logger_stderr.add(*l)
76 if $log_thread && $log_thread.alive?
85 def restart_logger(newlogger = false)
88 $logger = newlogger if newlogger
90 $log_thread = Thread.new do
92 while ls = $log_queue.pop
93 ls.each { |l| $logger.add(*l) }
100 def log_session_start
101 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
106 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
110 def debug(message=nil, who_pos=1)
111 rawlog(Logger::Severity::DEBUG, message, who_pos)
114 def log(message=nil, who_pos=1)
115 rawlog(Logger::Severity::INFO, message, who_pos)
118 def warning(message=nil, who_pos=1)
119 rawlog(Logger::Severity::WARN, message, who_pos)
122 def error(message=nil, who_pos=1)
123 rawlog(Logger::Severity::ERROR, message, who_pos)
126 def fatal(message=nil, who_pos=1)
127 rawlog(Logger::Severity::FATAL, message, who_pos)
132 warning "warning test"
136 # The following global is used for the improved signal handling.
140 require 'rbot/rbotconfig'
144 log "rubygems unavailable"
147 require 'rbot/load-gettext'
148 require 'rbot/config'
151 require 'rbot/rfc2812'
152 require 'rbot/ircsocket'
153 require 'rbot/botuser'
155 require 'rbot/registry'
156 require 'rbot/plugins'
157 require 'rbot/message'
158 require 'rbot/language'
162 # Main bot class, which manages the various components, receives messages,
163 # handles them or passes them to plugins, and contains core functionality.
165 COPYRIGHT_NOTICE = "(c) Giuseppe Bilotta and the rbot development team"
166 SOURCE_URL = "http://ruby-rbot.org"
167 # the bot's Auth data
170 # the bot's Config data
173 # the botclass for this bot (determines configdir among other things)
174 attr_reader :botclass
176 # used to perform actions periodically (saves configuration once per minute
180 # synchronize with this mutex while touching permanent data files:
181 # saving, flushing, cleaning up ...
182 attr_reader :save_mutex
184 # bot's Language data
191 # bot's plugins. This is an instance of class Plugins
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
198 # mechanize agent factory
201 # loads and opens new registry databases, used by the plugins
202 attr_accessor :registry_factory
205 attr_accessor :webservice
207 # server we are connected to
213 # bot User in the client/server connection
219 # bot nick in the client/server connection
224 # bot channels in the client/server connection
229 # nick wanted by the bot. This defaults to the irc.nick config value,
230 # but may be overridden by a manual !nick command
232 @wanted_nick || config['irc.nick']
235 # set the nick wanted by the bot
237 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
240 @wanted_nick = wn.to_s.dup
248 ret = self.to_s[0..-2]
249 ret << ' version=' << $version.inspect
250 ret << ' botclass=' << botclass.inspect
251 ret << ' lang="' << lang.language
256 ret << ' nick=' << nick.inspect
259 ret << (server.to_s + (socket ?
260 ' [' << socket.server_uri.to_s << ']' : '')).inspect
261 unless server.channels.empty?
263 ret << server.channels.map { |c|
264 "%s%s" % [c.modes_of(nick).map { |m|
265 server.prefix_for_mode(m)
272 ret << ' plugins=' << plugins.inspect
277 # create a new Bot with botclass +botclass+
278 def initialize(botclass, params = {})
279 # Config for the core bot
280 # TODO should we split socket stuff into ircsocket, etc?
281 Config.register Config::ArrayValue.new('server.list',
282 :default => ['irc://localhost'], :wizard => true,
283 :requires_restart => true,
284 :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.")
285 Config.register Config::BooleanValue.new('server.ssl',
286 :default => false, :requires_restart => true, :wizard => true,
287 :desc => "Use SSL to connect to this server?")
288 Config.register Config::BooleanValue.new('server.ssl_verify',
289 :default => false, :requires_restart => true,
290 :desc => "Verify the SSL connection?",
292 Config.register Config::StringValue.new('server.ssl_ca_file',
293 :default => default_ssl_ca_file, :requires_restart => true,
294 :desc => "The CA file used to verify the SSL connection.",
296 Config.register Config::StringValue.new('server.ssl_ca_path',
297 :default => default_ssl_ca_path, :requires_restart => true,
298 :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
300 Config.register Config::StringValue.new('server.password',
301 :default => false, :requires_restart => true,
302 :desc => "Password for connecting to this server (if required)",
304 Config.register Config::StringValue.new('server.bindhost',
305 :default => false, :requires_restart => true,
306 :desc => "Specific local host or IP for the bot to bind to (if required)",
308 Config.register Config::IntegerValue.new('server.reconnect_wait',
309 :default => 5, :validate => Proc.new{|v| v >= 0},
310 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
311 Config.register Config::IntegerValue.new('server.ping_timeout',
312 :default => 30, :validate => Proc.new{|v| v >= 0},
313 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
314 Config.register Config::ArrayValue.new('server.nocolor_modes',
315 :default => ['c'], :wizard => false,
316 :requires_restart => false,
317 :desc => "List of channel modes that require messages to be without colors")
319 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
320 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
321 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
322 Config.register Config::StringValue.new('irc.name',
323 :default => "Ruby bot", :requires_restart => true,
324 :desc => "IRC realname the bot should use")
325 Config.register Config::BooleanValue.new('irc.name_copyright',
326 :default => true, :requires_restart => true,
327 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
328 Config.register Config::StringValue.new('irc.user', :default => "rbot",
329 :requires_restart => true,
330 :desc => "local user the bot should appear to be", :wizard => true)
331 Config.register Config::ArrayValue.new('irc.join_channels',
332 :default => [], :wizard => true,
333 :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'")
334 Config.register Config::ArrayValue.new('irc.ignore_users',
336 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
337 Config.register Config::ArrayValue.new('irc.ignore_channels',
339 :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)")
341 Config.register Config::IntegerValue.new('core.save_every',
342 :default => 60, :validate => Proc.new{|v| v >= 0},
343 :on_change => Proc.new { |bot, v|
346 @timer.reschedule(@save_timer, v)
347 @timer.unblock(@save_timer)
349 @timer.block(@save_timer)
353 @save_timer = @timer.add(v) { bot.save }
355 # Nothing to do when v == 0
358 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
360 Config.register Config::BooleanValue.new('core.run_as_daemon',
361 :default => false, :requires_restart => true,
362 :desc => "Should the bot run as a daemon?")
364 Config.register Config::StringValue.new('log.file',
365 :default => false, :requires_restart => true,
366 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
367 Config.register Config::IntegerValue.new('log.level',
368 :default => 1, :requires_restart => false,
369 :validate => Proc.new { |v| (0..5).include?(v) },
370 :on_change => Proc.new { |bot, v|
373 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
374 Config.register Config::IntegerValue.new('log.keep',
375 :default => 1, :requires_restart => true,
376 :validate => Proc.new { |v| v >= 0 },
377 :desc => "How many old console messages logfiles to keep")
378 Config.register Config::IntegerValue.new('log.max_size',
379 :default => 10, :requires_restart => true,
380 :validate => Proc.new { |v| v > 0 },
381 :desc => "Maximum console messages logfile size (in megabytes)")
383 Config.register Config::ArrayValue.new('plugins.path',
384 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
385 :requires_restart => false,
386 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
387 :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")
389 Config.register Config::EnumValue.new('send.newlines',
390 :values => ['split', 'join'], :default => 'split',
391 :on_change => Proc.new { |bot, v|
392 bot.set_default_send_options :newlines => v.to_sym
394 :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")
395 Config.register Config::StringValue.new('send.join_with',
397 :on_change => Proc.new { |bot, v|
398 bot.set_default_send_options :join_with => v.dup
400 :desc => "String used to replace newlines when send.newlines is set to join")
401 Config.register Config::IntegerValue.new('send.max_lines',
403 :validate => Proc.new { |v| v >= 0 },
404 :on_change => Proc.new { |bot, v|
405 bot.set_default_send_options :max_lines => v
407 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
408 Config.register Config::EnumValue.new('send.overlong',
409 :values => ['split', 'truncate'], :default => 'split',
410 :on_change => Proc.new { |bot, v|
411 bot.set_default_send_options :overlong => v.to_sym
413 :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")
414 Config.register Config::StringValue.new('send.split_at',
416 :on_change => Proc.new { |bot, v|
417 bot.set_default_send_options :split_at => Regexp.new(v)
419 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
420 Config.register Config::BooleanValue.new('send.purge_split',
422 :on_change => Proc.new { |bot, v|
423 bot.set_default_send_options :purge_split => v
425 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
426 Config.register Config::StringValue.new('send.truncate_text',
427 :default => "#{Reverse}...#{Reverse}",
428 :on_change => Proc.new { |bot, v|
429 bot.set_default_send_options :truncate_text => v.dup
431 :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")
432 Config.register Config::IntegerValue.new('send.penalty_pct',
434 :validate => Proc.new { |v| v >= 0 },
435 :on_change => Proc.new { |bot, v|
436 bot.socket.penalty_pct = v
438 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
439 Config.register Config::StringValue.new('core.db',
440 :default => default_db, :store_default => true,
442 :validate => Proc.new { |v| Registry::formats.include? v },
443 :requires_restart => true,
444 :desc => "DB adaptor to use for storing the plugin data/registries. Options: " + Registry::formats.join(', '))
446 @argv = params[:argv]
447 @run_dir = params[:run_dir] || Dir.pwd
449 unless FileTest.directory? Config::coredir
450 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
454 unless FileTest.directory? Config::datadir
455 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
459 unless botclass and not botclass.empty?
460 # We want to find a sensible default.
461 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
462 # * On Windows (at least the NT versions) we want to put our stuff in the
463 # Application Data folder.
464 # We don't use any particular O/S detection magic, exploiting the fact that
465 # Etc.getpwuid is nil on Windows
466 if Etc.getpwuid(Process::Sys.geteuid)
467 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
469 if ENV.has_key?('APPDATA')
470 botclass = ENV['APPDATA'].dup
471 botclass.gsub!("\\","/")
474 botclass = File.join(botclass, ".rbot")
476 botclass = File.expand_path(botclass)
477 @botclass = botclass.gsub(/\/$/, "")
479 repopulate_botclass_directory
481 save_dir = File.join(@botclass, 'safe_save')
482 Dir.mkdir(save_dir) unless File.exist?(save_dir)
483 unless FileTest.directory? save_dir
484 error "safe save location #{save_dir} is not a directory"
488 # Time at which the last PING was sent
490 # Time at which the last line was RECV'd from the server
493 @startup_time = Time.new
496 @config = Config.manager
497 @config.bot_associate(self)
498 rescue Exception => e
504 if @config['core.run_as_daemon']
508 @registry_factory = Registry.new @config['core.db']
509 @registry_factory.migrate_registry_folder(path)
511 @logfile = @config['log.file']
512 if @logfile.class!=String || @logfile.empty?
513 logfname = File.basename(botclass).gsub(/^\.+/,'')
515 @logfile = File.join(botclass, logfname)
516 debug "Using `#{@logfile}' as debug log"
519 # See http://blog.humlab.umu.se/samuel/archives/000107.html
520 # for the backgrounding code
526 rescue NotImplementedError
527 warning "Could not background, fork not supported"
530 rescue Exception => e
531 warning "Could not background. #{e.pretty_inspect}"
534 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
537 logger = Logger.new(@logfile,
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
545 restart_logger(logger)
550 log "Redirecting standard input/output/error"
551 [$stdin, $stdout, $stderr].each do |fd|
553 fd.reopen "/dev/null"
555 # On Windows, there's not such thing as /dev/null
560 def $stdout.write(str=nil)
564 def $stdout.write(str=nil)
565 if str.to_s.match(/:\d+: warning:/)
574 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
579 @save_mutex = Mutex.new
580 if @config['core.save_every'] > 0
581 @save_timer = @timer.add(@config['core.save_every']) { save }
585 @quit_mutex = Mutex.new
588 @lang = Language.new(self, @config['core.language'])
591 @auth = Auth::manager
592 @auth.bot_associate(self)
593 # @auth.load("#{botclass}/botusers.yaml")
594 rescue Exception => e
599 @auth.everyone.set_default_permission("*", true)
600 @auth.botowner.password= @config['auth.password']
602 @plugins = Plugins::manager
603 @plugins.bot_associate(self)
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}"
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'])
626 # Channels where we are quiet
627 # Array of channels names where the bot should be quiet
628 # '*' means all channels
631 # but we always speak here
634 # the nick we want, if it's different from the irc.nick config value
635 # (e.g. as set by a !nick command)
638 @client[:welcome] = proc {|data|
639 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
641 @plugins.delegate("welcome", m)
642 @plugins.delegate("connect")
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
655 @client[:datastr] = proc { |data|
656 if data[:text] == "IDENTIFY-MSG"
657 server.capabilities[:"identify-msg"] = true
659 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
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}"
669 @config['irc.ignore_channels'].each { |channel|
670 if m.target.downcase == channel.downcase
675 @config['irc.ignore_users'].each { |mask|
676 if m.source.matches?(server.new_netmask(mask))
682 @plugins.irc_delegate('privmsg', m)
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
689 @client[:motd] = proc { |data|
690 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
691 @plugins.delegate "motd", m
693 @client[:nicktaken] = proc { |data|
694 new = "#{data[:nick]}_"
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}"
703 @plugins.delegate "nicktaken", data[:nick]
705 @client[:badnick] = proc {|data|
706 warning "bad nick (#{data[:nick]})"
708 @client[:ping] = proc {|data|
709 sendq "PONG #{data[:pingid]}"
711 @client[:pong] = proc {|data|
714 @client[:nick] = proc {|data|
715 # debug "Message source is #{data[:source].inspect}"
716 # debug "Bot is #{myself.inspect}"
717 source = data[:source]
720 m = NickMessage.new(self, server, source, old, new)
721 m.is_on = data[:is_on]
723 debug "my nick is now #{new}"
725 @plugins.irc_delegate("nick", m)
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)
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
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
745 @client[:list] = proc {|data|
746 source = data[:source]
747 m = ListMessage.new(self, server, source, source, data[:list])
748 @plugins.delegate "irclist", m
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?
756 @client[:part] = proc {|data|
757 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
758 @plugins.irc_delegate("part", m)
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)
764 @client[:invite] = proc {|data|
765 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
766 @plugins.irc_delegate("invite", m)
768 @client[:changetopic] = proc {|data|
769 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
771 @plugins.irc_delegate("topic", m)
773 # @client[:topic] = proc { |data|
774 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
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)
783 @client[:names] = proc { |data|
784 m = NamesMessage.new(self, server, server, data[:channel])
785 m.users = data[:users]
786 @plugins.delegate "names", m
788 @client[:banlist] = proc { |data|
789 m = BanlistMessage.new(self, server, server, data[:channel])
791 @plugins.delegate "banlist", m
793 @client[:nosuchtarget] = proc { |data|
794 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
795 @plugins.delegate "nosuchtarget", m
797 @client[:error] = proc { |data|
798 raise ServerError, data[:message]
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
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
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
828 def default_ssl_ca_path
829 file = default_ssl_ca_file
830 File.dirname file if file
833 # Determine if tokyocabinet is installed, if it is use it as a default.
836 require 'tokyocabinet'
843 def repopulate_botclass_directory
844 template_dir = File.join Config::datadir, 'templates'
845 if FileTest.directory? @botclass
846 # compare the templates dir with the current botclass dir, filling up the
847 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
848 # :update option, so we have to do it manually.
849 # Note that we use the */** pattern because we don't want to match
850 # keywords.rbot, which gets deleted on load and would therefore be missing
852 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
854 dest = File.join(@botclass, f)
855 FileUtils.mkdir_p(File.dirname(dest))
856 FileUtils.cp File.join(template_dir, f), dest
859 log "no #{@botclass} directory found, creating from templates..."
860 if FileTest.exist? @botclass
861 error "file #{@botclass} exists but isn't a directory"
864 FileUtils.cp_r template_dir, @botclass
868 # Return a path under the current botclass by joining the mentioned
869 # components. The components are automatically converted to String
870 def path(*components)
871 File.join(@botclass, *(components.map {|c| c.to_s}))
874 def setup_plugins_path
875 plugdir_default = File.join(Config::datadir, 'plugins')
876 plugdir_local = File.join(@botclass, 'plugins')
877 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
879 @plugins.clear_botmodule_dirs
880 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
881 @plugins.add_core_module_dir(Config::coredir)
882 if FileTest.directory? plugdir_local
883 @plugins.add_plugin_dir(plugdir_local)
885 warning "local plugin location #{plugdir_local} is not a directory"
888 @config['plugins.path'].each do |_|
889 path = _.sub(/^\(default\)/, plugdir_default)
890 @plugins.add_plugin_dir(path)
894 def set_default_send_options(opts={})
895 # Default send options for NOTICE and PRIVMSG
896 unless defined? @default_send_options
897 @default_send_options = {
898 :queue_channel => nil, # use default queue channel
899 :queue_ring => nil, # use default queue ring
900 :newlines => :split, # or :join
901 :join_with => ' ', # by default, use a single space
902 :max_lines => 0, # maximum number of lines to send with a single command
903 :overlong => :split, # or :truncate
904 # TODO an array of splitpoints would be preferrable for this option:
905 :split_at => /\s+/, # by default, split overlong lines at whitespace
906 :purge_split => true, # should the split string be removed?
907 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
910 @default_send_options.update opts unless opts.empty?
913 # checks if we should be quiet on a channel
914 def quiet_on?(channel)
915 ch = channel.downcase
916 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
919 def set_quiet(channel = nil)
921 ch = channel.downcase.dup
922 @not_quiet.delete(ch)
931 def reset_quiet(channel = nil)
933 ch = channel.downcase.dup
942 # things to do when we receive a signal
943 def handle_signal(sig)
952 debug "received #{sig}, queueing #{func}"
953 # this is not an interruption if we just need to reconnect
954 $interrupted += 1 unless func == :reconnect
955 self.send(func) unless @quit_mutex.locked?
956 debug "interrupted #{$interrupted} times"
967 %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
968 trap(sig) { Thread.new { handle_signal sig } }
970 rescue ArgumentError => e
971 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
972 rescue Exception => e
973 debug "failed to trap signals: #{e.pretty_inspect}"
977 # connect the bot to IRC
979 # make sure we don't have any spurious ping checks running
980 # (and initialize the vars if this is the first time we connect)
983 quit if $interrupted > 0
986 rescue Exception => e
987 uri = @socket.server_uri || '<unknown>'
988 error "failed to connect to IRC server at #{uri}"
992 quit if $interrupted > 0
994 realname = @config['irc.name'].clone || 'Ruby bot'
995 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
997 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
998 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
999 quit if $interrupted > 0
1000 myself.nick = @config['irc.nick']
1001 myself.user = @config['irc.user']
1004 # disconnect the bot from IRC, if connected, and then connect (again)
1005 def reconnect(message=nil, too_fast=0)
1006 # we will wait only if @last_rec was not nil, i.e. if we were connected or
1007 # got disconnected by a network error
1008 # if someone wants to manually call disconnect() _and_ reconnect(), they
1009 # will have to take care of the waiting themselves
1010 will_wait = !!@last_rec
1012 if @socket.connected?
1018 log "\n\nDisconnected\n\n"
1020 quit if $interrupted > 0
1022 log "\n\nWaiting to reconnect\n\n"
1023 sleep @config['server.reconnect_wait']
1025 tf = too_fast*@config['server.reconnect_wait']
1026 tfu = Utils.secs_to_string(tf)
1027 log "Will sleep for an extra #{tf}s (#{tfu})"
1036 rescue Exception => e
1043 # begin event handling loop
1048 valid_recv = false # did we receive anything (valid) from the server yet?
1050 reconnect(quit_msg, too_fast)
1051 quit if $interrupted > 0
1053 while @socket.connected?
1054 quit if $interrupted > 0
1056 # Wait for messages and process them as they arrive. If nothing is
1057 # received, we call the ping_server() method that will PING the
1058 # server if appropriate, or raise a TimeoutError if no PONG has been
1059 # received in the user-chosen timeout since the last PING sent.
1060 if @socket.select(1)
1061 break unless reply = @socket.gets
1062 @last_rec = Time.now
1063 @client.process reply
1071 # I despair of this. Some of my users get "connection reset by peer"
1072 # exceptions that ARENT SocketError's. How am I supposed to handle
1077 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1078 error "network exception: #{e.pretty_inspect}"
1080 too_fast += 10 if valid_recv
1081 rescue ServerMessageParseError => e
1082 # if the bot tried reconnecting too often, we can get forcefully
1083 # disconnected by the server, while still receiving an empty message
1084 # wait at least 10 minutes in this case
1087 too_fast = [too_fast, 300].max
1089 log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1091 quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1093 rescue ServerError => e
1094 quit_msg = "server ERROR: " + e.message
1096 idx = e.message.index("connect too fast")
1097 debug "'connect too fast' @ #{idx}"
1100 too_fast += (idx+1)*2
1101 log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1103 idx = e.message.index(/a(uto)kill/i)
1104 debug "'autokill' @ #{idx}"
1106 # we got auto-killed. since we don't have an easy way to tell
1107 # if it's permanent or temporary, we just set a rather high
1108 # reconnection timeout
1110 too_fast += (idx+1)*5
1111 log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1114 rescue Exception => e
1115 error "non-net exception: #{e.pretty_inspect}"
1118 fatal "unexpected exception: #{e.pretty_inspect}"
1125 # type:: message type
1126 # where:: message target
1127 # message:: message text
1128 # send message +message+ of type +type+ to target +where+
1129 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1130 # relevant say() or notice() methods. This one should be used for IRCd
1131 # extensions you want to use in modules.
1132 def sendmsg(original_type, original_where, original_message, options={})
1134 # filter message with sendmsg filters
1135 ds = DataStream.new original_message.to_s.dup,
1136 :type => original_type, :dest => original_where,
1137 :options => @default_send_options.merge(options)
1138 filters = filter_names(:sendmsg)
1139 filters.each do |fname|
1140 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1141 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1147 filtered = ds[:text]
1149 if defined? WebServiceUser and where.instance_of? WebServiceUser
1150 debug 'sendmsg to web service!'
1151 where.response << filtered
1155 # For starters, set up appropriate queue channels and rings
1156 mchan = opts[:queue_channel]
1157 mring = opts[:queue_ring]
1174 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1176 # if target is a channel with nocolor modes, strip colours
1177 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1178 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1181 messages = Array.new
1182 case opts[:newlines]
1184 messages << [multi_line.gsub("\n", opts[:join_with])]
1186 multi_line.each_line { |line|
1188 next unless(line.size > 0)
1192 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1195 # The IRC protocol requires that each raw message must be not longer
1196 # than 512 characters. From this length with have to subtract the EOL
1197 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1198 # that will be prepended by the server to all of our messages.
1200 # The maximum raw message length we can send is therefore 512 - 2 - 2
1201 # minus the length of our hostmask.
1203 max_len = 508 - myself.fullform.size
1205 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1206 # will have a + or - prepended
1207 if server.capabilities[:"identify-msg"]
1211 # When splitting the message, we'll be prefixing the following string:
1212 # (e.g. "PRIVMSG #rbot :")
1213 fixed = "#{type} #{where} :"
1215 # And this is what's left
1216 left = max_len - fixed.size
1218 truncate = opts[:truncate_text]
1219 truncate = @default_send_options[:truncate_text] if truncate.size > left
1220 truncate = "" if truncate.size > left
1222 all_lines = messages.map { |line|
1226 case opts[:overlong]
1229 sub_lines = Array.new
1231 sub_lines << msg.slice!(0, left)
1233 lastspace = sub_lines.last.rindex(opts[:split_at])
1235 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1236 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1238 end until msg.empty?
1241 line.slice(0, left - truncate.size) << truncate
1243 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1248 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1249 lines = all_lines[0...opts[:max_lines]]
1250 new_last = lines.last.slice(0, left - truncate.size) << truncate
1251 lines.last.replace(new_last)
1257 sendq "#{fixed}#{line}", chan, ring
1258 delegate_sent(type, where, line)
1262 # queue an arbitraty message for the server
1263 def sendq(message="", chan=nil, ring=0)
1265 @socket.queue(message, chan, ring)
1268 # send a notice message to channel/nick +where+
1269 def notice(where, message, options={})
1270 return if where.kind_of?(Channel) and quiet_on?(where)
1271 sendmsg "NOTICE", where, message, options
1274 # say something (PRIVMSG) to channel/nick +where+
1275 def say(where, message, options={})
1276 return if where.kind_of?(Channel) and quiet_on?(where)
1277 sendmsg "PRIVMSG", where, message, options
1280 def ctcp_notice(where, command, message, options={})
1281 return if where.kind_of?(Channel) and quiet_on?(where)
1282 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1285 def ctcp_say(where, command, message, options={})
1286 return if where.kind_of?(Channel) and quiet_on?(where)
1287 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1290 # perform a CTCP action with message +message+ to channel/nick +where+
1291 def action(where, message, options={})
1292 ctcp_say(where, 'ACTION', message, options)
1295 # quick way to say "okay" (or equivalent) to +where+
1297 say where, @lang.get("okay")
1300 # set topic of channel +where+ to +topic+
1301 # can also be used to retrieve the topic of channel +where+
1302 # by omitting the last argument
1303 def topic(where, topic=nil)
1305 sendq "TOPIC #{where}", where, 2
1307 sendq "TOPIC #{where} :#{topic}", where, 2
1311 def disconnect(message=nil)
1312 message = @lang.get("quit") if (!message || message.empty?)
1313 if @socket.connected?
1315 debug "Clearing socket"
1317 debug "Sending quit message"
1318 @socket.emergency_puts "QUIT :#{message}"
1319 debug "Logging quits"
1320 delegate_sent('QUIT', myself, message)
1321 debug "Flushing socket"
1323 rescue SocketError => e
1324 error "error while disconnecting socket: #{e.pretty_inspect}"
1326 debug "Shutting down socket"
1333 # disconnect from the server and cleanup all plugins and modules
1334 def shutdown(message=nil)
1335 @quit_mutex.synchronize do
1336 debug "Shutting down: #{message}"
1337 ## No we don't restore them ... let everything run through
1339 # trap("SIGINT", "DEFAULT")
1340 # trap("SIGTERM", "DEFAULT")
1341 # trap("SIGHUP", "DEFAULT")
1343 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1345 debug "\tdisconnecting..."
1347 debug "\tstopping timer..."
1349 debug "\tsaving ..."
1351 debug "\tcleaning up ..."
1352 @save_mutex.synchronize do
1356 debug "\tignoring cleanup error: #{$!}"
1359 # debug "\tstopping timers ..."
1361 # debug "Closing registries"
1363 log "rbot quit (#{message})"
1367 # message:: optional IRC quit message
1368 # quit IRC, shutdown the bot
1369 def quit(message=nil)
1377 # totally shutdown and respawn the bot
1378 def restart(message=nil)
1379 message = _("restarting, back in %{wait}...") % {
1380 :wait => @config['server.reconnect_wait']
1381 } if (!message || message.empty?)
1383 sleep @config['server.reconnect_wait']
1386 # Note, this fails on Windows
1387 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1391 rescue Errno::ENOENT
1393 exec("ruby", *(@argv.unshift $0))
1394 rescue Exception => e
1400 # call the save method for all or the specified botmodule
1403 # optional botmodule to save
1404 def save(botmodule=nil)
1405 @save_mutex.synchronize do
1406 @plugins.save(botmodule)
1410 # call the rescan method for all or just the specified botmodule
1413 # instance of the botmodule to rescan
1414 def rescan(botmodule=nil)
1415 debug "\tstopping timer..."
1417 @save_mutex.synchronize do
1419 @plugins.rescan(botmodule)
1424 # channel:: channel to join
1425 # key:: optional channel key if channel is +s
1427 def join(channel, key=nil)
1429 sendq "JOIN #{channel} :#{key}", channel, 2
1431 sendq "JOIN #{channel}", channel, 2
1436 def part(channel, message="")
1437 sendq "PART #{channel} :#{message}", channel, 2
1440 # attempt to change bot's nick to +name+
1442 sendq "NICK #{name}"
1446 def mode(channel, mode, target=nil)
1447 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1451 def whois(nick, target=nil)
1452 sendq "WHOIS #{target} #{nick}", nil, 0
1456 def kick(channel, user, msg)
1457 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1460 # m:: message asking for help
1461 # topic:: optional topic help is requested for
1462 # respond to online help requests
1464 topic = nil if topic == ""
1467 helpstr = _("help topics: ")
1468 helpstr += @plugins.helptopics
1469 helpstr += _(" (help <topic> for more info)")
1471 unless(helpstr = @plugins.help(topic))
1472 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1478 # returns a string describing the current status of the bot (uptime etc)
1480 secs_up = Time.new - @startup_time
1481 uptime = Utils.secs_to_string secs_up
1482 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1483 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1485 :up => uptime, :plug => @plugins.length,
1486 :sent => @socket.lines_sent, :recv => @socket.lines_received
1490 # We want to respond to a hung server in a timely manner. If nothing was received
1491 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1492 # the server. If the PONG is not received within the user-defined timeout, we
1493 # assume we're in ping timeout and act accordingly.
1495 act_timeout = @config['server.ping_timeout']
1496 return if act_timeout <= 0
1498 if @last_rec && now > @last_rec + act_timeout
1500 # No previous PING pending, send a new one
1502 @last_ping = Time.now
1504 diff = now - @last_ping
1505 if diff > act_timeout
1506 debug "no PONG from server in #{diff} seconds, reconnecting"
1507 # the actual reconnect is handled in the main loop:
1508 raise TimeoutError, "no PONG from server in #{diff} seconds"
1514 def stop_server_pings
1515 # cancel previous PINGs and reset time of last RECV
1522 # delegate sent messages
1523 def delegate_sent(type, where, message)
1524 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1527 m = NoticeMessage.new(*args)
1529 m = PrivMessage.new(*args)
1531 m = QuitMessage.new(*args)
1532 m.was_on = myself.channels
1534 @plugins.delegate('sent', m)