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 class ServerError < RuntimeError
47 def rawlog(level, message=nil, who_pos=1)
49 if call_stack.length > who_pos
50 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
54 # Output each line. To distinguish between separate messages and multi-line
55 # messages originating at the same time, we blank #{who} after the first message
57 # Also, we output strings as-is but for other objects we use pretty_inspect
62 str = message.pretty_inspect
66 qmsg.push [level, l.chomp, who]
73 if $log_thread && $log_thread.alive?
82 def restart_logger(newlogger = false)
85 $logger = newlogger if newlogger
87 $log_thread = Thread.new do
89 while ls = $log_queue.pop
90 ls.each { |l| $logger.add(*l) }
98 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
103 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
107 def debug(message=nil, who_pos=1)
108 rawlog(Logger::Severity::DEBUG, message, who_pos)
111 def log(message=nil, who_pos=1)
112 rawlog(Logger::Severity::INFO, message, who_pos)
115 def warning(message=nil, who_pos=1)
116 rawlog(Logger::Severity::WARN, message, who_pos)
119 def error(message=nil, who_pos=1)
120 rawlog(Logger::Severity::ERROR, message, who_pos)
123 def fatal(message=nil, who_pos=1)
124 rawlog(Logger::Severity::FATAL, message, who_pos)
129 warning "warning test"
133 # The following global is used for the improved signal handling.
137 require 'rbot/rbotconfig'
138 require 'rbot/load-gettext'
139 require 'rbot/config'
140 require 'rbot/config-compat'
143 require 'rbot/rfc2812'
144 require 'rbot/ircsocket'
145 require 'rbot/botuser'
147 require 'rbot/plugins'
148 require 'rbot/message'
149 require 'rbot/language'
150 require 'rbot/dbhash'
151 require 'rbot/registry'
155 # Main bot class, which manages the various components, receives messages,
156 # handles them or passes them to plugins, and contains core functionality.
158 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
159 SOURCE_URL = "http://ruby-rbot.org"
160 # the bot's Auth data
163 # the bot's Config data
166 # the botclass for this bot (determines configdir among other things)
167 attr_reader :botclass
169 # used to perform actions periodically (saves configuration once per minute
173 # synchronize with this mutex while touching permanent data files:
174 # saving, flushing, cleaning up ...
175 attr_reader :save_mutex
177 # bot's Language data
184 # bot's object registry, plugins get an interface to this for persistant
185 # storage (hash interface tied to a bdb file, plugins use Accessors to store
186 # and restore objects in their own namespaces.)
187 attr_reader :registry
189 # bot's plugins. This is an instance of class Plugins
192 # bot's httputil help 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 User in the client/server connection
213 # nick wanted by the bot. This defaults to the irc.nick config value,
214 # but may be overridden by a manual !nick command
216 @wanted_nick || config['irc.nick']
219 # set the nick wanted by the bot
221 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
224 @wanted_nick = wn.to_s.dup
232 ret = self.to_s[0..-2]
233 ret << ' version=' << $version.inspect
234 ret << ' botclass=' << botclass.inspect
235 ret << ' lang="' << lang.language
240 ret << ' nick=' << nick.inspect
243 ret << (server.to_s + (socket ?
244 ' [' << socket.server_uri.to_s << ']' : '')).inspect
245 unless server.channels.empty?
247 ret << server.channels.map { |c|
248 "%s%s" % [c.modes_of(nick).map { |m|
249 server.prefix_for_mode(m)
256 ret << ' plugins=' << plugins.inspect
261 # create a new Bot with botclass +botclass+
262 def initialize(botclass, params = {})
263 # Config for the core bot
264 # TODO should we split socket stuff into ircsocket, etc?
265 Config.register Config::ArrayValue.new('server.list',
266 :default => ['irc://localhost'], :wizard => true,
267 :requires_restart => true,
268 :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.")
269 Config.register Config::BooleanValue.new('server.ssl',
270 :default => false, :requires_restart => true, :wizard => true,
271 :desc => "Use SSL to connect to this server?")
272 Config.register Config::StringValue.new('server.password',
273 :default => false, :requires_restart => true,
274 :desc => "Password for connecting to this server (if required)",
276 Config.register Config::StringValue.new('server.bindhost',
277 :default => false, :requires_restart => true,
278 :desc => "Specific local host or IP for the bot to bind to (if required)",
280 Config.register Config::IntegerValue.new('server.reconnect_wait',
281 :default => 5, :validate => Proc.new{|v| v >= 0},
282 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
283 Config.register Config::IntegerValue.new('server.ping_timeout',
284 :default => 30, :validate => Proc.new{|v| v >= 0},
285 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
286 Config.register Config::ArrayValue.new('server.nocolor_modes',
287 :default => ['c'], :wizard => false,
288 :requires_restart => false,
289 :desc => "List of channel modes that require messages to be without colors")
291 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
292 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
293 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
294 Config.register Config::StringValue.new('irc.name',
295 :default => "Ruby bot", :requires_restart => true,
296 :desc => "IRC realname the bot should use")
297 Config.register Config::BooleanValue.new('irc.name_copyright',
298 :default => true, :requires_restart => true,
299 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
300 Config.register Config::StringValue.new('irc.user', :default => "rbot",
301 :requires_restart => true,
302 :desc => "local user the bot should appear to be", :wizard => true)
303 Config.register Config::ArrayValue.new('irc.join_channels',
304 :default => [], :wizard => true,
305 :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'")
306 Config.register Config::ArrayValue.new('irc.ignore_users',
308 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
309 Config.register Config::ArrayValue.new('irc.ignore_channels',
311 :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)")
313 Config.register Config::IntegerValue.new('core.save_every',
314 :default => 60, :validate => Proc.new{|v| v >= 0},
315 :on_change => Proc.new { |bot, v|
318 @timer.reschedule(@save_timer, v)
319 @timer.unblock(@save_timer)
321 @timer.block(@save_timer)
325 @save_timer = @timer.add(v) { bot.save }
327 # Nothing to do when v == 0
330 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
332 Config.register Config::BooleanValue.new('core.run_as_daemon',
333 :default => false, :requires_restart => true,
334 :desc => "Should the bot run as a daemon?")
336 Config.register Config::StringValue.new('log.file',
337 :default => false, :requires_restart => true,
338 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
339 Config.register Config::IntegerValue.new('log.level',
340 :default => 1, :requires_restart => false,
341 :validate => Proc.new { |v| (0..5).include?(v) },
342 :on_change => Proc.new { |bot, v|
345 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
346 Config.register Config::IntegerValue.new('log.keep',
347 :default => 1, :requires_restart => true,
348 :validate => Proc.new { |v| v >= 0 },
349 :desc => "How many old console messages logfiles to keep")
350 Config.register Config::IntegerValue.new('log.max_size',
351 :default => 10, :requires_restart => true,
352 :validate => Proc.new { |v| v > 0 },
353 :desc => "Maximum console messages logfile size (in megabytes)")
355 Config.register Config::ArrayValue.new('plugins.path',
356 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
357 :requires_restart => false,
358 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
359 :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")
361 Config.register Config::EnumValue.new('send.newlines',
362 :values => ['split', 'join'], :default => 'split',
363 :on_change => Proc.new { |bot, v|
364 bot.set_default_send_options :newlines => v.to_sym
366 :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")
367 Config.register Config::StringValue.new('send.join_with',
369 :on_change => Proc.new { |bot, v|
370 bot.set_default_send_options :join_with => v.dup
372 :desc => "String used to replace newlines when send.newlines is set to join")
373 Config.register Config::IntegerValue.new('send.max_lines',
375 :validate => Proc.new { |v| v >= 0 },
376 :on_change => Proc.new { |bot, v|
377 bot.set_default_send_options :max_lines => v
379 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
380 Config.register Config::EnumValue.new('send.overlong',
381 :values => ['split', 'truncate'], :default => 'split',
382 :on_change => Proc.new { |bot, v|
383 bot.set_default_send_options :overlong => v.to_sym
385 :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")
386 Config.register Config::StringValue.new('send.split_at',
388 :on_change => Proc.new { |bot, v|
389 bot.set_default_send_options :split_at => Regexp.new(v)
391 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
392 Config.register Config::BooleanValue.new('send.purge_split',
394 :on_change => Proc.new { |bot, v|
395 bot.set_default_send_options :purge_split => v
397 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
398 Config.register Config::StringValue.new('send.truncate_text',
399 :default => "#{Reverse}...#{Reverse}",
400 :on_change => Proc.new { |bot, v|
401 bot.set_default_send_options :truncate_text => v.dup
403 :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")
404 Config.register Config::IntegerValue.new('send.penalty_pct',
406 :validate => Proc.new { |v| v >= 0 },
407 :on_change => Proc.new { |bot, v|
408 bot.socket.penalty_pct = v
410 :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
412 @argv = params[:argv]
413 @run_dir = params[:run_dir] || Dir.pwd
415 unless FileTest.directory? Config::coredir
416 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
420 unless FileTest.directory? Config::datadir
421 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
425 unless botclass and not botclass.empty?
426 # We want to find a sensible default.
427 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
428 # * On Windows (at least the NT versions) we want to put our stuff in the
429 # Application Data folder.
430 # We don't use any particular O/S detection magic, exploiting the fact that
431 # Etc.getpwuid is nil on Windows
432 if Etc.getpwuid(Process::Sys.geteuid)
433 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
435 if ENV.has_key?('APPDATA')
436 botclass = ENV['APPDATA'].dup
437 botclass.gsub!("\\","/")
442 botclass = File.expand_path(botclass)
443 @botclass = botclass.gsub(/\/$/, "")
445 if FileTest.directory? botclass
446 # compare the templates dir with the current botclass, and fill it in with
448 # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
450 template = File.join Config::datadir, 'templates'
451 # note that we use the */** pattern because we don't want to match
452 # keywords.rbot, which gets deleted on load and would therefore be missing always
453 missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
455 dest = File.join(botclass, f)
456 FileUtils.mkdir_p File.dirname dest
457 FileUtils.cp File.join(template, f), dest
460 log "no #{botclass} directory found, creating from templates.."
461 if FileTest.exist? botclass
462 error "file #{botclass} exists but isn't a directory"
465 FileUtils.cp_r Config::datadir+'/templates', botclass
468 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
469 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
471 # Time at which the last PING was sent
473 # Time at which the last line was RECV'd from the server
476 @startup_time = Time.new
479 @config = Config.manager
480 @config.bot_associate(self)
481 rescue Exception => e
487 if @config['core.run_as_daemon']
491 @logfile = @config['log.file']
492 if @logfile.class!=String || @logfile.empty?
493 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
494 debug "Using `#{@logfile}' as debug log"
497 # See http://blog.humlab.umu.se/samuel/archives/000107.html
498 # for the backgrounding code
504 rescue NotImplementedError
505 warning "Could not background, fork not supported"
508 rescue Exception => e
509 warning "Could not background. #{e.pretty_inspect}"
512 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
515 logger = Logger.new(@logfile,
517 @config['log.max_size']*1024*1024)
518 logger.datetime_format= $dateformat
519 logger.level = @config['log.level']
520 logger.level = $cl_loglevel if defined? $cl_loglevel
521 logger.level = 0 if $debug
523 restart_logger(logger)
528 log "Redirecting standard input/output/error"
529 [$stdin, $stdout, $stderr].each do |fd|
531 fd.reopen "/dev/null"
533 # On Windows, there's not such thing as /dev/null
538 def $stdout.write(str=nil)
542 def $stdout.write(str=nil)
543 if str.to_s.match(/:\d+: warning:/)
552 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
556 @registry = Registry.new self
559 @save_mutex = Mutex.new
560 if @config['core.save_every'] > 0
561 @save_timer = @timer.add(@config['core.save_every']) { save }
565 @quit_mutex = Mutex.new
568 @lang = Language.new(self, @config['core.language'])
571 @auth = Auth::manager
572 @auth.bot_associate(self)
573 # @auth.load("#{botclass}/botusers.yaml")
574 rescue Exception => e
579 @auth.everyone.set_default_permission("*", true)
580 @auth.botowner.password= @config['auth.password']
582 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
583 @plugins = Plugins::manager
584 @plugins.bot_associate(self)
587 if @config['server.name']
588 debug "upgrading configuration (server.name => server.list)"
589 srv_uri = 'irc://' + @config['server.name']
590 srv_uri += ":#{@config['server.port']}" if @config['server.port']
591 @config.items['server.list'.to_sym].set_string(srv_uri)
592 @config.delete('server.name'.to_sym)
593 @config.delete('server.port'.to_sym)
594 debug "server.list is now #{@config['server.list'].inspect}"
597 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
602 # Channels where we are quiet
603 # Array of channels names where the bot should be quiet
604 # '*' means all channels
607 # but we always speak here
610 # the nick we want, if it's different from the irc.nick config value
611 # (e.g. as set by a !nick command)
614 @client[:welcome] = proc {|data|
615 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
617 @plugins.delegate("welcome", m)
618 @plugins.delegate("connect")
621 # TODO the next two @client should go into rfc2812.rb, probably
622 # Since capabs are two-steps processes, server.supports[:capab]
623 # should be a three-state: nil, [], [....]
624 asked_for = { :"identify-msg" => false }
625 @client[:isupport] = proc { |data|
626 if server.supports[:capab] and !asked_for[:"identify-msg"]
627 sendq "CAPAB IDENTIFY-MSG"
628 asked_for[:"identify-msg"] = true
631 @client[:datastr] = proc { |data|
632 if data[:text] == "IDENTIFY-MSG"
633 server.capabilities[:"identify-msg"] = true
635 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
639 @client[:privmsg] = proc { |data|
640 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
641 # debug "Message source is #{data[:source].inspect}"
642 # debug "Message target is #{data[:target].inspect}"
643 # debug "Bot is #{myself.inspect}"
645 @config['irc.ignore_channels'].each { |channel|
646 if m.target.downcase == channel.downcase
650 @config['irc.ignore_users'].each { |mask|
651 if m.source.matches?(server.new_netmask(mask))
656 @plugins.irc_delegate('privmsg', m)
658 @client[:notice] = proc { |data|
659 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
660 # pass it off to plugins that want to hear everything
661 @plugins.irc_delegate "notice", message
663 @client[:motd] = proc { |data|
664 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
665 @plugins.delegate "motd", m
667 @client[:nicktaken] = proc { |data|
668 new = "#{data[:nick]}_"
670 # If we're setting our nick at connection because our choice was taken,
671 # we have to fix our nick manually, because there will be no NICK message
672 # to inform us that our nick has been changed.
673 if data[:target] == '*'
674 debug "setting my connection nick to #{new}"
677 @plugins.delegate "nicktaken", data[:nick]
679 @client[:badnick] = proc {|data|
680 warning "bad nick (#{data[:nick]})"
682 @client[:ping] = proc {|data|
683 sendq "PONG #{data[:pingid]}"
685 @client[:pong] = proc {|data|
688 @client[:nick] = proc {|data|
689 # debug "Message source is #{data[:source].inspect}"
690 # debug "Bot is #{myself.inspect}"
691 source = data[:source]
694 m = NickMessage.new(self, server, source, old, new)
695 m.is_on = data[:is_on]
697 debug "my nick is now #{new}"
699 @plugins.irc_delegate("nick", m)
701 @client[:quit] = proc {|data|
702 source = data[:source]
703 message = data[:message]
704 m = QuitMessage.new(self, server, source, source, message)
705 m.was_on = data[:was_on]
706 @plugins.irc_delegate("quit", m)
708 @client[:mode] = proc {|data|
709 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
710 m.modes = data[:modes]
711 @plugins.delegate "modechange", m
713 @client[:whois] = proc {|data|
714 source = data[:source]
715 target = server.get_user(data[:whois][:nick])
716 m = WhoisMessage.new(self, server, source, target, data[:whois])
717 @plugins.delegate "whois", m
719 @client[:join] = proc {|data|
720 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
721 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
722 @plugins.irc_delegate("join", m)
723 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
725 @client[:part] = proc {|data|
726 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
727 @plugins.irc_delegate("part", m)
729 @client[:kick] = proc {|data|
730 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
731 @plugins.irc_delegate("kick", m)
733 @client[:invite] = proc {|data|
734 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
735 @plugins.irc_delegate("invite", m)
737 @client[:changetopic] = proc {|data|
738 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
740 @plugins.irc_delegate("topic", m)
742 # @client[:topic] = proc { |data|
743 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
745 @client[:topicinfo] = proc { |data|
746 channel = data[:channel]
747 topic = channel.topic
748 m = TopicMessage.new(self, server, data[:source], channel, topic)
749 m.info_or_set = :info
750 @plugins.irc_delegate("topic", m)
752 @client[:names] = proc { |data|
753 m = NamesMessage.new(self, server, server, data[:channel])
754 m.users = data[:users]
755 @plugins.delegate "names", m
757 @client[:error] = proc { |data|
758 raise ServerError, data[:message]
760 @client[:unknown] = proc { |data|
761 #debug "UNKNOWN: #{data[:serverstring]}"
762 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
763 @plugins.delegate "unknown_message", m
766 set_default_send_options :newlines => @config['send.newlines'].to_sym,
767 :join_with => @config['send.join_with'].dup,
768 :max_lines => @config['send.max_lines'],
769 :overlong => @config['send.overlong'].to_sym,
770 :split_at => Regexp.new(@config['send.split_at']),
771 :purge_split => @config['send.purge_split'],
772 :truncate_text => @config['send.truncate_text'].dup
777 def setup_plugins_path
778 @plugins.clear_botmodule_dirs
779 @plugins.add_botmodule_dir(Config::coredir + "/utils")
780 @plugins.add_botmodule_dir(Config::coredir)
781 @plugins.add_botmodule_dir("#{botclass}/plugins")
783 @config['plugins.path'].each do |_|
784 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
785 @plugins.add_botmodule_dir(path)
789 def set_default_send_options(opts={})
790 # Default send options for NOTICE and PRIVMSG
791 unless defined? @default_send_options
792 @default_send_options = {
793 :queue_channel => nil, # use default queue channel
794 :queue_ring => nil, # use default queue ring
795 :newlines => :split, # or :join
796 :join_with => ' ', # by default, use a single space
797 :max_lines => 0, # maximum number of lines to send with a single command
798 :overlong => :split, # or :truncate
799 # TODO an array of splitpoints would be preferrable for this option:
800 :split_at => /\s+/, # by default, split overlong lines at whitespace
801 :purge_split => true, # should the split string be removed?
802 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
805 @default_send_options.update opts unless opts.empty?
808 # checks if we should be quiet on a channel
809 def quiet_on?(channel)
810 ch = channel.downcase
811 return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
814 def set_quiet(channel = nil)
816 ch = channel.downcase.dup
817 @not_quiet.delete(ch)
826 def reset_quiet(channel = nil)
828 ch = channel.downcase.dup
837 # things to do when we receive a signal
838 def got_sig(sig, func=:quit)
839 debug "received #{sig}, queueing #{func}"
840 # this is not an interruption if we just need to reconnect
841 $interrupted += 1 unless func == :reconnect
842 self.send(func) unless @quit_mutex.locked?
843 debug "interrupted #{$interrupted} times"
854 trap("SIGINT") { got_sig("SIGINT") }
855 trap("SIGTERM") { got_sig("SIGTERM") }
856 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
857 trap("SIGUSR1") { got_sig("SIGUSR1", :reconnect) }
858 rescue ArgumentError => e
859 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
860 rescue Exception => e
861 debug "failed to trap signals: #{e.pretty_inspect}"
865 # connect the bot to IRC
868 quit if $interrupted > 0
872 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
874 quit if $interrupted > 0
876 realname = @config['irc.name'].clone || 'Ruby bot'
877 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
879 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
880 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
881 quit if $interrupted > 0
882 myself.nick = @config['irc.nick']
883 myself.user = @config['irc.user']
886 # disconnect the bot from IRC, if connected, and then connect (again)
887 def reconnect(message=nil, too_fast=false)
888 # we will wait only if @last_rec was not nil, i.e. if we were connected or
889 # got disconnected by a network error
890 # if someone wants to manually call disconnect() _and_ reconnect(), they
891 # will have to take care of the waiting themselves
892 will_wait = !!@last_rec
894 if @socket.connected?
899 log "\n\nDisconnected\n\n"
901 quit if $interrupted > 0
903 log "\n\nWaiting to reconnect\n\n"
904 sleep @config['server.reconnect_wait']
905 sleep 10*@config['server.reconnect_wait'] if too_fast
911 # begin event handling loop
917 reconnect(quit_msg, too_fast)
918 quit if $interrupted > 0
919 while @socket.connected?
920 quit if $interrupted > 0
922 # Wait for messages and process them as they arrive. If nothing is
923 # received, we call the ping_server() method that will PING the
924 # server if appropriate, or raise a TimeoutError if no PONG has been
925 # received in the user-chosen timeout since the last PING sent.
927 break unless reply = @socket.gets
929 @client.process reply
935 # I despair of this. Some of my users get "connection reset by peer"
936 # exceptions that ARENT SocketError's. How am I supposed to handle
941 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
942 error "network exception: #{e.pretty_inspect}"
945 # received an ERROR from the server
946 quit_msg = "server ERROR: " + e.message
947 too_fast = e.message.index("reconnect too fast")
949 rescue BDB::Fatal => e
950 fatal "fatal bdb error: #{e.pretty_inspect}"
952 # Why restart? DB problems are serious stuff ...
953 # restart("Oops, we seem to have registry problems ...")
956 rescue Exception => e
957 error "non-net exception: #{e.pretty_inspect}"
960 fatal "unexpected exception: #{e.pretty_inspect}"
967 # type:: message type
968 # where:: message target
969 # message:: message text
970 # send message +message+ of type +type+ to target +where+
971 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
972 # relevant say() or notice() methods. This one should be used for IRCd
973 # extensions you want to use in modules.
974 def sendmsg(type, where, original_message, options={})
975 opts = @default_send_options.merge(options)
977 # For starters, set up appropriate queue channels and rings
978 mchan = opts[:queue_channel]
979 mring = opts[:queue_ring]
996 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
998 # if target is a channel with nocolor modes, strip colours
999 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1000 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1003 messages = Array.new
1004 case opts[:newlines]
1006 messages << [multi_line.gsub("\n", opts[:join_with])]
1008 multi_line.each_line { |line|
1010 next unless(line.size > 0)
1014 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1017 # The IRC protocol requires that each raw message must be not longer
1018 # than 512 characters. From this length with have to subtract the EOL
1019 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1020 # that will be prepended by the server to all of our messages.
1022 # The maximum raw message length we can send is therefore 512 - 2 - 2
1023 # minus the length of our hostmask.
1025 max_len = 508 - myself.fullform.size
1027 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1028 # will have a + or - prepended
1029 if server.capabilities[:"identify-msg"]
1033 # When splitting the message, we'll be prefixing the following string:
1034 # (e.g. "PRIVMSG #rbot :")
1035 fixed = "#{type} #{where} :"
1037 # And this is what's left
1038 left = max_len - fixed.size
1040 truncate = opts[:truncate_text]
1041 truncate = @default_send_options[:truncate_text] if truncate.size > left
1042 truncate = "" if truncate.size > left
1044 all_lines = messages.map { |line|
1048 case opts[:overlong]
1051 sub_lines = Array.new
1053 sub_lines << msg.slice!(0, left)
1055 lastspace = sub_lines.last.rindex(opts[:split_at])
1057 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1058 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1060 end until msg.empty?
1063 line.slice(0, left - truncate.size) << truncate
1065 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1070 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1071 lines = all_lines[0...opts[:max_lines]]
1072 new_last = lines.last.slice(0, left - truncate.size) << truncate
1073 lines.last.replace(new_last)
1079 sendq "#{fixed}#{line}", chan, ring
1080 delegate_sent(type, where, line)
1084 # queue an arbitraty message for the server
1085 def sendq(message="", chan=nil, ring=0)
1087 @socket.queue(message, chan, ring)
1090 # send a notice message to channel/nick +where+
1091 def notice(where, message, options={})
1092 return if where.kind_of?(Channel) and quiet_on?(where)
1093 sendmsg "NOTICE", where, message, options
1096 # say something (PRIVMSG) to channel/nick +where+
1097 def say(where, message, options={})
1098 return if where.kind_of?(Channel) and quiet_on?(where)
1099 sendmsg "PRIVMSG", where, message, options
1102 def ctcp_notice(where, command, message, options={})
1103 return if where.kind_of?(Channel) and quiet_on?(where)
1104 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1107 def ctcp_say(where, command, message, options={})
1108 return if where.kind_of?(Channel) and quiet_on?(where)
1109 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1112 # perform a CTCP action with message +message+ to channel/nick +where+
1113 def action(where, message, options={})
1114 ctcp_say(where, 'ACTION', message, options)
1117 # quick way to say "okay" (or equivalent) to +where+
1119 say where, @lang.get("okay")
1122 # set topic of channel +where+ to +topic+
1123 # can also be used to retrieve the topic of channel +where+
1124 # by omitting the last argument
1125 def topic(where, topic=nil)
1127 sendq "TOPIC #{where}", where, 2
1129 sendq "TOPIC #{where} :#{topic}", where, 2
1133 def disconnect(message=nil)
1134 message = @lang.get("quit") if (!message || message.empty?)
1135 if @socket.connected?
1137 debug "Clearing socket"
1139 debug "Sending quit message"
1140 @socket.emergency_puts "QUIT :#{message}"
1141 debug "Logging quits"
1142 delegate_sent('QUIT', myself, message)
1143 debug "Flushing socket"
1145 rescue SocketError => e
1146 error "error while disconnecting socket: #{e.pretty_inspect}"
1148 debug "Shutting down socket"
1155 # disconnect from the server and cleanup all plugins and modules
1156 def shutdown(message=nil)
1157 @quit_mutex.synchronize do
1158 debug "Shutting down: #{message}"
1159 ## No we don't restore them ... let everything run through
1161 # trap("SIGINT", "DEFAULT")
1162 # trap("SIGTERM", "DEFAULT")
1163 # trap("SIGHUP", "DEFAULT")
1165 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1167 debug "\tdisconnecting..."
1169 debug "\tstopping timer..."
1171 debug "\tsaving ..."
1173 debug "\tcleaning up ..."
1174 @save_mutex.synchronize do
1177 # debug "\tstopping timers ..."
1179 # debug "Closing registries"
1181 debug "\t\tcleaning up the db environment ..."
1183 log "rbot quit (#{message})"
1187 # message:: optional IRC quit message
1188 # quit IRC, shutdown the bot
1189 def quit(message=nil)
1197 # totally shutdown and respawn the bot
1198 def restart(message=nil)
1199 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1201 sleep @config['server.reconnect_wait']
1204 # Note, this fails on Windows
1205 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1209 rescue Errno::ENOENT
1211 exec("ruby", *(@argv.unshift $0))
1212 rescue Exception => e
1218 # call the save method for all of the botmodules
1220 @save_mutex.synchronize do
1226 # call the rescan method for all of the botmodules
1228 debug "\tstopping timer..."
1230 @save_mutex.synchronize do
1237 # channel:: channel to join
1238 # key:: optional channel key if channel is +s
1240 def join(channel, key=nil)
1242 sendq "JOIN #{channel} :#{key}", channel, 2
1244 sendq "JOIN #{channel}", channel, 2
1249 def part(channel, message="")
1250 sendq "PART #{channel} :#{message}", channel, 2
1253 # attempt to change bot's nick to +name+
1255 sendq "NICK #{name}"
1259 def mode(channel, mode, target=nil)
1260 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1264 def whois(nick, target=nil)
1265 sendq "WHOIS #{target} #{nick}", nil, 0
1269 def kick(channel, user, msg)
1270 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1273 # m:: message asking for help
1274 # topic:: optional topic help is requested for
1275 # respond to online help requests
1277 topic = nil if topic == ""
1280 helpstr = _("help topics: ")
1281 helpstr += @plugins.helptopics
1282 helpstr += _(" (help <topic> for more info)")
1284 unless(helpstr = @plugins.help(topic))
1285 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1291 # returns a string describing the current status of the bot (uptime etc)
1293 secs_up = Time.new - @startup_time
1294 uptime = Utils.secs_to_string secs_up
1295 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1296 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1298 :up => uptime, :plug => @plugins.length,
1299 :sent => @socket.lines_sent, :recv => @socket.lines_received
1303 # We want to respond to a hung server in a timely manner. If nothing was received
1304 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1305 # the server. If the PONG is not received within the user-defined timeout, we
1306 # assume we're in ping timeout and act accordingly.
1308 act_timeout = @config['server.ping_timeout']
1309 return if act_timeout <= 0
1311 if @last_rec && now > @last_rec + act_timeout
1313 # No previous PING pending, send a new one
1315 @last_ping = Time.now
1317 diff = now - @last_ping
1318 if diff > act_timeout
1319 debug "no PONG from server in #{diff} seconds, reconnecting"
1320 # the actual reconnect is handled in the main loop:
1321 raise TimeoutError, "no PONG from server in #{diff} seconds"
1327 def stop_server_pings
1328 # cancel previous PINGs and reset time of last RECV
1335 # delegate sent messages
1336 def delegate_sent(type, where, message)
1337 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1340 m = NoticeMessage.new(*args)
1342 m = PrivMessage.new(*args)
1344 m = QuitMessage.new(*args)
1345 m.was_on = myself.channels
1347 @plugins.delegate('sent', m)