13 $debug = false unless $debug
14 $daemonize = false unless $daemonize
16 $dateformat = "%Y/%m/%d %H:%M:%S"
17 $logger = Logger.new($stderr)
18 $logger.datetime_format = $dateformat
19 $logger.level = $cl_loglevel if defined? $cl_loglevel
20 $logger.level = 0 if $debug
22 $log_queue = Queue.new
27 unless Kernel.respond_to? :pretty_inspect
31 public :pretty_inspect
36 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
37 if self.backtrace and not self.backtrace.empty?
39 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
45 class ServerError < RuntimeError
48 def rawlog(level, message=nil, who_pos=1)
50 if call_stack.length > who_pos
51 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
55 # Output each line. To distinguish between separate messages and multi-line
56 # messages originating at the same time, we blank #{who} after the first message
58 # Also, we output strings as-is but for other objects we use pretty_inspect
63 str = message.pretty_inspect rescue '?'
67 qmsg.push [level, l.chomp, who]
70 if level == Logger::Severity::ERROR or level == Logger::Severity::FATAL and not $daemonize
77 if $log_thread && $log_thread.alive?
86 def restart_logger(newlogger = false)
89 $logger = newlogger if newlogger
91 $log_thread = Thread.new do
93 while ls = $log_queue.pop
94 ls.each { |l| $logger.add(*l) }
101 def log_session_start
102 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
107 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
111 def debug(message=nil, who_pos=1)
112 rawlog(Logger::Severity::DEBUG, message, who_pos)
115 def log(message=nil, who_pos=1)
116 rawlog(Logger::Severity::INFO, message, who_pos)
119 def warning(message=nil, who_pos=1)
120 rawlog(Logger::Severity::WARN, message, who_pos)
123 def error(message=nil, who_pos=1)
124 rawlog(Logger::Severity::ERROR, message, who_pos)
127 def fatal(message=nil, who_pos=1)
128 rawlog(Logger::Severity::FATAL, message, who_pos)
133 warning "warning test"
137 # The following global is used for the improved signal handling.
141 require 'rbot/rbotconfig'
145 log "rubygems unavailable"
148 require 'rbot/load-gettext'
149 require 'rbot/config'
152 require 'rbot/rfc2812'
153 require 'rbot/ircsocket'
154 require 'rbot/botuser'
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) Tom Gilbert 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 # server we are connected to
204 # bot User in the client/server connection
210 # bot nick in the client/server connection
215 # bot channels in the client/server connection
220 # nick wanted by the bot. This defaults to the irc.nick config value,
221 # but may be overridden by a manual !nick command
223 @wanted_nick || config['irc.nick']
226 # set the nick wanted by the bot
228 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
231 @wanted_nick = wn.to_s.dup
239 ret = self.to_s[0..-2]
240 ret << ' version=' << $version.inspect
241 ret << ' botclass=' << botclass.inspect
242 ret << ' lang="' << lang.language
247 ret << ' nick=' << nick.inspect
250 ret << (server.to_s + (socket ?
251 ' [' << socket.server_uri.to_s << ']' : '')).inspect
252 unless server.channels.empty?
254 ret << server.channels.map { |c|
255 "%s%s" % [c.modes_of(nick).map { |m|
256 server.prefix_for_mode(m)
263 ret << ' plugins=' << plugins.inspect
268 # create a new Bot with botclass +botclass+
269 def initialize(botclass, params = {})
270 # Config for the core bot
271 # TODO should we split socket stuff into ircsocket, etc?
272 Config.register Config::ArrayValue.new('server.list',
273 :default => ['irc://localhost'], :wizard => true,
274 :requires_restart => true,
275 :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.")
276 Config.register Config::BooleanValue.new('server.ssl',
277 :default => false, :requires_restart => true, :wizard => true,
278 :desc => "Use SSL to connect to this server?")
279 Config.register Config::BooleanValue.new('server.ssl_verify',
280 :default => false, :requires_restart => true,
281 :desc => "Verify the SSL connection?",
283 Config.register Config::StringValue.new('server.ssl_ca_file',
284 :default => default_ssl_ca_file, :requires_restart => true,
285 :desc => "The CA file used to verify the SSL connection.",
287 Config.register Config::StringValue.new('server.ssl_ca_path',
288 :default => '', :requires_restart => true,
289 :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
291 Config.register Config::StringValue.new('server.password',
292 :default => false, :requires_restart => true,
293 :desc => "Password for connecting to this server (if required)",
295 Config.register Config::StringValue.new('server.bindhost',
296 :default => false, :requires_restart => true,
297 :desc => "Specific local host or IP for the bot to bind to (if required)",
299 Config.register Config::IntegerValue.new('server.reconnect_wait',
300 :default => 5, :validate => Proc.new{|v| v >= 0},
301 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
302 Config.register Config::IntegerValue.new('server.ping_timeout',
303 :default => 30, :validate => Proc.new{|v| v >= 0},
304 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
305 Config.register Config::ArrayValue.new('server.nocolor_modes',
306 :default => ['c'], :wizard => false,
307 :requires_restart => false,
308 :desc => "List of channel modes that require messages to be without colors")
310 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
311 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
312 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
313 Config.register Config::StringValue.new('irc.name',
314 :default => "Ruby bot", :requires_restart => true,
315 :desc => "IRC realname the bot should use")
316 Config.register Config::BooleanValue.new('irc.name_copyright',
317 :default => true, :requires_restart => true,
318 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
319 Config.register Config::StringValue.new('irc.user', :default => "rbot",
320 :requires_restart => true,
321 :desc => "local user the bot should appear to be", :wizard => true)
322 Config.register Config::ArrayValue.new('irc.join_channels',
323 :default => [], :wizard => true,
324 :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'")
325 Config.register Config::ArrayValue.new('irc.ignore_users',
327 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
328 Config.register Config::ArrayValue.new('irc.ignore_channels',
330 :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)")
332 Config.register Config::IntegerValue.new('core.save_every',
333 :default => 60, :validate => Proc.new{|v| v >= 0},
334 :on_change => Proc.new { |bot, v|
337 @timer.reschedule(@save_timer, v)
338 @timer.unblock(@save_timer)
340 @timer.block(@save_timer)
344 @save_timer = @timer.add(v) { bot.save }
346 # Nothing to do when v == 0
349 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
351 Config.register Config::BooleanValue.new('core.run_as_daemon',
352 :default => false, :requires_restart => true,
353 :desc => "Should the bot run as a daemon?")
355 Config.register Config::StringValue.new('log.file',
356 :default => false, :requires_restart => true,
357 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
358 Config.register Config::IntegerValue.new('log.level',
359 :default => 1, :requires_restart => false,
360 :validate => Proc.new { |v| (0..5).include?(v) },
361 :on_change => Proc.new { |bot, v|
364 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
365 Config.register Config::IntegerValue.new('log.keep',
366 :default => 1, :requires_restart => true,
367 :validate => Proc.new { |v| v >= 0 },
368 :desc => "How many old console messages logfiles to keep")
369 Config.register Config::IntegerValue.new('log.max_size',
370 :default => 10, :requires_restart => true,
371 :validate => Proc.new { |v| v > 0 },
372 :desc => "Maximum console messages logfile size (in megabytes)")
374 Config.register Config::ArrayValue.new('plugins.path',
375 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
376 :requires_restart => false,
377 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
378 :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")
380 Config.register Config::EnumValue.new('send.newlines',
381 :values => ['split', 'join'], :default => 'split',
382 :on_change => Proc.new { |bot, v|
383 bot.set_default_send_options :newlines => v.to_sym
385 :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")
386 Config.register Config::StringValue.new('send.join_with',
388 :on_change => Proc.new { |bot, v|
389 bot.set_default_send_options :join_with => v.dup
391 :desc => "String used to replace newlines when send.newlines is set to join")
392 Config.register Config::IntegerValue.new('send.max_lines',
394 :validate => Proc.new { |v| v >= 0 },
395 :on_change => Proc.new { |bot, v|
396 bot.set_default_send_options :max_lines => v
398 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
399 Config.register Config::EnumValue.new('send.overlong',
400 :values => ['split', 'truncate'], :default => 'split',
401 :on_change => Proc.new { |bot, v|
402 bot.set_default_send_options :overlong => v.to_sym
404 :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")
405 Config.register Config::StringValue.new('send.split_at',
407 :on_change => Proc.new { |bot, v|
408 bot.set_default_send_options :split_at => Regexp.new(v)
410 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
411 Config.register Config::BooleanValue.new('send.purge_split',
413 :on_change => Proc.new { |bot, v|
414 bot.set_default_send_options :purge_split => v
416 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
417 Config.register Config::StringValue.new('send.truncate_text',
418 :default => "#{Reverse}...#{Reverse}",
419 :on_change => Proc.new { |bot, v|
420 bot.set_default_send_options :truncate_text => v.dup
422 :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")
423 Config.register Config::IntegerValue.new('send.penalty_pct',
425 :validate => Proc.new { |v| v >= 0 },
426 :on_change => Proc.new { |bot, v|
427 bot.socket.penalty_pct = v
429 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
430 Config.register Config::StringValue.new('core.db',
432 :wizard => true, :default => "dbm",
433 :validate => Proc.new { |v| ["dbm", "daybreak"].include? v },
434 :requires_restart => true,
435 :desc => "DB adaptor to use for storing the plugin data/registries. Options: dbm (included in ruby), daybreak")
437 @argv = params[:argv]
438 @run_dir = params[:run_dir] || Dir.pwd
440 unless FileTest.directory? Config::coredir
441 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
445 unless FileTest.directory? Config::datadir
446 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
450 unless botclass and not botclass.empty?
451 # We want to find a sensible default.
452 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
453 # * On Windows (at least the NT versions) we want to put our stuff in the
454 # Application Data folder.
455 # We don't use any particular O/S detection magic, exploiting the fact that
456 # Etc.getpwuid is nil on Windows
457 if Etc.getpwuid(Process::Sys.geteuid)
458 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
460 if ENV.has_key?('APPDATA')
461 botclass = ENV['APPDATA'].dup
462 botclass.gsub!("\\","/")
465 botclass = File.join(botclass, ".rbot")
467 botclass = File.expand_path(botclass)
468 @botclass = botclass.gsub(/\/$/, "")
470 repopulate_botclass_directory
472 save_dir = File.join(@botclass, 'safe_save')
473 Dir.mkdir(save_dir) unless File.exist?(save_dir)
474 unless FileTest.directory? save_dir
475 error "safe save location #{save_dir} is not a directory"
479 # Time at which the last PING was sent
481 # Time at which the last line was RECV'd from the server
484 @startup_time = Time.new
487 @config = Config.manager
488 @config.bot_associate(self)
489 rescue Exception => e
495 if @config['core.run_as_daemon']
499 case @config["core.db"]
501 require 'rbot/registry/dbm'
503 require 'rbot/registry/daybreak'
505 raise _("Unknown DB adaptor: %s") % @config["core.db"]
508 @logfile = @config['log.file']
509 if @logfile.class!=String || @logfile.empty?
510 logfname = File.basename(botclass).gsub(/^\.+/,'')
512 @logfile = File.join(botclass, logfname)
513 debug "Using `#{@logfile}' as debug log"
516 # See http://blog.humlab.umu.se/samuel/archives/000107.html
517 # for the backgrounding code
523 rescue NotImplementedError
524 warning "Could not background, fork not supported"
527 rescue Exception => e
528 warning "Could not background. #{e.pretty_inspect}"
531 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
534 logger = Logger.new(@logfile,
536 @config['log.max_size']*1024*1024)
537 logger.datetime_format= $dateformat
538 logger.level = @config['log.level']
539 logger.level = $cl_loglevel if defined? $cl_loglevel
540 logger.level = 0 if $debug
542 restart_logger(logger)
547 log "Redirecting standard input/output/error"
548 [$stdin, $stdout, $stderr].each do |fd|
550 fd.reopen "/dev/null"
552 # On Windows, there's not such thing as /dev/null
557 def $stdout.write(str=nil)
561 def $stdout.write(str=nil)
562 if str.to_s.match(/:\d+: warning:/)
571 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
576 @save_mutex = Mutex.new
577 if @config['core.save_every'] > 0
578 @save_timer = @timer.add(@config['core.save_every']) { save }
582 @quit_mutex = Mutex.new
585 @lang = Language.new(self, @config['core.language'])
588 @auth = Auth::manager
589 @auth.bot_associate(self)
590 # @auth.load("#{botclass}/botusers.yaml")
591 rescue Exception => e
596 @auth.everyone.set_default_permission("*", true)
597 @auth.botowner.password= @config['auth.password']
599 @plugins = Plugins::manager
600 @plugins.bot_associate(self)
603 if @config['server.name']
604 debug "upgrading configuration (server.name => server.list)"
605 srv_uri = 'irc://' + @config['server.name']
606 srv_uri += ":#{@config['server.port']}" if @config['server.port']
607 @config.items['server.list'.to_sym].set_string(srv_uri)
608 @config.delete('server.name'.to_sym)
609 @config.delete('server.port'.to_sym)
610 debug "server.list is now #{@config['server.list'].inspect}"
613 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'],
614 :ssl => @config['server.ssl'],
615 :ssl_verify => @config['server.ssl_verify'],
616 :ssl_ca_file => @config['server.ssl_ca_file'],
617 :ssl_ca_path => @config['server.ssl_ca_path'],
618 :penalty_pct => @config['send.penalty_pct'])
623 # Channels where we are quiet
624 # Array of channels names where the bot should be quiet
625 # '*' means all channels
628 # but we always speak here
631 # the nick we want, if it's different from the irc.nick config value
632 # (e.g. as set by a !nick command)
635 @client[:welcome] = proc {|data|
636 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
638 @plugins.delegate("welcome", m)
639 @plugins.delegate("connect")
642 # TODO the next two @client should go into rfc2812.rb, probably
643 # Since capabs are two-steps processes, server.supports[:capab]
644 # should be a three-state: nil, [], [....]
645 asked_for = { :"identify-msg" => false }
646 @client[:isupport] = proc { |data|
647 if server.supports[:capab] and !asked_for[:"identify-msg"]
648 sendq "CAPAB IDENTIFY-MSG"
649 asked_for[:"identify-msg"] = true
652 @client[:datastr] = proc { |data|
653 if data[:text] == "IDENTIFY-MSG"
654 server.capabilities[:"identify-msg"] = true
656 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
660 @client[:privmsg] = proc { |data|
661 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
662 # debug "Message source is #{data[:source].inspect}"
663 # debug "Message target is #{data[:target].inspect}"
664 # debug "Bot is #{myself.inspect}"
666 @config['irc.ignore_channels'].each { |channel|
667 if m.target.downcase == channel.downcase
672 @config['irc.ignore_users'].each { |mask|
673 if m.source.matches?(server.new_netmask(mask))
679 @plugins.irc_delegate('privmsg', m)
681 @client[:notice] = proc { |data|
682 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
683 # pass it off to plugins that want to hear everything
684 @plugins.irc_delegate "notice", message
686 @client[:motd] = proc { |data|
687 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
688 @plugins.delegate "motd", m
690 @client[:nicktaken] = proc { |data|
691 new = "#{data[:nick]}_"
693 # If we're setting our nick at connection because our choice was taken,
694 # we have to fix our nick manually, because there will be no NICK message
695 # to inform us that our nick has been changed.
696 if data[:target] == '*'
697 debug "setting my connection nick to #{new}"
700 @plugins.delegate "nicktaken", data[:nick]
702 @client[:badnick] = proc {|data|
703 warning "bad nick (#{data[:nick]})"
705 @client[:ping] = proc {|data|
706 sendq "PONG #{data[:pingid]}"
708 @client[:pong] = proc {|data|
711 @client[:nick] = proc {|data|
712 # debug "Message source is #{data[:source].inspect}"
713 # debug "Bot is #{myself.inspect}"
714 source = data[:source]
717 m = NickMessage.new(self, server, source, old, new)
718 m.is_on = data[:is_on]
720 debug "my nick is now #{new}"
722 @plugins.irc_delegate("nick", m)
724 @client[:quit] = proc {|data|
725 source = data[:source]
726 message = data[:message]
727 m = QuitMessage.new(self, server, source, source, message)
728 m.was_on = data[:was_on]
729 @plugins.irc_delegate("quit", m)
731 @client[:mode] = proc {|data|
732 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
733 m.modes = data[:modes]
734 @plugins.delegate "modechange", m
736 @client[:whois] = proc {|data|
737 source = data[:source]
738 target = server.get_user(data[:whois][:nick])
739 m = WhoisMessage.new(self, server, source, target, data[:whois])
740 @plugins.delegate "whois", m
742 @client[:list] = proc {|data|
743 source = data[:source]
744 m = ListMessage.new(self, server, source, source, data[:list])
745 @plugins.delegate "irclist", m
747 @client[:join] = proc {|data|
748 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
749 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
750 @plugins.irc_delegate("join", m)
751 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
753 @client[:part] = proc {|data|
754 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
755 @plugins.irc_delegate("part", m)
757 @client[:kick] = proc {|data|
758 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
759 @plugins.irc_delegate("kick", m)
761 @client[:invite] = proc {|data|
762 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
763 @plugins.irc_delegate("invite", m)
765 @client[:changetopic] = proc {|data|
766 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
768 @plugins.irc_delegate("topic", m)
770 # @client[:topic] = proc { |data|
771 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
773 @client[:topicinfo] = proc { |data|
774 channel = data[:channel]
775 topic = channel.topic
776 m = TopicMessage.new(self, server, data[:source], channel, topic)
777 m.info_or_set = :info
778 @plugins.irc_delegate("topic", m)
780 @client[:names] = proc { |data|
781 m = NamesMessage.new(self, server, server, data[:channel])
782 m.users = data[:users]
783 @plugins.delegate "names", m
785 @client[:banlist] = proc { |data|
786 m = BanlistMessage.new(self, server, server, data[:channel])
788 @plugins.delegate "banlist", m
790 @client[:nosuchtarget] = proc { |data|
791 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
792 @plugins.delegate "nosuchtarget", m
794 @client[:error] = proc { |data|
795 raise ServerError, data[:message]
797 @client[:unknown] = proc { |data|
798 #debug "UNKNOWN: #{data[:serverstring]}"
799 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
800 @plugins.delegate "unknown_message", m
803 set_default_send_options :newlines => @config['send.newlines'].to_sym,
804 :join_with => @config['send.join_with'].dup,
805 :max_lines => @config['send.max_lines'],
806 :overlong => @config['send.overlong'].to_sym,
807 :split_at => Regexp.new(@config['send.split_at']),
808 :purge_split => @config['send.purge_split'],
809 :truncate_text => @config['send.truncate_text'].dup
814 # Determine (if possible) a valid path to a CA certificate bundle.
815 def default_ssl_ca_file
816 [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
817 '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
818 '/etc/ssl/ca-bundle.pem', # OpenSUSE
819 '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
825 def repopulate_botclass_directory
826 template_dir = File.join Config::datadir, 'templates'
827 if FileTest.directory? @botclass
828 # compare the templates dir with the current botclass dir, filling up the
829 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
830 # :update option, so we have to do it manually.
831 # Note that we use the */** pattern because we don't want to match
832 # keywords.rbot, which gets deleted on load and would therefore be missing
834 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
836 dest = File.join(@botclass, f)
837 FileUtils.mkdir_p(File.dirname(dest))
838 FileUtils.cp File.join(template_dir, f), dest
841 log "no #{@botclass} directory found, creating from templates..."
842 if FileTest.exist? @botclass
843 error "file #{@botclass} exists but isn't a directory"
846 FileUtils.cp_r template_dir, @botclass
850 # Return a path under the current botclass by joining the mentioned
851 # components. The components are automatically converted to String
852 def path(*components)
853 File.join(@botclass, *(components.map {|c| c.to_s}))
856 def setup_plugins_path
857 plugdir_default = File.join(Config::datadir, 'plugins')
858 plugdir_local = File.join(@botclass, 'plugins')
859 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
861 @plugins.clear_botmodule_dirs
862 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
863 @plugins.add_core_module_dir(Config::coredir)
864 if FileTest.directory? plugdir_local
865 @plugins.add_plugin_dir(plugdir_local)
867 warning "local plugin location #{plugdir_local} is not a directory"
870 @config['plugins.path'].each do |_|
871 path = _.sub(/^\(default\)/, plugdir_default)
872 @plugins.add_plugin_dir(path)
876 def set_default_send_options(opts={})
877 # Default send options for NOTICE and PRIVMSG
878 unless defined? @default_send_options
879 @default_send_options = {
880 :queue_channel => nil, # use default queue channel
881 :queue_ring => nil, # use default queue ring
882 :newlines => :split, # or :join
883 :join_with => ' ', # by default, use a single space
884 :max_lines => 0, # maximum number of lines to send with a single command
885 :overlong => :split, # or :truncate
886 # TODO an array of splitpoints would be preferrable for this option:
887 :split_at => /\s+/, # by default, split overlong lines at whitespace
888 :purge_split => true, # should the split string be removed?
889 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
892 @default_send_options.update opts unless opts.empty?
895 # checks if we should be quiet on a channel
896 def quiet_on?(channel)
897 ch = channel.downcase
898 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
901 def set_quiet(channel = nil)
903 ch = channel.downcase.dup
904 @not_quiet.delete(ch)
913 def reset_quiet(channel = nil)
915 ch = channel.downcase.dup
924 # things to do when we receive a signal
925 def handle_signal(sig)
934 debug "received #{sig}, queueing #{func}"
935 # this is not an interruption if we just need to reconnect
936 $interrupted += 1 unless func == :reconnect
937 self.send(func) unless @quit_mutex.locked?
938 debug "interrupted #{$interrupted} times"
949 %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
950 trap(sig) { Thread.new { handle_signal sig } }
952 rescue ArgumentError => e
953 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
954 rescue Exception => e
955 debug "failed to trap signals: #{e.pretty_inspect}"
959 # connect the bot to IRC
961 # make sure we don't have any spurious ping checks running
962 # (and initialize the vars if this is the first time we connect)
965 quit if $interrupted > 0
968 rescue Exception => e
969 uri = @socket.server_uri || '<unknown>'
970 error "failed to connect to IRC server at #{uri}"
974 quit if $interrupted > 0
976 realname = @config['irc.name'].clone || 'Ruby bot'
977 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
979 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
980 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
981 quit if $interrupted > 0
982 myself.nick = @config['irc.nick']
983 myself.user = @config['irc.user']
986 # disconnect the bot from IRC, if connected, and then connect (again)
987 def reconnect(message=nil, too_fast=0)
988 # we will wait only if @last_rec was not nil, i.e. if we were connected or
989 # got disconnected by a network error
990 # if someone wants to manually call disconnect() _and_ reconnect(), they
991 # will have to take care of the waiting themselves
992 will_wait = !!@last_rec
994 if @socket.connected?
1000 log "\n\nDisconnected\n\n"
1002 quit if $interrupted > 0
1004 log "\n\nWaiting to reconnect\n\n"
1005 sleep @config['server.reconnect_wait']
1007 tf = too_fast*@config['server.reconnect_wait']
1008 tfu = Utils.secs_to_string(tf)
1009 log "Will sleep for an extra #{tf}s (#{tfu})"
1018 rescue Exception => e
1025 # begin event handling loop
1030 valid_recv = false # did we receive anything (valid) from the server yet?
1032 reconnect(quit_msg, too_fast)
1033 quit if $interrupted > 0
1035 while @socket.connected?
1036 quit if $interrupted > 0
1038 # Wait for messages and process them as they arrive. If nothing is
1039 # received, we call the ping_server() method that will PING the
1040 # server if appropriate, or raise a TimeoutError if no PONG has been
1041 # received in the user-chosen timeout since the last PING sent.
1042 if @socket.select(1)
1043 break unless reply = @socket.gets
1044 @last_rec = Time.now
1045 @client.process reply
1053 # I despair of this. Some of my users get "connection reset by peer"
1054 # exceptions that ARENT SocketError's. How am I supposed to handle
1059 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1060 error "network exception: #{e.pretty_inspect}"
1062 too_fast += 10 if valid_recv
1063 rescue ServerMessageParseError => e
1064 # if the bot tried reconnecting too often, we can get forcefully
1065 # disconnected by the server, while still receiving an empty message
1066 # wait at least 10 minutes in this case
1069 too_fast = [too_fast, 300].max
1071 log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1073 quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1075 rescue ServerError => e
1076 quit_msg = "server ERROR: " + e.message
1078 idx = e.message.index("connect too fast")
1079 debug "'connect too fast' @ #{idx}"
1082 too_fast += (idx+1)*2
1083 log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1085 idx = e.message.index(/a(uto)kill/i)
1086 debug "'autokill' @ #{idx}"
1088 # we got auto-killed. since we don't have an easy way to tell
1089 # if it's permanent or temporary, we just set a rather high
1090 # reconnection timeout
1092 too_fast += (idx+1)*5
1093 log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1096 rescue Exception => e
1097 error "non-net exception: #{e.pretty_inspect}"
1100 fatal "unexpected exception: #{e.pretty_inspect}"
1107 # type:: message type
1108 # where:: message target
1109 # message:: message text
1110 # send message +message+ of type +type+ to target +where+
1111 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1112 # relevant say() or notice() methods. This one should be used for IRCd
1113 # extensions you want to use in modules.
1114 def sendmsg(original_type, original_where, original_message, options={})
1116 # filter message with sendmsg filters
1117 ds = DataStream.new original_message.to_s.dup,
1118 :type => original_type, :dest => original_where,
1119 :options => @default_send_options.merge(options)
1120 filters = filter_names(:sendmsg)
1121 filters.each do |fname|
1122 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1123 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1129 filtered = ds[:text]
1131 if defined? WebServiceUser and where.instance_of? WebServiceUser
1132 debug 'sendmsg to web service!'
1133 where.response << filtered
1137 # For starters, set up appropriate queue channels and rings
1138 mchan = opts[:queue_channel]
1139 mring = opts[:queue_ring]
1156 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1158 # if target is a channel with nocolor modes, strip colours
1159 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1160 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1163 messages = Array.new
1164 case opts[:newlines]
1166 messages << [multi_line.gsub("\n", opts[:join_with])]
1168 multi_line.each_line { |line|
1170 next unless(line.size > 0)
1174 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1177 # The IRC protocol requires that each raw message must be not longer
1178 # than 512 characters. From this length with have to subtract the EOL
1179 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1180 # that will be prepended by the server to all of our messages.
1182 # The maximum raw message length we can send is therefore 512 - 2 - 2
1183 # minus the length of our hostmask.
1185 max_len = 508 - myself.fullform.size
1187 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1188 # will have a + or - prepended
1189 if server.capabilities[:"identify-msg"]
1193 # When splitting the message, we'll be prefixing the following string:
1194 # (e.g. "PRIVMSG #rbot :")
1195 fixed = "#{type} #{where} :"
1197 # And this is what's left
1198 left = max_len - fixed.size
1200 truncate = opts[:truncate_text]
1201 truncate = @default_send_options[:truncate_text] if truncate.size > left
1202 truncate = "" if truncate.size > left
1204 all_lines = messages.map { |line|
1208 case opts[:overlong]
1211 sub_lines = Array.new
1213 sub_lines << msg.slice!(0, left)
1215 lastspace = sub_lines.last.rindex(opts[:split_at])
1217 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1218 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1220 end until msg.empty?
1223 line.slice(0, left - truncate.size) << truncate
1225 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1230 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1231 lines = all_lines[0...opts[:max_lines]]
1232 new_last = lines.last.slice(0, left - truncate.size) << truncate
1233 lines.last.replace(new_last)
1239 sendq "#{fixed}#{line}", chan, ring
1240 delegate_sent(type, where, line)
1244 # queue an arbitraty message for the server
1245 def sendq(message="", chan=nil, ring=0)
1247 @socket.queue(message, chan, ring)
1250 # send a notice message to channel/nick +where+
1251 def notice(where, message, options={})
1252 return if where.kind_of?(Channel) and quiet_on?(where)
1253 sendmsg "NOTICE", where, message, options
1256 # say something (PRIVMSG) to channel/nick +where+
1257 def say(where, message, options={})
1258 return if where.kind_of?(Channel) and quiet_on?(where)
1259 sendmsg "PRIVMSG", where, message, options
1262 def ctcp_notice(where, command, message, options={})
1263 return if where.kind_of?(Channel) and quiet_on?(where)
1264 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1267 def ctcp_say(where, command, message, options={})
1268 return if where.kind_of?(Channel) and quiet_on?(where)
1269 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1272 # perform a CTCP action with message +message+ to channel/nick +where+
1273 def action(where, message, options={})
1274 ctcp_say(where, 'ACTION', message, options)
1277 # quick way to say "okay" (or equivalent) to +where+
1279 say where, @lang.get("okay")
1282 # set topic of channel +where+ to +topic+
1283 # can also be used to retrieve the topic of channel +where+
1284 # by omitting the last argument
1285 def topic(where, topic=nil)
1287 sendq "TOPIC #{where}", where, 2
1289 sendq "TOPIC #{where} :#{topic}", where, 2
1293 def disconnect(message=nil)
1294 message = @lang.get("quit") if (!message || message.empty?)
1295 if @socket.connected?
1297 debug "Clearing socket"
1299 debug "Sending quit message"
1300 @socket.emergency_puts "QUIT :#{message}"
1301 debug "Logging quits"
1302 delegate_sent('QUIT', myself, message)
1303 debug "Flushing socket"
1305 rescue SocketError => e
1306 error "error while disconnecting socket: #{e.pretty_inspect}"
1308 debug "Shutting down socket"
1315 # disconnect from the server and cleanup all plugins and modules
1316 def shutdown(message=nil)
1317 @quit_mutex.synchronize do
1318 debug "Shutting down: #{message}"
1319 ## No we don't restore them ... let everything run through
1321 # trap("SIGINT", "DEFAULT")
1322 # trap("SIGTERM", "DEFAULT")
1323 # trap("SIGHUP", "DEFAULT")
1325 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1327 debug "\tdisconnecting..."
1329 debug "\tstopping timer..."
1331 debug "\tsaving ..."
1333 debug "\tcleaning up ..."
1334 @save_mutex.synchronize do
1338 debug "\tignoring cleanup error: #{$!}"
1341 # debug "\tstopping timers ..."
1343 # debug "Closing registries"
1345 log "rbot quit (#{message})"
1349 # message:: optional IRC quit message
1350 # quit IRC, shutdown the bot
1351 def quit(message=nil)
1359 # totally shutdown and respawn the bot
1360 def restart(message=nil)
1361 message = _("restarting, back in %{wait}...") % {
1362 :wait => @config['server.reconnect_wait']
1363 } if (!message || message.empty?)
1365 sleep @config['server.reconnect_wait']
1368 # Note, this fails on Windows
1369 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1373 rescue Errno::ENOENT
1375 exec("ruby", *(@argv.unshift $0))
1376 rescue Exception => e
1382 # call the save method for all of the botmodules
1384 @save_mutex.synchronize do
1389 # call the rescan method for all of the botmodules
1391 debug "\tstopping timer..."
1393 @save_mutex.synchronize do
1400 # channel:: channel to join
1401 # key:: optional channel key if channel is +s
1403 def join(channel, key=nil)
1405 sendq "JOIN #{channel} :#{key}", channel, 2
1407 sendq "JOIN #{channel}", channel, 2
1412 def part(channel, message="")
1413 sendq "PART #{channel} :#{message}", channel, 2
1416 # attempt to change bot's nick to +name+
1418 sendq "NICK #{name}"
1422 def mode(channel, mode, target=nil)
1423 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1427 def whois(nick, target=nil)
1428 sendq "WHOIS #{target} #{nick}", nil, 0
1432 def kick(channel, user, msg)
1433 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1436 # m:: message asking for help
1437 # topic:: optional topic help is requested for
1438 # respond to online help requests
1440 topic = nil if topic == ""
1443 helpstr = _("help topics: ")
1444 helpstr += @plugins.helptopics
1445 helpstr += _(" (help <topic> for more info)")
1447 unless(helpstr = @plugins.help(topic))
1448 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1454 # returns a string describing the current status of the bot (uptime etc)
1456 secs_up = Time.new - @startup_time
1457 uptime = Utils.secs_to_string secs_up
1458 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1459 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1461 :up => uptime, :plug => @plugins.length,
1462 :sent => @socket.lines_sent, :recv => @socket.lines_received
1466 # We want to respond to a hung server in a timely manner. If nothing was received
1467 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1468 # the server. If the PONG is not received within the user-defined timeout, we
1469 # assume we're in ping timeout and act accordingly.
1471 act_timeout = @config['server.ping_timeout']
1472 return if act_timeout <= 0
1474 if @last_rec && now > @last_rec + act_timeout
1476 # No previous PING pending, send a new one
1478 @last_ping = Time.now
1480 diff = now - @last_ping
1481 if diff > act_timeout
1482 debug "no PONG from server in #{diff} seconds, reconnecting"
1483 # the actual reconnect is handled in the main loop:
1484 raise TimeoutError, "no PONG from server in #{diff} seconds"
1490 def stop_server_pings
1491 # cancel previous PINGs and reset time of last RECV
1498 # delegate sent messages
1499 def delegate_sent(type, where, message)
1500 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1503 m = NoticeMessage.new(*args)
1505 m = PrivMessage.new(*args)
1507 m = QuitMessage.new(*args)
1508 m.was_on = myself.channels
1510 @plugins.delegate('sent', m)