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'
159 # Main bot class, which manages the various components, receives messages,
160 # handles them or passes them to plugins, and contains core functionality.
162 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
163 SOURCE_URL = "http://ruby-rbot.org"
164 # the bot's Auth data
167 # the bot's Config data
170 # the botclass for this bot (determines configdir among other things)
171 attr_reader :botclass
173 # used to perform actions periodically (saves configuration once per minute
177 # synchronize with this mutex while touching permanent data files:
178 # saving, flushing, cleaning up ...
179 attr_reader :save_mutex
181 # bot's Language data
188 # bot's object registry, plugins get an interface to this for persistant
189 # storage (hash interface tied to a db file, plugins use Accessors to store
190 # and restore objects in their own namespaces.)
191 attr_reader :registry
193 # bot's plugins. This is an instance of class Plugins
196 # bot's httputil helper object, for fetching resources via http. Sets up
197 # proxies etc as defined by the bot configuration/environment
198 attr_accessor :httputil
200 # server we are connected to
206 # bot User in the client/server connection
212 # bot nick in the client/server connection
217 # bot channels in the client/server connection
222 # nick wanted by the bot. This defaults to the irc.nick config value,
223 # but may be overridden by a manual !nick command
225 @wanted_nick || config['irc.nick']
228 # set the nick wanted by the bot
230 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
233 @wanted_nick = wn.to_s.dup
241 ret = self.to_s[0..-2]
242 ret << ' version=' << $version.inspect
243 ret << ' botclass=' << botclass.inspect
244 ret << ' lang="' << lang.language
249 ret << ' nick=' << nick.inspect
252 ret << (server.to_s + (socket ?
253 ' [' << socket.server_uri.to_s << ']' : '')).inspect
254 unless server.channels.empty?
256 ret << server.channels.map { |c|
257 "%s%s" % [c.modes_of(nick).map { |m|
258 server.prefix_for_mode(m)
265 ret << ' plugins=' << plugins.inspect
270 # create a new Bot with botclass +botclass+
271 def initialize(botclass, params = {})
272 # Config for the core bot
273 # TODO should we split socket stuff into ircsocket, etc?
274 Config.register Config::ArrayValue.new('server.list',
275 :default => ['irc://localhost'], :wizard => true,
276 :requires_restart => true,
277 :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.")
278 Config.register Config::BooleanValue.new('server.ssl',
279 :default => false, :requires_restart => true, :wizard => true,
280 :desc => "Use SSL to connect to this server?")
281 Config.register Config::StringValue.new('server.password',
282 :default => false, :requires_restart => true,
283 :desc => "Password for connecting to this server (if required)",
285 Config.register Config::StringValue.new('server.bindhost',
286 :default => false, :requires_restart => true,
287 :desc => "Specific local host or IP for the bot to bind to (if required)",
289 Config.register Config::IntegerValue.new('server.reconnect_wait',
290 :default => 5, :validate => Proc.new{|v| v >= 0},
291 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
292 Config.register Config::IntegerValue.new('server.ping_timeout',
293 :default => 30, :validate => Proc.new{|v| v >= 0},
294 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
295 Config.register Config::ArrayValue.new('server.nocolor_modes',
296 :default => ['c'], :wizard => false,
297 :requires_restart => false,
298 :desc => "List of channel modes that require messages to be without colors")
300 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
301 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
302 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
303 Config.register Config::StringValue.new('irc.name',
304 :default => "Ruby bot", :requires_restart => true,
305 :desc => "IRC realname the bot should use")
306 Config.register Config::BooleanValue.new('irc.name_copyright',
307 :default => true, :requires_restart => true,
308 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
309 Config.register Config::StringValue.new('irc.user', :default => "rbot",
310 :requires_restart => true,
311 :desc => "local user the bot should appear to be", :wizard => true)
312 Config.register Config::ArrayValue.new('irc.join_channels',
313 :default => [], :wizard => true,
314 :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'")
315 Config.register Config::ArrayValue.new('irc.ignore_users',
317 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
318 Config.register Config::ArrayValue.new('irc.ignore_channels',
320 :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)")
322 Config.register Config::IntegerValue.new('core.save_every',
323 :default => 60, :validate => Proc.new{|v| v >= 0},
324 :on_change => Proc.new { |bot, v|
327 @timer.reschedule(@save_timer, v)
328 @timer.unblock(@save_timer)
330 @timer.block(@save_timer)
334 @save_timer = @timer.add(v) { bot.save }
336 # Nothing to do when v == 0
339 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
341 Config.register Config::BooleanValue.new('core.run_as_daemon',
342 :default => false, :requires_restart => true,
343 :desc => "Should the bot run as a daemon?")
345 Config.register Config::StringValue.new('log.file',
346 :default => false, :requires_restart => true,
347 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
348 Config.register Config::IntegerValue.new('log.level',
349 :default => 1, :requires_restart => false,
350 :validate => Proc.new { |v| (0..5).include?(v) },
351 :on_change => Proc.new { |bot, v|
354 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
355 Config.register Config::IntegerValue.new('log.keep',
356 :default => 1, :requires_restart => true,
357 :validate => Proc.new { |v| v >= 0 },
358 :desc => "How many old console messages logfiles to keep")
359 Config.register Config::IntegerValue.new('log.max_size',
360 :default => 10, :requires_restart => true,
361 :validate => Proc.new { |v| v > 0 },
362 :desc => "Maximum console messages logfile size (in megabytes)")
364 Config.register Config::ArrayValue.new('plugins.path',
365 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
366 :requires_restart => false,
367 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
368 :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")
370 Config.register Config::EnumValue.new('send.newlines',
371 :values => ['split', 'join'], :default => 'split',
372 :on_change => Proc.new { |bot, v|
373 bot.set_default_send_options :newlines => v.to_sym
375 :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")
376 Config.register Config::StringValue.new('send.join_with',
378 :on_change => Proc.new { |bot, v|
379 bot.set_default_send_options :join_with => v.dup
381 :desc => "String used to replace newlines when send.newlines is set to join")
382 Config.register Config::IntegerValue.new('send.max_lines',
384 :validate => Proc.new { |v| v >= 0 },
385 :on_change => Proc.new { |bot, v|
386 bot.set_default_send_options :max_lines => v
388 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
389 Config.register Config::EnumValue.new('send.overlong',
390 :values => ['split', 'truncate'], :default => 'split',
391 :on_change => Proc.new { |bot, v|
392 bot.set_default_send_options :overlong => v.to_sym
394 :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")
395 Config.register Config::StringValue.new('send.split_at',
397 :on_change => Proc.new { |bot, v|
398 bot.set_default_send_options :split_at => Regexp.new(v)
400 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
401 Config.register Config::BooleanValue.new('send.purge_split',
403 :on_change => Proc.new { |bot, v|
404 bot.set_default_send_options :purge_split => v
406 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
407 Config.register Config::StringValue.new('send.truncate_text',
408 :default => "#{Reverse}...#{Reverse}",
409 :on_change => Proc.new { |bot, v|
410 bot.set_default_send_options :truncate_text => v.dup
412 :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")
413 Config.register Config::IntegerValue.new('send.penalty_pct',
415 :validate => Proc.new { |v| v >= 0 },
416 :on_change => Proc.new { |bot, v|
417 bot.socket.penalty_pct = v
419 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
420 Config.register Config::StringValue.new('core.db',
422 :wizard => true, :default => "bdb",
423 :validate => Proc.new { |v| ["bdb", "tc"].include? v },
424 :requires_restart => true,
425 :desc => "DB adaptor to use for storing settings and plugin data. Options are: bdb (Berkeley DB, stable adaptor, but troublesome to install and unmaintained), tc (Tokyo Cabinet, new adaptor, fast and furious, but may be not available and contain bugs)")
427 @argv = params[:argv]
428 @run_dir = params[:run_dir] || Dir.pwd
430 unless FileTest.directory? Config::coredir
431 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
435 unless FileTest.directory? Config::datadir
436 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
440 unless botclass and not botclass.empty?
441 # We want to find a sensible default.
442 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
443 # * On Windows (at least the NT versions) we want to put our stuff in the
444 # Application Data folder.
445 # We don't use any particular O/S detection magic, exploiting the fact that
446 # Etc.getpwuid is nil on Windows
447 if Etc.getpwuid(Process::Sys.geteuid)
448 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
450 if ENV.has_key?('APPDATA')
451 botclass = ENV['APPDATA'].dup
452 botclass.gsub!("\\","/")
455 botclass = File.join(botclass, ".rbot")
457 botclass = File.expand_path(botclass)
458 @botclass = botclass.gsub(/\/$/, "")
460 repopulate_botclass_directory
462 registry_dir = File.join(@botclass, 'registry')
463 Dir.mkdir(registry_dir) unless File.exist?(registry_dir)
464 unless FileTest.directory? registry_dir
465 error "registry storage location #{registry_dir} is not a directory"
468 save_dir = File.join(@botclass, 'safe_save')
469 Dir.mkdir(save_dir) unless File.exist?(save_dir)
470 unless FileTest.directory? save_dir
471 error "safe save location #{save_dir} is not a directory"
475 # Time at which the last PING was sent
477 # Time at which the last line was RECV'd from the server
480 @startup_time = Time.new
483 @config = Config.manager
484 @config.bot_associate(self)
485 rescue Exception => e
491 if @config['core.run_as_daemon']
495 case @config["core.db"]
497 require 'rbot/registry/bdb'
499 require 'rbot/registry/tc'
501 raise _("Unknown DB adaptor: %s") % @config["core.db"]
504 @logfile = @config['log.file']
505 if @logfile.class!=String || @logfile.empty?
506 logfname = File.basename(botclass).gsub(/^\.+/,'')
508 @logfile = File.join(botclass, logfname)
509 debug "Using `#{@logfile}' as debug log"
512 # See http://blog.humlab.umu.se/samuel/archives/000107.html
513 # for the backgrounding code
519 rescue NotImplementedError
520 warning "Could not background, fork not supported"
523 rescue Exception => e
524 warning "Could not background. #{e.pretty_inspect}"
527 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
530 logger = Logger.new(@logfile,
532 @config['log.max_size']*1024*1024)
533 logger.datetime_format= $dateformat
534 logger.level = @config['log.level']
535 logger.level = $cl_loglevel if defined? $cl_loglevel
536 logger.level = 0 if $debug
538 restart_logger(logger)
543 log "Redirecting standard input/output/error"
544 [$stdin, $stdout, $stderr].each do |fd|
546 fd.reopen "/dev/null"
548 # On Windows, there's not such thing as /dev/null
553 def $stdout.write(str=nil)
557 def $stdout.write(str=nil)
558 if str.to_s.match(/:\d+: warning:/)
567 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
571 @registry = Registry.new self
574 @save_mutex = Mutex.new
575 if @config['core.save_every'] > 0
576 @save_timer = @timer.add(@config['core.save_every']) { save }
580 @quit_mutex = Mutex.new
583 @lang = Language.new(self, @config['core.language'])
586 @auth = Auth::manager
587 @auth.bot_associate(self)
588 # @auth.load("#{botclass}/botusers.yaml")
589 rescue Exception => e
594 @auth.everyone.set_default_permission("*", true)
595 @auth.botowner.password= @config['auth.password']
597 @plugins = Plugins::manager
598 @plugins.bot_associate(self)
601 if @config['server.name']
602 debug "upgrading configuration (server.name => server.list)"
603 srv_uri = 'irc://' + @config['server.name']
604 srv_uri += ":#{@config['server.port']}" if @config['server.port']
605 @config.items['server.list'.to_sym].set_string(srv_uri)
606 @config.delete('server.name'.to_sym)
607 @config.delete('server.port'.to_sym)
608 debug "server.list is now #{@config['server.list'].inspect}"
611 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
616 # Channels where we are quiet
617 # Array of channels names where the bot should be quiet
618 # '*' means all channels
621 # but we always speak here
624 # the nick we want, if it's different from the irc.nick config value
625 # (e.g. as set by a !nick command)
628 @client[:welcome] = proc {|data|
629 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
631 @plugins.delegate("welcome", m)
632 @plugins.delegate("connect")
635 # TODO the next two @client should go into rfc2812.rb, probably
636 # Since capabs are two-steps processes, server.supports[:capab]
637 # should be a three-state: nil, [], [....]
638 asked_for = { :"identify-msg" => false }
639 @client[:isupport] = proc { |data|
640 if server.supports[:capab] and !asked_for[:"identify-msg"]
641 sendq "CAPAB IDENTIFY-MSG"
642 asked_for[:"identify-msg"] = true
645 @client[:datastr] = proc { |data|
646 if data[:text] == "IDENTIFY-MSG"
647 server.capabilities[:"identify-msg"] = true
649 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
653 @client[:privmsg] = proc { |data|
654 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
655 # debug "Message source is #{data[:source].inspect}"
656 # debug "Message target is #{data[:target].inspect}"
657 # debug "Bot is #{myself.inspect}"
659 @config['irc.ignore_channels'].each { |channel|
660 if m.target.downcase == channel.downcase
665 @config['irc.ignore_users'].each { |mask|
666 if m.source.matches?(server.new_netmask(mask))
672 @plugins.irc_delegate('privmsg', m)
674 @client[:notice] = proc { |data|
675 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
676 # pass it off to plugins that want to hear everything
677 @plugins.irc_delegate "notice", message
679 @client[:motd] = proc { |data|
680 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
681 @plugins.delegate "motd", m
683 @client[:nicktaken] = proc { |data|
684 new = "#{data[:nick]}_"
686 # If we're setting our nick at connection because our choice was taken,
687 # we have to fix our nick manually, because there will be no NICK message
688 # to inform us that our nick has been changed.
689 if data[:target] == '*'
690 debug "setting my connection nick to #{new}"
693 @plugins.delegate "nicktaken", data[:nick]
695 @client[:badnick] = proc {|data|
696 warning "bad nick (#{data[:nick]})"
698 @client[:ping] = proc {|data|
699 sendq "PONG #{data[:pingid]}"
701 @client[:pong] = proc {|data|
704 @client[:nick] = proc {|data|
705 # debug "Message source is #{data[:source].inspect}"
706 # debug "Bot is #{myself.inspect}"
707 source = data[:source]
710 m = NickMessage.new(self, server, source, old, new)
711 m.is_on = data[:is_on]
713 debug "my nick is now #{new}"
715 @plugins.irc_delegate("nick", m)
717 @client[:quit] = proc {|data|
718 source = data[:source]
719 message = data[:message]
720 m = QuitMessage.new(self, server, source, source, message)
721 m.was_on = data[:was_on]
722 @plugins.irc_delegate("quit", m)
724 @client[:mode] = proc {|data|
725 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
726 m.modes = data[:modes]
727 @plugins.delegate "modechange", m
729 @client[:whois] = proc {|data|
730 source = data[:source]
731 target = server.get_user(data[:whois][:nick])
732 m = WhoisMessage.new(self, server, source, target, data[:whois])
733 @plugins.delegate "whois", m
735 @client[:list] = proc {|data|
736 source = data[:source]
737 m = ListMessage.new(self, server, source, source, data[:list])
738 @plugins.delegate "irclist", m
740 @client[:join] = proc {|data|
741 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
742 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
743 @plugins.irc_delegate("join", m)
744 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
746 @client[:part] = proc {|data|
747 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
748 @plugins.irc_delegate("part", m)
750 @client[:kick] = proc {|data|
751 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
752 @plugins.irc_delegate("kick", m)
754 @client[:invite] = proc {|data|
755 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
756 @plugins.irc_delegate("invite", m)
758 @client[:changetopic] = proc {|data|
759 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
761 @plugins.irc_delegate("topic", m)
763 # @client[:topic] = proc { |data|
764 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
766 @client[:topicinfo] = proc { |data|
767 channel = data[:channel]
768 topic = channel.topic
769 m = TopicMessage.new(self, server, data[:source], channel, topic)
770 m.info_or_set = :info
771 @plugins.irc_delegate("topic", m)
773 @client[:names] = proc { |data|
774 m = NamesMessage.new(self, server, server, data[:channel])
775 m.users = data[:users]
776 @plugins.delegate "names", m
778 @client[:banlist] = proc { |data|
779 m = BanlistMessage.new(self, server, server, data[:channel])
781 @plugins.delegate "banlist", m
783 @client[:nosuchtarget] = proc { |data|
784 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
785 @plugins.delegate "nosuchtarget", m
787 @client[:error] = proc { |data|
788 raise ServerError, data[:message]
790 @client[:unknown] = proc { |data|
791 #debug "UNKNOWN: #{data[:serverstring]}"
792 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
793 @plugins.delegate "unknown_message", m
796 set_default_send_options :newlines => @config['send.newlines'].to_sym,
797 :join_with => @config['send.join_with'].dup,
798 :max_lines => @config['send.max_lines'],
799 :overlong => @config['send.overlong'].to_sym,
800 :split_at => Regexp.new(@config['send.split_at']),
801 :purge_split => @config['send.purge_split'],
802 :truncate_text => @config['send.truncate_text'].dup
807 def repopulate_botclass_directory
808 template_dir = File.join Config::datadir, 'templates'
809 if FileTest.directory? @botclass
810 # compare the templates dir with the current botclass dir, filling up the
811 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
812 # :update option, so we have to do it manually.
813 # Note that we use the */** pattern because we don't want to match
814 # keywords.rbot, which gets deleted on load and would therefore be missing
816 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
818 dest = File.join(@botclass, f)
819 FileUtils.mkdir_p(File.dirname(dest))
820 FileUtils.cp File.join(template_dir, f), dest
823 log "no #{@botclass} directory found, creating from templates..."
824 if FileTest.exist? @botclass
825 error "file #{@botclass} exists but isn't a directory"
828 FileUtils.cp_r template_dir, @botclass
832 # Return a path under the current botclass by joining the mentioned
833 # components. The components are automatically converted to String
834 def path(*components)
835 File.join(@botclass, *(components.map {|c| c.to_s}))
838 def setup_plugins_path
839 plugdir_default = File.join(Config::datadir, 'plugins')
840 plugdir_local = File.join(@botclass, 'plugins')
841 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
843 @plugins.clear_botmodule_dirs
844 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
845 @plugins.add_core_module_dir(Config::coredir)
846 if FileTest.directory? plugdir_local
847 @plugins.add_plugin_dir(plugdir_local)
849 warning "local plugin location #{plugdir_local} is not a directory"
852 @config['plugins.path'].each do |_|
853 path = _.sub(/^\(default\)/, plugdir_default)
854 @plugins.add_plugin_dir(path)
858 def set_default_send_options(opts={})
859 # Default send options for NOTICE and PRIVMSG
860 unless defined? @default_send_options
861 @default_send_options = {
862 :queue_channel => nil, # use default queue channel
863 :queue_ring => nil, # use default queue ring
864 :newlines => :split, # or :join
865 :join_with => ' ', # by default, use a single space
866 :max_lines => 0, # maximum number of lines to send with a single command
867 :overlong => :split, # or :truncate
868 # TODO an array of splitpoints would be preferrable for this option:
869 :split_at => /\s+/, # by default, split overlong lines at whitespace
870 :purge_split => true, # should the split string be removed?
871 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
874 @default_send_options.update opts unless opts.empty?
877 # checks if we should be quiet on a channel
878 def quiet_on?(channel)
879 ch = channel.downcase
880 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
883 def set_quiet(channel = nil)
885 ch = channel.downcase.dup
886 @not_quiet.delete(ch)
895 def reset_quiet(channel = nil)
897 ch = channel.downcase.dup
906 # things to do when we receive a signal
907 def got_sig(sig, func=:quit)
908 debug "received #{sig}, queueing #{func}"
909 # this is not an interruption if we just need to reconnect
910 $interrupted += 1 unless func == :reconnect
911 self.send(func) unless @quit_mutex.locked?
912 debug "interrupted #{$interrupted} times"
923 trap("SIGINT") { got_sig("SIGINT") }
924 trap("SIGTERM") { got_sig("SIGTERM") }
925 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
926 trap("SIGUSR1") { got_sig("SIGUSR1", :reconnect) }
927 rescue ArgumentError => e
928 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
929 rescue Exception => e
930 debug "failed to trap signals: #{e.pretty_inspect}"
934 # connect the bot to IRC
936 # make sure we don't have any spurious ping checks running
937 # (and initialize the vars if this is the first time we connect)
940 quit if $interrupted > 0
943 rescue Exception => e
944 uri = @socket.server_uri || '<unknown>'
945 error "failed to connect to IRC server at #{uri}"
949 quit if $interrupted > 0
951 realname = @config['irc.name'].clone || 'Ruby bot'
952 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
954 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
955 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
956 quit if $interrupted > 0
957 myself.nick = @config['irc.nick']
958 myself.user = @config['irc.user']
961 # disconnect the bot from IRC, if connected, and then connect (again)
962 def reconnect(message=nil, too_fast=false)
963 # we will wait only if @last_rec was not nil, i.e. if we were connected or
964 # got disconnected by a network error
965 # if someone wants to manually call disconnect() _and_ reconnect(), they
966 # will have to take care of the waiting themselves
967 will_wait = !!@last_rec
969 if @socket.connected?
975 log "\n\nDisconnected\n\n"
977 quit if $interrupted > 0
979 log "\n\nWaiting to reconnect\n\n"
980 sleep @config['server.reconnect_wait']
981 sleep 10*@config['server.reconnect_wait'] if too_fast
985 rescue Exception => e
991 # begin event handling loop
997 reconnect(quit_msg, too_fast)
998 quit if $interrupted > 0
999 while @socket.connected?
1000 quit if $interrupted > 0
1002 # Wait for messages and process them as they arrive. If nothing is
1003 # received, we call the ping_server() method that will PING the
1004 # server if appropriate, or raise a TimeoutError if no PONG has been
1005 # received in the user-chosen timeout since the last PING sent.
1006 if @socket.select(1)
1007 break unless reply = @socket.gets
1008 @last_rec = Time.now
1009 @client.process reply
1015 # I despair of this. Some of my users get "connection reset by peer"
1016 # exceptions that ARENT SocketError's. How am I supposed to handle
1021 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1022 error "network exception: #{e.pretty_inspect}"
1024 rescue ServerError => e
1025 # received an ERROR from the server
1026 quit_msg = "server ERROR: " + e.message
1027 too_fast = e.message.index("reconnect too fast")
1030 fatal "fatal db error: #{e.pretty_inspect}"
1032 # Why restart? DB problems are serious stuff ...
1033 # restart("Oops, we seem to have registry problems ...")
1036 rescue Exception => e
1037 error "non-net exception: #{e.pretty_inspect}"
1040 fatal "unexpected exception: #{e.pretty_inspect}"
1047 # type:: message type
1048 # where:: message target
1049 # message:: message text
1050 # send message +message+ of type +type+ to target +where+
1051 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1052 # relevant say() or notice() methods. This one should be used for IRCd
1053 # extensions you want to use in modules.
1054 def sendmsg(original_type, original_where, original_message, options={})
1056 # filter message with sendmsg filters
1057 ds = DataStream.new original_message.to_s.dup,
1058 :type => original_type, :dest => original_where,
1059 :options => @default_send_options.merge(options)
1060 filters = filter_names(:sendmsg)
1061 filters.each do |fname|
1062 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1063 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1069 filtered = ds[:text]
1071 # For starters, set up appropriate queue channels and rings
1072 mchan = opts[:queue_channel]
1073 mring = opts[:queue_ring]
1090 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1092 # if target is a channel with nocolor modes, strip colours
1093 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1094 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1097 messages = Array.new
1098 case opts[:newlines]
1100 messages << [multi_line.gsub("\n", opts[:join_with])]
1102 multi_line.each_line { |line|
1104 next unless(line.size > 0)
1108 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1111 # The IRC protocol requires that each raw message must be not longer
1112 # than 512 characters. From this length with have to subtract the EOL
1113 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1114 # that will be prepended by the server to all of our messages.
1116 # The maximum raw message length we can send is therefore 512 - 2 - 2
1117 # minus the length of our hostmask.
1119 max_len = 508 - myself.fullform.size
1121 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1122 # will have a + or - prepended
1123 if server.capabilities[:"identify-msg"]
1127 # When splitting the message, we'll be prefixing the following string:
1128 # (e.g. "PRIVMSG #rbot :")
1129 fixed = "#{type} #{where} :"
1131 # And this is what's left
1132 left = max_len - fixed.size
1134 truncate = opts[:truncate_text]
1135 truncate = @default_send_options[:truncate_text] if truncate.size > left
1136 truncate = "" if truncate.size > left
1138 all_lines = messages.map { |line|
1142 case opts[:overlong]
1145 sub_lines = Array.new
1147 sub_lines << msg.slice!(0, left)
1149 lastspace = sub_lines.last.rindex(opts[:split_at])
1151 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1152 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1154 end until msg.empty?
1157 line.slice(0, left - truncate.size) << truncate
1159 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1164 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1165 lines = all_lines[0...opts[:max_lines]]
1166 new_last = lines.last.slice(0, left - truncate.size) << truncate
1167 lines.last.replace(new_last)
1173 sendq "#{fixed}#{line}", chan, ring
1174 delegate_sent(type, where, line)
1178 # queue an arbitraty message for the server
1179 def sendq(message="", chan=nil, ring=0)
1181 @socket.queue(message, chan, ring)
1184 # send a notice message to channel/nick +where+
1185 def notice(where, message, options={})
1186 return if where.kind_of?(Channel) and quiet_on?(where)
1187 sendmsg "NOTICE", where, message, options
1190 # say something (PRIVMSG) to channel/nick +where+
1191 def say(where, message, options={})
1192 return if where.kind_of?(Channel) and quiet_on?(where)
1193 sendmsg "PRIVMSG", where, message, options
1196 def ctcp_notice(where, command, message, options={})
1197 return if where.kind_of?(Channel) and quiet_on?(where)
1198 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1201 def ctcp_say(where, command, message, options={})
1202 return if where.kind_of?(Channel) and quiet_on?(where)
1203 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1206 # perform a CTCP action with message +message+ to channel/nick +where+
1207 def action(where, message, options={})
1208 ctcp_say(where, 'ACTION', message, options)
1211 # quick way to say "okay" (or equivalent) to +where+
1213 say where, @lang.get("okay")
1216 # set topic of channel +where+ to +topic+
1217 # can also be used to retrieve the topic of channel +where+
1218 # by omitting the last argument
1219 def topic(where, topic=nil)
1221 sendq "TOPIC #{where}", where, 2
1223 sendq "TOPIC #{where} :#{topic}", where, 2
1227 def disconnect(message=nil)
1228 message = @lang.get("quit") if (!message || message.empty?)
1229 if @socket.connected?
1231 debug "Clearing socket"
1233 debug "Sending quit message"
1234 @socket.emergency_puts "QUIT :#{message}"
1235 debug "Logging quits"
1236 delegate_sent('QUIT', myself, message)
1237 debug "Flushing socket"
1239 rescue SocketError => e
1240 error "error while disconnecting socket: #{e.pretty_inspect}"
1242 debug "Shutting down socket"
1249 # disconnect from the server and cleanup all plugins and modules
1250 def shutdown(message=nil)
1251 @quit_mutex.synchronize do
1252 debug "Shutting down: #{message}"
1253 ## No we don't restore them ... let everything run through
1255 # trap("SIGINT", "DEFAULT")
1256 # trap("SIGTERM", "DEFAULT")
1257 # trap("SIGHUP", "DEFAULT")
1259 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1261 debug "\tdisconnecting..."
1263 debug "\tstopping timer..."
1265 debug "\tsaving ..."
1267 debug "\tcleaning up ..."
1268 @save_mutex.synchronize do
1271 # debug "\tstopping timers ..."
1273 # debug "Closing registries"
1275 debug "\t\tcleaning up the db environment ..."
1277 log "rbot quit (#{message})"
1281 # message:: optional IRC quit message
1282 # quit IRC, shutdown the bot
1283 def quit(message=nil)
1291 # totally shutdown and respawn the bot
1292 def restart(message=nil)
1293 message = _("restarting, back in %{wait}...") % {
1294 :wait => @config['server.reconnect_wait']
1295 } if (!message || message.empty?)
1297 sleep @config['server.reconnect_wait']
1300 # Note, this fails on Windows
1301 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1305 rescue Errno::ENOENT
1307 exec("ruby", *(@argv.unshift $0))
1308 rescue Exception => e
1314 # call the save method for all of the botmodules
1316 @save_mutex.synchronize do
1322 # call the rescan method for all of the botmodules
1324 debug "\tstopping timer..."
1326 @save_mutex.synchronize do
1333 # channel:: channel to join
1334 # key:: optional channel key if channel is +s
1336 def join(channel, key=nil)
1338 sendq "JOIN #{channel} :#{key}", channel, 2
1340 sendq "JOIN #{channel}", channel, 2
1345 def part(channel, message="")
1346 sendq "PART #{channel} :#{message}", channel, 2
1349 # attempt to change bot's nick to +name+
1351 sendq "NICK #{name}"
1355 def mode(channel, mode, target=nil)
1356 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1360 def whois(nick, target=nil)
1361 sendq "WHOIS #{target} #{nick}", nil, 0
1365 def kick(channel, user, msg)
1366 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1369 # m:: message asking for help
1370 # topic:: optional topic help is requested for
1371 # respond to online help requests
1373 topic = nil if topic == ""
1376 helpstr = _("help topics: ")
1377 helpstr += @plugins.helptopics
1378 helpstr += _(" (help <topic> for more info)")
1380 unless(helpstr = @plugins.help(topic))
1381 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1387 # returns a string describing the current status of the bot (uptime etc)
1389 secs_up = Time.new - @startup_time
1390 uptime = Utils.secs_to_string secs_up
1391 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1392 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1394 :up => uptime, :plug => @plugins.length,
1395 :sent => @socket.lines_sent, :recv => @socket.lines_received
1399 # We want to respond to a hung server in a timely manner. If nothing was received
1400 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1401 # the server. If the PONG is not received within the user-defined timeout, we
1402 # assume we're in ping timeout and act accordingly.
1404 act_timeout = @config['server.ping_timeout']
1405 return if act_timeout <= 0
1407 if @last_rec && now > @last_rec + act_timeout
1409 # No previous PING pending, send a new one
1411 @last_ping = Time.now
1413 diff = now - @last_ping
1414 if diff > act_timeout
1415 debug "no PONG from server in #{diff} seconds, reconnecting"
1416 # the actual reconnect is handled in the main loop:
1417 raise TimeoutError, "no PONG from server in #{diff} seconds"
1423 def stop_server_pings
1424 # cancel previous PINGs and reset time of last RECV
1431 # delegate sent messages
1432 def delegate_sent(type, where, message)
1433 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1436 m = NoticeMessage.new(*args)
1438 m = PrivMessage.new(*args)
1440 m = QuitMessage.new(*args)
1441 m.was_on = myself.channels
1443 @plugins.delegate('sent', m)