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
204 attr_accessor :webservice
206 # server we are connected to
212 # bot User in the client/server connection
218 # bot nick in the client/server connection
223 # bot channels in the client/server connection
228 # nick wanted by the bot. This defaults to the irc.nick config value,
229 # but may be overridden by a manual !nick command
231 @wanted_nick || config['irc.nick']
234 # set the nick wanted by the bot
236 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
239 @wanted_nick = wn.to_s.dup
247 ret = self.to_s[0..-2]
248 ret << ' version=' << $version.inspect
249 ret << ' botclass=' << botclass.inspect
250 ret << ' lang="' << lang.language
255 ret << ' nick=' << nick.inspect
258 ret << (server.to_s + (socket ?
259 ' [' << socket.server_uri.to_s << ']' : '')).inspect
260 unless server.channels.empty?
262 ret << server.channels.map { |c|
263 "%s%s" % [c.modes_of(nick).map { |m|
264 server.prefix_for_mode(m)
271 ret << ' plugins=' << plugins.inspect
276 # create a new Bot with botclass +botclass+
277 def initialize(botclass, params = {})
278 # Config for the core bot
279 # TODO should we split socket stuff into ircsocket, etc?
280 Config.register Config::ArrayValue.new('server.list',
281 :default => ['irc://localhost'], :wizard => true,
282 :requires_restart => true,
283 :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.")
284 Config.register Config::BooleanValue.new('server.ssl',
285 :default => false, :requires_restart => true, :wizard => true,
286 :desc => "Use SSL to connect to this server?")
287 Config.register Config::BooleanValue.new('server.ssl_verify',
288 :default => false, :requires_restart => true,
289 :desc => "Verify the SSL connection?",
291 Config.register Config::StringValue.new('server.ssl_ca_file',
292 :default => default_ssl_ca_file, :requires_restart => true,
293 :desc => "The CA file used to verify the SSL connection.",
295 Config.register Config::StringValue.new('server.ssl_ca_path',
296 :default => default_ssl_ca_path, :requires_restart => true,
297 :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
299 Config.register Config::StringValue.new('server.password',
300 :default => false, :requires_restart => true,
301 :desc => "Password for connecting to this server (if required)",
303 Config.register Config::StringValue.new('server.bindhost',
304 :default => false, :requires_restart => true,
305 :desc => "Specific local host or IP for the bot to bind to (if required)",
307 Config.register Config::IntegerValue.new('server.reconnect_wait',
308 :default => 5, :validate => Proc.new{|v| v >= 0},
309 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
310 Config.register Config::IntegerValue.new('server.ping_timeout',
311 :default => 30, :validate => Proc.new{|v| v >= 0},
312 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
313 Config.register Config::ArrayValue.new('server.nocolor_modes',
314 :default => ['c'], :wizard => false,
315 :requires_restart => false,
316 :desc => "List of channel modes that require messages to be without colors")
318 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
319 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
320 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
321 Config.register Config::StringValue.new('irc.name',
322 :default => "Ruby bot", :requires_restart => true,
323 :desc => "IRC realname the bot should use")
324 Config.register Config::BooleanValue.new('irc.name_copyright',
325 :default => true, :requires_restart => true,
326 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
327 Config.register Config::StringValue.new('irc.user', :default => "rbot",
328 :requires_restart => true,
329 :desc => "local user the bot should appear to be", :wizard => true)
330 Config.register Config::ArrayValue.new('irc.join_channels',
331 :default => [], :wizard => true,
332 :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'")
333 Config.register Config::ArrayValue.new('irc.ignore_users',
335 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
336 Config.register Config::ArrayValue.new('irc.ignore_channels',
338 :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)")
340 Config.register Config::IntegerValue.new('core.save_every',
341 :default => 60, :validate => Proc.new{|v| v >= 0},
342 :on_change => Proc.new { |bot, v|
345 @timer.reschedule(@save_timer, v)
346 @timer.unblock(@save_timer)
348 @timer.block(@save_timer)
352 @save_timer = @timer.add(v) { bot.save }
354 # Nothing to do when v == 0
357 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
359 Config.register Config::BooleanValue.new('core.run_as_daemon',
360 :default => false, :requires_restart => true,
361 :desc => "Should the bot run as a daemon?")
363 Config.register Config::StringValue.new('log.file',
364 :default => false, :requires_restart => true,
365 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
366 Config.register Config::IntegerValue.new('log.level',
367 :default => 1, :requires_restart => false,
368 :validate => Proc.new { |v| (0..5).include?(v) },
369 :on_change => Proc.new { |bot, v|
372 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
373 Config.register Config::IntegerValue.new('log.keep',
374 :default => 1, :requires_restart => true,
375 :validate => Proc.new { |v| v >= 0 },
376 :desc => "How many old console messages logfiles to keep")
377 Config.register Config::IntegerValue.new('log.max_size',
378 :default => 10, :requires_restart => true,
379 :validate => Proc.new { |v| v > 0 },
380 :desc => "Maximum console messages logfile size (in megabytes)")
382 Config.register Config::ArrayValue.new('plugins.path',
383 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
384 :requires_restart => false,
385 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
386 :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")
388 Config.register Config::EnumValue.new('send.newlines',
389 :values => ['split', 'join'], :default => 'split',
390 :on_change => Proc.new { |bot, v|
391 bot.set_default_send_options :newlines => v.to_sym
393 :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")
394 Config.register Config::StringValue.new('send.join_with',
396 :on_change => Proc.new { |bot, v|
397 bot.set_default_send_options :join_with => v.dup
399 :desc => "String used to replace newlines when send.newlines is set to join")
400 Config.register Config::IntegerValue.new('send.max_lines',
402 :validate => Proc.new { |v| v >= 0 },
403 :on_change => Proc.new { |bot, v|
404 bot.set_default_send_options :max_lines => v
406 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
407 Config.register Config::EnumValue.new('send.overlong',
408 :values => ['split', 'truncate'], :default => 'split',
409 :on_change => Proc.new { |bot, v|
410 bot.set_default_send_options :overlong => v.to_sym
412 :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")
413 Config.register Config::StringValue.new('send.split_at',
415 :on_change => Proc.new { |bot, v|
416 bot.set_default_send_options :split_at => Regexp.new(v)
418 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
419 Config.register Config::BooleanValue.new('send.purge_split',
421 :on_change => Proc.new { |bot, v|
422 bot.set_default_send_options :purge_split => v
424 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
425 Config.register Config::StringValue.new('send.truncate_text',
426 :default => "#{Reverse}...#{Reverse}",
427 :on_change => Proc.new { |bot, v|
428 bot.set_default_send_options :truncate_text => v.dup
430 :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")
431 Config.register Config::IntegerValue.new('send.penalty_pct',
433 :validate => Proc.new { |v| v >= 0 },
434 :on_change => Proc.new { |bot, v|
435 bot.socket.penalty_pct = v
437 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
438 Config.register Config::StringValue.new('core.db',
439 :default => default_db, :store_default => true,
441 :validate => Proc.new { |v| Registry::formats.include? v },
442 :requires_restart => true,
443 :desc => "DB adaptor to use for storing the plugin data/registries. Options: " + Registry::formats.join(', '))
445 @argv = params[:argv]
446 @run_dir = params[:run_dir] || Dir.pwd
448 unless FileTest.directory? Config::coredir
449 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
453 unless FileTest.directory? Config::datadir
454 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
458 unless botclass and not botclass.empty?
459 # We want to find a sensible default.
460 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
461 # * On Windows (at least the NT versions) we want to put our stuff in the
462 # Application Data folder.
463 # We don't use any particular O/S detection magic, exploiting the fact that
464 # Etc.getpwuid is nil on Windows
465 if Etc.getpwuid(Process::Sys.geteuid)
466 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
468 if ENV.has_key?('APPDATA')
469 botclass = ENV['APPDATA'].dup
470 botclass.gsub!("\\","/")
473 botclass = File.join(botclass, ".rbot")
475 botclass = File.expand_path(botclass)
476 @botclass = botclass.gsub(/\/$/, "")
478 repopulate_botclass_directory
480 save_dir = File.join(@botclass, 'safe_save')
481 Dir.mkdir(save_dir) unless File.exist?(save_dir)
482 unless FileTest.directory? save_dir
483 error "safe save location #{save_dir} is not a directory"
487 # Time at which the last PING was sent
489 # Time at which the last line was RECV'd from the server
492 @startup_time = Time.new
495 @config = Config.manager
496 @config.bot_associate(self)
497 rescue Exception => e
503 if @config['core.run_as_daemon']
507 @registry_factory = Registry.new @config['core.db']
508 @registry_factory.migrate_registry_folder(path)
510 @logfile = @config['log.file']
511 if @logfile.class!=String || @logfile.empty?
512 logfname = File.basename(botclass).gsub(/^\.+/,'')
514 @logfile = File.join(botclass, logfname)
515 debug "Using `#{@logfile}' as debug log"
518 # See http://blog.humlab.umu.se/samuel/archives/000107.html
519 # for the backgrounding code
525 rescue NotImplementedError
526 warning "Could not background, fork not supported"
529 rescue Exception => e
530 warning "Could not background. #{e.pretty_inspect}"
533 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
536 logger = Logger.new(@logfile,
538 @config['log.max_size']*1024*1024)
539 logger.datetime_format= $dateformat
540 logger.level = @config['log.level']
541 logger.level = $cl_loglevel if defined? $cl_loglevel
542 logger.level = 0 if $debug
544 restart_logger(logger)
549 log "Redirecting standard input/output/error"
550 [$stdin, $stdout, $stderr].each do |fd|
552 fd.reopen "/dev/null"
554 # On Windows, there's not such thing as /dev/null
559 def $stdout.write(str=nil)
563 def $stdout.write(str=nil)
564 if str.to_s.match(/:\d+: warning:/)
573 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
578 @save_mutex = Mutex.new
579 if @config['core.save_every'] > 0
580 @save_timer = @timer.add(@config['core.save_every']) { save }
584 @quit_mutex = Mutex.new
587 @lang = Language.new(self, @config['core.language'])
590 @auth = Auth::manager
591 @auth.bot_associate(self)
592 # @auth.load("#{botclass}/botusers.yaml")
593 rescue Exception => e
598 @auth.everyone.set_default_permission("*", true)
599 @auth.botowner.password= @config['auth.password']
601 @plugins = Plugins::manager
602 @plugins.bot_associate(self)
605 if @config['server.name']
606 debug "upgrading configuration (server.name => server.list)"
607 srv_uri = 'irc://' + @config['server.name']
608 srv_uri += ":#{@config['server.port']}" if @config['server.port']
609 @config.items['server.list'.to_sym].set_string(srv_uri)
610 @config.delete('server.name'.to_sym)
611 @config.delete('server.port'.to_sym)
612 debug "server.list is now #{@config['server.list'].inspect}"
615 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'],
616 :ssl => @config['server.ssl'],
617 :ssl_verify => @config['server.ssl_verify'],
618 :ssl_ca_file => @config['server.ssl_ca_file'],
619 :ssl_ca_path => @config['server.ssl_ca_path'],
620 :penalty_pct => @config['send.penalty_pct'])
625 # Channels where we are quiet
626 # Array of channels names where the bot should be quiet
627 # '*' means all channels
630 # but we always speak here
633 # the nick we want, if it's different from the irc.nick config value
634 # (e.g. as set by a !nick command)
637 @client[:welcome] = proc {|data|
638 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
640 @plugins.delegate("welcome", m)
641 @plugins.delegate("connect")
644 # TODO the next two @client should go into rfc2812.rb, probably
645 # Since capabs are two-steps processes, server.supports[:capab]
646 # should be a three-state: nil, [], [....]
647 asked_for = { :"identify-msg" => false }
648 @client[:isupport] = proc { |data|
649 if server.supports[:capab] and !asked_for[:"identify-msg"]
650 sendq "CAPAB IDENTIFY-MSG"
651 asked_for[:"identify-msg"] = true
654 @client[:datastr] = proc { |data|
655 if data[:text] == "IDENTIFY-MSG"
656 server.capabilities[:"identify-msg"] = true
658 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
662 @client[:privmsg] = proc { |data|
663 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
664 # debug "Message source is #{data[:source].inspect}"
665 # debug "Message target is #{data[:target].inspect}"
666 # debug "Bot is #{myself.inspect}"
668 @config['irc.ignore_channels'].each { |channel|
669 if m.target.downcase == channel.downcase
674 @config['irc.ignore_users'].each { |mask|
675 if m.source.matches?(server.new_netmask(mask))
681 @plugins.irc_delegate('privmsg', m)
683 @client[:notice] = proc { |data|
684 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
685 # pass it off to plugins that want to hear everything
686 @plugins.irc_delegate "notice", message
688 @client[:motd] = proc { |data|
689 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
690 @plugins.delegate "motd", m
692 @client[:nicktaken] = proc { |data|
693 new = "#{data[:nick]}_"
695 # If we're setting our nick at connection because our choice was taken,
696 # we have to fix our nick manually, because there will be no NICK message
697 # to inform us that our nick has been changed.
698 if data[:target] == '*'
699 debug "setting my connection nick to #{new}"
702 @plugins.delegate "nicktaken", data[:nick]
704 @client[:badnick] = proc {|data|
705 warning "bad nick (#{data[:nick]})"
707 @client[:ping] = proc {|data|
708 sendq "PONG #{data[:pingid]}"
710 @client[:pong] = proc {|data|
713 @client[:nick] = proc {|data|
714 # debug "Message source is #{data[:source].inspect}"
715 # debug "Bot is #{myself.inspect}"
716 source = data[:source]
719 m = NickMessage.new(self, server, source, old, new)
720 m.is_on = data[:is_on]
722 debug "my nick is now #{new}"
724 @plugins.irc_delegate("nick", m)
726 @client[:quit] = proc {|data|
727 source = data[:source]
728 message = data[:message]
729 m = QuitMessage.new(self, server, source, source, message)
730 m.was_on = data[:was_on]
731 @plugins.irc_delegate("quit", m)
733 @client[:mode] = proc {|data|
734 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
735 m.modes = data[:modes]
736 @plugins.delegate "modechange", m
738 @client[:whois] = proc {|data|
739 source = data[:source]
740 target = server.get_user(data[:whois][:nick])
741 m = WhoisMessage.new(self, server, source, target, data[:whois])
742 @plugins.delegate "whois", m
744 @client[:list] = proc {|data|
745 source = data[:source]
746 m = ListMessage.new(self, server, source, source, data[:list])
747 @plugins.delegate "irclist", m
749 @client[:join] = proc {|data|
750 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
751 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
752 @plugins.irc_delegate("join", m)
753 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
755 @client[:part] = proc {|data|
756 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
757 @plugins.irc_delegate("part", m)
759 @client[:kick] = proc {|data|
760 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
761 @plugins.irc_delegate("kick", m)
763 @client[:invite] = proc {|data|
764 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
765 @plugins.irc_delegate("invite", m)
767 @client[:changetopic] = proc {|data|
768 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
770 @plugins.irc_delegate("topic", m)
772 # @client[:topic] = proc { |data|
773 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
775 @client[:topicinfo] = proc { |data|
776 channel = data[:channel]
777 topic = channel.topic
778 m = TopicMessage.new(self, server, data[:source], channel, topic)
779 m.info_or_set = :info
780 @plugins.irc_delegate("topic", m)
782 @client[:names] = proc { |data|
783 m = NamesMessage.new(self, server, server, data[:channel])
784 m.users = data[:users]
785 @plugins.delegate "names", m
787 @client[:banlist] = proc { |data|
788 m = BanlistMessage.new(self, server, server, data[:channel])
790 @plugins.delegate "banlist", m
792 @client[:nosuchtarget] = proc { |data|
793 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
794 @plugins.delegate "nosuchtarget", m
796 @client[:error] = proc { |data|
797 raise ServerError, data[:message]
799 @client[:unknown] = proc { |data|
800 #debug "UNKNOWN: #{data[:serverstring]}"
801 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
802 @plugins.delegate "unknown_message", m
805 set_default_send_options :newlines => @config['send.newlines'].to_sym,
806 :join_with => @config['send.join_with'].dup,
807 :max_lines => @config['send.max_lines'],
808 :overlong => @config['send.overlong'].to_sym,
809 :split_at => Regexp.new(@config['send.split_at']),
810 :purge_split => @config['send.purge_split'],
811 :truncate_text => @config['send.truncate_text'].dup
816 # Determine (if possible) a valid path to a CA certificate bundle.
817 def default_ssl_ca_file
818 [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
819 '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
820 '/etc/ssl/ca-bundle.pem', # OpenSUSE
821 '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
827 def default_ssl_ca_path
828 file = default_ssl_ca_file
829 File.dirname file if file
832 # Determine if tokyocabinet is installed, if it is use it as a default.
835 require 'tokyocabinet'
842 def repopulate_botclass_directory
843 template_dir = File.join Config::datadir, 'templates'
844 if FileTest.directory? @botclass
845 # compare the templates dir with the current botclass dir, filling up the
846 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
847 # :update option, so we have to do it manually.
848 # Note that we use the */** pattern because we don't want to match
849 # keywords.rbot, which gets deleted on load and would therefore be missing
851 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
853 dest = File.join(@botclass, f)
854 FileUtils.mkdir_p(File.dirname(dest))
855 FileUtils.cp File.join(template_dir, f), dest
858 log "no #{@botclass} directory found, creating from templates..."
859 if FileTest.exist? @botclass
860 error "file #{@botclass} exists but isn't a directory"
863 FileUtils.cp_r template_dir, @botclass
867 # Return a path under the current botclass by joining the mentioned
868 # components. The components are automatically converted to String
869 def path(*components)
870 File.join(@botclass, *(components.map {|c| c.to_s}))
873 def setup_plugins_path
874 plugdir_default = File.join(Config::datadir, 'plugins')
875 plugdir_local = File.join(@botclass, 'plugins')
876 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
878 @plugins.clear_botmodule_dirs
879 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
880 @plugins.add_core_module_dir(Config::coredir)
881 if FileTest.directory? plugdir_local
882 @plugins.add_plugin_dir(plugdir_local)
884 warning "local plugin location #{plugdir_local} is not a directory"
887 @config['plugins.path'].each do |_|
888 path = _.sub(/^\(default\)/, plugdir_default)
889 @plugins.add_plugin_dir(path)
893 def set_default_send_options(opts={})
894 # Default send options for NOTICE and PRIVMSG
895 unless defined? @default_send_options
896 @default_send_options = {
897 :queue_channel => nil, # use default queue channel
898 :queue_ring => nil, # use default queue ring
899 :newlines => :split, # or :join
900 :join_with => ' ', # by default, use a single space
901 :max_lines => 0, # maximum number of lines to send with a single command
902 :overlong => :split, # or :truncate
903 # TODO an array of splitpoints would be preferrable for this option:
904 :split_at => /\s+/, # by default, split overlong lines at whitespace
905 :purge_split => true, # should the split string be removed?
906 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
909 @default_send_options.update opts unless opts.empty?
912 # checks if we should be quiet on a channel
913 def quiet_on?(channel)
914 ch = channel.downcase
915 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
918 def set_quiet(channel = nil)
920 ch = channel.downcase.dup
921 @not_quiet.delete(ch)
930 def reset_quiet(channel = nil)
932 ch = channel.downcase.dup
941 # things to do when we receive a signal
942 def handle_signal(sig)
951 debug "received #{sig}, queueing #{func}"
952 # this is not an interruption if we just need to reconnect
953 $interrupted += 1 unless func == :reconnect
954 self.send(func) unless @quit_mutex.locked?
955 debug "interrupted #{$interrupted} times"
966 %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
967 trap(sig) { Thread.new { handle_signal sig } }
969 rescue ArgumentError => e
970 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
971 rescue Exception => e
972 debug "failed to trap signals: #{e.pretty_inspect}"
976 # connect the bot to IRC
978 # make sure we don't have any spurious ping checks running
979 # (and initialize the vars if this is the first time we connect)
982 quit if $interrupted > 0
985 rescue Exception => e
986 uri = @socket.server_uri || '<unknown>'
987 error "failed to connect to IRC server at #{uri}"
991 quit if $interrupted > 0
993 realname = @config['irc.name'].clone || 'Ruby bot'
994 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
996 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
997 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
998 quit if $interrupted > 0
999 myself.nick = @config['irc.nick']
1000 myself.user = @config['irc.user']
1003 # disconnect the bot from IRC, if connected, and then connect (again)
1004 def reconnect(message=nil, too_fast=0)
1005 # we will wait only if @last_rec was not nil, i.e. if we were connected or
1006 # got disconnected by a network error
1007 # if someone wants to manually call disconnect() _and_ reconnect(), they
1008 # will have to take care of the waiting themselves
1009 will_wait = !!@last_rec
1011 if @socket.connected?
1017 log "\n\nDisconnected\n\n"
1019 quit if $interrupted > 0
1021 log "\n\nWaiting to reconnect\n\n"
1022 sleep @config['server.reconnect_wait']
1024 tf = too_fast*@config['server.reconnect_wait']
1025 tfu = Utils.secs_to_string(tf)
1026 log "Will sleep for an extra #{tf}s (#{tfu})"
1035 rescue Exception => e
1042 # begin event handling loop
1047 valid_recv = false # did we receive anything (valid) from the server yet?
1049 reconnect(quit_msg, too_fast)
1050 quit if $interrupted > 0
1052 while @socket.connected?
1053 quit if $interrupted > 0
1055 # Wait for messages and process them as they arrive. If nothing is
1056 # received, we call the ping_server() method that will PING the
1057 # server if appropriate, or raise a TimeoutError if no PONG has been
1058 # received in the user-chosen timeout since the last PING sent.
1059 if @socket.select(1)
1060 break unless reply = @socket.gets
1061 @last_rec = Time.now
1062 @client.process reply
1070 # I despair of this. Some of my users get "connection reset by peer"
1071 # exceptions that ARENT SocketError's. How am I supposed to handle
1076 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1077 error "network exception: #{e.pretty_inspect}"
1079 too_fast += 10 if valid_recv
1080 rescue ServerMessageParseError => e
1081 # if the bot tried reconnecting too often, we can get forcefully
1082 # disconnected by the server, while still receiving an empty message
1083 # wait at least 10 minutes in this case
1086 too_fast = [too_fast, 300].max
1088 log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1090 quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1092 rescue ServerError => e
1093 quit_msg = "server ERROR: " + e.message
1095 idx = e.message.index("connect too fast")
1096 debug "'connect too fast' @ #{idx}"
1099 too_fast += (idx+1)*2
1100 log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1102 idx = e.message.index(/a(uto)kill/i)
1103 debug "'autokill' @ #{idx}"
1105 # we got auto-killed. since we don't have an easy way to tell
1106 # if it's permanent or temporary, we just set a rather high
1107 # reconnection timeout
1109 too_fast += (idx+1)*5
1110 log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1113 rescue Exception => e
1114 error "non-net exception: #{e.pretty_inspect}"
1117 fatal "unexpected exception: #{e.pretty_inspect}"
1124 # type:: message type
1125 # where:: message target
1126 # message:: message text
1127 # send message +message+ of type +type+ to target +where+
1128 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1129 # relevant say() or notice() methods. This one should be used for IRCd
1130 # extensions you want to use in modules.
1131 def sendmsg(original_type, original_where, original_message, options={})
1133 # filter message with sendmsg filters
1134 ds = DataStream.new original_message.to_s.dup,
1135 :type => original_type, :dest => original_where,
1136 :options => @default_send_options.merge(options)
1137 filters = filter_names(:sendmsg)
1138 filters.each do |fname|
1139 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1140 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1146 filtered = ds[:text]
1148 if defined? WebServiceUser and where.instance_of? WebServiceUser
1149 debug 'sendmsg to web service!'
1150 where.response << filtered
1154 # For starters, set up appropriate queue channels and rings
1155 mchan = opts[:queue_channel]
1156 mring = opts[:queue_ring]
1173 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1175 # if target is a channel with nocolor modes, strip colours
1176 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1177 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1180 messages = Array.new
1181 case opts[:newlines]
1183 messages << [multi_line.gsub("\n", opts[:join_with])]
1185 multi_line.each_line { |line|
1187 next unless(line.size > 0)
1191 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1194 # The IRC protocol requires that each raw message must be not longer
1195 # than 512 characters. From this length with have to subtract the EOL
1196 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1197 # that will be prepended by the server to all of our messages.
1199 # The maximum raw message length we can send is therefore 512 - 2 - 2
1200 # minus the length of our hostmask.
1202 max_len = 508 - myself.fullform.size
1204 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1205 # will have a + or - prepended
1206 if server.capabilities[:"identify-msg"]
1210 # When splitting the message, we'll be prefixing the following string:
1211 # (e.g. "PRIVMSG #rbot :")
1212 fixed = "#{type} #{where} :"
1214 # And this is what's left
1215 left = max_len - fixed.size
1217 truncate = opts[:truncate_text]
1218 truncate = @default_send_options[:truncate_text] if truncate.size > left
1219 truncate = "" if truncate.size > left
1221 all_lines = messages.map { |line|
1225 case opts[:overlong]
1228 sub_lines = Array.new
1230 sub_lines << msg.slice!(0, left)
1232 lastspace = sub_lines.last.rindex(opts[:split_at])
1234 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1235 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1237 end until msg.empty?
1240 line.slice(0, left - truncate.size) << truncate
1242 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1247 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1248 lines = all_lines[0...opts[:max_lines]]
1249 new_last = lines.last.slice(0, left - truncate.size) << truncate
1250 lines.last.replace(new_last)
1256 sendq "#{fixed}#{line}", chan, ring
1257 delegate_sent(type, where, line)
1261 # queue an arbitraty message for the server
1262 def sendq(message="", chan=nil, ring=0)
1264 @socket.queue(message, chan, ring)
1267 # send a notice message to channel/nick +where+
1268 def notice(where, message, options={})
1269 return if where.kind_of?(Channel) and quiet_on?(where)
1270 sendmsg "NOTICE", where, message, options
1273 # say something (PRIVMSG) to channel/nick +where+
1274 def say(where, message, options={})
1275 return if where.kind_of?(Channel) and quiet_on?(where)
1276 sendmsg "PRIVMSG", where, message, options
1279 def ctcp_notice(where, command, message, options={})
1280 return if where.kind_of?(Channel) and quiet_on?(where)
1281 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1284 def ctcp_say(where, command, message, options={})
1285 return if where.kind_of?(Channel) and quiet_on?(where)
1286 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1289 # perform a CTCP action with message +message+ to channel/nick +where+
1290 def action(where, message, options={})
1291 ctcp_say(where, 'ACTION', message, options)
1294 # quick way to say "okay" (or equivalent) to +where+
1296 say where, @lang.get("okay")
1299 # set topic of channel +where+ to +topic+
1300 # can also be used to retrieve the topic of channel +where+
1301 # by omitting the last argument
1302 def topic(where, topic=nil)
1304 sendq "TOPIC #{where}", where, 2
1306 sendq "TOPIC #{where} :#{topic}", where, 2
1310 def disconnect(message=nil)
1311 message = @lang.get("quit") if (!message || message.empty?)
1312 if @socket.connected?
1314 debug "Clearing socket"
1316 debug "Sending quit message"
1317 @socket.emergency_puts "QUIT :#{message}"
1318 debug "Logging quits"
1319 delegate_sent('QUIT', myself, message)
1320 debug "Flushing socket"
1322 rescue SocketError => e
1323 error "error while disconnecting socket: #{e.pretty_inspect}"
1325 debug "Shutting down socket"
1332 # disconnect from the server and cleanup all plugins and modules
1333 def shutdown(message=nil)
1334 @quit_mutex.synchronize do
1335 debug "Shutting down: #{message}"
1336 ## No we don't restore them ... let everything run through
1338 # trap("SIGINT", "DEFAULT")
1339 # trap("SIGTERM", "DEFAULT")
1340 # trap("SIGHUP", "DEFAULT")
1342 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1344 debug "\tdisconnecting..."
1346 debug "\tstopping timer..."
1348 debug "\tsaving ..."
1350 debug "\tcleaning up ..."
1351 @save_mutex.synchronize do
1355 debug "\tignoring cleanup error: #{$!}"
1358 # debug "\tstopping timers ..."
1360 # debug "Closing registries"
1362 log "rbot quit (#{message})"
1366 # message:: optional IRC quit message
1367 # quit IRC, shutdown the bot
1368 def quit(message=nil)
1376 # totally shutdown and respawn the bot
1377 def restart(message=nil)
1378 message = _("restarting, back in %{wait}...") % {
1379 :wait => @config['server.reconnect_wait']
1380 } if (!message || message.empty?)
1382 sleep @config['server.reconnect_wait']
1385 # Note, this fails on Windows
1386 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1390 rescue Errno::ENOENT
1392 exec("ruby", *(@argv.unshift $0))
1393 rescue Exception => e
1399 # call the save method for all or the specified botmodule
1402 # optional botmodule to save
1403 def save(botmodule=nil)
1404 @save_mutex.synchronize do
1405 @plugins.save(botmodule)
1409 # call the rescan method for all or just the specified botmodule
1412 # instance of the botmodule to rescan
1413 def rescan(botmodule=nil)
1414 debug "\tstopping timer..."
1416 @save_mutex.synchronize do
1418 @plugins.rescan(botmodule)
1423 # channel:: channel to join
1424 # key:: optional channel key if channel is +s
1426 def join(channel, key=nil)
1428 sendq "JOIN #{channel} :#{key}", channel, 2
1430 sendq "JOIN #{channel}", channel, 2
1435 def part(channel, message="")
1436 sendq "PART #{channel} :#{message}", channel, 2
1439 # attempt to change bot's nick to +name+
1441 sendq "NICK #{name}"
1445 def mode(channel, mode, target=nil)
1446 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1450 def whois(nick, target=nil)
1451 sendq "WHOIS #{target} #{nick}", nil, 0
1455 def kick(channel, user, msg)
1456 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1459 # m:: message asking for help
1460 # topic:: optional topic help is requested for
1461 # respond to online help requests
1463 topic = nil if topic == ""
1466 helpstr = _("help topics: ")
1467 helpstr += @plugins.helptopics
1468 helpstr += _(" (help <topic> for more info)")
1470 unless(helpstr = @plugins.help(topic))
1471 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1477 # returns a string describing the current status of the bot (uptime etc)
1479 secs_up = Time.new - @startup_time
1480 uptime = Utils.secs_to_string secs_up
1481 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1482 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1484 :up => uptime, :plug => @plugins.length,
1485 :sent => @socket.lines_sent, :recv => @socket.lines_received
1489 # We want to respond to a hung server in a timely manner. If nothing was received
1490 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1491 # the server. If the PONG is not received within the user-defined timeout, we
1492 # assume we're in ping timeout and act accordingly.
1494 act_timeout = @config['server.ping_timeout']
1495 return if act_timeout <= 0
1497 if @last_rec && now > @last_rec + act_timeout
1499 # No previous PING pending, send a new one
1501 @last_ping = Time.now
1503 diff = now - @last_ping
1504 if diff > act_timeout
1505 debug "no PONG from server in #{diff} seconds, reconnecting"
1506 # the actual reconnect is handled in the main loop:
1507 raise TimeoutError, "no PONG from server in #{diff} seconds"
1513 def stop_server_pings
1514 # cancel previous PINGs and reset time of last RECV
1521 # delegate sent messages
1522 def delegate_sent(type, where, message)
1523 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1526 m = NoticeMessage.new(*args)
1528 m = PrivMessage.new(*args)
1530 m = QuitMessage.new(*args)
1531 m.was_on = myself.channels
1533 @plugins.delegate('sent', m)