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 # returns the journal
231 if @plugins['journal']
232 @plugins['journal'].broker
236 # nick wanted by the bot. This defaults to the irc.nick config value,
237 # but may be overridden by a manual !nick command
239 @wanted_nick || config['irc.nick']
242 # set the nick wanted by the bot
244 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
247 @wanted_nick = wn.to_s.dup
255 ret = self.to_s[0..-2]
256 ret << ' version=' << $version.inspect
257 ret << ' botclass=' << botclass.inspect
258 ret << ' lang="' << lang.language
263 ret << ' nick=' << nick.inspect
266 ret << (server.to_s + (socket ?
267 ' [' << socket.server_uri.to_s << ']' : '')).inspect
268 unless server.channels.empty?
270 ret << server.channels.map { |c|
271 "%s%s" % [c.modes_of(nick).map { |m|
272 server.prefix_for_mode(m)
279 ret << ' plugins=' << plugins.inspect
284 # create a new Bot with botclass +botclass+
285 def initialize(botclass, params = {})
286 # Config for the core bot
287 # TODO should we split socket stuff into ircsocket, etc?
288 Config.register Config::ArrayValue.new('server.list',
289 :default => ['irc://localhost'], :wizard => true,
290 :requires_restart => true,
291 :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.")
292 Config.register Config::BooleanValue.new('server.ssl',
293 :default => false, :requires_restart => true, :wizard => true,
294 :desc => "Use SSL to connect to this server?")
295 Config.register Config::BooleanValue.new('server.ssl_verify',
296 :default => false, :requires_restart => true,
297 :desc => "Verify the SSL connection?",
299 Config.register Config::StringValue.new('server.ssl_ca_file',
300 :default => default_ssl_ca_file, :requires_restart => true,
301 :desc => "The CA file used to verify the SSL connection.",
303 Config.register Config::StringValue.new('server.ssl_ca_path',
304 :default => default_ssl_ca_path, :requires_restart => true,
305 :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
307 Config.register Config::StringValue.new('server.password',
308 :default => false, :requires_restart => true,
309 :desc => "Password for connecting to this server (if required)",
311 Config.register Config::StringValue.new('server.bindhost',
312 :default => false, :requires_restart => true,
313 :desc => "Specific local host or IP for the bot to bind to (if required)",
315 Config.register Config::IntegerValue.new('server.reconnect_wait',
316 :default => 5, :validate => Proc.new{|v| v >= 0},
317 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
318 Config.register Config::IntegerValue.new('server.ping_timeout',
319 :default => 30, :validate => Proc.new{|v| v >= 0},
320 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
321 Config.register Config::ArrayValue.new('server.nocolor_modes',
322 :default => ['c'], :wizard => false,
323 :requires_restart => false,
324 :desc => "List of channel modes that require messages to be without colors")
326 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
327 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
328 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
329 Config.register Config::StringValue.new('irc.name',
330 :default => "Ruby bot", :requires_restart => true,
331 :desc => "IRC realname the bot should use")
332 Config.register Config::BooleanValue.new('irc.name_copyright',
333 :default => true, :requires_restart => true,
334 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
335 Config.register Config::StringValue.new('irc.user', :default => "rbot",
336 :requires_restart => true,
337 :desc => "local user the bot should appear to be", :wizard => true)
338 Config.register Config::ArrayValue.new('irc.join_channels',
339 :default => [], :wizard => true,
340 :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'")
341 Config.register Config::ArrayValue.new('irc.ignore_users',
343 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
344 Config.register Config::ArrayValue.new('irc.ignore_channels',
346 :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)")
348 Config.register Config::IntegerValue.new('core.save_every',
349 :default => 60, :validate => Proc.new{|v| v >= 0},
350 :on_change => Proc.new { |bot, v|
353 @timer.reschedule(@save_timer, v)
354 @timer.unblock(@save_timer)
356 @timer.block(@save_timer)
360 @save_timer = @timer.add(v) { bot.save }
362 # Nothing to do when v == 0
365 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
367 Config.register Config::BooleanValue.new('core.run_as_daemon',
368 :default => false, :requires_restart => true,
369 :desc => "Should the bot run as a daemon?")
371 Config.register Config::StringValue.new('log.file',
372 :default => false, :requires_restart => true,
373 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
374 Config.register Config::IntegerValue.new('log.level',
375 :default => 1, :requires_restart => false,
376 :validate => Proc.new { |v| (0..5).include?(v) },
377 :on_change => Proc.new { |bot, v|
380 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
381 Config.register Config::IntegerValue.new('log.keep',
382 :default => 1, :requires_restart => true,
383 :validate => Proc.new { |v| v >= 0 },
384 :desc => "How many old console messages logfiles to keep")
385 Config.register Config::IntegerValue.new('log.max_size',
386 :default => 10, :requires_restart => true,
387 :validate => Proc.new { |v| v > 0 },
388 :desc => "Maximum console messages logfile size (in megabytes)")
390 Config.register Config::ArrayValue.new('plugins.path',
391 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
392 :requires_restart => false,
393 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
394 :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")
396 Config.register Config::EnumValue.new('send.newlines',
397 :values => ['split', 'join'], :default => 'split',
398 :on_change => Proc.new { |bot, v|
399 bot.set_default_send_options :newlines => v.to_sym
401 :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")
402 Config.register Config::StringValue.new('send.join_with',
404 :on_change => Proc.new { |bot, v|
405 bot.set_default_send_options :join_with => v.dup
407 :desc => "String used to replace newlines when send.newlines is set to join")
408 Config.register Config::IntegerValue.new('send.max_lines',
410 :validate => Proc.new { |v| v >= 0 },
411 :on_change => Proc.new { |bot, v|
412 bot.set_default_send_options :max_lines => v
414 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
415 Config.register Config::EnumValue.new('send.overlong',
416 :values => ['split', 'truncate'], :default => 'split',
417 :on_change => Proc.new { |bot, v|
418 bot.set_default_send_options :overlong => v.to_sym
420 :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")
421 Config.register Config::StringValue.new('send.split_at',
423 :on_change => Proc.new { |bot, v|
424 bot.set_default_send_options :split_at => Regexp.new(v)
426 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
427 Config.register Config::BooleanValue.new('send.purge_split',
429 :on_change => Proc.new { |bot, v|
430 bot.set_default_send_options :purge_split => v
432 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
433 Config.register Config::StringValue.new('send.truncate_text',
434 :default => "#{Reverse}...#{Reverse}",
435 :on_change => Proc.new { |bot, v|
436 bot.set_default_send_options :truncate_text => v.dup
438 :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")
439 Config.register Config::IntegerValue.new('send.penalty_pct',
441 :validate => Proc.new { |v| v >= 0 },
442 :on_change => Proc.new { |bot, v|
443 bot.socket.penalty_pct = v
445 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
446 Config.register Config::StringValue.new('core.db',
447 :default => default_db, :store_default => true,
449 :validate => Proc.new { |v| Registry::formats.include? v },
450 :requires_restart => true,
451 :desc => "DB adaptor to use for storing the plugin data/registries. Options: " + Registry::formats.join(', '))
453 @argv = params[:argv]
454 @run_dir = params[:run_dir] || Dir.pwd
456 unless FileTest.directory? Config::coredir
457 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
461 unless FileTest.directory? Config::datadir
462 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
466 unless botclass and not botclass.empty?
467 # We want to find a sensible default.
468 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
469 # * On Windows (at least the NT versions) we want to put our stuff in the
470 # Application Data folder.
471 # We don't use any particular O/S detection magic, exploiting the fact that
472 # Etc.getpwuid is nil on Windows
473 if Etc.getpwuid(Process::Sys.geteuid)
474 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
476 if ENV.has_key?('APPDATA')
477 botclass = ENV['APPDATA'].dup
478 botclass.gsub!("\\","/")
481 botclass = File.join(botclass, ".rbot")
483 botclass = File.expand_path(botclass)
484 @botclass = botclass.gsub(/\/$/, "")
486 repopulate_botclass_directory
488 save_dir = File.join(@botclass, 'safe_save')
489 Dir.mkdir(save_dir) unless File.exist?(save_dir)
490 unless FileTest.directory? save_dir
491 error "safe save location #{save_dir} is not a directory"
495 # Time at which the last PING was sent
497 # Time at which the last line was RECV'd from the server
500 @startup_time = Time.new
503 @config = Config.manager
504 @config.bot_associate(self)
505 rescue Exception => e
511 if @config['core.run_as_daemon']
515 @registry_factory = Registry.new @config['core.db']
516 @registry_factory.migrate_registry_folder(path)
518 @logfile = @config['log.file']
519 if @logfile.class!=String || @logfile.empty?
520 logfname = File.basename(botclass).gsub(/^\.+/,'')
522 @logfile = File.join(botclass, logfname)
523 debug "Using `#{@logfile}' as debug log"
526 # See http://blog.humlab.umu.se/samuel/archives/000107.html
527 # for the backgrounding code
533 rescue NotImplementedError
534 warning "Could not background, fork not supported"
537 rescue Exception => e
538 warning "Could not background. #{e.pretty_inspect}"
541 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
544 logger = Logger.new(@logfile,
546 @config['log.max_size']*1024*1024)
547 logger.datetime_format= $dateformat
548 logger.level = @config['log.level']
549 logger.level = $cl_loglevel if defined? $cl_loglevel
550 logger.level = 0 if $debug
552 restart_logger(logger)
557 log "Redirecting standard input/output/error"
558 [$stdin, $stdout, $stderr].each do |fd|
560 fd.reopen "/dev/null"
562 # On Windows, there's not such thing as /dev/null
567 def $stdout.write(str=nil)
571 def $stdout.write(str=nil)
572 if str.to_s.match(/:\d+: warning:/)
581 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
586 @save_mutex = Mutex.new
587 if @config['core.save_every'] > 0
588 @save_timer = @timer.add(@config['core.save_every']) { save }
592 @quit_mutex = Mutex.new
595 @lang = Language.new(self, @config['core.language'])
598 @auth = Auth::manager
599 @auth.bot_associate(self)
600 # @auth.load("#{botclass}/botusers.yaml")
601 rescue Exception => e
606 @auth.everyone.set_default_permission("*", true)
607 @auth.botowner.password= @config['auth.password']
609 @plugins = Plugins::manager
610 @plugins.bot_associate(self)
613 if @config['server.name']
614 debug "upgrading configuration (server.name => server.list)"
615 srv_uri = 'irc://' + @config['server.name']
616 srv_uri += ":#{@config['server.port']}" if @config['server.port']
617 @config.items['server.list'.to_sym].set_string(srv_uri)
618 @config.delete('server.name'.to_sym)
619 @config.delete('server.port'.to_sym)
620 debug "server.list is now #{@config['server.list'].inspect}"
623 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'],
624 :ssl => @config['server.ssl'],
625 :ssl_verify => @config['server.ssl_verify'],
626 :ssl_ca_file => @config['server.ssl_ca_file'],
627 :ssl_ca_path => @config['server.ssl_ca_path'],
628 :penalty_pct => @config['send.penalty_pct'])
633 # Channels where we are quiet
634 # Array of channels names where the bot should be quiet
635 # '*' means all channels
638 # but we always speak here
641 # the nick we want, if it's different from the irc.nick config value
642 # (e.g. as set by a !nick command)
645 @client[:welcome] = proc {|data|
646 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
648 @plugins.delegate("welcome", m)
649 @plugins.delegate("connect")
652 # TODO the next two @client should go into rfc2812.rb, probably
653 # Since capabs are two-steps processes, server.supports[:capab]
654 # should be a three-state: nil, [], [....]
655 asked_for = { :"identify-msg" => false }
656 @client[:isupport] = proc { |data|
657 if server.supports[:capab] and !asked_for[:"identify-msg"]
658 sendq "CAPAB IDENTIFY-MSG"
659 asked_for[:"identify-msg"] = true
662 @client[:datastr] = proc { |data|
663 if data[:text] == "IDENTIFY-MSG"
664 server.capabilities[:"identify-msg"] = true
666 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
670 @client[:privmsg] = proc { |data|
671 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
672 # debug "Message source is #{data[:source].inspect}"
673 # debug "Message target is #{data[:target].inspect}"
674 # debug "Bot is #{myself.inspect}"
676 @config['irc.ignore_channels'].each { |channel|
677 if m.target.downcase == channel.downcase
682 @config['irc.ignore_users'].each { |mask|
683 if m.source.matches?(server.new_netmask(mask))
689 @plugins.irc_delegate('privmsg', m)
691 @client[:notice] = proc { |data|
692 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
693 # pass it off to plugins that want to hear everything
694 @plugins.irc_delegate "notice", message
696 @client[:motd] = proc { |data|
697 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
698 @plugins.delegate "motd", m
700 @client[:nicktaken] = proc { |data|
701 new = "#{data[:nick]}_"
703 # If we're setting our nick at connection because our choice was taken,
704 # we have to fix our nick manually, because there will be no NICK message
705 # to inform us that our nick has been changed.
706 if data[:target] == '*'
707 debug "setting my connection nick to #{new}"
710 @plugins.delegate "nicktaken", data[:nick]
712 @client[:badnick] = proc {|data|
713 warning "bad nick (#{data[:nick]})"
715 @client[:ping] = proc {|data|
716 sendq "PONG #{data[:pingid]}"
718 @client[:pong] = proc {|data|
721 @client[:nick] = proc {|data|
722 # debug "Message source is #{data[:source].inspect}"
723 # debug "Bot is #{myself.inspect}"
724 source = data[:source]
727 m = NickMessage.new(self, server, source, old, new)
728 m.is_on = data[:is_on]
730 debug "my nick is now #{new}"
732 @plugins.irc_delegate("nick", m)
734 @client[:quit] = proc {|data|
735 source = data[:source]
736 message = data[:message]
737 m = QuitMessage.new(self, server, source, source, message)
738 m.was_on = data[:was_on]
739 @plugins.irc_delegate("quit", m)
741 @client[:mode] = proc {|data|
742 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
743 m.modes = data[:modes]
744 @plugins.delegate "modechange", m
746 @client[:whois] = proc {|data|
747 source = data[:source]
748 target = server.get_user(data[:whois][:nick])
749 m = WhoisMessage.new(self, server, source, target, data[:whois])
750 @plugins.delegate "whois", m
752 @client[:list] = proc {|data|
753 source = data[:source]
754 m = ListMessage.new(self, server, source, source, data[:list])
755 @plugins.delegate "irclist", m
757 @client[:join] = proc {|data|
758 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
759 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
760 @plugins.irc_delegate("join", m)
761 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
763 @client[:part] = proc {|data|
764 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
765 @plugins.irc_delegate("part", m)
767 @client[:kick] = proc {|data|
768 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
769 @plugins.irc_delegate("kick", m)
771 @client[:invite] = proc {|data|
772 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
773 @plugins.irc_delegate("invite", m)
775 @client[:changetopic] = proc {|data|
776 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
778 @plugins.irc_delegate("topic", m)
780 # @client[:topic] = proc { |data|
781 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
783 @client[:topicinfo] = proc { |data|
784 channel = data[:channel]
785 topic = channel.topic
786 m = TopicMessage.new(self, server, data[:source], channel, topic)
787 m.info_or_set = :info
788 @plugins.irc_delegate("topic", m)
790 @client[:names] = proc { |data|
791 m = NamesMessage.new(self, server, server, data[:channel])
792 m.users = data[:users]
793 @plugins.delegate "names", m
795 @client[:banlist] = proc { |data|
796 m = BanlistMessage.new(self, server, server, data[:channel])
798 @plugins.delegate "banlist", m
800 @client[:nosuchtarget] = proc { |data|
801 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
802 @plugins.delegate "nosuchtarget", m
804 @client[:error] = proc { |data|
805 raise ServerError, data[:message]
807 @client[:unknown] = proc { |data|
808 #debug "UNKNOWN: #{data[:serverstring]}"
809 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
810 @plugins.delegate "unknown_message", m
813 set_default_send_options :newlines => @config['send.newlines'].to_sym,
814 :join_with => @config['send.join_with'].dup,
815 :max_lines => @config['send.max_lines'],
816 :overlong => @config['send.overlong'].to_sym,
817 :split_at => Regexp.new(@config['send.split_at']),
818 :purge_split => @config['send.purge_split'],
819 :truncate_text => @config['send.truncate_text'].dup
824 # Determine (if possible) a valid path to a CA certificate bundle.
825 def default_ssl_ca_file
826 [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
827 '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
828 '/etc/ssl/ca-bundle.pem', # OpenSUSE
829 '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
835 def default_ssl_ca_path
836 file = default_ssl_ca_file
837 File.dirname file if file
840 # Determine if tokyocabinet is installed, if it is use it as a default.
843 require 'tokyocabinet'
850 def repopulate_botclass_directory
851 template_dir = File.join Config::datadir, 'templates'
852 if FileTest.directory? @botclass
853 # compare the templates dir with the current botclass dir, filling up the
854 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
855 # :update option, so we have to do it manually.
856 # Note that we use the */** pattern because we don't want to match
857 # keywords.rbot, which gets deleted on load and would therefore be missing
859 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
861 dest = File.join(@botclass, f)
862 FileUtils.mkdir_p(File.dirname(dest))
863 FileUtils.cp File.join(template_dir, f), dest
866 log "no #{@botclass} directory found, creating from templates..."
867 if FileTest.exist? @botclass
868 error "file #{@botclass} exists but isn't a directory"
871 FileUtils.cp_r template_dir, @botclass
875 # Return a path under the current botclass by joining the mentioned
876 # components. The components are automatically converted to String
877 def path(*components)
878 File.join(@botclass, *(components.map {|c| c.to_s}))
881 def setup_plugins_path
882 plugdir_default = File.join(Config::datadir, 'plugins')
883 plugdir_local = File.join(@botclass, 'plugins')
884 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
886 @plugins.clear_botmodule_dirs
887 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
888 @plugins.add_core_module_dir(Config::coredir)
889 if FileTest.directory? plugdir_local
890 @plugins.add_plugin_dir(plugdir_local)
892 warning "local plugin location #{plugdir_local} is not a directory"
895 @config['plugins.path'].each do |_|
896 path = _.sub(/^\(default\)/, plugdir_default)
897 @plugins.add_plugin_dir(path)
901 def set_default_send_options(opts={})
902 # Default send options for NOTICE and PRIVMSG
903 unless defined? @default_send_options
904 @default_send_options = {
905 :queue_channel => nil, # use default queue channel
906 :queue_ring => nil, # use default queue ring
907 :newlines => :split, # or :join
908 :join_with => ' ', # by default, use a single space
909 :max_lines => 0, # maximum number of lines to send with a single command
910 :overlong => :split, # or :truncate
911 # TODO an array of splitpoints would be preferrable for this option:
912 :split_at => /\s+/, # by default, split overlong lines at whitespace
913 :purge_split => true, # should the split string be removed?
914 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
917 @default_send_options.update opts unless opts.empty?
920 # checks if we should be quiet on a channel
921 def quiet_on?(channel)
922 ch = channel.downcase
923 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
926 def set_quiet(channel = nil)
928 ch = channel.downcase.dup
929 @not_quiet.delete(ch)
938 def reset_quiet(channel = nil)
940 ch = channel.downcase.dup
949 # things to do when we receive a signal
950 def handle_signal(sig)
959 debug "received #{sig}, queueing #{func}"
960 # this is not an interruption if we just need to reconnect
961 $interrupted += 1 unless func == :reconnect
962 self.send(func) unless @quit_mutex.locked?
963 debug "interrupted #{$interrupted} times"
974 %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
975 trap(sig) { Thread.new { handle_signal sig } }
977 rescue ArgumentError => e
978 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
979 rescue Exception => e
980 debug "failed to trap signals: #{e.pretty_inspect}"
984 # connect the bot to IRC
986 # make sure we don't have any spurious ping checks running
987 # (and initialize the vars if this is the first time we connect)
990 quit if $interrupted > 0
993 rescue Exception => e
994 uri = @socket.server_uri || '<unknown>'
995 error "failed to connect to IRC server at #{uri}"
999 quit if $interrupted > 0
1001 realname = @config['irc.name'].clone || 'Ruby bot'
1002 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
1004 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
1005 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
1006 quit if $interrupted > 0
1007 myself.nick = @config['irc.nick']
1008 myself.user = @config['irc.user']
1011 # disconnect the bot from IRC, if connected, and then connect (again)
1012 def reconnect(message=nil, too_fast=0)
1013 # we will wait only if @last_rec was not nil, i.e. if we were connected or
1014 # got disconnected by a network error
1015 # if someone wants to manually call disconnect() _and_ reconnect(), they
1016 # will have to take care of the waiting themselves
1017 will_wait = !!@last_rec
1019 if @socket.connected?
1025 log "\n\nDisconnected\n\n"
1027 quit if $interrupted > 0
1029 log "\n\nWaiting to reconnect\n\n"
1030 sleep @config['server.reconnect_wait']
1032 tf = too_fast*@config['server.reconnect_wait']
1033 tfu = Utils.secs_to_string(tf)
1034 log "Will sleep for an extra #{tf}s (#{tfu})"
1043 rescue Exception => e
1050 # begin event handling loop
1055 valid_recv = false # did we receive anything (valid) from the server yet?
1057 reconnect(quit_msg, too_fast)
1058 quit if $interrupted > 0
1060 while @socket.connected?
1061 quit if $interrupted > 0
1063 # Wait for messages and process them as they arrive. If nothing is
1064 # received, we call the ping_server() method that will PING the
1065 # server if appropriate, or raise a TimeoutError if no PONG has been
1066 # received in the user-chosen timeout since the last PING sent.
1067 if @socket.select(1)
1068 break unless reply = @socket.gets
1069 @last_rec = Time.now
1070 @client.process reply
1078 # I despair of this. Some of my users get "connection reset by peer"
1079 # exceptions that ARENT SocketError's. How am I supposed to handle
1084 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1085 error "network exception: #{e.pretty_inspect}"
1087 too_fast += 10 if valid_recv
1088 rescue ServerMessageParseError => e
1089 # if the bot tried reconnecting too often, we can get forcefully
1090 # disconnected by the server, while still receiving an empty message
1091 # wait at least 10 minutes in this case
1094 too_fast = [too_fast, 300].max
1096 log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1098 quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1100 rescue ServerError => e
1101 quit_msg = "server ERROR: " + e.message
1103 idx = e.message.index("connect too fast")
1104 debug "'connect too fast' @ #{idx}"
1107 too_fast += (idx+1)*2
1108 log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1110 idx = e.message.index(/a(uto)kill/i)
1111 debug "'autokill' @ #{idx}"
1113 # we got auto-killed. since we don't have an easy way to tell
1114 # if it's permanent or temporary, we just set a rather high
1115 # reconnection timeout
1117 too_fast += (idx+1)*5
1118 log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1121 rescue Exception => e
1122 error "non-net exception: #{e.pretty_inspect}"
1125 fatal "unexpected exception: #{e.pretty_inspect}"
1132 # type:: message type
1133 # where:: message target
1134 # message:: message text
1135 # send message +message+ of type +type+ to target +where+
1136 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1137 # relevant say() or notice() methods. This one should be used for IRCd
1138 # extensions you want to use in modules.
1139 def sendmsg(original_type, original_where, original_message, options={})
1141 # filter message with sendmsg filters
1142 ds = DataStream.new original_message.to_s.dup,
1143 :type => original_type, :dest => original_where,
1144 :options => @default_send_options.merge(options)
1145 filters = filter_names(:sendmsg)
1146 filters.each do |fname|
1147 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1148 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1154 filtered = ds[:text]
1156 if defined? WebServiceUser and where.instance_of? WebServiceUser
1157 debug 'sendmsg to web service!'
1158 where.response << filtered
1162 # For starters, set up appropriate queue channels and rings
1163 mchan = opts[:queue_channel]
1164 mring = opts[:queue_ring]
1181 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1183 # if target is a channel with nocolor modes, strip colours
1184 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1185 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1188 messages = Array.new
1189 case opts[:newlines]
1191 messages << [multi_line.gsub("\n", opts[:join_with])]
1193 multi_line.each_line { |line|
1195 next unless(line.size > 0)
1199 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1202 # The IRC protocol requires that each raw message must be not longer
1203 # than 512 characters. From this length with have to subtract the EOL
1204 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1205 # that will be prepended by the server to all of our messages.
1207 # The maximum raw message length we can send is therefore 512 - 2 - 2
1208 # minus the length of our hostmask.
1210 max_len = 508 - myself.fullform.size
1212 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1213 # will have a + or - prepended
1214 if server.capabilities[:"identify-msg"]
1218 # When splitting the message, we'll be prefixing the following string:
1219 # (e.g. "PRIVMSG #rbot :")
1220 fixed = "#{type} #{where} :"
1222 # And this is what's left
1223 left = max_len - fixed.size
1225 truncate = opts[:truncate_text]
1226 truncate = @default_send_options[:truncate_text] if truncate.size > left
1227 truncate = "" if truncate.size > left
1229 all_lines = messages.map { |line|
1233 case opts[:overlong]
1236 sub_lines = Array.new
1238 sub_lines << msg.slice!(0, left)
1240 lastspace = sub_lines.last.rindex(opts[:split_at])
1242 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1243 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1245 end until msg.empty?
1248 line.slice(0, left - truncate.size) << truncate
1250 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1255 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1256 lines = all_lines[0...opts[:max_lines]]
1257 new_last = lines.last.slice(0, left - truncate.size) << truncate
1258 lines.last.replace(new_last)
1264 sendq "#{fixed}#{line}", chan, ring
1265 delegate_sent(type, where, line)
1269 # queue an arbitraty message for the server
1270 def sendq(message="", chan=nil, ring=0)
1272 @socket.queue(message, chan, ring)
1275 # send a notice message to channel/nick +where+
1276 def notice(where, message, options={})
1277 return if where.kind_of?(Channel) and quiet_on?(where)
1278 sendmsg "NOTICE", where, message, options
1281 # say something (PRIVMSG) to channel/nick +where+
1282 def say(where, message, options={})
1283 return if where.kind_of?(Channel) and quiet_on?(where)
1284 sendmsg "PRIVMSG", where, message, options
1287 def ctcp_notice(where, command, message, options={})
1288 return if where.kind_of?(Channel) and quiet_on?(where)
1289 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1292 def ctcp_say(where, command, message, options={})
1293 return if where.kind_of?(Channel) and quiet_on?(where)
1294 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1297 # perform a CTCP action with message +message+ to channel/nick +where+
1298 def action(where, message, options={})
1299 ctcp_say(where, 'ACTION', message, options)
1302 # quick way to say "okay" (or equivalent) to +where+
1304 say where, @lang.get("okay")
1307 # set topic of channel +where+ to +topic+
1308 # can also be used to retrieve the topic of channel +where+
1309 # by omitting the last argument
1310 def topic(where, topic=nil)
1312 sendq "TOPIC #{where}", where, 2
1314 sendq "TOPIC #{where} :#{topic}", where, 2
1318 def disconnect(message=nil)
1319 message = @lang.get("quit") if (!message || message.empty?)
1320 if @socket.connected?
1322 debug "Clearing socket"
1324 debug "Sending quit message"
1325 @socket.emergency_puts "QUIT :#{message}"
1326 debug "Logging quits"
1327 delegate_sent('QUIT', myself, message)
1328 debug "Flushing socket"
1330 rescue SocketError => e
1331 error "error while disconnecting socket: #{e.pretty_inspect}"
1333 debug "Shutting down socket"
1340 # disconnect from the server and cleanup all plugins and modules
1341 def shutdown(message=nil)
1342 @quit_mutex.synchronize do
1343 debug "Shutting down: #{message}"
1344 ## No we don't restore them ... let everything run through
1346 # trap("SIGINT", "DEFAULT")
1347 # trap("SIGTERM", "DEFAULT")
1348 # trap("SIGHUP", "DEFAULT")
1350 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1352 debug "\tdisconnecting..."
1354 debug "\tstopping timer..."
1356 debug "\tsaving ..."
1358 debug "\tcleaning up ..."
1359 @save_mutex.synchronize do
1363 debug "\tignoring cleanup error: #{$!}"
1366 # debug "\tstopping timers ..."
1368 # debug "Closing registries"
1370 log "rbot quit (#{message})"
1374 # message:: optional IRC quit message
1375 # quit IRC, shutdown the bot
1376 def quit(message=nil)
1384 # totally shutdown and respawn the bot
1385 def restart(message=nil)
1386 message = _("restarting, back in %{wait}...") % {
1387 :wait => @config['server.reconnect_wait']
1388 } if (!message || message.empty?)
1390 sleep @config['server.reconnect_wait']
1393 # Note, this fails on Windows
1394 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1398 rescue Errno::ENOENT
1400 exec("ruby", *(@argv.unshift $0))
1401 rescue Exception => e
1407 # call the save method for all or the specified botmodule
1410 # optional botmodule to save
1411 def save(botmodule=nil)
1412 @save_mutex.synchronize do
1413 @plugins.save(botmodule)
1417 # call the rescan method for all or just the specified botmodule
1420 # instance of the botmodule to rescan
1421 def rescan(botmodule=nil)
1422 debug "\tstopping timer..."
1424 @save_mutex.synchronize do
1426 @plugins.rescan(botmodule)
1431 # channel:: channel to join
1432 # key:: optional channel key if channel is +s
1434 def join(channel, key=nil)
1436 sendq "JOIN #{channel} :#{key}", channel, 2
1438 sendq "JOIN #{channel}", channel, 2
1443 def part(channel, message="")
1444 sendq "PART #{channel} :#{message}", channel, 2
1447 # attempt to change bot's nick to +name+
1449 sendq "NICK #{name}"
1453 def mode(channel, mode, target=nil)
1454 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1458 def whois(nick, target=nil)
1459 sendq "WHOIS #{target} #{nick}", nil, 0
1463 def kick(channel, user, msg)
1464 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1467 # m:: message asking for help
1468 # topic:: optional topic help is requested for
1469 # respond to online help requests
1471 topic = nil if topic == ""
1474 helpstr = _("help topics: ")
1475 helpstr += @plugins.helptopics
1476 helpstr += _(" (help <topic> for more info)")
1478 unless(helpstr = @plugins.help(topic))
1479 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1485 # returns a string describing the current status of the bot (uptime etc)
1487 secs_up = Time.new - @startup_time
1488 uptime = Utils.secs_to_string secs_up
1489 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1490 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1492 :up => uptime, :plug => @plugins.length,
1493 :sent => @socket.lines_sent, :recv => @socket.lines_received
1497 # We want to respond to a hung server in a timely manner. If nothing was received
1498 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1499 # the server. If the PONG is not received within the user-defined timeout, we
1500 # assume we're in ping timeout and act accordingly.
1502 act_timeout = @config['server.ping_timeout']
1503 return if act_timeout <= 0
1505 if @last_rec && now > @last_rec + act_timeout
1507 # No previous PING pending, send a new one
1509 @last_ping = Time.now
1511 diff = now - @last_ping
1512 if diff > act_timeout
1513 debug "no PONG from server in #{diff} seconds, reconnecting"
1514 # the actual reconnect is handled in the main loop:
1515 raise TimeoutError, "no PONG from server in #{diff} seconds"
1521 def stop_server_pings
1522 # cancel previous PINGs and reset time of last RECV
1529 # delegate sent messages
1530 def delegate_sent(type, where, message)
1531 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1534 m = NoticeMessage.new(*args)
1536 m = PrivMessage.new(*args)
1538 m = QuitMessage.new(*args)
1539 m.was_on = myself.channels
1541 @plugins.delegate('sent', m)