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.instance_methods.include?("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 def rawlog(level, message=nil, who_pos=1)
46 if call_stack.length > who_pos
47 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
51 # Output each line. To distinguish between separate messages and multi-line
52 # messages originating at the same time, we blank #{who} after the first message
54 # Also, we output strings as-is but for other objects we use pretty_inspect
59 str = message.pretty_inspect
63 qmsg.push [level, l.chomp, who]
70 if $log_thread && $log_thread.alive?
79 def restart_logger(newlogger = false)
82 $logger = newlogger if newlogger
84 $log_thread = Thread.new do
86 while ls = $log_queue.pop
87 ls.each { |l| $logger.add(*l) }
95 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
100 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
104 def debug(message=nil, who_pos=1)
105 rawlog(Logger::Severity::DEBUG, message, who_pos)
108 def log(message=nil, who_pos=1)
109 rawlog(Logger::Severity::INFO, message, who_pos)
112 def warning(message=nil, who_pos=1)
113 rawlog(Logger::Severity::WARN, message, who_pos)
116 def error(message=nil, who_pos=1)
117 rawlog(Logger::Severity::ERROR, message, who_pos)
120 def fatal(message=nil, who_pos=1)
121 rawlog(Logger::Severity::FATAL, message, who_pos)
126 warning "warning test"
130 # The following global is used for the improved signal handling.
134 require 'rbot/rbotconfig'
135 require 'rbot/load-gettext'
136 require 'rbot/config'
137 require 'rbot/config-compat'
140 require 'rbot/rfc2812'
141 require 'rbot/ircsocket'
142 require 'rbot/botuser'
144 require 'rbot/plugins'
145 require 'rbot/message'
146 require 'rbot/language'
147 require 'rbot/dbhash'
148 require 'rbot/registry'
152 # Main bot class, which manages the various components, receives messages,
153 # handles them or passes them to plugins, and contains core functionality.
155 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
156 SOURCE_URL = "http://ruby-rbot.org"
157 # the bot's Auth data
160 # the bot's Config data
163 # the botclass for this bot (determines configdir among other things)
164 attr_reader :botclass
166 # used to perform actions periodically (saves configuration once per minute
170 # synchronize with this mutex while touching permanent data files:
171 # saving, flushing, cleaning up ...
172 attr_reader :save_mutex
174 # bot's Language data
181 # bot's object registry, plugins get an interface to this for persistant
182 # storage (hash interface tied to a bdb file, plugins use Accessors to store
183 # and restore objects in their own namespaces.)
184 attr_reader :registry
186 # bot's plugins. This is an instance of class Plugins
189 # bot's httputil help object, for fetching resources via http. Sets up
190 # proxies etc as defined by the bot configuration/environment
191 attr_accessor :httputil
193 # server we are connected to
199 # bot User in the client/server connection
205 # bot User in the client/server connection
210 # nick wanted by the bot. This defaults to the irc.nick config value,
211 # but may be overridden by a manual !nick command
213 @wanted_nick || config['irc.nick']
216 # set the nick wanted by the bot
218 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
221 @wanted_nick = wn.to_s.dup
229 ret = self.to_s[0..-2]
230 ret << ' version=' << $version.inspect
231 ret << ' botclass=' << botclass.inspect
232 ret << ' lang="' << lang.language
237 ret << ' nick=' << nick.inspect
240 ret << (server.to_s + (socket ?
241 ' [' << socket.server_uri.to_s << ']' : '')).inspect
242 unless server.channels.empty?
244 ret << server.channels.map { |c|
245 "%s%s" % [c.modes_of(nick).map { |m|
246 server.prefix_for_mode(m)
253 ret << ' plugins=' << plugins.inspect
258 # create a new Bot with botclass +botclass+
259 def initialize(botclass, params = {})
260 # Config for the core bot
261 # TODO should we split socket stuff into ircsocket, etc?
262 Config.register Config::ArrayValue.new('server.list',
263 :default => ['irc://localhost'], :wizard => true,
264 :requires_restart => true,
265 :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.")
266 Config.register Config::BooleanValue.new('server.ssl',
267 :default => false, :requires_restart => true, :wizard => true,
268 :desc => "Use SSL to connect to this server?")
269 Config.register Config::StringValue.new('server.password',
270 :default => false, :requires_restart => true,
271 :desc => "Password for connecting to this server (if required)",
273 Config.register Config::StringValue.new('server.bindhost',
274 :default => false, :requires_restart => true,
275 :desc => "Specific local host or IP for the bot to bind to (if required)",
277 Config.register Config::IntegerValue.new('server.reconnect_wait',
278 :default => 5, :validate => Proc.new{|v| v >= 0},
279 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
280 Config.register Config::IntegerValue.new('server.ping_timeout',
281 :default => 30, :validate => Proc.new{|v| v >= 0},
282 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
283 Config.register Config::ArrayValue.new('server.nocolor_modes',
284 :default => ['c'], :wizard => false,
285 :requires_restart => false,
286 :desc => "List of channel modes that require messages to be without colors")
288 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
289 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
290 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
291 Config.register Config::StringValue.new('irc.name',
292 :default => "Ruby bot", :requires_restart => true,
293 :desc => "IRC realname the bot should use")
294 Config.register Config::BooleanValue.new('irc.name_copyright',
295 :default => true, :requires_restart => true,
296 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
297 Config.register Config::StringValue.new('irc.user', :default => "rbot",
298 :requires_restart => true,
299 :desc => "local user the bot should appear to be", :wizard => true)
300 Config.register Config::ArrayValue.new('irc.join_channels',
301 :default => [], :wizard => true,
302 :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'")
303 Config.register Config::ArrayValue.new('irc.ignore_users',
305 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
307 Config.register Config::IntegerValue.new('core.save_every',
308 :default => 60, :validate => Proc.new{|v| v >= 0},
309 :on_change => Proc.new { |bot, v|
312 @timer.reschedule(@save_timer, v)
313 @timer.unblock(@save_timer)
315 @timer.block(@save_timer)
319 @save_timer = @timer.add(v) { bot.save }
321 # Nothing to do when v == 0
324 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
326 Config.register Config::BooleanValue.new('core.run_as_daemon',
327 :default => false, :requires_restart => true,
328 :desc => "Should the bot run as a daemon?")
330 Config.register Config::StringValue.new('log.file',
331 :default => false, :requires_restart => true,
332 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
333 Config.register Config::IntegerValue.new('log.level',
334 :default => 1, :requires_restart => false,
335 :validate => Proc.new { |v| (0..5).include?(v) },
336 :on_change => Proc.new { |bot, v|
339 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
340 Config.register Config::IntegerValue.new('log.keep',
341 :default => 1, :requires_restart => true,
342 :validate => Proc.new { |v| v >= 0 },
343 :desc => "How many old console messages logfiles to keep")
344 Config.register Config::IntegerValue.new('log.max_size',
345 :default => 10, :requires_restart => true,
346 :validate => Proc.new { |v| v > 0 },
347 :desc => "Maximum console messages logfile size (in megabytes)")
349 Config.register Config::ArrayValue.new('plugins.path',
350 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
351 :requires_restart => false,
352 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
353 :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")
355 Config.register Config::EnumValue.new('send.newlines',
356 :values => ['split', 'join'], :default => 'split',
357 :on_change => Proc.new { |bot, v|
358 bot.set_default_send_options :newlines => v.to_sym
360 :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")
361 Config.register Config::StringValue.new('send.join_with',
363 :on_change => Proc.new { |bot, v|
364 bot.set_default_send_options :join_with => v.dup
366 :desc => "String used to replace newlines when send.newlines is set to join")
367 Config.register Config::IntegerValue.new('send.max_lines',
369 :validate => Proc.new { |v| v >= 0 },
370 :on_change => Proc.new { |bot, v|
371 bot.set_default_send_options :max_lines => v
373 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
374 Config.register Config::EnumValue.new('send.overlong',
375 :values => ['split', 'truncate'], :default => 'split',
376 :on_change => Proc.new { |bot, v|
377 bot.set_default_send_options :overlong => v.to_sym
379 :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")
380 Config.register Config::StringValue.new('send.split_at',
382 :on_change => Proc.new { |bot, v|
383 bot.set_default_send_options :split_at => Regexp.new(v)
385 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
386 Config.register Config::BooleanValue.new('send.purge_split',
388 :on_change => Proc.new { |bot, v|
389 bot.set_default_send_options :purge_split => v
391 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
392 Config.register Config::StringValue.new('send.truncate_text',
393 :default => "#{Reverse}...#{Reverse}",
394 :on_change => Proc.new { |bot, v|
395 bot.set_default_send_options :truncate_text => v.dup
397 :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")
398 Config.register Config::IntegerValue.new('send.penalty_pct',
400 :validate => Proc.new { |v| v >= 0 },
401 :on_change => Proc.new { |bot, v|
402 bot.socket.penalty_pct = v
404 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
406 @argv = params[:argv]
407 @run_dir = params[:run_dir] || Dir.pwd
409 unless FileTest.directory? Config::coredir
410 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
414 unless FileTest.directory? Config::datadir
415 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
419 unless botclass and not botclass.empty?
420 # We want to find a sensible default.
421 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
422 # * On Windows (at least the NT versions) we want to put our stuff in the
423 # Application Data folder.
424 # We don't use any particular O/S detection magic, exploiting the fact that
425 # Etc.getpwuid is nil on Windows
426 if Etc.getpwuid(Process::Sys.geteuid)
427 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
429 if ENV.has_key?('APPDATA')
430 botclass = ENV['APPDATA'].dup
431 botclass.gsub!("\\","/")
436 botclass = File.expand_path(botclass)
437 @botclass = botclass.gsub(/\/$/, "")
439 if FileTest.directory? botclass
440 # compare the templates dir with the current botclass, and fill it in with
442 # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
444 template = File.join Config::datadir, 'templates'
445 # note that we use the */** pattern because we don't want to match
446 # keywords.rbot, which gets deleted on load and would therefore be missing always
447 missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
449 dest = File.join(botclass, f)
450 FileUtils.mkdir_p File.dirname dest
451 FileUtils.cp File.join(template, f), dest
454 log "no #{botclass} directory found, creating from templates.."
455 if FileTest.exist? botclass
456 error "file #{botclass} exists but isn't a directory"
459 FileUtils.cp_r Config::datadir+'/templates', botclass
462 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
463 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
465 # Time at which the last PING was sent
467 # Time at which the last line was RECV'd from the server
470 @startup_time = Time.new
473 @config = Config.manager
474 @config.bot_associate(self)
475 rescue Exception => e
481 if @config['core.run_as_daemon']
485 @logfile = @config['log.file']
486 if @logfile.class!=String || @logfile.empty?
487 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
488 debug "Using `#{@logfile}' as debug log"
491 # See http://blog.humlab.umu.se/samuel/archives/000107.html
492 # for the backgrounding code
498 rescue NotImplementedError
499 warning "Could not background, fork not supported"
502 rescue Exception => e
503 warning "Could not background. #{e.pretty_inspect}"
506 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
509 logger = Logger.new(@logfile,
511 @config['log.max_size']*1024*1024)
512 logger.datetime_format= $dateformat
513 logger.level = @config['log.level']
514 logger.level = $cl_loglevel if defined? $cl_loglevel
515 logger.level = 0 if $debug
517 restart_logger(logger)
522 log "Redirecting standard input/output/error"
523 [$stdin, $stdout, $stderr].each do |fd|
525 fd.reopen "/dev/null"
527 # On Windows, there's not such thing as /dev/null
532 def $stdout.write(str=nil)
536 def $stdout.write(str=nil)
537 if str.to_s.match(/:\d+: warning:/)
546 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
550 @registry = Registry.new self
553 @save_mutex = Mutex.new
554 if @config['core.save_every'] > 0
555 @save_timer = @timer.add(@config['core.save_every']) { save }
559 @quit_mutex = Mutex.new
562 @lang = Language.new(self, @config['core.language'])
565 @auth = Auth::manager
566 @auth.bot_associate(self)
567 # @auth.load("#{botclass}/botusers.yaml")
568 rescue Exception => e
573 @auth.everyone.set_default_permission("*", true)
574 @auth.botowner.password= @config['auth.password']
576 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
577 @plugins = Plugins::manager
578 @plugins.bot_associate(self)
581 if @config['server.name']
582 debug "upgrading configuration (server.name => server.list)"
583 srv_uri = 'irc://' + @config['server.name']
584 srv_uri += ":#{@config['server.port']}" if @config['server.port']
585 @config.items['server.list'.to_sym].set_string(srv_uri)
586 @config.delete('server.name'.to_sym)
587 @config.delete('server.port'.to_sym)
588 debug "server.list is now #{@config['server.list'].inspect}"
591 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
596 # Channels where we are quiet
597 # Array of channels names where the bot should be quiet
598 # '*' means all channels
601 # but we always speak here
604 # the nick we want, if it's different from the irc.nick config value
605 # (e.g. as set by a !nick command)
608 @client[:welcome] = proc {|data|
609 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
611 @plugins.delegate("welcome", m)
612 @plugins.delegate("connect")
615 # TODO the next two @client should go into rfc2812.rb, probably
616 # Since capabs are two-steps processes, server.supports[:capab]
617 # should be a three-state: nil, [], [....]
618 asked_for = { :"identify-msg" => false }
619 @client[:isupport] = proc { |data|
620 if server.supports[:capab] and !asked_for[:"identify-msg"]
621 sendq "CAPAB IDENTIFY-MSG"
622 asked_for[:"identify-msg"] = true
625 @client[:datastr] = proc { |data|
626 if data[:text] == "IDENTIFY-MSG"
627 server.capabilities[:"identify-msg"] = true
629 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
633 @client[:privmsg] = proc { |data|
634 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
635 # debug "Message source is #{data[:source].inspect}"
636 # debug "Message target is #{data[:target].inspect}"
637 # debug "Bot is #{myself.inspect}"
639 @config['irc.ignore_users'].each { |mask|
640 if m.source.matches?(server.new_netmask(mask))
645 @plugins.irc_delegate('privmsg', m)
647 @client[:notice] = proc { |data|
648 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
649 # pass it off to plugins that want to hear everything
650 @plugins.irc_delegate "notice", message
652 @client[:motd] = proc { |data|
653 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
654 @plugins.delegate "motd", m
656 @client[:nicktaken] = proc { |data|
657 new = "#{data[:nick]}_"
659 # If we're setting our nick at connection because our choice was taken,
660 # we have to fix our nick manually, because there will be no NICK message
661 # to inform us that our nick has been changed.
662 if data[:target] == '*'
663 debug "setting my connection nick to #{new}"
666 @plugins.delegate "nicktaken", data[:nick]
668 @client[:badnick] = proc {|data|
669 warning "bad nick (#{data[:nick]})"
671 @client[:ping] = proc {|data|
672 sendq "PONG #{data[:pingid]}"
674 @client[:pong] = proc {|data|
677 @client[:nick] = proc {|data|
678 # debug "Message source is #{data[:source].inspect}"
679 # debug "Bot is #{myself.inspect}"
680 source = data[:source]
683 m = NickMessage.new(self, server, source, old, new)
684 m.is_on = data[:is_on]
686 debug "my nick is now #{new}"
688 @plugins.irc_delegate("nick", m)
690 @client[:quit] = proc {|data|
691 source = data[:source]
692 message = data[:message]
693 m = QuitMessage.new(self, server, source, source, message)
694 m.was_on = data[:was_on]
695 @plugins.irc_delegate("quit", m)
697 @client[:mode] = proc {|data|
698 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
699 m.modes = data[:modes]
700 @plugins.delegate "modechange", m
702 @client[:whois] = proc {|data|
703 source = data[:source]
704 target = server.get_user(data[:whois][:nick])
705 m = WhoisMessage.new(self, server, source, target, data[:whois])
706 @plugins.delegate "whois", m
708 @client[:join] = proc {|data|
709 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
710 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
711 @plugins.irc_delegate("join", m)
712 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
714 @client[:part] = proc {|data|
715 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
716 @plugins.irc_delegate("part", m)
718 @client[:kick] = proc {|data|
719 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
720 @plugins.irc_delegate("kick", m)
722 @client[:invite] = proc {|data|
723 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
724 @plugins.irc_delegate("invite", m)
726 @client[:changetopic] = proc {|data|
727 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
729 @plugins.irc_delegate("topic", m)
731 # @client[:topic] = proc { |data|
732 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
734 @client[:topicinfo] = proc { |data|
735 channel = data[:channel]
736 topic = channel.topic
737 m = TopicMessage.new(self, server, data[:source], channel, topic)
738 m.info_or_set = :info
739 @plugins.irc_delegate("topic", m)
741 @client[:names] = proc { |data|
742 m = NamesMessage.new(self, server, server, data[:channel])
743 m.users = data[:users]
744 @plugins.delegate "names", m
746 @client[:unknown] = proc { |data|
747 #debug "UNKNOWN: #{data[:serverstring]}"
748 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
749 @plugins.delegate "unknown_message", m
752 set_default_send_options :newlines => @config['send.newlines'].to_sym,
753 :join_with => @config['send.join_with'].dup,
754 :max_lines => @config['send.max_lines'],
755 :overlong => @config['send.overlong'].to_sym,
756 :split_at => Regexp.new(@config['send.split_at']),
757 :purge_split => @config['send.purge_split'],
758 :truncate_text => @config['send.truncate_text'].dup
763 def setup_plugins_path
764 @plugins.clear_botmodule_dirs
765 @plugins.add_botmodule_dir(Config::coredir + "/utils")
766 @plugins.add_botmodule_dir(Config::coredir)
767 @plugins.add_botmodule_dir("#{botclass}/plugins")
769 @config['plugins.path'].each do |_|
770 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
771 @plugins.add_botmodule_dir(path)
775 def set_default_send_options(opts={})
776 # Default send options for NOTICE and PRIVMSG
777 unless defined? @default_send_options
778 @default_send_options = {
779 :queue_channel => nil, # use default queue channel
780 :queue_ring => nil, # use default queue ring
781 :newlines => :split, # or :join
782 :join_with => ' ', # by default, use a single space
783 :max_lines => 0, # maximum number of lines to send with a single command
784 :overlong => :split, # or :truncate
785 # TODO an array of splitpoints would be preferrable for this option:
786 :split_at => /\s+/, # by default, split overlong lines at whitespace
787 :purge_split => true, # should the split string be removed?
788 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
791 @default_send_options.update opts unless opts.empty?
794 # checks if we should be quiet on a channel
795 def quiet_on?(channel)
796 ch = channel.downcase
797 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
800 def set_quiet(channel = nil)
802 ch = channel.downcase.dup
803 @not_quiet.delete(ch)
812 def reset_quiet(channel = nil)
814 ch = channel.downcase.dup
823 # things to do when we receive a signal
824 def got_sig(sig, func=:quit)
825 debug "received #{sig}, queueing #{func}"
827 self.send(func) unless @quit_mutex.locked?
828 debug "interrupted #{$interrupted} times"
839 trap("SIGINT") { got_sig("SIGINT") }
840 trap("SIGTERM") { got_sig("SIGTERM") }
841 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
842 rescue ArgumentError => e
843 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
844 rescue Exception => e
845 debug "failed to trap signals: #{e.pretty_inspect}"
849 # connect the bot to IRC
852 quit if $interrupted > 0
855 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
857 quit if $interrupted > 0
859 realname = @config['irc.name'].clone || 'Ruby bot'
860 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
862 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
863 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
864 quit if $interrupted > 0
865 myself.nick = @config['irc.nick']
866 myself.user = @config['irc.user']
869 # begin event handling loop
873 quit if $interrupted > 0
877 while @socket.connected?
878 quit if $interrupted > 0
880 # Wait for messages and process them as they arrive. If nothing is
881 # received, we call the ping_server() method that will PING the
882 # server if appropriate, or raise a TimeoutError if no PONG has been
883 # received in the user-chosen timeout since the last PING sent.
885 break unless reply = @socket.gets
887 @client.process reply
893 # I despair of this. Some of my users get "connection reset by peer"
894 # exceptions that ARENT SocketError's. How am I supposed to handle
899 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
900 error "network exception: #{e.pretty_inspect}"
902 rescue BDB::Fatal => e
903 fatal "fatal bdb error: #{e.pretty_inspect}"
905 # Why restart? DB problems are serious stuff ...
906 # restart("Oops, we seem to have registry problems ...")
909 rescue Exception => e
910 error "non-net exception: #{e.pretty_inspect}"
913 fatal "unexpected exception: #{e.pretty_inspect}"
920 log "\n\nDisconnected\n\n"
922 quit if $interrupted > 0
924 log "\n\nWaiting to reconnect\n\n"
925 sleep @config['server.reconnect_wait']
929 # type:: message type
930 # where:: message target
931 # message:: message text
932 # send message +message+ of type +type+ to target +where+
933 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
934 # relevant say() or notice() methods. This one should be used for IRCd
935 # extensions you want to use in modules.
936 def sendmsg(type, where, original_message, options={})
937 opts = @default_send_options.merge(options)
939 # For starters, set up appropriate queue channels and rings
940 mchan = opts[:queue_channel]
941 mring = opts[:queue_ring]
958 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
960 # if target is a channel with nocolor modes, strip colours
961 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
962 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
968 messages << [multi_line.gsub("\n", opts[:join_with])]
970 multi_line.each_line { |line|
972 next unless(line.size > 0)
976 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
979 # The IRC protocol requires that each raw message must be not longer
980 # than 512 characters. From this length with have to subtract the EOL
981 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
982 # that will be prepended by the server to all of our messages.
984 # The maximum raw message length we can send is therefore 512 - 2 - 2
985 # minus the length of our hostmask.
987 max_len = 508 - myself.fullform.size
989 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
990 # will have a + or - prepended
991 if server.capabilities[:"identify-msg"]
995 # When splitting the message, we'll be prefixing the following string:
996 # (e.g. "PRIVMSG #rbot :")
997 fixed = "#{type} #{where} :"
999 # And this is what's left
1000 left = max_len - fixed.size
1002 truncate = opts[:truncate_text]
1003 truncate = @default_send_options[:truncate_text] if truncate.size > left
1004 truncate = "" if truncate.size > left
1006 all_lines = messages.map { |line|
1010 case opts[:overlong]
1013 sub_lines = Array.new
1015 sub_lines << msg.slice!(0, left)
1017 lastspace = sub_lines.last.rindex(opts[:split_at])
1019 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1020 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1022 end until msg.empty?
1025 line.slice(0, left - truncate.size) << truncate
1027 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1032 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1033 lines = all_lines[0...opts[:max_lines]]
1034 new_last = lines.last.slice(0, left - truncate.size) << truncate
1035 lines.last.replace(new_last)
1041 sendq "#{fixed}#{line}", chan, ring
1042 delegate_sent(type, where, line)
1046 # queue an arbitraty message for the server
1047 def sendq(message="", chan=nil, ring=0)
1049 @socket.queue(message, chan, ring)
1052 # send a notice message to channel/nick +where+
1053 def notice(where, message, options={})
1054 return if where.kind_of?(Channel) and quiet_on?(where)
1055 sendmsg "NOTICE", where, message, options
1058 # say something (PRIVMSG) to channel/nick +where+
1059 def say(where, message, options={})
1060 return if where.kind_of?(Channel) and quiet_on?(where)
1061 sendmsg "PRIVMSG", where, message, options
1064 def ctcp_notice(where, command, message, options={})
1065 return if where.kind_of?(Channel) and quiet_on?(where)
1066 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1069 def ctcp_say(where, command, message, options={})
1070 return if where.kind_of?(Channel) and quiet_on?(where)
1071 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1074 # perform a CTCP action with message +message+ to channel/nick +where+
1075 def action(where, message, options={})
1076 ctcp_say(where, 'ACTION', message, options)
1079 # quick way to say "okay" (or equivalent) to +where+
1081 say where, @lang.get("okay")
1084 # set topic of channel +where+ to +topic+
1085 # can also be used to retrieve the topic of channel +where+
1086 # by omitting the last argument
1087 def topic(where, topic=nil)
1089 sendq "TOPIC #{where}", where, 2
1091 sendq "TOPIC #{where} :#{topic}", where, 2
1095 def disconnect(message=nil)
1096 message = @lang.get("quit") if (!message || message.empty?)
1097 if @socket.connected?
1099 debug "Clearing socket"
1101 debug "Sending quit message"
1102 @socket.emergency_puts "QUIT :#{message}"
1103 debug "Logging quits"
1104 delegate_sent('QUIT', myself, message)
1105 debug "Flushing socket"
1107 rescue SocketError => e
1108 error "error while disconnecting socket: #{e.pretty_inspect}"
1110 debug "Shutting down socket"
1117 # disconnect from the server and cleanup all plugins and modules
1118 def shutdown(message=nil)
1119 @quit_mutex.synchronize do
1120 debug "Shutting down: #{message}"
1121 ## No we don't restore them ... let everything run through
1123 # trap("SIGINT", "DEFAULT")
1124 # trap("SIGTERM", "DEFAULT")
1125 # trap("SIGHUP", "DEFAULT")
1127 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1129 debug "\tdisconnecting..."
1131 debug "\tstopping timer..."
1133 debug "\tsaving ..."
1135 debug "\tcleaning up ..."
1136 @save_mutex.synchronize do
1139 # debug "\tstopping timers ..."
1141 # debug "Closing registries"
1143 debug "\t\tcleaning up the db environment ..."
1145 log "rbot quit (#{message})"
1149 # message:: optional IRC quit message
1150 # quit IRC, shutdown the bot
1151 def quit(message=nil)
1159 # totally shutdown and respawn the bot
1160 def restart(message=nil)
1161 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1163 sleep @config['server.reconnect_wait']
1166 # Note, this fails on Windows
1167 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1171 rescue Errno::ENOENT
1173 exec("ruby", *(@argv.unshift $0))
1174 rescue Exception => e
1180 # call the save method for all of the botmodules
1182 @save_mutex.synchronize do
1188 # call the rescan method for all of the botmodules
1190 debug "\tstopping timer..."
1192 @save_mutex.synchronize do
1199 # channel:: channel to join
1200 # key:: optional channel key if channel is +s
1202 def join(channel, key=nil)
1204 sendq "JOIN #{channel} :#{key}", channel, 2
1206 sendq "JOIN #{channel}", channel, 2
1211 def part(channel, message="")
1212 sendq "PART #{channel} :#{message}", channel, 2
1215 # attempt to change bot's nick to +name+
1217 sendq "NICK #{name}"
1221 def mode(channel, mode, target=nil)
1222 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1226 def whois(nick, target=nil)
1227 sendq "WHOIS #{target} #{nick}", nil, 0
1231 def kick(channel, user, msg)
1232 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1235 # m:: message asking for help
1236 # topic:: optional topic help is requested for
1237 # respond to online help requests
1239 topic = nil if topic == ""
1242 helpstr = _("help topics: ")
1243 helpstr += @plugins.helptopics
1244 helpstr += _(" (help <topic> for more info)")
1246 unless(helpstr = @plugins.help(topic))
1247 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1253 # returns a string describing the current status of the bot (uptime etc)
1255 secs_up = Time.new - @startup_time
1256 uptime = Utils.secs_to_string secs_up
1257 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1258 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1260 :up => uptime, :plug => @plugins.length,
1261 :sent => @socket.lines_sent, :recv => @socket.lines_received
1265 # We want to respond to a hung server in a timely manner. If nothing was received
1266 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1267 # the server. If the PONG is not received within the user-defined timeout, we
1268 # assume we're in ping timeout and act accordingly.
1270 act_timeout = @config['server.ping_timeout']
1271 return if act_timeout <= 0
1273 if @last_rec && now > @last_rec + act_timeout
1275 # No previous PING pending, send a new one
1277 @last_ping = Time.now
1279 diff = now - @last_ping
1280 if diff > act_timeout
1281 debug "no PONG from server in #{diff} seconds, reconnecting"
1282 # the actual reconnect is handled in the main loop:
1283 raise TimeoutError, "no PONG from server in #{diff} seconds"
1289 def stop_server_pings
1290 # cancel previous PINGs and reset time of last RECV
1297 # delegate sent messages
1298 def delegate_sent(type, where, message)
1299 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1302 m = NoticeMessage.new(*args)
1304 m = PrivMessage.new(*args)
1306 m = QuitMessage.new(*args)
1307 m.was_on = myself.channels
1309 @plugins.delegate('sent', m)