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::FloatValue.new('server.sendq_delay',
281 :default => 2.0, :validate => Proc.new{|v| v >= 0},
282 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
283 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
284 Config.register Config::IntegerValue.new('server.sendq_burst',
285 :default => 4, :validate => Proc.new{|v| v >= 0},
286 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
287 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
288 Config.register Config::IntegerValue.new('server.ping_timeout',
289 :default => 30, :validate => Proc.new{|v| v >= 0},
290 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
291 Config.register Config::ArrayValue.new('server.nocolor_modes',
292 :default => ['c'], :wizard => false,
293 :requires_restart => false,
294 :desc => "List of channel modes that require messages to be without colors")
296 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
297 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
298 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
299 Config.register Config::StringValue.new('irc.name',
300 :default => "Ruby bot", :requires_restart => true,
301 :desc => "IRC realname the bot should use")
302 Config.register Config::BooleanValue.new('irc.name_copyright',
303 :default => true, :requires_restart => true,
304 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
305 Config.register Config::StringValue.new('irc.user', :default => "rbot",
306 :requires_restart => true,
307 :desc => "local user the bot should appear to be", :wizard => true)
308 Config.register Config::ArrayValue.new('irc.join_channels',
309 :default => [], :wizard => true,
310 :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'")
311 Config.register Config::ArrayValue.new('irc.ignore_users',
313 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
315 Config.register Config::IntegerValue.new('core.save_every',
316 :default => 60, :validate => Proc.new{|v| v >= 0},
317 :on_change => Proc.new { |bot, v|
320 @timer.reschedule(@save_timer, v)
321 @timer.unblock(@save_timer)
323 @timer.block(@save_timer)
327 @save_timer = @timer.add(v) { bot.save }
329 # Nothing to do when v == 0
332 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
334 Config.register Config::BooleanValue.new('core.run_as_daemon',
335 :default => false, :requires_restart => true,
336 :desc => "Should the bot run as a daemon?")
338 Config.register Config::StringValue.new('log.file',
339 :default => false, :requires_restart => true,
340 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
341 Config.register Config::IntegerValue.new('log.level',
342 :default => 1, :requires_restart => false,
343 :validate => Proc.new { |v| (0..5).include?(v) },
344 :on_change => Proc.new { |bot, v|
347 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
348 Config.register Config::IntegerValue.new('log.keep',
349 :default => 1, :requires_restart => true,
350 :validate => Proc.new { |v| v >= 0 },
351 :desc => "How many old console messages logfiles to keep")
352 Config.register Config::IntegerValue.new('log.max_size',
353 :default => 10, :requires_restart => true,
354 :validate => Proc.new { |v| v > 0 },
355 :desc => "Maximum console messages logfile size (in megabytes)")
357 Config.register Config::ArrayValue.new('plugins.path',
358 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
359 :requires_restart => false,
360 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
361 :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")
363 Config.register Config::EnumValue.new('send.newlines',
364 :values => ['split', 'join'], :default => 'split',
365 :on_change => Proc.new { |bot, v|
366 bot.set_default_send_options :newlines => v.to_sym
368 :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")
369 Config.register Config::StringValue.new('send.join_with',
371 :on_change => Proc.new { |bot, v|
372 bot.set_default_send_options :join_with => v.dup
374 :desc => "String used to replace newlines when send.newlines is set to join")
375 Config.register Config::IntegerValue.new('send.max_lines',
377 :validate => Proc.new { |v| v >= 0 },
378 :on_change => Proc.new { |bot, v|
379 bot.set_default_send_options :max_lines => v
381 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
382 Config.register Config::EnumValue.new('send.overlong',
383 :values => ['split', 'truncate'], :default => 'split',
384 :on_change => Proc.new { |bot, v|
385 bot.set_default_send_options :overlong => v.to_sym
387 :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")
388 Config.register Config::StringValue.new('send.split_at',
390 :on_change => Proc.new { |bot, v|
391 bot.set_default_send_options :split_at => Regexp.new(v)
393 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
394 Config.register Config::BooleanValue.new('send.purge_split',
396 :on_change => Proc.new { |bot, v|
397 bot.set_default_send_options :purge_split => v
399 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
400 Config.register Config::StringValue.new('send.truncate_text',
401 :default => "#{Reverse}...#{Reverse}",
402 :on_change => Proc.new { |bot, v|
403 bot.set_default_send_options :truncate_text => v.dup
405 :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")
407 @argv = params[:argv]
408 @run_dir = params[:run_dir] || Dir.pwd
410 unless FileTest.directory? Config::coredir
411 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
415 unless FileTest.directory? Config::datadir
416 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
420 unless botclass and not botclass.empty?
421 # We want to find a sensible default.
422 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
423 # * On Windows (at least the NT versions) we want to put our stuff in the
424 # Application Data folder.
425 # We don't use any particular O/S detection magic, exploiting the fact that
426 # Etc.getpwuid is nil on Windows
427 if Etc.getpwuid(Process::Sys.geteuid)
428 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
430 if ENV.has_key?('APPDATA')
431 botclass = ENV['APPDATA'].dup
432 botclass.gsub!("\\","/")
437 botclass = File.expand_path(botclass)
438 @botclass = botclass.gsub(/\/$/, "")
440 if FileTest.directory? botclass
441 # compare the templates dir with the current botclass, and fill it in with
443 # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
445 template = File.join Config::datadir, 'templates'
446 # note that we use the */** pattern because we don't want to match
447 # keywords.rbot, which gets deleted on load and would therefore be missing always
448 missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
450 dest = File.join(botclass, f)
451 FileUtils.mkdir_p File.dirname dest
452 FileUtils.cp File.join(template, f), dest
455 log "no #{botclass} directory found, creating from templates.."
456 if FileTest.exist? botclass
457 error "file #{botclass} exists but isn't a directory"
460 FileUtils.cp_r Config::datadir+'/templates', botclass
463 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
464 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
466 # Time at which the last PING was sent
468 # Time at which the last line was RECV'd from the server
471 @startup_time = Time.new
474 @config = Config.manager
475 @config.bot_associate(self)
476 rescue Exception => e
482 if @config['core.run_as_daemon']
486 @logfile = @config['log.file']
487 if @logfile.class!=String || @logfile.empty?
488 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
489 debug "Using `#{@logfile}' as debug log"
492 # See http://blog.humlab.umu.se/samuel/archives/000107.html
493 # for the backgrounding code
499 rescue NotImplementedError
500 warning "Could not background, fork not supported"
503 rescue Exception => e
504 warning "Could not background. #{e.pretty_inspect}"
507 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
510 logger = Logger.new(@logfile,
512 @config['log.max_size']*1024*1024)
513 logger.datetime_format= $dateformat
514 logger.level = @config['log.level']
515 logger.level = $cl_loglevel if defined? $cl_loglevel
516 logger.level = 0 if $debug
518 restart_logger(logger)
523 log "Redirecting standard input/output/error"
524 [$stdin, $stdout, $stderr].each do |fd|
526 fd.reopen "/dev/null"
528 # On Windows, there's not such thing as /dev/null
533 def $stdout.write(str=nil)
537 def $stdout.write(str=nil)
538 if str.to_s.match(/:\d+: warning:/)
547 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
551 @registry = Registry.new self
554 @save_mutex = Mutex.new
555 if @config['core.save_every'] > 0
556 @save_timer = @timer.add(@config['core.save_every']) { save }
560 @quit_mutex = Mutex.new
563 @lang = Language.new(self, @config['core.language'])
566 @auth = Auth::manager
567 @auth.bot_associate(self)
568 # @auth.load("#{botclass}/botusers.yaml")
569 rescue Exception => e
574 @auth.everyone.set_default_permission("*", true)
575 @auth.botowner.password= @config['auth.password']
577 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
578 @plugins = Plugins::manager
579 @plugins.bot_associate(self)
582 if @config['server.name']
583 debug "upgrading configuration (server.name => server.list)"
584 srv_uri = 'irc://' + @config['server.name']
585 srv_uri += ":#{@config['server.port']}" if @config['server.port']
586 @config.items['server.list'.to_sym].set_string(srv_uri)
587 @config.delete('server.name'.to_sym)
588 @config.delete('server.port'.to_sym)
589 debug "server.list is now #{@config['server.list'].inspect}"
592 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
597 # Channels where we are quiet
598 # Array of channels names where the bot should be quiet
599 # '*' means all channels
603 # the nick we want, if it's different from the irc.nick config value
604 # (e.g. as set by a !nick command)
607 @client[:welcome] = proc {|data|
608 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
610 @plugins.delegate("welcome", m)
611 @plugins.delegate("connect")
614 # TODO the next two @client should go into rfc2812.rb, probably
615 # Since capabs are two-steps processes, server.supports[:capab]
616 # should be a three-state: nil, [], [....]
617 asked_for = { :"identify-msg" => false }
618 @client[:isupport] = proc { |data|
619 if server.supports[:capab] and !asked_for[:"identify-msg"]
620 sendq "CAPAB IDENTIFY-MSG"
621 asked_for[:"identify-msg"] = true
624 @client[:datastr] = proc { |data|
625 if data[:text] == "IDENTIFY-MSG"
626 server.capabilities[:"identify-msg"] = true
628 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
632 @client[:privmsg] = proc { |data|
633 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
634 # debug "Message source is #{data[:source].inspect}"
635 # debug "Message target is #{data[:target].inspect}"
636 # debug "Bot is #{myself.inspect}"
638 @config['irc.ignore_users'].each { |mask|
639 if m.source.matches?(server.new_netmask(mask))
644 @plugins.irc_delegate('privmsg', m)
646 @client[:notice] = proc { |data|
647 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
648 # pass it off to plugins that want to hear everything
649 @plugins.irc_delegate "notice", message
651 @client[:motd] = proc { |data|
652 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
653 @plugins.delegate "motd", m
655 @client[:nicktaken] = proc { |data|
656 new = "#{data[:nick]}_"
658 # If we're setting our nick at connection because our choice was taken,
659 # we have to fix our nick manually, because there will be no NICK message
660 # to inform us that our nick has been changed.
661 if data[:target] == '*'
662 debug "setting my connection nick to #{new}"
665 @plugins.delegate "nicktaken", data[:nick]
667 @client[:badnick] = proc {|data|
668 warning "bad nick (#{data[:nick]})"
670 @client[:ping] = proc {|data|
671 sendq "PONG #{data[:pingid]}"
673 @client[:pong] = proc {|data|
676 @client[:nick] = proc {|data|
677 # debug "Message source is #{data[:source].inspect}"
678 # debug "Bot is #{myself.inspect}"
679 source = data[:source]
682 m = NickMessage.new(self, server, source, old, new)
683 m.is_on = data[:is_on]
685 debug "my nick is now #{new}"
687 @plugins.irc_delegate("nick", m)
689 @client[:quit] = proc {|data|
690 source = data[:source]
691 message = data[:message]
692 m = QuitMessage.new(self, server, source, source, message)
693 m.was_on = data[:was_on]
694 @plugins.irc_delegate("quit", m)
696 @client[:mode] = proc {|data|
697 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
698 m.modes = data[:modes]
699 @plugins.delegate "modechange", m
701 @client[:whois] = proc {|data|
702 source = data[:source]
703 target = server.get_user(data[:whois][:nick])
704 m = WhoisMessage.new(self, server, source, target, data[:whois])
705 @plugins.delegate "whois", m
707 @client[:join] = proc {|data|
708 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
709 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
710 @plugins.irc_delegate("join", m)
711 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
713 @client[:part] = proc {|data|
714 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
715 @plugins.irc_delegate("part", m)
717 @client[:kick] = proc {|data|
718 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
719 @plugins.irc_delegate("kick", m)
721 @client[:invite] = proc {|data|
722 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
723 @plugins.irc_delegate("invite", m)
725 @client[:changetopic] = proc {|data|
726 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
728 @plugins.irc_delegate("topic", m)
730 # @client[:topic] = proc { |data|
731 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
733 @client[:topicinfo] = proc { |data|
734 channel = data[:channel]
735 topic = channel.topic
736 m = TopicMessage.new(self, server, data[:source], channel, topic)
737 m.info_or_set = :info
738 @plugins.irc_delegate("topic", m)
740 @client[:names] = proc { |data|
741 m = NamesMessage.new(self, server, server, data[:channel])
742 m.users = data[:users]
743 @plugins.delegate "names", m
745 @client[:unknown] = proc { |data|
746 #debug "UNKNOWN: #{data[:serverstring]}"
747 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
748 @plugins.delegate "unknown_message", m
751 set_default_send_options :newlines => @config['send.newlines'].to_sym,
752 :join_with => @config['send.join_with'].dup,
753 :max_lines => @config['send.max_lines'],
754 :overlong => @config['send.overlong'].to_sym,
755 :split_at => Regexp.new(@config['send.split_at']),
756 :purge_split => @config['send.purge_split'],
757 :truncate_text => @config['send.truncate_text'].dup
762 def setup_plugins_path
763 @plugins.clear_botmodule_dirs
764 @plugins.add_botmodule_dir(Config::coredir + "/utils")
765 @plugins.add_botmodule_dir(Config::coredir)
766 @plugins.add_botmodule_dir("#{botclass}/plugins")
768 @config['plugins.path'].each do |_|
769 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
770 @plugins.add_botmodule_dir(path)
774 def set_default_send_options(opts={})
775 # Default send options for NOTICE and PRIVMSG
776 unless defined? @default_send_options
777 @default_send_options = {
778 :queue_channel => nil, # use default queue channel
779 :queue_ring => nil, # use default queue ring
780 :newlines => :split, # or :join
781 :join_with => ' ', # by default, use a single space
782 :max_lines => 0, # maximum number of lines to send with a single command
783 :overlong => :split, # or :truncate
784 # TODO an array of splitpoints would be preferrable for this option:
785 :split_at => /\s+/, # by default, split overlong lines at whitespace
786 :purge_split => true, # should the split string be removed?
787 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
790 @default_send_options.update opts unless opts.empty?
793 # checks if we should be quiet on a channel
794 def quiet_on?(channel)
795 return @quiet.include?('*') || @quiet.include?(channel.downcase)
798 def set_quiet(channel = nil)
800 ch = channel.downcase.dup
808 def reset_quiet(channel = nil)
810 @quiet.delete channel.downcase
816 # things to do when we receive a signal
817 def got_sig(sig, func=:quit)
818 debug "received #{sig}, queueing #{func}"
820 self.send(func) unless @quit_mutex.locked?
821 debug "interrupted #{$interrupted} times"
832 trap("SIGINT") { got_sig("SIGINT") }
833 trap("SIGTERM") { got_sig("SIGTERM") }
834 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
835 rescue ArgumentError => e
836 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
837 rescue Exception => e
838 debug "failed to trap signals: #{e.pretty_inspect}"
842 # connect the bot to IRC
845 quit if $interrupted > 0
848 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
850 quit if $interrupted > 0
852 realname = @config['irc.name'].clone || 'Ruby bot'
853 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
855 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
856 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
857 quit if $interrupted > 0
858 myself.nick = @config['irc.nick']
859 myself.user = @config['irc.user']
862 # begin event handling loop
866 quit if $interrupted > 0
870 while @socket.connected?
871 quit if $interrupted > 0
873 # Wait for messages and process them as they arrive. If nothing is
874 # received, we call the ping_server() method that will PING the
875 # server if appropriate, or raise a TimeoutError if no PONG has been
876 # received in the user-chosen timeout since the last PING sent.
878 break unless reply = @socket.gets
880 @client.process reply
886 # I despair of this. Some of my users get "connection reset by peer"
887 # exceptions that ARENT SocketError's. How am I supposed to handle
892 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
893 error "network exception: #{e.pretty_inspect}"
895 rescue BDB::Fatal => e
896 fatal "fatal bdb error: #{e.pretty_inspect}"
898 # Why restart? DB problems are serious stuff ...
899 # restart("Oops, we seem to have registry problems ...")
902 rescue Exception => e
903 error "non-net exception: #{e.pretty_inspect}"
906 fatal "unexpected exception: #{e.pretty_inspect}"
913 log "\n\nDisconnected\n\n"
915 quit if $interrupted > 0
917 log "\n\nWaiting to reconnect\n\n"
918 sleep @config['server.reconnect_wait']
922 # type:: message type
923 # where:: message target
924 # message:: message text
925 # send message +message+ of type +type+ to target +where+
926 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
927 # relevant say() or notice() methods. This one should be used for IRCd
928 # extensions you want to use in modules.
929 def sendmsg(type, where, original_message, options={})
930 opts = @default_send_options.merge(options)
932 # For starters, set up appropriate queue channels and rings
933 mchan = opts[:queue_channel]
934 mring = opts[:queue_ring]
951 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
953 # if target is a channel with nocolor modes, strip colours
954 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
955 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
961 messages << [multi_line.gsub("\n", opts[:join_with])]
963 multi_line.each_line { |line|
965 next unless(line.size > 0)
969 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
972 # The IRC protocol requires that each raw message must be not longer
973 # than 512 characters. From this length with have to subtract the EOL
974 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
975 # that will be prepended by the server to all of our messages.
977 # The maximum raw message length we can send is therefore 512 - 2 - 2
978 # minus the length of our hostmask.
980 max_len = 508 - myself.fullform.size
982 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
983 # will have a + or - prepended
984 if server.capabilities[:"identify-msg"]
988 # When splitting the message, we'll be prefixing the following string:
989 # (e.g. "PRIVMSG #rbot :")
990 fixed = "#{type} #{where} :"
992 # And this is what's left
993 left = max_len - fixed.size
995 truncate = opts[:truncate_text]
996 truncate = @default_send_options[:truncate_text] if truncate.size > left
997 truncate = "" if truncate.size > left
999 all_lines = messages.map { |line|
1003 case opts[:overlong]
1006 sub_lines = Array.new
1008 sub_lines << msg.slice!(0, left)
1010 lastspace = sub_lines.last.rindex(opts[:split_at])
1012 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1013 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1015 end until msg.empty?
1018 line.slice(0, left - truncate.size) << truncate
1020 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1025 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1026 lines = all_lines[0...opts[:max_lines]]
1027 new_last = lines.last.slice(0, left - truncate.size) << truncate
1028 lines.last.replace(new_last)
1034 sendq "#{fixed}#{line}", chan, ring
1035 delegate_sent(type, where, line)
1039 # queue an arbitraty message for the server
1040 def sendq(message="", chan=nil, ring=0)
1042 @socket.queue(message, chan, ring)
1045 # send a notice message to channel/nick +where+
1046 def notice(where, message, options={})
1047 return if where.kind_of?(Channel) and quiet_on?(where)
1048 sendmsg "NOTICE", where, message, options
1051 # say something (PRIVMSG) to channel/nick +where+
1052 def say(where, message, options={})
1053 return if where.kind_of?(Channel) and quiet_on?(where)
1054 sendmsg "PRIVMSG", where, message, options
1057 def ctcp_notice(where, command, message, options={})
1058 return if where.kind_of?(Channel) and quiet_on?(where)
1059 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1062 def ctcp_say(where, command, message, options={})
1063 return if where.kind_of?(Channel) and quiet_on?(where)
1064 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1067 # perform a CTCP action with message +message+ to channel/nick +where+
1068 def action(where, message, options={})
1069 ctcp_say(where, 'ACTION', message, options)
1072 # quick way to say "okay" (or equivalent) to +where+
1074 say where, @lang.get("okay")
1077 # set topic of channel +where+ to +topic+
1078 # can also be used to retrieve the topic of channel +where+
1079 # by omitting the last argument
1080 def topic(where, topic=nil)
1082 sendq "TOPIC #{where}", where, 2
1084 sendq "TOPIC #{where} :#{topic}", where, 2
1088 def disconnect(message=nil)
1089 message = @lang.get("quit") if (!message || message.empty?)
1090 if @socket.connected?
1092 debug "Clearing socket"
1094 debug "Sending quit message"
1095 @socket.emergency_puts "QUIT :#{message}"
1096 debug "Logging quits"
1097 delegate_sent('QUIT', myself, message)
1098 debug "Flushing socket"
1100 rescue SocketError => e
1101 error "error while disconnecting socket: #{e.pretty_inspect}"
1103 debug "Shutting down socket"
1110 # disconnect from the server and cleanup all plugins and modules
1111 def shutdown(message=nil)
1112 @quit_mutex.synchronize do
1113 debug "Shutting down: #{message}"
1114 ## No we don't restore them ... let everything run through
1116 # trap("SIGINT", "DEFAULT")
1117 # trap("SIGTERM", "DEFAULT")
1118 # trap("SIGHUP", "DEFAULT")
1120 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1122 debug "\tdisconnecting..."
1124 debug "\tstopping timer..."
1126 debug "\tsaving ..."
1128 debug "\tcleaning up ..."
1129 @save_mutex.synchronize do
1132 # debug "\tstopping timers ..."
1134 # debug "Closing registries"
1136 debug "\t\tcleaning up the db environment ..."
1138 log "rbot quit (#{message})"
1142 # message:: optional IRC quit message
1143 # quit IRC, shutdown the bot
1144 def quit(message=nil)
1152 # totally shutdown and respawn the bot
1153 def restart(message=nil)
1154 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1156 sleep @config['server.reconnect_wait']
1159 # Note, this fails on Windows
1160 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1164 rescue Errno::ENOENT
1166 exec("ruby", *(@argv.unshift $0))
1167 rescue Exception => e
1173 # call the save method for all of the botmodules
1175 @save_mutex.synchronize do
1181 # call the rescan method for all of the botmodules
1183 debug "\tstopping timer..."
1185 @save_mutex.synchronize do
1192 # channel:: channel to join
1193 # key:: optional channel key if channel is +s
1195 def join(channel, key=nil)
1197 sendq "JOIN #{channel} :#{key}", channel, 2
1199 sendq "JOIN #{channel}", channel, 2
1204 def part(channel, message="")
1205 sendq "PART #{channel} :#{message}", channel, 2
1208 # attempt to change bot's nick to +name+
1210 sendq "NICK #{name}"
1214 def mode(channel, mode, target=nil)
1215 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1219 def whois(nick, target=nil)
1220 sendq "WHOIS #{target} #{nick}", nil, 0
1224 def kick(channel, user, msg)
1225 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1228 # m:: message asking for help
1229 # topic:: optional topic help is requested for
1230 # respond to online help requests
1232 topic = nil if topic == ""
1235 helpstr = _("help topics: ")
1236 helpstr += @plugins.helptopics
1237 helpstr += _(" (help <topic> for more info)")
1239 unless(helpstr = @plugins.help(topic))
1240 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1246 # returns a string describing the current status of the bot (uptime etc)
1248 secs_up = Time.new - @startup_time
1249 uptime = Utils.secs_to_string secs_up
1250 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1251 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1253 :up => uptime, :plug => @plugins.length,
1254 :sent => @socket.lines_sent, :recv => @socket.lines_received
1258 # We want to respond to a hung server in a timely manner. If nothing was received
1259 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1260 # the server. If the PONG is not received within the user-defined timeout, we
1261 # assume we're in ping timeout and act accordingly.
1263 act_timeout = @config['server.ping_timeout']
1264 return if act_timeout <= 0
1266 if @last_rec && now > @last_rec + act_timeout
1268 # No previous PING pending, send a new one
1270 @last_ping = Time.now
1272 diff = now - @last_ping
1273 if diff > act_timeout
1274 debug "no PONG from server in #{diff} seconds, reconnecting"
1275 # the actual reconnect is handled in the main loop:
1276 raise TimeoutError, "no PONG from server in #{diff} seconds"
1282 def stop_server_pings
1283 # cancel previous PINGs and reset time of last RECV
1290 # delegate sent messages
1291 def delegate_sent(type, where, message)
1292 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1295 m = NoticeMessage.new(*args)
1297 m = PrivMessage.new(*args)
1299 m = QuitMessage.new(*args)
1301 @plugins.delegate('sent', m)