12 $debug = false unless $debug
13 $daemonize = false unless $daemonize
15 $dateformat = "%Y/%m/%d %H:%M:%S"
16 $logger = Logger.new($stderr)
17 $logger.datetime_format = $dateformat
18 $logger.level = $cl_loglevel if defined? $cl_loglevel
19 $logger.level = 0 if $debug
21 $log_queue = Queue.new
26 unless Kernel.respond_to? :pretty_inspect
30 public :pretty_inspect
35 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
36 if self.backtrace and not self.backtrace.empty?
38 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
44 class ServerError < RuntimeError
47 def rawlog(level, message=nil, who_pos=1)
49 if call_stack.length > who_pos
50 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
54 # Output each line. To distinguish between separate messages and multi-line
55 # messages originating at the same time, we blank #{who} after the first message
57 # Also, we output strings as-is but for other objects we use pretty_inspect
62 str = message.pretty_inspect
66 qmsg.push [level, l.chomp, who]
73 if $log_thread && $log_thread.alive?
82 def restart_logger(newlogger = false)
85 $logger = newlogger if newlogger
87 $log_thread = Thread.new do
89 while ls = $log_queue.pop
90 ls.each { |l| $logger.add(*l) }
98 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
103 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
107 def debug(message=nil, who_pos=1)
108 rawlog(Logger::Severity::DEBUG, message, who_pos)
111 def log(message=nil, who_pos=1)
112 rawlog(Logger::Severity::INFO, message, who_pos)
115 def warning(message=nil, who_pos=1)
116 rawlog(Logger::Severity::WARN, message, who_pos)
119 def error(message=nil, who_pos=1)
120 rawlog(Logger::Severity::ERROR, message, who_pos)
123 def fatal(message=nil, who_pos=1)
124 rawlog(Logger::Severity::FATAL, message, who_pos)
129 warning "warning test"
133 # The following global is used for the improved signal handling.
137 require 'rbot/rbotconfig'
141 log "rubygems unavailable"
144 require 'rbot/load-gettext'
145 require 'rbot/config'
146 require 'rbot/config-compat'
149 require 'rbot/rfc2812'
150 require 'rbot/ircsocket'
151 require 'rbot/botuser'
153 require 'rbot/plugins'
154 require 'rbot/message'
155 require 'rbot/language'
156 require 'rbot/registry/bdb'
160 # Main bot class, which manages the various components, receives messages,
161 # handles them or passes them to plugins, and contains core functionality.
163 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
164 SOURCE_URL = "http://ruby-rbot.org"
165 # the bot's Auth data
168 # the bot's Config data
171 # the botclass for this bot (determines configdir among other things)
172 attr_reader :botclass
174 # used to perform actions periodically (saves configuration once per minute
178 # synchronize with this mutex while touching permanent data files:
179 # saving, flushing, cleaning up ...
180 attr_reader :save_mutex
182 # bot's Language data
189 # bot's object registry, plugins get an interface to this for persistant
190 # storage (hash interface tied to a bdb file, plugins use Accessors to store
191 # and restore objects in their own namespaces.)
192 attr_reader :registry
194 # bot's plugins. This is an instance of class Plugins
197 # bot's httputil help object, for fetching resources via http. Sets up
198 # proxies etc as defined by the bot configuration/environment
199 attr_accessor :httputil
201 # server we are connected to
207 # bot User in the client/server connection
213 # bot nick in the client/server connection
218 # bot channels in the client/server connection
223 # nick wanted by the bot. This defaults to the irc.nick config value,
224 # but may be overridden by a manual !nick command
226 @wanted_nick || config['irc.nick']
229 # set the nick wanted by the bot
231 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
234 @wanted_nick = wn.to_s.dup
242 ret = self.to_s[0..-2]
243 ret << ' version=' << $version.inspect
244 ret << ' botclass=' << botclass.inspect
245 ret << ' lang="' << lang.language
250 ret << ' nick=' << nick.inspect
253 ret << (server.to_s + (socket ?
254 ' [' << socket.server_uri.to_s << ']' : '')).inspect
255 unless server.channels.empty?
257 ret << server.channels.map { |c|
258 "%s%s" % [c.modes_of(nick).map { |m|
259 server.prefix_for_mode(m)
266 ret << ' plugins=' << plugins.inspect
271 # create a new Bot with botclass +botclass+
272 def initialize(botclass, params = {})
273 # Config for the core bot
274 # TODO should we split socket stuff into ircsocket, etc?
275 Config.register Config::ArrayValue.new('server.list',
276 :default => ['irc://localhost'], :wizard => true,
277 :requires_restart => true,
278 :desc => "List of irc servers rbot should try to connect to. Use comma to separate values. Servers are in format 'server.doma.in:port'. If port is not specified, default value (6667) is used.")
279 Config.register Config::BooleanValue.new('server.ssl',
280 :default => false, :requires_restart => true, :wizard => true,
281 :desc => "Use SSL to connect to this server?")
282 Config.register Config::StringValue.new('server.password',
283 :default => false, :requires_restart => true,
284 :desc => "Password for connecting to this server (if required)",
286 Config.register Config::StringValue.new('server.bindhost',
287 :default => false, :requires_restart => true,
288 :desc => "Specific local host or IP for the bot to bind to (if required)",
290 Config.register Config::IntegerValue.new('server.reconnect_wait',
291 :default => 5, :validate => Proc.new{|v| v >= 0},
292 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
293 Config.register Config::IntegerValue.new('server.ping_timeout',
294 :default => 30, :validate => Proc.new{|v| v >= 0},
295 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
296 Config.register Config::ArrayValue.new('server.nocolor_modes',
297 :default => ['c'], :wizard => false,
298 :requires_restart => false,
299 :desc => "List of channel modes that require messages to be without colors")
301 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
302 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
303 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
304 Config.register Config::StringValue.new('irc.name',
305 :default => "Ruby bot", :requires_restart => true,
306 :desc => "IRC realname the bot should use")
307 Config.register Config::BooleanValue.new('irc.name_copyright',
308 :default => true, :requires_restart => true,
309 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
310 Config.register Config::StringValue.new('irc.user', :default => "rbot",
311 :requires_restart => true,
312 :desc => "local user the bot should appear to be", :wizard => true)
313 Config.register Config::ArrayValue.new('irc.join_channels',
314 :default => [], :wizard => true,
315 :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'")
316 Config.register Config::ArrayValue.new('irc.ignore_users',
318 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
319 Config.register Config::ArrayValue.new('irc.ignore_channels',
321 :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)")
323 Config.register Config::IntegerValue.new('core.save_every',
324 :default => 60, :validate => Proc.new{|v| v >= 0},
325 :on_change => Proc.new { |bot, v|
328 @timer.reschedule(@save_timer, v)
329 @timer.unblock(@save_timer)
331 @timer.block(@save_timer)
335 @save_timer = @timer.add(v) { bot.save }
337 # Nothing to do when v == 0
340 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
342 Config.register Config::BooleanValue.new('core.run_as_daemon',
343 :default => false, :requires_restart => true,
344 :desc => "Should the bot run as a daemon?")
346 Config.register Config::StringValue.new('log.file',
347 :default => false, :requires_restart => true,
348 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
349 Config.register Config::IntegerValue.new('log.level',
350 :default => 1, :requires_restart => false,
351 :validate => Proc.new { |v| (0..5).include?(v) },
352 :on_change => Proc.new { |bot, v|
355 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
356 Config.register Config::IntegerValue.new('log.keep',
357 :default => 1, :requires_restart => true,
358 :validate => Proc.new { |v| v >= 0 },
359 :desc => "How many old console messages logfiles to keep")
360 Config.register Config::IntegerValue.new('log.max_size',
361 :default => 10, :requires_restart => true,
362 :validate => Proc.new { |v| v > 0 },
363 :desc => "Maximum console messages logfile size (in megabytes)")
365 Config.register Config::ArrayValue.new('plugins.path',
366 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
367 :requires_restart => false,
368 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
369 :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")
371 Config.register Config::EnumValue.new('send.newlines',
372 :values => ['split', 'join'], :default => 'split',
373 :on_change => Proc.new { |bot, v|
374 bot.set_default_send_options :newlines => v.to_sym
376 :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")
377 Config.register Config::StringValue.new('send.join_with',
379 :on_change => Proc.new { |bot, v|
380 bot.set_default_send_options :join_with => v.dup
382 :desc => "String used to replace newlines when send.newlines is set to join")
383 Config.register Config::IntegerValue.new('send.max_lines',
385 :validate => Proc.new { |v| v >= 0 },
386 :on_change => Proc.new { |bot, v|
387 bot.set_default_send_options :max_lines => v
389 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
390 Config.register Config::EnumValue.new('send.overlong',
391 :values => ['split', 'truncate'], :default => 'split',
392 :on_change => Proc.new { |bot, v|
393 bot.set_default_send_options :overlong => v.to_sym
395 :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")
396 Config.register Config::StringValue.new('send.split_at',
398 :on_change => Proc.new { |bot, v|
399 bot.set_default_send_options :split_at => Regexp.new(v)
401 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
402 Config.register Config::BooleanValue.new('send.purge_split',
404 :on_change => Proc.new { |bot, v|
405 bot.set_default_send_options :purge_split => v
407 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
408 Config.register Config::StringValue.new('send.truncate_text',
409 :default => "#{Reverse}...#{Reverse}",
410 :on_change => Proc.new { |bot, v|
411 bot.set_default_send_options :truncate_text => v.dup
413 :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")
414 Config.register Config::IntegerValue.new('send.penalty_pct',
416 :validate => Proc.new { |v| v >= 0 },
417 :on_change => Proc.new { |bot, v|
418 bot.socket.penalty_pct = v
420 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
422 @argv = params[:argv]
423 @run_dir = params[:run_dir] || Dir.pwd
425 unless FileTest.directory? Config::coredir
426 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
430 unless FileTest.directory? Config::datadir
431 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
435 unless botclass and not botclass.empty?
436 # We want to find a sensible default.
437 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
438 # * On Windows (at least the NT versions) we want to put our stuff in the
439 # Application Data folder.
440 # We don't use any particular O/S detection magic, exploiting the fact that
441 # Etc.getpwuid is nil on Windows
442 if Etc.getpwuid(Process::Sys.geteuid)
443 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
445 if ENV.has_key?('APPDATA')
446 botclass = ENV['APPDATA'].dup
447 botclass.gsub!("\\","/")
450 botclass = File.join(botclass, ".rbot")
452 botclass = File.expand_path(botclass)
453 @botclass = botclass.gsub(/\/$/, "")
455 repopulate_botclass_directory
457 registry_dir = File.join(@botclass, 'registry')
458 Dir.mkdir(registry_dir) unless File.exist?(registry_dir)
459 unless FileTest.directory? registry_dir
460 error "registry storage location #{registry_dir} is not a directory"
463 save_dir = File.join(@botclass, 'safe_save')
464 Dir.mkdir(save_dir) unless File.exist?(save_dir)
465 unless FileTest.directory? save_dir
466 error "safe save location #{save_dir} is not a directory"
470 # Time at which the last PING was sent
472 # Time at which the last line was RECV'd from the server
475 @startup_time = Time.new
478 @config = Config.manager
479 @config.bot_associate(self)
480 rescue Exception => e
486 if @config['core.run_as_daemon']
490 @logfile = @config['log.file']
491 if @logfile.class!=String || @logfile.empty?
492 logfname = File.basename(botclass).gsub(/^\.+/,'')
494 @logfile = File.join(botclass, logfname)
495 debug "Using `#{@logfile}' as debug log"
498 # See http://blog.humlab.umu.se/samuel/archives/000107.html
499 # for the backgrounding code
505 rescue NotImplementedError
506 warning "Could not background, fork not supported"
509 rescue Exception => e
510 warning "Could not background. #{e.pretty_inspect}"
513 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
516 logger = Logger.new(@logfile,
518 @config['log.max_size']*1024*1024)
519 logger.datetime_format= $dateformat
520 logger.level = @config['log.level']
521 logger.level = $cl_loglevel if defined? $cl_loglevel
522 logger.level = 0 if $debug
524 restart_logger(logger)
529 log "Redirecting standard input/output/error"
530 [$stdin, $stdout, $stderr].each do |fd|
532 fd.reopen "/dev/null"
534 # On Windows, there's not such thing as /dev/null
539 def $stdout.write(str=nil)
543 def $stdout.write(str=nil)
544 if str.to_s.match(/:\d+: warning:/)
553 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
557 @registry = Registry.new self
560 @save_mutex = Mutex.new
561 if @config['core.save_every'] > 0
562 @save_timer = @timer.add(@config['core.save_every']) { save }
566 @quit_mutex = Mutex.new
569 @lang = Language.new(self, @config['core.language'])
572 @auth = Auth::manager
573 @auth.bot_associate(self)
574 # @auth.load("#{botclass}/botusers.yaml")
575 rescue Exception => e
580 @auth.everyone.set_default_permission("*", true)
581 @auth.botowner.password= @config['auth.password']
583 @plugins = Plugins::manager
584 @plugins.bot_associate(self)
587 if @config['server.name']
588 debug "upgrading configuration (server.name => server.list)"
589 srv_uri = 'irc://' + @config['server.name']
590 srv_uri += ":#{@config['server.port']}" if @config['server.port']
591 @config.items['server.list'.to_sym].set_string(srv_uri)
592 @config.delete('server.name'.to_sym)
593 @config.delete('server.port'.to_sym)
594 debug "server.list is now #{@config['server.list'].inspect}"
597 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
602 # Channels where we are quiet
603 # Array of channels names where the bot should be quiet
604 # '*' means all channels
607 # but we always speak here
610 # the nick we want, if it's different from the irc.nick config value
611 # (e.g. as set by a !nick command)
614 @client[:welcome] = proc {|data|
615 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
617 @plugins.delegate("welcome", m)
618 @plugins.delegate("connect")
621 # TODO the next two @client should go into rfc2812.rb, probably
622 # Since capabs are two-steps processes, server.supports[:capab]
623 # should be a three-state: nil, [], [....]
624 asked_for = { :"identify-msg" => false }
625 @client[:isupport] = proc { |data|
626 if server.supports[:capab] and !asked_for[:"identify-msg"]
627 sendq "CAPAB IDENTIFY-MSG"
628 asked_for[:"identify-msg"] = true
631 @client[:datastr] = proc { |data|
632 if data[:text] == "IDENTIFY-MSG"
633 server.capabilities[:"identify-msg"] = true
635 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
639 @client[:privmsg] = proc { |data|
640 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
641 # debug "Message source is #{data[:source].inspect}"
642 # debug "Message target is #{data[:target].inspect}"
643 # debug "Bot is #{myself.inspect}"
645 @config['irc.ignore_channels'].each { |channel|
646 if m.target.downcase == channel.downcase
651 @config['irc.ignore_users'].each { |mask|
652 if m.source.matches?(server.new_netmask(mask))
658 @plugins.irc_delegate('privmsg', m)
660 @client[:notice] = proc { |data|
661 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
662 # pass it off to plugins that want to hear everything
663 @plugins.irc_delegate "notice", message
665 @client[:motd] = proc { |data|
666 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
667 @plugins.delegate "motd", m
669 @client[:nicktaken] = proc { |data|
670 new = "#{data[:nick]}_"
672 # If we're setting our nick at connection because our choice was taken,
673 # we have to fix our nick manually, because there will be no NICK message
674 # to inform us that our nick has been changed.
675 if data[:target] == '*'
676 debug "setting my connection nick to #{new}"
679 @plugins.delegate "nicktaken", data[:nick]
681 @client[:badnick] = proc {|data|
682 warning "bad nick (#{data[:nick]})"
684 @client[:ping] = proc {|data|
685 sendq "PONG #{data[:pingid]}"
687 @client[:pong] = proc {|data|
690 @client[:nick] = proc {|data|
691 # debug "Message source is #{data[:source].inspect}"
692 # debug "Bot is #{myself.inspect}"
693 source = data[:source]
696 m = NickMessage.new(self, server, source, old, new)
697 m.is_on = data[:is_on]
699 debug "my nick is now #{new}"
701 @plugins.irc_delegate("nick", m)
703 @client[:quit] = proc {|data|
704 source = data[:source]
705 message = data[:message]
706 m = QuitMessage.new(self, server, source, source, message)
707 m.was_on = data[:was_on]
708 @plugins.irc_delegate("quit", m)
710 @client[:mode] = proc {|data|
711 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
712 m.modes = data[:modes]
713 @plugins.delegate "modechange", m
715 @client[:whois] = proc {|data|
716 source = data[:source]
717 target = server.get_user(data[:whois][:nick])
718 m = WhoisMessage.new(self, server, source, target, data[:whois])
719 @plugins.delegate "whois", m
721 @client[:join] = proc {|data|
722 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
723 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
724 @plugins.irc_delegate("join", m)
725 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
727 @client[:part] = proc {|data|
728 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
729 @plugins.irc_delegate("part", m)
731 @client[:kick] = proc {|data|
732 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
733 @plugins.irc_delegate("kick", m)
735 @client[:invite] = proc {|data|
736 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
737 @plugins.irc_delegate("invite", m)
739 @client[:changetopic] = proc {|data|
740 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
742 @plugins.irc_delegate("topic", m)
744 # @client[:topic] = proc { |data|
745 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
747 @client[:topicinfo] = proc { |data|
748 channel = data[:channel]
749 topic = channel.topic
750 m = TopicMessage.new(self, server, data[:source], channel, topic)
751 m.info_or_set = :info
752 @plugins.irc_delegate("topic", m)
754 @client[:names] = proc { |data|
755 m = NamesMessage.new(self, server, server, data[:channel])
756 m.users = data[:users]
757 @plugins.delegate "names", m
759 @client[:banlist] = proc { |data|
760 m = BanlistMessage.new(self, server, server, data[:channel])
762 @plugins.delegate "banlist", m
764 @client[:nosuchtarget] = proc { |data|
765 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
766 @plugins.delegate "nosuchtarget", m
768 @client[:error] = proc { |data|
769 raise ServerError, data[:message]
771 @client[:unknown] = proc { |data|
772 #debug "UNKNOWN: #{data[:serverstring]}"
773 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
774 @plugins.delegate "unknown_message", m
777 set_default_send_options :newlines => @config['send.newlines'].to_sym,
778 :join_with => @config['send.join_with'].dup,
779 :max_lines => @config['send.max_lines'],
780 :overlong => @config['send.overlong'].to_sym,
781 :split_at => Regexp.new(@config['send.split_at']),
782 :purge_split => @config['send.purge_split'],
783 :truncate_text => @config['send.truncate_text'].dup
788 def repopulate_botclass_directory
789 template_dir = File.join Config::datadir, 'templates'
790 if FileTest.directory? @botclass
791 # compare the templates dir with the current botclass dir, filling up the
792 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
793 # :update option, so we have to do it manually.
794 # Note that we use the */** pattern because we don't want to match
795 # keywords.rbot, which gets deleted on load and would therefore be missing
797 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
799 dest = File.join(@botclass, f)
800 FileUtils.mkdir_p(File.dirname(dest))
801 FileUtils.cp File.join(template_dir, f), dest
804 log "no #{@botclass} directory found, creating from templates..."
805 if FileTest.exist? @botclass
806 error "file #{@botclass} exists but isn't a directory"
809 FileUtils.cp_r template_dir, @botclass
813 # Return a path under the current botclass by joining the mentioned
814 # components. The components are automatically converted to String
815 def path(*components)
816 File.join(@botclass, *(components.map {|c| c.to_s}))
819 def setup_plugins_path
820 plugdir_default = File.join(Config::datadir, 'plugins')
821 plugdir_local = File.join(@botclass, 'plugins')
822 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
824 @plugins.clear_botmodule_dirs
825 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
826 @plugins.add_core_module_dir(Config::coredir)
827 if FileTest.directory? plugdir_local
828 @plugins.add_plugin_dir(plugdir_local)
830 warning "local plugin location #{plugdir_local} is not a directory"
833 @config['plugins.path'].each do |_|
834 path = _.sub(/^\(default\)/, plugdir_default)
835 @plugins.add_plugin_dir(path)
839 def set_default_send_options(opts={})
840 # Default send options for NOTICE and PRIVMSG
841 unless defined? @default_send_options
842 @default_send_options = {
843 :queue_channel => nil, # use default queue channel
844 :queue_ring => nil, # use default queue ring
845 :newlines => :split, # or :join
846 :join_with => ' ', # by default, use a single space
847 :max_lines => 0, # maximum number of lines to send with a single command
848 :overlong => :split, # or :truncate
849 # TODO an array of splitpoints would be preferrable for this option:
850 :split_at => /\s+/, # by default, split overlong lines at whitespace
851 :purge_split => true, # should the split string be removed?
852 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
855 @default_send_options.update opts unless opts.empty?
858 # checks if we should be quiet on a channel
859 def quiet_on?(channel)
860 ch = channel.downcase
861 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
864 def set_quiet(channel = nil)
866 ch = channel.downcase.dup
867 @not_quiet.delete(ch)
876 def reset_quiet(channel = nil)
878 ch = channel.downcase.dup
887 # things to do when we receive a signal
888 def got_sig(sig, func=:quit)
889 debug "received #{sig}, queueing #{func}"
890 # this is not an interruption if we just need to reconnect
891 $interrupted += 1 unless func == :reconnect
892 self.send(func) unless @quit_mutex.locked?
893 debug "interrupted #{$interrupted} times"
904 trap("SIGINT") { got_sig("SIGINT") }
905 trap("SIGTERM") { got_sig("SIGTERM") }
906 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
907 trap("SIGUSR1") { got_sig("SIGUSR1", :reconnect) }
908 rescue ArgumentError => e
909 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
910 rescue Exception => e
911 debug "failed to trap signals: #{e.pretty_inspect}"
915 # connect the bot to IRC
917 # make sure we don't have any spurious ping checks running
918 # (and initialize the vars if this is the first time we connect)
921 quit if $interrupted > 0
925 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: #{e}"
927 quit if $interrupted > 0
929 realname = @config['irc.name'].clone || 'Ruby bot'
930 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
932 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
933 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
934 quit if $interrupted > 0
935 myself.nick = @config['irc.nick']
936 myself.user = @config['irc.user']
939 # disconnect the bot from IRC, if connected, and then connect (again)
940 def reconnect(message=nil, too_fast=false)
941 # we will wait only if @last_rec was not nil, i.e. if we were connected or
942 # got disconnected by a network error
943 # if someone wants to manually call disconnect() _and_ reconnect(), they
944 # will have to take care of the waiting themselves
945 will_wait = !!@last_rec
947 if @socket.connected?
953 log "\n\nDisconnected\n\n"
955 quit if $interrupted > 0
957 log "\n\nWaiting to reconnect\n\n"
958 sleep @config['server.reconnect_wait']
959 sleep 10*@config['server.reconnect_wait'] if too_fast
963 rescue Exception => e
969 # begin event handling loop
975 reconnect(quit_msg, too_fast)
976 quit if $interrupted > 0
977 while @socket.connected?
978 quit if $interrupted > 0
980 # Wait for messages and process them as they arrive. If nothing is
981 # received, we call the ping_server() method that will PING the
982 # server if appropriate, or raise a TimeoutError if no PONG has been
983 # received in the user-chosen timeout since the last PING sent.
985 break unless reply = @socket.gets
987 @client.process reply
993 # I despair of this. Some of my users get "connection reset by peer"
994 # exceptions that ARENT SocketError's. How am I supposed to handle
999 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1000 error "network exception: #{e.pretty_inspect}"
1002 rescue ServerError => e
1003 # received an ERROR from the server
1004 quit_msg = "server ERROR: " + e.message
1005 too_fast = e.message.index("reconnect too fast")
1007 rescue BDB::Fatal => e
1008 fatal "fatal bdb error: #{e.pretty_inspect}"
1010 # Why restart? DB problems are serious stuff ...
1011 # restart("Oops, we seem to have registry problems ...")
1014 rescue Exception => e
1015 error "non-net exception: #{e.pretty_inspect}"
1018 fatal "unexpected exception: #{e.pretty_inspect}"
1025 # type:: message type
1026 # where:: message target
1027 # message:: message text
1028 # send message +message+ of type +type+ to target +where+
1029 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1030 # relevant say() or notice() methods. This one should be used for IRCd
1031 # extensions you want to use in modules.
1032 def sendmsg(original_type, original_where, original_message, options={})
1034 # filter message with sendmsg filters
1035 ds = DataStream.new original_message.to_s.dup,
1036 :type => original_type, :dest => original_where,
1037 :options => @default_send_options.merge(options)
1038 filters = filter_names(:sendmsg)
1039 filters.each do |fname|
1040 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1041 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1047 filtered = ds[:text]
1049 # For starters, set up appropriate queue channels and rings
1050 mchan = opts[:queue_channel]
1051 mring = opts[:queue_ring]
1068 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1070 # if target is a channel with nocolor modes, strip colours
1071 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1072 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1075 messages = Array.new
1076 case opts[:newlines]
1078 messages << [multi_line.gsub("\n", opts[:join_with])]
1080 multi_line.each_line { |line|
1082 next unless(line.size > 0)
1086 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1089 # The IRC protocol requires that each raw message must be not longer
1090 # than 512 characters. From this length with have to subtract the EOL
1091 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1092 # that will be prepended by the server to all of our messages.
1094 # The maximum raw message length we can send is therefore 512 - 2 - 2
1095 # minus the length of our hostmask.
1097 max_len = 508 - myself.fullform.size
1099 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1100 # will have a + or - prepended
1101 if server.capabilities[:"identify-msg"]
1105 # When splitting the message, we'll be prefixing the following string:
1106 # (e.g. "PRIVMSG #rbot :")
1107 fixed = "#{type} #{where} :"
1109 # And this is what's left
1110 left = max_len - fixed.size
1112 truncate = opts[:truncate_text]
1113 truncate = @default_send_options[:truncate_text] if truncate.size > left
1114 truncate = "" if truncate.size > left
1116 all_lines = messages.map { |line|
1120 case opts[:overlong]
1123 sub_lines = Array.new
1125 sub_lines << msg.slice!(0, left)
1127 lastspace = sub_lines.last.rindex(opts[:split_at])
1129 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1130 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1132 end until msg.empty?
1135 line.slice(0, left - truncate.size) << truncate
1137 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1142 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1143 lines = all_lines[0...opts[:max_lines]]
1144 new_last = lines.last.slice(0, left - truncate.size) << truncate
1145 lines.last.replace(new_last)
1151 sendq "#{fixed}#{line}", chan, ring
1152 delegate_sent(type, where, line)
1156 # queue an arbitraty message for the server
1157 def sendq(message="", chan=nil, ring=0)
1159 @socket.queue(message, chan, ring)
1162 # send a notice message to channel/nick +where+
1163 def notice(where, message, options={})
1164 return if where.kind_of?(Channel) and quiet_on?(where)
1165 sendmsg "NOTICE", where, message, options
1168 # say something (PRIVMSG) to channel/nick +where+
1169 def say(where, message, options={})
1170 return if where.kind_of?(Channel) and quiet_on?(where)
1171 sendmsg "PRIVMSG", where, message, options
1174 def ctcp_notice(where, command, message, options={})
1175 return if where.kind_of?(Channel) and quiet_on?(where)
1176 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1179 def ctcp_say(where, command, message, options={})
1180 return if where.kind_of?(Channel) and quiet_on?(where)
1181 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1184 # perform a CTCP action with message +message+ to channel/nick +where+
1185 def action(where, message, options={})
1186 ctcp_say(where, 'ACTION', message, options)
1189 # quick way to say "okay" (or equivalent) to +where+
1191 say where, @lang.get("okay")
1194 # set topic of channel +where+ to +topic+
1195 # can also be used to retrieve the topic of channel +where+
1196 # by omitting the last argument
1197 def topic(where, topic=nil)
1199 sendq "TOPIC #{where}", where, 2
1201 sendq "TOPIC #{where} :#{topic}", where, 2
1205 def disconnect(message=nil)
1206 message = @lang.get("quit") if (!message || message.empty?)
1207 if @socket.connected?
1209 debug "Clearing socket"
1211 debug "Sending quit message"
1212 @socket.emergency_puts "QUIT :#{message}"
1213 debug "Logging quits"
1214 delegate_sent('QUIT', myself, message)
1215 debug "Flushing socket"
1217 rescue SocketError => e
1218 error "error while disconnecting socket: #{e.pretty_inspect}"
1220 debug "Shutting down socket"
1227 # disconnect from the server and cleanup all plugins and modules
1228 def shutdown(message=nil)
1229 @quit_mutex.synchronize do
1230 debug "Shutting down: #{message}"
1231 ## No we don't restore them ... let everything run through
1233 # trap("SIGINT", "DEFAULT")
1234 # trap("SIGTERM", "DEFAULT")
1235 # trap("SIGHUP", "DEFAULT")
1237 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1239 debug "\tdisconnecting..."
1241 debug "\tstopping timer..."
1243 debug "\tsaving ..."
1245 debug "\tcleaning up ..."
1246 @save_mutex.synchronize do
1249 # debug "\tstopping timers ..."
1251 # debug "Closing registries"
1253 debug "\t\tcleaning up the db environment ..."
1255 log "rbot quit (#{message})"
1259 # message:: optional IRC quit message
1260 # quit IRC, shutdown the bot
1261 def quit(message=nil)
1269 # totally shutdown and respawn the bot
1270 def restart(message=nil)
1271 message = _("restarting, back in %{wait}...") % {
1272 :wait => @config['server.reconnect_wait']
1273 } if (!message || message.empty?)
1275 sleep @config['server.reconnect_wait']
1278 # Note, this fails on Windows
1279 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1283 rescue Errno::ENOENT
1285 exec("ruby", *(@argv.unshift $0))
1286 rescue Exception => e
1292 # call the save method for all of the botmodules
1294 @save_mutex.synchronize do
1300 # call the rescan method for all of the botmodules
1302 debug "\tstopping timer..."
1304 @save_mutex.synchronize do
1311 # channel:: channel to join
1312 # key:: optional channel key if channel is +s
1314 def join(channel, key=nil)
1316 sendq "JOIN #{channel} :#{key}", channel, 2
1318 sendq "JOIN #{channel}", channel, 2
1323 def part(channel, message="")
1324 sendq "PART #{channel} :#{message}", channel, 2
1327 # attempt to change bot's nick to +name+
1329 sendq "NICK #{name}"
1333 def mode(channel, mode, target=nil)
1334 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1338 def whois(nick, target=nil)
1339 sendq "WHOIS #{target} #{nick}", nil, 0
1343 def kick(channel, user, msg)
1344 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1347 # m:: message asking for help
1348 # topic:: optional topic help is requested for
1349 # respond to online help requests
1351 topic = nil if topic == ""
1354 helpstr = _("help topics: ")
1355 helpstr += @plugins.helptopics
1356 helpstr += _(" (help <topic> for more info)")
1358 unless(helpstr = @plugins.help(topic))
1359 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1365 # returns a string describing the current status of the bot (uptime etc)
1367 secs_up = Time.new - @startup_time
1368 uptime = Utils.secs_to_string secs_up
1369 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1370 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1372 :up => uptime, :plug => @plugins.length,
1373 :sent => @socket.lines_sent, :recv => @socket.lines_received
1377 # We want to respond to a hung server in a timely manner. If nothing was received
1378 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1379 # the server. If the PONG is not received within the user-defined timeout, we
1380 # assume we're in ping timeout and act accordingly.
1382 act_timeout = @config['server.ping_timeout']
1383 return if act_timeout <= 0
1385 if @last_rec && now > @last_rec + act_timeout
1387 # No previous PING pending, send a new one
1389 @last_ping = Time.now
1391 diff = now - @last_ping
1392 if diff > act_timeout
1393 debug "no PONG from server in #{diff} seconds, reconnecting"
1394 # the actual reconnect is handled in the main loop:
1395 raise TimeoutError, "no PONG from server in #{diff} seconds"
1401 def stop_server_pings
1402 # cancel previous PINGs and reset time of last RECV
1409 # delegate sent messages
1410 def delegate_sent(type, where, message)
1411 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1414 m = NoticeMessage.new(*args)
1416 m = PrivMessage.new(*args)
1418 m = QuitMessage.new(*args)
1419 m.was_on = myself.channels
1421 @plugins.delegate('sent', m)