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]
69 def restart_logger(newlogger = false)
70 if $log_thread && $log_thread.alive?
76 $logger = newlogger if newlogger
78 $log_thread = Thread.new do
80 while ls = $log_queue.pop
81 ls.each { |l| $logger.add(*l) }
89 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
94 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
98 def debug(message=nil, who_pos=1)
99 rawlog(Logger::Severity::DEBUG, message, who_pos)
102 def log(message=nil, who_pos=1)
103 rawlog(Logger::Severity::INFO, message, who_pos)
106 def warning(message=nil, who_pos=1)
107 rawlog(Logger::Severity::WARN, message, who_pos)
110 def error(message=nil, who_pos=1)
111 rawlog(Logger::Severity::ERROR, message, who_pos)
114 def fatal(message=nil, who_pos=1)
115 rawlog(Logger::Severity::FATAL, message, who_pos)
120 warning "warning test"
124 # The following global is used for the improved signal handling.
128 require 'rbot/rbotconfig'
129 require 'rbot/load-gettext'
130 require 'rbot/config'
131 require 'rbot/config-compat'
134 require 'rbot/rfc2812'
135 require 'rbot/ircsocket'
136 require 'rbot/botuser'
138 require 'rbot/plugins'
139 require 'rbot/message'
140 require 'rbot/language'
141 require 'rbot/dbhash'
142 require 'rbot/registry'
146 # Main bot class, which manages the various components, receives messages,
147 # handles them or passes them to plugins, and contains core functionality.
149 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
150 SOURCE_URL = "http://ruby-rbot.org"
151 # the bot's Auth data
154 # the bot's Config data
157 # the botclass for this bot (determines configdir among other things)
158 attr_reader :botclass
160 # used to perform actions periodically (saves configuration once per minute
164 # synchronize with this mutex while touching permanent data files:
165 # saving, flushing, cleaning up ...
166 attr_reader :save_mutex
168 # bot's Language data
175 # bot's object registry, plugins get an interface to this for persistant
176 # storage (hash interface tied to a bdb file, plugins use Accessors to store
177 # and restore objects in their own namespaces.)
178 attr_reader :registry
180 # bot's plugins. This is an instance of class Plugins
183 # bot's httputil help object, for fetching resources via http. Sets up
184 # proxies etc as defined by the bot configuration/environment
185 attr_accessor :httputil
187 # server we are connected to
193 # bot User in the client/server connection
199 # bot User in the client/server connection
207 ret = self.to_s[0..-2]
208 ret << ' version=' << $version.inspect
209 ret << ' botclass=' << botclass.inspect
210 ret << ' lang="' << lang.language
215 ret << ' nick=' << nick.inspect
218 ret << (server.to_s + (socket ?
219 ' [' << socket.server_uri.to_s << ']' : '')).inspect
220 unless server.channels.empty?
222 ret << server.channels.map { |c|
223 "%s%s" % [c.modes_of(nick).map { |m|
224 server.prefix_for_mode(m)
231 ret << ' plugins=' << plugins.inspect
236 # create a new Bot with botclass +botclass+
237 def initialize(botclass, params = {})
238 # Config for the core bot
239 # TODO should we split socket stuff into ircsocket, etc?
240 Config.register Config::ArrayValue.new('server.list',
241 :default => ['irc://localhost'], :wizard => true,
242 :requires_restart => true,
243 :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.")
244 Config.register Config::BooleanValue.new('server.ssl',
245 :default => false, :requires_restart => true, :wizard => true,
246 :desc => "Use SSL to connect to this server?")
247 Config.register Config::StringValue.new('server.password',
248 :default => false, :requires_restart => true,
249 :desc => "Password for connecting to this server (if required)",
251 Config.register Config::StringValue.new('server.bindhost',
252 :default => false, :requires_restart => true,
253 :desc => "Specific local host or IP for the bot to bind to (if required)",
255 Config.register Config::IntegerValue.new('server.reconnect_wait',
256 :default => 5, :validate => Proc.new{|v| v >= 0},
257 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
258 Config.register Config::FloatValue.new('server.sendq_delay',
259 :default => 2.0, :validate => Proc.new{|v| v >= 0},
260 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
261 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
262 Config.register Config::IntegerValue.new('server.sendq_burst',
263 :default => 4, :validate => Proc.new{|v| v >= 0},
264 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
265 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
266 Config.register Config::IntegerValue.new('server.ping_timeout',
267 :default => 30, :validate => Proc.new{|v| v >= 0},
268 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
270 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
271 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
272 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
273 Config.register Config::StringValue.new('irc.name',
274 :default => "Ruby bot", :requires_restart => true,
275 :desc => "IRC realname the bot should use")
276 Config.register Config::BooleanValue.new('irc.name_copyright',
277 :default => true, :requires_restart => true,
278 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
279 Config.register Config::StringValue.new('irc.user', :default => "rbot",
280 :requires_restart => true,
281 :desc => "local user the bot should appear to be", :wizard => true)
282 Config.register Config::ArrayValue.new('irc.join_channels',
283 :default => [], :wizard => true,
284 :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'")
285 Config.register Config::ArrayValue.new('irc.ignore_users',
287 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
289 Config.register Config::IntegerValue.new('core.save_every',
290 :default => 60, :validate => Proc.new{|v| v >= 0},
291 :on_change => Proc.new { |bot, v|
294 @timer.reschedule(@save_timer, v)
295 @timer.unblock(@save_timer)
297 @timer.block(@save_timer)
301 @save_timer = @timer.add(v) { bot.save }
303 # Nothing to do when v == 0
306 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
308 Config.register Config::BooleanValue.new('core.run_as_daemon',
309 :default => false, :requires_restart => true,
310 :desc => "Should the bot run as a daemon?")
312 Config.register Config::StringValue.new('log.file',
313 :default => false, :requires_restart => true,
314 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
315 Config.register Config::IntegerValue.new('log.level',
316 :default => 1, :requires_restart => false,
317 :validate => Proc.new { |v| (0..5).include?(v) },
318 :on_change => Proc.new { |bot, v|
321 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
322 Config.register Config::IntegerValue.new('log.keep',
323 :default => 1, :requires_restart => true,
324 :validate => Proc.new { |v| v >= 0 },
325 :desc => "How many old console messages logfiles to keep")
326 Config.register Config::IntegerValue.new('log.max_size',
327 :default => 10, :requires_restart => true,
328 :validate => Proc.new { |v| v > 0 },
329 :desc => "Maximum console messages logfile size (in megabytes)")
331 Config.register Config::ArrayValue.new('plugins.path',
332 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
333 :requires_restart => false,
334 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
335 :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")
337 Config.register Config::EnumValue.new('send.newlines',
338 :values => ['split', 'join'], :default => 'split',
339 :on_change => Proc.new { |bot, v|
340 bot.set_default_send_options :newlines => v.to_sym
342 :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")
343 Config.register Config::StringValue.new('send.join_with',
345 :on_change => Proc.new { |bot, v|
346 bot.set_default_send_options :join_with => v.dup
348 :desc => "String used to replace newlines when send.newlines is set to join")
349 Config.register Config::IntegerValue.new('send.max_lines',
351 :validate => Proc.new { |v| v >= 0 },
352 :on_change => Proc.new { |bot, v|
353 bot.set_default_send_options :max_lines => v
355 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
356 Config.register Config::EnumValue.new('send.overlong',
357 :values => ['split', 'truncate'], :default => 'split',
358 :on_change => Proc.new { |bot, v|
359 bot.set_default_send_options :overlong => v.to_sym
361 :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")
362 Config.register Config::StringValue.new('send.split_at',
364 :on_change => Proc.new { |bot, v|
365 bot.set_default_send_options :split_at => Regexp.new(v)
367 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
368 Config.register Config::BooleanValue.new('send.purge_split',
370 :on_change => Proc.new { |bot, v|
371 bot.set_default_send_options :purge_split => v
373 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
374 Config.register Config::StringValue.new('send.truncate_text',
375 :default => "#{Reverse}...#{Reverse}",
376 :on_change => Proc.new { |bot, v|
377 bot.set_default_send_options :truncate_text => v.dup
379 :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")
381 @argv = params[:argv]
382 @run_dir = params[:run_dir] || Dir.pwd
384 unless FileTest.directory? Config::coredir
385 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
389 unless FileTest.directory? Config::datadir
390 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
394 unless botclass and not botclass.empty?
395 # We want to find a sensible default.
396 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
397 # * On Windows (at least the NT versions) we want to put our stuff in the
398 # Application Data folder.
399 # We don't use any particular O/S detection magic, exploiting the fact that
400 # Etc.getpwuid is nil on Windows
401 if Etc.getpwuid(Process::Sys.geteuid)
402 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
404 if ENV.has_key?('APPDATA')
405 botclass = ENV['APPDATA'].dup
406 botclass.gsub!("\\","/")
411 botclass = File.expand_path(botclass)
412 @botclass = botclass.gsub(/\/$/, "")
414 unless FileTest.directory? botclass
415 log "no #{botclass} directory found, creating from templates.."
416 if FileTest.exist? botclass
417 error "file #{botclass} exists but isn't a directory"
420 FileUtils.cp_r Config::datadir+'/templates', botclass
423 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
424 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
426 # Time at which the last PING was sent
428 # Time at which the last line was RECV'd from the server
431 @startup_time = Time.new
434 @config = Config.manager
435 @config.bot_associate(self)
436 rescue Exception => e
442 if @config['core.run_as_daemon']
446 @logfile = @config['log.file']
447 if @logfile.class!=String || @logfile.empty?
448 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
449 debug "Using `#{@logfile}' as debug log"
452 # See http://blog.humlab.umu.se/samuel/archives/000107.html
453 # for the backgrounding code
459 rescue NotImplementedError
460 warning "Could not background, fork not supported"
463 rescue Exception => e
464 warning "Could not background. #{e.pretty_inspect}"
467 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
470 logger = Logger.new(@logfile,
472 @config['log.max_size']*1024*1024)
473 logger.datetime_format= $dateformat
474 logger.level = @config['log.level']
475 logger.level = $cl_loglevel if defined? $cl_loglevel
476 logger.level = 0 if $debug
478 restart_logger(logger)
483 log "Redirecting standard input/output/error"
484 [$stdin, $stdout, $stderr].each do |fd|
486 fd.reopen "/dev/null"
488 # On Windows, there's not such thing as /dev/null
493 def $stdout.write(str=nil)
497 def $stdout.write(str=nil)
498 if str.to_s.match(/:\d+: warning:/)
507 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
511 @registry = Registry.new self
514 @save_mutex = Mutex.new
515 if @config['core.save_every'] > 0
516 @save_timer = @timer.add(@config['core.save_every']) { save }
520 @quit_mutex = Mutex.new
523 @lang = Language.new(self, @config['core.language'])
526 @auth = Auth::manager
527 @auth.bot_associate(self)
528 # @auth.load("#{botclass}/botusers.yaml")
529 rescue Exception => e
534 @auth.everyone.set_default_permission("*", true)
535 @auth.botowner.password= @config['auth.password']
537 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
538 @plugins = Plugins::manager
539 @plugins.bot_associate(self)
542 if @config['server.name']
543 debug "upgrading configuration (server.name => server.list)"
544 srv_uri = 'irc://' + @config['server.name']
545 srv_uri += ":#{@config['server.port']}" if @config['server.port']
546 @config.items['server.list'.to_sym].set_string(srv_uri)
547 @config.delete('server.name'.to_sym)
548 @config.delete('server.port'.to_sym)
549 debug "server.list is now #{@config['server.list'].inspect}"
552 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
557 # Channels where we are quiet
558 # Array of channels names where the bot should be quiet
559 # '*' means all channels
563 @client[:welcome] = proc {|data|
564 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
566 @plugins.delegate("welcome", m)
567 @plugins.delegate("connect")
569 @config['irc.join_channels'].each { |c|
570 debug "autojoining channel #{c}"
571 if(c =~ /^(\S+)\s+(\S+)$/i)
579 # TODO the next two @client should go into rfc2812.rb, probably
580 # Since capabs are two-steps processes, server.supports[:capab]
581 # should be a three-state: nil, [], [....]
582 asked_for = { :"identify-msg" => false }
583 @client[:isupport] = proc { |data|
584 if server.supports[:capab] and !asked_for[:"identify-msg"]
585 sendq "CAPAB IDENTIFY-MSG"
586 asked_for[:"identify-msg"] = true
589 @client[:datastr] = proc { |data|
590 if data[:text] == "IDENTIFY-MSG"
591 server.capabilities[:"identify-msg"] = true
593 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
597 @client[:privmsg] = proc { |data|
598 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
599 # debug "Message source is #{data[:source].inspect}"
600 # debug "Message target is #{data[:target].inspect}"
601 # debug "Bot is #{myself.inspect}"
603 @config['irc.ignore_users'].each { |mask|
604 if m.source.matches?(server.new_netmask(mask))
609 @plugins.irc_delegate('privmsg', m)
611 @client[:notice] = proc { |data|
612 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
613 # pass it off to plugins that want to hear everything
614 @plugins.irc_delegate "notice", message
616 @client[:motd] = proc { |data|
617 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
618 @plugins.delegate "motd", m
620 @client[:nicktaken] = proc { |data|
621 new = "#{data[:nick]}_"
623 # If we're setting our nick at connection because our choice was taken,
624 # we have to fix our nick manually, because there will be no NICK message
625 # to inform us that our nick has been changed.
626 if data[:target] == '*'
627 debug "setting my connection nick to #{new}"
630 @plugins.delegate "nicktaken", data[:nick]
632 @client[:badnick] = proc {|data|
633 warning "bad nick (#{data[:nick]})"
635 @client[:ping] = proc {|data|
636 sendq "PONG #{data[:pingid]}"
638 @client[:pong] = proc {|data|
641 @client[:nick] = proc {|data|
642 # debug "Message source is #{data[:source].inspect}"
643 # debug "Bot is #{myself.inspect}"
644 source = data[:source]
647 m = NickMessage.new(self, server, source, old, new)
648 m.is_on = data[:is_on]
650 debug "my nick is now #{new}"
652 @plugins.irc_delegate("nick", m)
654 @client[:quit] = proc {|data|
655 source = data[:source]
656 message = data[:message]
657 m = QuitMessage.new(self, server, source, source, message)
658 m.was_on = data[:was_on]
659 @plugins.irc_delegate("quit", m)
661 @client[:mode] = proc {|data|
662 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
663 m.modes = data[:modes]
664 @plugins.delegate "modechange", m
666 @client[:join] = proc {|data|
667 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
668 @plugins.irc_delegate("join", m)
669 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
671 @client[:part] = proc {|data|
672 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
673 @plugins.irc_delegate("part", m)
675 @client[:kick] = proc {|data|
676 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
677 @plugins.irc_delegate("kick", m)
679 @client[:invite] = proc {|data|
680 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
681 @plugins.irc_delegate("invite", m)
683 @client[:changetopic] = proc {|data|
684 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
686 @plugins.irc_delegate("topic", m)
688 # @client[:topic] = proc { |data|
689 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
691 @client[:topicinfo] = proc { |data|
692 channel = data[:channel]
693 topic = channel.topic
694 m = TopicMessage.new(self, server, data[:source], channel, topic)
695 m.info_or_set = :info
696 @plugins.irc_delegate("topic", m)
698 @client[:names] = proc { |data|
699 m = NamesMessage.new(self, server, server, data[:channel])
700 m.users = data[:users]
701 @plugins.delegate "names", m
703 @client[:unknown] = proc { |data|
704 #debug "UNKNOWN: #{data[:serverstring]}"
705 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
706 @plugins.delegate "unknown_message", m
709 set_default_send_options :newlines => @config['send.newlines'].to_sym,
710 :join_with => @config['send.join_with'].dup,
711 :max_lines => @config['send.max_lines'],
712 :overlong => @config['send.overlong'].to_sym,
713 :split_at => Regexp.new(@config['send.split_at']),
714 :purge_split => @config['send.purge_split'],
715 :truncate_text => @config['send.truncate_text'].dup
720 def setup_plugins_path
721 @plugins.clear_botmodule_dirs
722 @plugins.add_botmodule_dir(Config::coredir + "/utils")
723 @plugins.add_botmodule_dir(Config::coredir)
724 @plugins.add_botmodule_dir("#{botclass}/plugins")
726 @config['plugins.path'].each do |_|
727 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
728 @plugins.add_botmodule_dir(path)
732 def set_default_send_options(opts={})
733 # Default send options for NOTICE and PRIVMSG
734 unless defined? @default_send_options
735 @default_send_options = {
736 :queue_channel => nil, # use default queue channel
737 :queue_ring => nil, # use default queue ring
738 :newlines => :split, # or :join
739 :join_with => ' ', # by default, use a single space
740 :max_lines => 0, # maximum number of lines to send with a single command
741 :overlong => :split, # or :truncate
742 # TODO an array of splitpoints would be preferrable for this option:
743 :split_at => /\s+/, # by default, split overlong lines at whitespace
744 :purge_split => true, # should the split string be removed?
745 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
748 @default_send_options.update opts unless opts.empty?
751 # checks if we should be quiet on a channel
752 def quiet_on?(channel)
753 return @quiet.include?('*') || @quiet.include?(channel.downcase)
756 def set_quiet(channel)
758 ch = channel.downcase.dup
759 @quiet << ch unless @quiet.include?(ch)
766 def reset_quiet(channel)
768 @quiet.delete channel.downcase
774 # things to do when we receive a signal
775 def got_sig(sig, func=:quit)
776 debug "received #{sig}, queueing #{func}"
778 self.send(func) unless @quit_mutex.locked?
779 debug "interrupted #{$interrupted} times"
790 trap("SIGINT") { got_sig("SIGINT") }
791 trap("SIGTERM") { got_sig("SIGTERM") }
792 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
793 rescue ArgumentError => e
794 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
795 rescue Exception => e
796 debug "failed to trap signals: #{e.pretty_inspect}"
800 # connect the bot to IRC
803 quit if $interrupted > 0
806 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
808 quit if $interrupted > 0
810 realname = @config['irc.name'].clone || 'Ruby bot'
811 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
813 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
814 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
815 quit if $interrupted > 0
816 myself.nick = @config['irc.nick']
817 myself.user = @config['irc.user']
820 # begin event handling loop
824 quit if $interrupted > 0
828 while @socket.connected?
829 quit if $interrupted > 0
831 # Wait for messages and process them as they arrive. If nothing is
832 # received, we call the ping_server() method that will PING the
833 # server if appropriate, or raise a TimeoutError if no PONG has been
834 # received in the user-chosen timeout since the last PING sent.
836 break unless reply = @socket.gets
838 @client.process reply
844 # I despair of this. Some of my users get "connection reset by peer"
845 # exceptions that ARENT SocketError's. How am I supposed to handle
850 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
851 error "network exception: #{e.pretty_inspect}"
853 rescue BDB::Fatal => e
854 fatal "fatal bdb error: #{e.pretty_inspect}"
856 # Why restart? DB problems are serious stuff ...
857 # restart("Oops, we seem to have registry problems ...")
860 rescue Exception => e
861 error "non-net exception: #{e.pretty_inspect}"
864 fatal "unexpected exception: #{e.pretty_inspect}"
871 log "\n\nDisconnected\n\n"
873 quit if $interrupted > 0
875 log "\n\nWaiting to reconnect\n\n"
876 sleep @config['server.reconnect_wait']
880 # type:: message type
881 # where:: message target
882 # message:: message text
883 # send message +message+ of type +type+ to target +where+
884 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
885 # relevant say() or notice() methods. This one should be used for IRCd
886 # extensions you want to use in modules.
887 def sendmsg(type, where, original_message, options={})
888 opts = @default_send_options.merge(options)
890 # For starters, set up appropriate queue channels and rings
891 mchan = opts[:queue_channel]
892 mring = opts[:queue_ring]
909 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
913 messages << [multi_line.gsub("\n", opts[:join_with])]
915 multi_line.each_line { |line|
917 next unless(line.size > 0)
921 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
924 # The IRC protocol requires that each raw message must be not longer
925 # than 512 characters. From this length with have to subtract the EOL
926 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
927 # that will be prepended by the server to all of our messages.
929 # The maximum raw message length we can send is therefore 512 - 2 - 2
930 # minus the length of our hostmask.
932 max_len = 508 - myself.fullform.size
934 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
935 # will have a + or - prepended
936 if server.capabilities[:"identify-msg"]
940 # When splitting the message, we'll be prefixing the following string:
941 # (e.g. "PRIVMSG #rbot :")
942 fixed = "#{type} #{where} :"
944 # And this is what's left
945 left = max_len - fixed.size
947 truncate = opts[:truncate_text]
948 truncate = @default_send_options[:truncate_text] if truncate.size > left
949 truncate = "" if truncate.size > left
951 all_lines = messages.map { |line|
958 sub_lines = Array.new
960 sub_lines << msg.slice!(0, left)
962 lastspace = sub_lines.last.rindex(opts[:split_at])
964 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
965 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
970 line.slice(0, left - truncate.size) << truncate
972 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
977 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
978 lines = all_lines[0...opts[:max_lines]]
979 new_last = lines.last.slice(0, left - truncate.size) << truncate
980 lines.last.replace(new_last)
986 sendq "#{fixed}#{line}", chan, ring
987 delegate_sent(type, where, line)
991 # queue an arbitraty message for the server
992 def sendq(message="", chan=nil, ring=0)
994 @socket.queue(message, chan, ring)
997 # send a notice message to channel/nick +where+
998 def notice(where, message, options={})
999 return if where.kind_of?(Channel) and quiet_on?(where)
1000 sendmsg "NOTICE", where, message, options
1003 # say something (PRIVMSG) to channel/nick +where+
1004 def say(where, message, options={})
1005 return if where.kind_of?(Channel) and quiet_on?(where)
1006 sendmsg "PRIVMSG", where, message, options
1009 def ctcp_notice(where, command, message, options={})
1010 return if where.kind_of?(Channel) and quiet_on?(where)
1011 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1014 def ctcp_say(where, command, message, options={})
1015 return if where.kind_of?(Channel) and quiet_on?(where)
1016 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1019 # perform a CTCP action with message +message+ to channel/nick +where+
1020 def action(where, message, options={})
1021 ctcp_say(where, 'ACTION', message, options)
1024 # quick way to say "okay" (or equivalent) to +where+
1026 say where, @lang.get("okay")
1029 # set topic of channel +where+ to +topic+
1030 def topic(where, topic)
1031 sendq "TOPIC #{where} :#{topic}", where, 2
1034 def disconnect(message=nil)
1035 message = @lang.get("quit") if (!message || message.empty?)
1036 if @socket.connected?
1038 debug "Clearing socket"
1040 debug "Sending quit message"
1041 @socket.emergency_puts "QUIT :#{message}"
1042 debug "Logging quits"
1043 delegate_sent('QUIT', myself, message)
1044 debug "Flushing socket"
1046 rescue SocketError => e
1047 error "error while disconnecting socket: #{e.pretty_inspect}"
1049 debug "Shutting down socket"
1056 # disconnect from the server and cleanup all plugins and modules
1057 def shutdown(message=nil)
1058 @quit_mutex.synchronize do
1059 debug "Shutting down: #{message}"
1060 ## No we don't restore them ... let everything run through
1062 # trap("SIGINT", "DEFAULT")
1063 # trap("SIGTERM", "DEFAULT")
1064 # trap("SIGHUP", "DEFAULT")
1066 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1068 debug "\tdisconnecting..."
1070 debug "\tstopping timer..."
1072 debug "\tsaving ..."
1074 debug "\tcleaning up ..."
1075 @save_mutex.synchronize do
1078 # debug "\tstopping timers ..."
1080 # debug "Closing registries"
1082 debug "\t\tcleaning up the db environment ..."
1084 log "rbot quit (#{message})"
1088 # message:: optional IRC quit message
1089 # quit IRC, shutdown the bot
1090 def quit(message=nil)
1098 # totally shutdown and respawn the bot
1099 def restart(message=nil)
1100 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1102 sleep @config['server.reconnect_wait']
1105 # Note, this fails on Windows
1106 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1110 rescue Errno::ENOENT
1112 exec("ruby", *(@argv.unshift $0))
1113 rescue Exception => e
1119 # call the save method for all of the botmodules
1121 @save_mutex.synchronize do
1127 # call the rescan method for all of the botmodules
1129 debug "\tstopping timer..."
1131 @save_mutex.synchronize do
1138 # channel:: channel to join
1139 # key:: optional channel key if channel is +s
1141 def join(channel, key=nil)
1143 sendq "JOIN #{channel} :#{key}", channel, 2
1145 sendq "JOIN #{channel}", channel, 2
1150 def part(channel, message="")
1151 sendq "PART #{channel} :#{message}", channel, 2
1154 # attempt to change bot's nick to +name+
1156 sendq "NICK #{name}"
1160 def mode(channel, mode, target)
1161 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1165 def kick(channel, user, msg)
1166 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1169 # m:: message asking for help
1170 # topic:: optional topic help is requested for
1171 # respond to online help requests
1173 topic = nil if topic == ""
1176 helpstr = _("help topics: ")
1177 helpstr += @plugins.helptopics
1178 helpstr += _(" (help <topic> for more info)")
1180 unless(helpstr = @plugins.help(topic))
1181 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1187 # returns a string describing the current status of the bot (uptime etc)
1189 secs_up = Time.new - @startup_time
1190 uptime = Utils.secs_to_string secs_up
1191 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1192 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1194 :up => uptime, :plug => @plugins.length,
1195 :sent => @socket.lines_sent, :recv => @socket.lines_received
1199 # We want to respond to a hung server in a timely manner. If nothing was received
1200 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1201 # the server. If the PONG is not received within the user-defined timeout, we
1202 # assume we're in ping timeout and act accordingly.
1204 act_timeout = @config['server.ping_timeout']
1205 return if act_timeout <= 0
1207 if @last_rec && now > @last_rec + act_timeout
1209 # No previous PING pending, send a new one
1211 @last_ping = Time.now
1213 diff = now - @last_ping
1214 if diff > act_timeout
1215 debug "no PONG from server in #{diff} seconds, reconnecting"
1216 # the actual reconnect is handled in the main loop:
1217 raise TimeoutError, "no PONG from server in #{diff} seconds"
1223 def stop_server_pings
1224 # cancel previous PINGs and reset time of last RECV
1231 # delegate sent messages
1232 def delegate_sent(type, where, message)
1233 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1236 m = NoticeMessage.new(*args)
1238 m = PrivMessage.new(*args)
1240 m = QuitMessage.new(*args)
1242 @plugins.delegate('sent', m)