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]
74 if $log_thread && $log_thread.alive?
83 def restart_logger(newlogger = false)
86 $logger = newlogger if newlogger
88 $log_thread = Thread.new do
90 while ls = $log_queue.pop
91 ls.each { |l| $logger.add(*l) }
99 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
104 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
108 def debug(message=nil, who_pos=1)
109 rawlog(Logger::Severity::DEBUG, message, who_pos)
112 def log(message=nil, who_pos=1)
113 rawlog(Logger::Severity::INFO, message, who_pos)
116 def warning(message=nil, who_pos=1)
117 rawlog(Logger::Severity::WARN, message, who_pos)
120 def error(message=nil, who_pos=1)
121 rawlog(Logger::Severity::ERROR, message, who_pos)
124 def fatal(message=nil, who_pos=1)
125 rawlog(Logger::Severity::FATAL, message, who_pos)
130 warning "warning test"
134 # The following global is used for the improved signal handling.
138 require 'rbot/rbotconfig'
142 log "rubygems unavailable"
145 require 'rbot/load-gettext'
146 require 'rbot/config'
147 require 'rbot/config-compat'
150 require 'rbot/rfc2812'
151 require 'rbot/ircsocket'
152 require 'rbot/botuser'
154 require 'rbot/plugins'
155 require 'rbot/message'
156 require 'rbot/language'
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 plugins. This is an instance of class Plugins
192 # bot's httputil helper object, for fetching resources via http. Sets up
193 # proxies etc as defined by the bot configuration/environment
194 attr_accessor :httputil
196 # server we are connected to
202 # bot User in the client/server connection
208 # bot nick in the client/server connection
213 # bot channels in the client/server connection
218 # nick wanted by the bot. This defaults to the irc.nick config value,
219 # but may be overridden by a manual !nick command
221 @wanted_nick || config['irc.nick']
224 # set the nick wanted by the bot
226 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
229 @wanted_nick = wn.to_s.dup
237 ret = self.to_s[0..-2]
238 ret << ' version=' << $version.inspect
239 ret << ' botclass=' << botclass.inspect
240 ret << ' lang="' << lang.language
245 ret << ' nick=' << nick.inspect
248 ret << (server.to_s + (socket ?
249 ' [' << socket.server_uri.to_s << ']' : '')).inspect
250 unless server.channels.empty?
252 ret << server.channels.map { |c|
253 "%s%s" % [c.modes_of(nick).map { |m|
254 server.prefix_for_mode(m)
261 ret << ' plugins=' << plugins.inspect
266 # create a new Bot with botclass +botclass+
267 def initialize(botclass, params = {})
268 # Config for the core bot
269 # TODO should we split socket stuff into ircsocket, etc?
270 Config.register Config::ArrayValue.new('server.list',
271 :default => ['irc://localhost'], :wizard => true,
272 :requires_restart => true,
273 :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.")
274 Config.register Config::BooleanValue.new('server.ssl',
275 :default => false, :requires_restart => true, :wizard => true,
276 :desc => "Use SSL to connect to this server?")
277 Config.register Config::BooleanValue.new('server.ssl_verify',
278 :default => false, :requires_restart => true,
279 :desc => "Verify the SSL connection?",
281 Config.register Config::StringValue.new('server.ssl_ca_file',
282 :default => default_ssl_ca_file, :requires_restart => true,
283 :desc => "The CA file used to verify the SSL connection.",
285 Config.register Config::StringValue.new('server.ssl_ca_path',
286 :default => '', :requires_restart => true,
287 :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
289 Config.register Config::StringValue.new('server.password',
290 :default => false, :requires_restart => true,
291 :desc => "Password for connecting to this server (if required)",
293 Config.register Config::StringValue.new('server.bindhost',
294 :default => false, :requires_restart => true,
295 :desc => "Specific local host or IP for the bot to bind to (if required)",
297 Config.register Config::IntegerValue.new('server.reconnect_wait',
298 :default => 5, :validate => Proc.new{|v| v >= 0},
299 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
300 Config.register Config::IntegerValue.new('server.ping_timeout',
301 :default => 30, :validate => Proc.new{|v| v >= 0},
302 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
303 Config.register Config::ArrayValue.new('server.nocolor_modes',
304 :default => ['c'], :wizard => false,
305 :requires_restart => false,
306 :desc => "List of channel modes that require messages to be without colors")
308 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
309 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
310 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
311 Config.register Config::StringValue.new('irc.name',
312 :default => "Ruby bot", :requires_restart => true,
313 :desc => "IRC realname the bot should use")
314 Config.register Config::BooleanValue.new('irc.name_copyright',
315 :default => true, :requires_restart => true,
316 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
317 Config.register Config::StringValue.new('irc.user', :default => "rbot",
318 :requires_restart => true,
319 :desc => "local user the bot should appear to be", :wizard => true)
320 Config.register Config::ArrayValue.new('irc.join_channels',
321 :default => [], :wizard => true,
322 :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'")
323 Config.register Config::ArrayValue.new('irc.ignore_users',
325 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
326 Config.register Config::ArrayValue.new('irc.ignore_channels',
328 :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)")
330 Config.register Config::IntegerValue.new('core.save_every',
331 :default => 60, :validate => Proc.new{|v| v >= 0},
332 :on_change => Proc.new { |bot, v|
335 @timer.reschedule(@save_timer, v)
336 @timer.unblock(@save_timer)
338 @timer.block(@save_timer)
342 @save_timer = @timer.add(v) { bot.save }
344 # Nothing to do when v == 0
347 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
349 Config.register Config::BooleanValue.new('core.run_as_daemon',
350 :default => false, :requires_restart => true,
351 :desc => "Should the bot run as a daemon?")
353 Config.register Config::StringValue.new('log.file',
354 :default => false, :requires_restart => true,
355 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
356 Config.register Config::IntegerValue.new('log.level',
357 :default => 1, :requires_restart => false,
358 :validate => Proc.new { |v| (0..5).include?(v) },
359 :on_change => Proc.new { |bot, v|
362 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
363 Config.register Config::IntegerValue.new('log.keep',
364 :default => 1, :requires_restart => true,
365 :validate => Proc.new { |v| v >= 0 },
366 :desc => "How many old console messages logfiles to keep")
367 Config.register Config::IntegerValue.new('log.max_size',
368 :default => 10, :requires_restart => true,
369 :validate => Proc.new { |v| v > 0 },
370 :desc => "Maximum console messages logfile size (in megabytes)")
372 Config.register Config::ArrayValue.new('plugins.path',
373 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
374 :requires_restart => false,
375 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
376 :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")
378 Config.register Config::EnumValue.new('send.newlines',
379 :values => ['split', 'join'], :default => 'split',
380 :on_change => Proc.new { |bot, v|
381 bot.set_default_send_options :newlines => v.to_sym
383 :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")
384 Config.register Config::StringValue.new('send.join_with',
386 :on_change => Proc.new { |bot, v|
387 bot.set_default_send_options :join_with => v.dup
389 :desc => "String used to replace newlines when send.newlines is set to join")
390 Config.register Config::IntegerValue.new('send.max_lines',
392 :validate => Proc.new { |v| v >= 0 },
393 :on_change => Proc.new { |bot, v|
394 bot.set_default_send_options :max_lines => v
396 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
397 Config.register Config::EnumValue.new('send.overlong',
398 :values => ['split', 'truncate'], :default => 'split',
399 :on_change => Proc.new { |bot, v|
400 bot.set_default_send_options :overlong => v.to_sym
402 :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")
403 Config.register Config::StringValue.new('send.split_at',
405 :on_change => Proc.new { |bot, v|
406 bot.set_default_send_options :split_at => Regexp.new(v)
408 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
409 Config.register Config::BooleanValue.new('send.purge_split',
411 :on_change => Proc.new { |bot, v|
412 bot.set_default_send_options :purge_split => v
414 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
415 Config.register Config::StringValue.new('send.truncate_text',
416 :default => "#{Reverse}...#{Reverse}",
417 :on_change => Proc.new { |bot, v|
418 bot.set_default_send_options :truncate_text => v.dup
420 :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")
421 Config.register Config::IntegerValue.new('send.penalty_pct',
423 :validate => Proc.new { |v| v >= 0 },
424 :on_change => Proc.new { |bot, v|
425 bot.socket.penalty_pct = v
427 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
428 Config.register Config::StringValue.new('core.db',
430 :wizard => true, :default => "dbm",
431 :validate => Proc.new { |v| ["dbm"].include? v },
432 :requires_restart => true,
433 :desc => "DB adaptor to use for storing the plugin data/registries. Options: dbm (included in ruby)")
435 @argv = params[:argv]
436 @run_dir = params[:run_dir] || Dir.pwd
438 unless FileTest.directory? Config::coredir
439 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
443 unless FileTest.directory? Config::datadir
444 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
448 unless botclass and not botclass.empty?
449 # We want to find a sensible default.
450 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
451 # * On Windows (at least the NT versions) we want to put our stuff in the
452 # Application Data folder.
453 # We don't use any particular O/S detection magic, exploiting the fact that
454 # Etc.getpwuid is nil on Windows
455 if Etc.getpwuid(Process::Sys.geteuid)
456 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
458 if ENV.has_key?('APPDATA')
459 botclass = ENV['APPDATA'].dup
460 botclass.gsub!("\\","/")
463 botclass = File.join(botclass, ".rbot")
465 botclass = File.expand_path(botclass)
466 @botclass = botclass.gsub(/\/$/, "")
468 repopulate_botclass_directory
470 registry_dir = File.join(@botclass, 'registry')
471 Dir.mkdir(registry_dir) unless File.exist?(registry_dir)
472 unless FileTest.directory? registry_dir
473 error "registry storage location #{registry_dir} is not a directory"
476 save_dir = File.join(@botclass, 'safe_save')
477 Dir.mkdir(save_dir) unless File.exist?(save_dir)
478 unless FileTest.directory? save_dir
479 error "safe save location #{save_dir} is not a directory"
483 # Time at which the last PING was sent
485 # Time at which the last line was RECV'd from the server
488 @startup_time = Time.new
491 @config = Config.manager
492 @config.bot_associate(self)
493 rescue Exception => e
499 if @config['core.run_as_daemon']
503 case @config["core.db"]
505 require 'rbot/registry/dbm'
507 raise _("Unknown DB adaptor: %s") % @config["core.db"]
510 @logfile = @config['log.file']
511 if @logfile.class!=String || @logfile.empty?
512 logfname = File.basename(botclass).gsub(/^\.+/,'')
514 @logfile = File.join(botclass, logfname)
515 debug "Using `#{@logfile}' as debug log"
518 # See http://blog.humlab.umu.se/samuel/archives/000107.html
519 # for the backgrounding code
525 rescue NotImplementedError
526 warning "Could not background, fork not supported"
529 rescue Exception => e
530 warning "Could not background. #{e.pretty_inspect}"
533 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
536 logger = Logger.new(@logfile,
538 @config['log.max_size']*1024*1024)
539 logger.datetime_format= $dateformat
540 logger.level = @config['log.level']
541 logger.level = $cl_loglevel if defined? $cl_loglevel
542 logger.level = 0 if $debug
544 restart_logger(logger)
549 log "Redirecting standard input/output/error"
550 [$stdin, $stdout, $stderr].each do |fd|
552 fd.reopen "/dev/null"
554 # On Windows, there's not such thing as /dev/null
559 def $stdout.write(str=nil)
563 def $stdout.write(str=nil)
564 if str.to_s.match(/:\d+: warning:/)
573 File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
578 @save_mutex = Mutex.new
579 if @config['core.save_every'] > 0
580 @save_timer = @timer.add(@config['core.save_every']) { save }
584 @quit_mutex = Mutex.new
587 @lang = Language.new(self, @config['core.language'])
590 @auth = Auth::manager
591 @auth.bot_associate(self)
592 # @auth.load("#{botclass}/botusers.yaml")
593 rescue Exception => e
598 @auth.everyone.set_default_permission("*", true)
599 @auth.botowner.password= @config['auth.password']
601 @plugins = Plugins::manager
602 @plugins.bot_associate(self)
605 if @config['server.name']
606 debug "upgrading configuration (server.name => server.list)"
607 srv_uri = 'irc://' + @config['server.name']
608 srv_uri += ":#{@config['server.port']}" if @config['server.port']
609 @config.items['server.list'.to_sym].set_string(srv_uri)
610 @config.delete('server.name'.to_sym)
611 @config.delete('server.port'.to_sym)
612 debug "server.list is now #{@config['server.list'].inspect}"
615 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'],
616 :ssl => @config['server.ssl'],
617 :ssl_verify => @config['server.ssl_verify'],
618 :ssl_ca_file => @config['server.ssl_ca_file'],
619 :ssl_ca_path => @config['server.ssl_ca_path'],
620 :penalty_pct => @config['send.penalty_pct'])
625 # Channels where we are quiet
626 # Array of channels names where the bot should be quiet
627 # '*' means all channels
630 # but we always speak here
633 # the nick we want, if it's different from the irc.nick config value
634 # (e.g. as set by a !nick command)
637 @client[:welcome] = proc {|data|
638 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
640 @plugins.delegate("welcome", m)
641 @plugins.delegate("connect")
644 # TODO the next two @client should go into rfc2812.rb, probably
645 # Since capabs are two-steps processes, server.supports[:capab]
646 # should be a three-state: nil, [], [....]
647 asked_for = { :"identify-msg" => false }
648 @client[:isupport] = proc { |data|
649 if server.supports[:capab] and !asked_for[:"identify-msg"]
650 sendq "CAPAB IDENTIFY-MSG"
651 asked_for[:"identify-msg"] = true
654 @client[:datastr] = proc { |data|
655 if data[:text] == "IDENTIFY-MSG"
656 server.capabilities[:"identify-msg"] = true
658 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
662 @client[:privmsg] = proc { |data|
663 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
664 # debug "Message source is #{data[:source].inspect}"
665 # debug "Message target is #{data[:target].inspect}"
666 # debug "Bot is #{myself.inspect}"
668 @config['irc.ignore_channels'].each { |channel|
669 if m.target.downcase == channel.downcase
674 @config['irc.ignore_users'].each { |mask|
675 if m.source.matches?(server.new_netmask(mask))
681 @plugins.irc_delegate('privmsg', m)
683 @client[:notice] = proc { |data|
684 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
685 # pass it off to plugins that want to hear everything
686 @plugins.irc_delegate "notice", message
688 @client[:motd] = proc { |data|
689 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
690 @plugins.delegate "motd", m
692 @client[:nicktaken] = proc { |data|
693 new = "#{data[:nick]}_"
695 # If we're setting our nick at connection because our choice was taken,
696 # we have to fix our nick manually, because there will be no NICK message
697 # to inform us that our nick has been changed.
698 if data[:target] == '*'
699 debug "setting my connection nick to #{new}"
702 @plugins.delegate "nicktaken", data[:nick]
704 @client[:badnick] = proc {|data|
705 warning "bad nick (#{data[:nick]})"
707 @client[:ping] = proc {|data|
708 sendq "PONG #{data[:pingid]}"
710 @client[:pong] = proc {|data|
713 @client[:nick] = proc {|data|
714 # debug "Message source is #{data[:source].inspect}"
715 # debug "Bot is #{myself.inspect}"
716 source = data[:source]
719 m = NickMessage.new(self, server, source, old, new)
720 m.is_on = data[:is_on]
722 debug "my nick is now #{new}"
724 @plugins.irc_delegate("nick", m)
726 @client[:quit] = proc {|data|
727 source = data[:source]
728 message = data[:message]
729 m = QuitMessage.new(self, server, source, source, message)
730 m.was_on = data[:was_on]
731 @plugins.irc_delegate("quit", m)
733 @client[:mode] = proc {|data|
734 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
735 m.modes = data[:modes]
736 @plugins.delegate "modechange", m
738 @client[:whois] = proc {|data|
739 source = data[:source]
740 target = server.get_user(data[:whois][:nick])
741 m = WhoisMessage.new(self, server, source, target, data[:whois])
742 @plugins.delegate "whois", m
744 @client[:list] = proc {|data|
745 source = data[:source]
746 m = ListMessage.new(self, server, source, source, data[:list])
747 @plugins.delegate "irclist", m
749 @client[:join] = proc {|data|
750 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
751 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
752 @plugins.irc_delegate("join", m)
753 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
755 @client[:part] = proc {|data|
756 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
757 @plugins.irc_delegate("part", m)
759 @client[:kick] = proc {|data|
760 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
761 @plugins.irc_delegate("kick", m)
763 @client[:invite] = proc {|data|
764 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
765 @plugins.irc_delegate("invite", m)
767 @client[:changetopic] = proc {|data|
768 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
770 @plugins.irc_delegate("topic", m)
772 # @client[:topic] = proc { |data|
773 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
775 @client[:topicinfo] = proc { |data|
776 channel = data[:channel]
777 topic = channel.topic
778 m = TopicMessage.new(self, server, data[:source], channel, topic)
779 m.info_or_set = :info
780 @plugins.irc_delegate("topic", m)
782 @client[:names] = proc { |data|
783 m = NamesMessage.new(self, server, server, data[:channel])
784 m.users = data[:users]
785 @plugins.delegate "names", m
787 @client[:banlist] = proc { |data|
788 m = BanlistMessage.new(self, server, server, data[:channel])
790 @plugins.delegate "banlist", m
792 @client[:nosuchtarget] = proc { |data|
793 m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
794 @plugins.delegate "nosuchtarget", m
796 @client[:error] = proc { |data|
797 raise ServerError, data[:message]
799 @client[:unknown] = proc { |data|
800 #debug "UNKNOWN: #{data[:serverstring]}"
801 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
802 @plugins.delegate "unknown_message", m
805 set_default_send_options :newlines => @config['send.newlines'].to_sym,
806 :join_with => @config['send.join_with'].dup,
807 :max_lines => @config['send.max_lines'],
808 :overlong => @config['send.overlong'].to_sym,
809 :split_at => Regexp.new(@config['send.split_at']),
810 :purge_split => @config['send.purge_split'],
811 :truncate_text => @config['send.truncate_text'].dup
816 # Determine (if possible) a valid path to a CA certificate bundle.
817 def default_ssl_ca_file
818 [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
819 '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
820 '/etc/ssl/ca-bundle.pem', # OpenSUSE
821 '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
827 def repopulate_botclass_directory
828 template_dir = File.join Config::datadir, 'templates'
829 if FileTest.directory? @botclass
830 # compare the templates dir with the current botclass dir, filling up the
831 # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
832 # :update option, so we have to do it manually.
833 # Note that we use the */** pattern because we don't want to match
834 # keywords.rbot, which gets deleted on load and would therefore be missing
836 missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
838 dest = File.join(@botclass, f)
839 FileUtils.mkdir_p(File.dirname(dest))
840 FileUtils.cp File.join(template_dir, f), dest
843 log "no #{@botclass} directory found, creating from templates..."
844 if FileTest.exist? @botclass
845 error "file #{@botclass} exists but isn't a directory"
848 FileUtils.cp_r template_dir, @botclass
852 # Return a path under the current botclass by joining the mentioned
853 # components. The components are automatically converted to String
854 def path(*components)
855 File.join(@botclass, *(components.map {|c| c.to_s}))
858 def setup_plugins_path
859 plugdir_default = File.join(Config::datadir, 'plugins')
860 plugdir_local = File.join(@botclass, 'plugins')
861 Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
863 @plugins.clear_botmodule_dirs
864 @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
865 @plugins.add_core_module_dir(Config::coredir)
866 if FileTest.directory? plugdir_local
867 @plugins.add_plugin_dir(plugdir_local)
869 warning "local plugin location #{plugdir_local} is not a directory"
872 @config['plugins.path'].each do |_|
873 path = _.sub(/^\(default\)/, plugdir_default)
874 @plugins.add_plugin_dir(path)
878 def set_default_send_options(opts={})
879 # Default send options for NOTICE and PRIVMSG
880 unless defined? @default_send_options
881 @default_send_options = {
882 :queue_channel => nil, # use default queue channel
883 :queue_ring => nil, # use default queue ring
884 :newlines => :split, # or :join
885 :join_with => ' ', # by default, use a single space
886 :max_lines => 0, # maximum number of lines to send with a single command
887 :overlong => :split, # or :truncate
888 # TODO an array of splitpoints would be preferrable for this option:
889 :split_at => /\s+/, # by default, split overlong lines at whitespace
890 :purge_split => true, # should the split string be removed?
891 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
894 @default_send_options.update opts unless opts.empty?
897 # checks if we should be quiet on a channel
898 def quiet_on?(channel)
899 ch = channel.downcase
900 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
903 def set_quiet(channel = nil)
905 ch = channel.downcase.dup
906 @not_quiet.delete(ch)
915 def reset_quiet(channel = nil)
917 ch = channel.downcase.dup
926 # things to do when we receive a signal
927 def handle_signal(sig)
936 debug "received #{sig}, queueing #{func}"
937 # this is not an interruption if we just need to reconnect
938 $interrupted += 1 unless func == :reconnect
939 self.send(func) unless @quit_mutex.locked?
940 debug "interrupted #{$interrupted} times"
951 %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
952 trap(sig) { Thread.new { handle_signal sig } }
954 rescue ArgumentError => e
955 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
956 rescue Exception => e
957 debug "failed to trap signals: #{e.pretty_inspect}"
961 # connect the bot to IRC
963 # make sure we don't have any spurious ping checks running
964 # (and initialize the vars if this is the first time we connect)
967 quit if $interrupted > 0
970 rescue Exception => e
971 uri = @socket.server_uri || '<unknown>'
972 error "failed to connect to IRC server at #{uri}"
976 quit if $interrupted > 0
978 realname = @config['irc.name'].clone || 'Ruby bot'
979 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
981 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
982 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
983 quit if $interrupted > 0
984 myself.nick = @config['irc.nick']
985 myself.user = @config['irc.user']
988 # disconnect the bot from IRC, if connected, and then connect (again)
989 def reconnect(message=nil, too_fast=0)
990 # we will wait only if @last_rec was not nil, i.e. if we were connected or
991 # got disconnected by a network error
992 # if someone wants to manually call disconnect() _and_ reconnect(), they
993 # will have to take care of the waiting themselves
994 will_wait = !!@last_rec
996 if @socket.connected?
1002 log "\n\nDisconnected\n\n"
1004 quit if $interrupted > 0
1006 log "\n\nWaiting to reconnect\n\n"
1007 sleep @config['server.reconnect_wait']
1009 tf = too_fast*@config['server.reconnect_wait']
1010 tfu = Utils.secs_to_string(tf)
1011 log "Will sleep for an extra #{tf}s (#{tfu})"
1020 rescue Exception => e
1027 # begin event handling loop
1032 valid_recv = false # did we receive anything (valid) from the server yet?
1034 reconnect(quit_msg, too_fast)
1035 quit if $interrupted > 0
1037 while @socket.connected?
1038 quit if $interrupted > 0
1040 # Wait for messages and process them as they arrive. If nothing is
1041 # received, we call the ping_server() method that will PING the
1042 # server if appropriate, or raise a TimeoutError if no PONG has been
1043 # received in the user-chosen timeout since the last PING sent.
1044 if @socket.select(1)
1045 break unless reply = @socket.gets
1046 @last_rec = Time.now
1047 @client.process reply
1055 # I despair of this. Some of my users get "connection reset by peer"
1056 # exceptions that ARENT SocketError's. How am I supposed to handle
1061 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1062 error "network exception: #{e.pretty_inspect}"
1064 too_fast += 10 if valid_recv
1065 rescue ServerMessageParseError => e
1066 # if the bot tried reconnecting too often, we can get forcefully
1067 # disconnected by the server, while still receiving an empty message
1068 # wait at least 10 minutes in this case
1071 too_fast = [too_fast, 300].max
1073 log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1075 quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1077 rescue ServerError => e
1078 quit_msg = "server ERROR: " + e.message
1080 idx = e.message.index("connect too fast")
1081 debug "'connect too fast' @ #{idx}"
1084 too_fast += (idx+1)*2
1085 log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1087 idx = e.message.index(/a(uto)kill/i)
1088 debug "'autokill' @ #{idx}"
1090 # we got auto-killed. since we don't have an easy way to tell
1091 # if it's permanent or temporary, we just set a rather high
1092 # reconnection timeout
1094 too_fast += (idx+1)*5
1095 log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1098 rescue Exception => e
1099 error "non-net exception: #{e.pretty_inspect}"
1102 fatal "unexpected exception: #{e.pretty_inspect}"
1109 # type:: message type
1110 # where:: message target
1111 # message:: message text
1112 # send message +message+ of type +type+ to target +where+
1113 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1114 # relevant say() or notice() methods. This one should be used for IRCd
1115 # extensions you want to use in modules.
1116 def sendmsg(original_type, original_where, original_message, options={})
1118 # filter message with sendmsg filters
1119 ds = DataStream.new original_message.to_s.dup,
1120 :type => original_type, :dest => original_where,
1121 :options => @default_send_options.merge(options)
1122 filters = filter_names(:sendmsg)
1123 filters.each do |fname|
1124 debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1125 ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1131 filtered = ds[:text]
1133 # For starters, set up appropriate queue channels and rings
1134 mchan = opts[:queue_channel]
1135 mring = opts[:queue_ring]
1152 multi_line = filtered.gsub(/[\r\n]+/, "\n")
1154 # if target is a channel with nocolor modes, strip colours
1155 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1156 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1159 messages = Array.new
1160 case opts[:newlines]
1162 messages << [multi_line.gsub("\n", opts[:join_with])]
1164 multi_line.each_line { |line|
1166 next unless(line.size > 0)
1170 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1173 # The IRC protocol requires that each raw message must be not longer
1174 # than 512 characters. From this length with have to subtract the EOL
1175 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1176 # that will be prepended by the server to all of our messages.
1178 # The maximum raw message length we can send is therefore 512 - 2 - 2
1179 # minus the length of our hostmask.
1181 max_len = 508 - myself.fullform.size
1183 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1184 # will have a + or - prepended
1185 if server.capabilities[:"identify-msg"]
1189 # When splitting the message, we'll be prefixing the following string:
1190 # (e.g. "PRIVMSG #rbot :")
1191 fixed = "#{type} #{where} :"
1193 # And this is what's left
1194 left = max_len - fixed.size
1196 truncate = opts[:truncate_text]
1197 truncate = @default_send_options[:truncate_text] if truncate.size > left
1198 truncate = "" if truncate.size > left
1200 all_lines = messages.map { |line|
1204 case opts[:overlong]
1207 sub_lines = Array.new
1209 sub_lines << msg.slice!(0, left)
1211 lastspace = sub_lines.last.rindex(opts[:split_at])
1213 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1214 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1216 end until msg.empty?
1219 line.slice(0, left - truncate.size) << truncate
1221 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1226 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1227 lines = all_lines[0...opts[:max_lines]]
1228 new_last = lines.last.slice(0, left - truncate.size) << truncate
1229 lines.last.replace(new_last)
1235 sendq "#{fixed}#{line}", chan, ring
1236 delegate_sent(type, where, line)
1240 # queue an arbitraty message for the server
1241 def sendq(message="", chan=nil, ring=0)
1243 @socket.queue(message, chan, ring)
1246 # send a notice message to channel/nick +where+
1247 def notice(where, message, options={})
1248 return if where.kind_of?(Channel) and quiet_on?(where)
1249 sendmsg "NOTICE", where, message, options
1252 # say something (PRIVMSG) to channel/nick +where+
1253 def say(where, message, options={})
1254 return if where.kind_of?(Channel) and quiet_on?(where)
1255 sendmsg "PRIVMSG", where, message, options
1258 def ctcp_notice(where, command, message, options={})
1259 return if where.kind_of?(Channel) and quiet_on?(where)
1260 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1263 def ctcp_say(where, command, message, options={})
1264 return if where.kind_of?(Channel) and quiet_on?(where)
1265 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1268 # perform a CTCP action with message +message+ to channel/nick +where+
1269 def action(where, message, options={})
1270 ctcp_say(where, 'ACTION', message, options)
1273 # quick way to say "okay" (or equivalent) to +where+
1275 say where, @lang.get("okay")
1278 # set topic of channel +where+ to +topic+
1279 # can also be used to retrieve the topic of channel +where+
1280 # by omitting the last argument
1281 def topic(where, topic=nil)
1283 sendq "TOPIC #{where}", where, 2
1285 sendq "TOPIC #{where} :#{topic}", where, 2
1289 def disconnect(message=nil)
1290 message = @lang.get("quit") if (!message || message.empty?)
1291 if @socket.connected?
1293 debug "Clearing socket"
1295 debug "Sending quit message"
1296 @socket.emergency_puts "QUIT :#{message}"
1297 debug "Logging quits"
1298 delegate_sent('QUIT', myself, message)
1299 debug "Flushing socket"
1301 rescue SocketError => e
1302 error "error while disconnecting socket: #{e.pretty_inspect}"
1304 debug "Shutting down socket"
1311 # disconnect from the server and cleanup all plugins and modules
1312 def shutdown(message=nil)
1313 @quit_mutex.synchronize do
1314 debug "Shutting down: #{message}"
1315 ## No we don't restore them ... let everything run through
1317 # trap("SIGINT", "DEFAULT")
1318 # trap("SIGTERM", "DEFAULT")
1319 # trap("SIGHUP", "DEFAULT")
1321 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1323 debug "\tdisconnecting..."
1325 debug "\tstopping timer..."
1327 debug "\tsaving ..."
1329 debug "\tcleaning up ..."
1330 @save_mutex.synchronize do
1334 debug "\tignoring cleanup error: #{$!}"
1337 # debug "\tstopping timers ..."
1339 # debug "Closing registries"
1341 log "rbot quit (#{message})"
1345 # message:: optional IRC quit message
1346 # quit IRC, shutdown the bot
1347 def quit(message=nil)
1355 # totally shutdown and respawn the bot
1356 def restart(message=nil)
1357 message = _("restarting, back in %{wait}...") % {
1358 :wait => @config['server.reconnect_wait']
1359 } if (!message || message.empty?)
1361 sleep @config['server.reconnect_wait']
1364 # Note, this fails on Windows
1365 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1369 rescue Errno::ENOENT
1371 exec("ruby", *(@argv.unshift $0))
1372 rescue Exception => e
1378 # call the save method for all of the botmodules
1380 @save_mutex.synchronize do
1385 # call the rescan method for all of the botmodules
1387 debug "\tstopping timer..."
1389 @save_mutex.synchronize do
1396 # channel:: channel to join
1397 # key:: optional channel key if channel is +s
1399 def join(channel, key=nil)
1401 sendq "JOIN #{channel} :#{key}", channel, 2
1403 sendq "JOIN #{channel}", channel, 2
1408 def part(channel, message="")
1409 sendq "PART #{channel} :#{message}", channel, 2
1412 # attempt to change bot's nick to +name+
1414 sendq "NICK #{name}"
1418 def mode(channel, mode, target=nil)
1419 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1423 def whois(nick, target=nil)
1424 sendq "WHOIS #{target} #{nick}", nil, 0
1428 def kick(channel, user, msg)
1429 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1432 # m:: message asking for help
1433 # topic:: optional topic help is requested for
1434 # respond to online help requests
1436 topic = nil if topic == ""
1439 helpstr = _("help topics: ")
1440 helpstr += @plugins.helptopics
1441 helpstr += _(" (help <topic> for more info)")
1443 unless(helpstr = @plugins.help(topic))
1444 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1450 # returns a string describing the current status of the bot (uptime etc)
1452 secs_up = Time.new - @startup_time
1453 uptime = Utils.secs_to_string secs_up
1454 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1455 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1457 :up => uptime, :plug => @plugins.length,
1458 :sent => @socket.lines_sent, :recv => @socket.lines_received
1462 # We want to respond to a hung server in a timely manner. If nothing was received
1463 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1464 # the server. If the PONG is not received within the user-defined timeout, we
1465 # assume we're in ping timeout and act accordingly.
1467 act_timeout = @config['server.ping_timeout']
1468 return if act_timeout <= 0
1470 if @last_rec && now > @last_rec + act_timeout
1472 # No previous PING pending, send a new one
1474 @last_ping = Time.now
1476 diff = now - @last_ping
1477 if diff > act_timeout
1478 debug "no PONG from server in #{diff} seconds, reconnecting"
1479 # the actual reconnect is handled in the main loop:
1480 raise TimeoutError, "no PONG from server in #{diff} seconds"
1486 def stop_server_pings
1487 # cancel previous PINGs and reset time of last RECV
1494 # delegate sent messages
1495 def delegate_sent(type, where, message)
1496 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1499 m = NoticeMessage.new(*args)
1501 m = PrivMessage.new(*args)
1503 m = QuitMessage.new(*args)
1504 m.was_on = myself.channels
1506 @plugins.delegate('sent', m)