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?
76 $log_thread = Thread.new do
78 while ls = $log_queue.pop
79 ls.each { |l| $logger.add(*l) }
87 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
92 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
96 def debug(message=nil, who_pos=1)
97 rawlog(Logger::Severity::DEBUG, message, who_pos)
100 def log(message=nil, who_pos=1)
101 rawlog(Logger::Severity::INFO, message, who_pos)
104 def warning(message=nil, who_pos=1)
105 rawlog(Logger::Severity::WARN, message, who_pos)
108 def error(message=nil, who_pos=1)
109 rawlog(Logger::Severity::ERROR, message, who_pos)
112 def fatal(message=nil, who_pos=1)
113 rawlog(Logger::Severity::FATAL, message, who_pos)
118 warning "warning test"
122 # The following global is used for the improved signal handling.
126 require 'rbot/rbotconfig'
127 require 'rbot/load-gettext'
128 require 'rbot/config'
129 require 'rbot/config-compat'
132 require 'rbot/rfc2812'
133 require 'rbot/ircsocket'
134 require 'rbot/botuser'
136 require 'rbot/plugins'
137 require 'rbot/message'
138 require 'rbot/language'
139 require 'rbot/dbhash'
140 require 'rbot/registry'
144 # Main bot class, which manages the various components, receives messages,
145 # handles them or passes them to plugins, and contains core functionality.
147 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
148 SOURCE_URL = "http://ruby-rbot.org"
149 # the bot's Auth data
152 # the bot's Config data
155 # the botclass for this bot (determines configdir among other things)
156 attr_reader :botclass
158 # used to perform actions periodically (saves configuration once per minute
162 # synchronize with this mutex while touching permanent data files:
163 # saving, flushing, cleaning up ...
164 attr_reader :save_mutex
166 # bot's Language data
173 # bot's object registry, plugins get an interface to this for persistant
174 # storage (hash interface tied to a bdb file, plugins use Accessors to store
175 # and restore objects in their own namespaces.)
176 attr_reader :registry
178 # bot's plugins. This is an instance of class Plugins
181 # bot's httputil help object, for fetching resources via http. Sets up
182 # proxies etc as defined by the bot configuration/environment
183 attr_accessor :httputil
185 # server we are connected to
191 # bot User in the client/server connection
197 # bot User in the client/server connection
205 ret = self.to_s[0..-2]
206 ret << ' version=' << $version.inspect
207 ret << ' botclass=' << botclass.inspect
208 ret << ' lang="' << lang.language
213 ret << ' nick=' << nick.inspect
216 ret << (server.to_s + (socket ?
217 ' [' << socket.server_uri.to_s << ']' : '')).inspect
218 unless server.channels.empty?
220 ret << server.channels.map { |c|
221 "%s%s" % [c.modes_of(nick).map { |m|
222 server.prefix_for_mode(m)
229 ret << ' plugins=' << plugins.inspect
234 # create a new Bot with botclass +botclass+
235 def initialize(botclass, params = {})
236 # Config for the core bot
237 # TODO should we split socket stuff into ircsocket, etc?
238 Config.register Config::ArrayValue.new('server.list',
239 :default => ['irc://localhost'], :wizard => true,
240 :requires_restart => true,
241 :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.")
242 Config.register Config::BooleanValue.new('server.ssl',
243 :default => false, :requires_restart => true, :wizard => true,
244 :desc => "Use SSL to connect to this server?")
245 Config.register Config::StringValue.new('server.password',
246 :default => false, :requires_restart => true,
247 :desc => "Password for connecting to this server (if required)",
249 Config.register Config::StringValue.new('server.bindhost',
250 :default => false, :requires_restart => true,
251 :desc => "Specific local host or IP for the bot to bind to (if required)",
253 Config.register Config::IntegerValue.new('server.reconnect_wait',
254 :default => 5, :validate => Proc.new{|v| v >= 0},
255 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
256 Config.register Config::FloatValue.new('server.sendq_delay',
257 :default => 2.0, :validate => Proc.new{|v| v >= 0},
258 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
259 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
260 Config.register Config::IntegerValue.new('server.sendq_burst',
261 :default => 4, :validate => Proc.new{|v| v >= 0},
262 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
263 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
264 Config.register Config::IntegerValue.new('server.ping_timeout',
265 :default => 30, :validate => Proc.new{|v| v >= 0},
266 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
268 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
269 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
270 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
271 Config.register Config::StringValue.new('irc.name',
272 :default => "Ruby bot", :requires_restart => true,
273 :desc => "IRC realname the bot should use")
274 Config.register Config::BooleanValue.new('irc.name_copyright',
275 :default => true, :requires_restart => true,
276 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
277 Config.register Config::StringValue.new('irc.user', :default => "rbot",
278 :requires_restart => true,
279 :desc => "local user the bot should appear to be", :wizard => true)
280 Config.register Config::ArrayValue.new('irc.join_channels',
281 :default => [], :wizard => true,
282 :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'")
283 Config.register Config::ArrayValue.new('irc.ignore_users',
285 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
287 Config.register Config::IntegerValue.new('core.save_every',
288 :default => 60, :validate => Proc.new{|v| v >= 0},
289 :on_change => Proc.new { |bot, v|
292 @timer.reschedule(@save_timer, v)
293 @timer.unblock(@save_timer)
295 @timer.block(@save_timer)
299 @save_timer = @timer.add(v) { bot.save }
301 # Nothing to do when v == 0
304 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
306 Config.register Config::BooleanValue.new('core.run_as_daemon',
307 :default => false, :requires_restart => true,
308 :desc => "Should the bot run as a daemon?")
310 Config.register Config::StringValue.new('log.file',
311 :default => false, :requires_restart => true,
312 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
313 Config.register Config::IntegerValue.new('log.level',
314 :default => 1, :requires_restart => false,
315 :validate => Proc.new { |v| (0..5).include?(v) },
316 :on_change => Proc.new { |bot, v|
319 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
320 Config.register Config::IntegerValue.new('log.keep',
321 :default => 1, :requires_restart => true,
322 :validate => Proc.new { |v| v >= 0 },
323 :desc => "How many old console messages logfiles to keep")
324 Config.register Config::IntegerValue.new('log.max_size',
325 :default => 10, :requires_restart => true,
326 :validate => Proc.new { |v| v > 0 },
327 :desc => "Maximum console messages logfile size (in megabytes)")
329 Config.register Config::ArrayValue.new('plugins.path',
330 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
331 :requires_restart => false,
332 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
333 :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")
335 Config.register Config::EnumValue.new('send.newlines',
336 :values => ['split', 'join'], :default => 'split',
337 :on_change => Proc.new { |bot, v|
338 bot.set_default_send_options :newlines => v.to_sym
340 :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")
341 Config.register Config::StringValue.new('send.join_with',
343 :on_change => Proc.new { |bot, v|
344 bot.set_default_send_options :join_with => v.dup
346 :desc => "String used to replace newlines when send.newlines is set to join")
347 Config.register Config::IntegerValue.new('send.max_lines',
349 :validate => Proc.new { |v| v >= 0 },
350 :on_change => Proc.new { |bot, v|
351 bot.set_default_send_options :max_lines => v
353 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
354 Config.register Config::EnumValue.new('send.overlong',
355 :values => ['split', 'truncate'], :default => 'split',
356 :on_change => Proc.new { |bot, v|
357 bot.set_default_send_options :overlong => v.to_sym
359 :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")
360 Config.register Config::StringValue.new('send.split_at',
362 :on_change => Proc.new { |bot, v|
363 bot.set_default_send_options :split_at => Regexp.new(v)
365 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
366 Config.register Config::BooleanValue.new('send.purge_split',
368 :on_change => Proc.new { |bot, v|
369 bot.set_default_send_options :purge_split => v
371 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
372 Config.register Config::StringValue.new('send.truncate_text',
373 :default => "#{Reverse}...#{Reverse}",
374 :on_change => Proc.new { |bot, v|
375 bot.set_default_send_options :truncate_text => v.dup
377 :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")
379 @argv = params[:argv]
380 @run_dir = params[:run_dir] || Dir.pwd
382 unless FileTest.directory? Config::coredir
383 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
387 unless FileTest.directory? Config::datadir
388 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
392 unless botclass and not botclass.empty?
393 # We want to find a sensible default.
394 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
395 # * On Windows (at least the NT versions) we want to put our stuff in the
396 # Application Data folder.
397 # We don't use any particular O/S detection magic, exploiting the fact that
398 # Etc.getpwuid is nil on Windows
399 if Etc.getpwuid(Process::Sys.geteuid)
400 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
402 if ENV.has_key?('APPDATA')
403 botclass = ENV['APPDATA'].dup
404 botclass.gsub!("\\","/")
409 botclass = File.expand_path(botclass)
410 @botclass = botclass.gsub(/\/$/, "")
412 unless FileTest.directory? botclass
413 log "no #{botclass} directory found, creating from templates.."
414 if FileTest.exist? botclass
415 error "file #{botclass} exists but isn't a directory"
418 FileUtils.cp_r Config::datadir+'/templates', botclass
421 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
422 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
424 # Time at which the last PING was sent
426 # Time at which the last line was RECV'd from the server
429 @startup_time = Time.new
432 @config = Config.manager
433 @config.bot_associate(self)
434 rescue Exception => e
440 if @config['core.run_as_daemon']
444 @logfile = @config['log.file']
445 if @logfile.class!=String || @logfile.empty?
446 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
449 # See http://blog.humlab.umu.se/samuel/archives/000107.html
450 # for the backgrounding code
456 rescue NotImplementedError
457 warning "Could not background, fork not supported"
460 rescue Exception => e
461 warning "Could not background. #{e.pretty_inspect}"
464 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
465 log "Redirecting standard input/output/error"
467 STDIN.reopen "/dev/null"
469 # On Windows, there's not such thing as /dev/null
472 def STDOUT.write(str=nil)
476 def STDERR.write(str=nil)
477 if str.to_s.match(/:\d+: warning:/)
486 # Set the new logfile and loglevel. This must be done after the daemonizing
487 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
488 $logger.datetime_format= $dateformat
489 $logger.level = @config['log.level']
490 $logger.level = $cl_loglevel if defined? $cl_loglevel
491 $logger.level = 0 if $debug
495 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
499 @registry = Registry.new self
502 @save_mutex = Mutex.new
503 if @config['core.save_every'] > 0
504 @save_timer = @timer.add(@config['core.save_every']) { save }
508 @quit_mutex = Mutex.new
511 @lang = Language.new(self, @config['core.language'])
514 @auth = Auth::manager
515 @auth.bot_associate(self)
516 # @auth.load("#{botclass}/botusers.yaml")
517 rescue Exception => e
522 @auth.everyone.set_default_permission("*", true)
523 @auth.botowner.password= @config['auth.password']
525 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
526 @plugins = Plugins::manager
527 @plugins.bot_associate(self)
530 if @config['server.name']
531 debug "upgrading configuration (server.name => server.list)"
532 srv_uri = 'irc://' + @config['server.name']
533 srv_uri += ":#{@config['server.port']}" if @config['server.port']
534 @config.items['server.list'.to_sym].set_string(srv_uri)
535 @config.delete('server.name'.to_sym)
536 @config.delete('server.port'.to_sym)
537 debug "server.list is now #{@config['server.list'].inspect}"
540 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
545 # Channels where we are quiet
546 # Array of channels names where the bot should be quiet
547 # '*' means all channels
551 @client[:welcome] = proc {|data|
552 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
554 @plugins.delegate("welcome", m)
555 @plugins.delegate("connect")
557 @config['irc.join_channels'].each { |c|
558 debug "autojoining channel #{c}"
559 if(c =~ /^(\S+)\s+(\S+)$/i)
567 # TODO the next two @client should go into rfc2812.rb, probably
568 # Since capabs are two-steps processes, server.supports[:capab]
569 # should be a three-state: nil, [], [....]
570 asked_for = { :"identify-msg" => false }
571 @client[:isupport] = proc { |data|
572 if server.supports[:capab] and !asked_for[:"identify-msg"]
573 sendq "CAPAB IDENTIFY-MSG"
574 asked_for[:"identify-msg"] = true
577 @client[:datastr] = proc { |data|
578 if data[:text] == "IDENTIFY-MSG"
579 server.capabilities[:"identify-msg"] = true
581 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
585 @client[:privmsg] = proc { |data|
586 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
587 # debug "Message source is #{data[:source].inspect}"
588 # debug "Message target is #{data[:target].inspect}"
589 # debug "Bot is #{myself.inspect}"
591 @config['irc.ignore_users'].each { |mask|
592 if m.source.matches?(server.new_netmask(mask))
597 @plugins.irc_delegate('privmsg', m)
599 @client[:notice] = proc { |data|
600 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
601 # pass it off to plugins that want to hear everything
602 @plugins.irc_delegate "notice", message
604 @client[:motd] = proc { |data|
605 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
606 @plugins.delegate "motd", m
608 @client[:nicktaken] = proc { |data|
609 new = "#{data[:nick]}_"
611 # If we're setting our nick at connection because our choice was taken,
612 # we have to fix our nick manually, because there will be no NICK message
613 # to inform us that our nick has been changed.
614 if data[:target] == '*'
615 debug "setting my connection nick to #{new}"
618 @plugins.delegate "nicktaken", data[:nick]
620 @client[:badnick] = proc {|data|
621 warning "bad nick (#{data[:nick]})"
623 @client[:ping] = proc {|data|
624 sendq "PONG #{data[:pingid]}"
626 @client[:pong] = proc {|data|
629 @client[:nick] = proc {|data|
630 # debug "Message source is #{data[:source].inspect}"
631 # debug "Bot is #{myself.inspect}"
632 source = data[:source]
635 m = NickMessage.new(self, server, source, old, new)
636 m.is_on = data[:is_on]
638 debug "my nick is now #{new}"
640 @plugins.irc_delegate("nick", m)
642 @client[:quit] = proc {|data|
643 source = data[:source]
644 message = data[:message]
645 m = QuitMessage.new(self, server, source, source, message)
646 m.was_on = data[:was_on]
647 @plugins.irc_delegate("quit", m)
649 @client[:mode] = proc {|data|
650 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
651 m.modes = data[:modes]
652 @plugins.delegate "modechange", m
654 @client[:join] = proc {|data|
655 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
656 @plugins.irc_delegate("join", m)
657 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
659 @client[:part] = proc {|data|
660 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
661 @plugins.irc_delegate("part", m)
663 @client[:kick] = proc {|data|
664 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
665 @plugins.irc_delegate("kick", m)
667 @client[:invite] = proc {|data|
668 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
669 @plugins.irc_delegate("invite", m)
671 @client[:changetopic] = proc {|data|
672 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
674 @plugins.irc_delegate("topic", m)
676 # @client[:topic] = proc { |data|
677 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
679 @client[:topicinfo] = proc { |data|
680 channel = data[:channel]
681 topic = channel.topic
682 m = TopicMessage.new(self, server, data[:source], channel, topic)
683 m.info_or_set = :info
684 @plugins.irc_delegate("topic", m)
686 @client[:names] = proc { |data|
687 m = NamesMessage.new(self, server, server, data[:channel])
688 m.users = data[:users]
689 @plugins.delegate "names", m
691 @client[:unknown] = proc { |data|
692 #debug "UNKNOWN: #{data[:serverstring]}"
693 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
694 @plugins.delegate "unknown_message", m
697 set_default_send_options :newlines => @config['send.newlines'].to_sym,
698 :join_with => @config['send.join_with'].dup,
699 :max_lines => @config['send.max_lines'],
700 :overlong => @config['send.overlong'].to_sym,
701 :split_at => Regexp.new(@config['send.split_at']),
702 :purge_split => @config['send.purge_split'],
703 :truncate_text => @config['send.truncate_text'].dup
706 def setup_plugins_path
707 @plugins.clear_botmodule_dirs
708 @plugins.add_botmodule_dir(Config::coredir + "/utils")
709 @plugins.add_botmodule_dir(Config::coredir)
710 @plugins.add_botmodule_dir("#{botclass}/plugins")
712 @config['plugins.path'].each do |_|
713 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
714 @plugins.add_botmodule_dir(path)
718 def set_default_send_options(opts={})
719 # Default send options for NOTICE and PRIVMSG
720 unless defined? @default_send_options
721 @default_send_options = {
722 :queue_channel => nil, # use default queue channel
723 :queue_ring => nil, # use default queue ring
724 :newlines => :split, # or :join
725 :join_with => ' ', # by default, use a single space
726 :max_lines => 0, # maximum number of lines to send with a single command
727 :overlong => :split, # or :truncate
728 # TODO an array of splitpoints would be preferrable for this option:
729 :split_at => /\s+/, # by default, split overlong lines at whitespace
730 :purge_split => true, # should the split string be removed?
731 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
734 @default_send_options.update opts unless opts.empty?
737 # checks if we should be quiet on a channel
738 def quiet_on?(channel)
739 return @quiet.include?('*') || @quiet.include?(channel.downcase)
742 def set_quiet(channel)
744 ch = channel.downcase.dup
745 @quiet << ch unless @quiet.include?(ch)
752 def reset_quiet(channel)
754 @quiet.delete channel.downcase
760 # things to do when we receive a signal
762 debug "received #{sig}, queueing quit"
764 quit unless @quit_mutex.locked?
765 debug "interrupted #{$interrupted} times"
773 # connect the bot to IRC
776 trap("SIGINT") { got_sig("SIGINT") }
777 trap("SIGTERM") { got_sig("SIGTERM") }
778 trap("SIGHUP") { got_sig("SIGHUP") }
779 rescue ArgumentError => e
780 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
781 rescue Exception => e
782 debug "failed to trap signals: #{e.pretty_inspect}"
785 quit if $interrupted > 0
788 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
790 quit if $interrupted > 0
792 realname = @config['irc.name'].clone || 'Ruby bot'
793 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
795 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
796 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
797 quit if $interrupted > 0
798 myself.nick = @config['irc.nick']
799 myself.user = @config['irc.user']
802 # begin event handling loop
806 quit if $interrupted > 0
810 while @socket.connected?
811 quit if $interrupted > 0
813 # Wait for messages and process them as they arrive. If nothing is
814 # received, we call the ping_server() method that will PING the
815 # server if appropriate, or raise a TimeoutError if no PONG has been
816 # received in the user-chosen timeout since the last PING sent.
818 break unless reply = @socket.gets
820 @client.process reply
826 # I despair of this. Some of my users get "connection reset by peer"
827 # exceptions that ARENT SocketError's. How am I supposed to handle
832 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
833 error "network exception: #{e.pretty_inspect}"
835 rescue BDB::Fatal => e
836 fatal "fatal bdb error: #{e.pretty_inspect}"
838 # Why restart? DB problems are serious stuff ...
839 # restart("Oops, we seem to have registry problems ...")
842 rescue Exception => e
843 error "non-net exception: #{e.pretty_inspect}"
846 fatal "unexpected exception: #{e.pretty_inspect}"
853 log "\n\nDisconnected\n\n"
855 quit if $interrupted > 0
857 log "\n\nWaiting to reconnect\n\n"
858 sleep @config['server.reconnect_wait']
862 # type:: message type
863 # where:: message target
864 # message:: message text
865 # send message +message+ of type +type+ to target +where+
866 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
867 # relevant say() or notice() methods. This one should be used for IRCd
868 # extensions you want to use in modules.
869 def sendmsg(type, where, original_message, options={})
870 opts = @default_send_options.merge(options)
872 # For starters, set up appropriate queue channels and rings
873 mchan = opts[:queue_channel]
874 mring = opts[:queue_ring]
891 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
895 messages << [multi_line.gsub("\n", opts[:join_with])]
897 multi_line.each_line { |line|
899 next unless(line.size > 0)
903 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
906 # The IRC protocol requires that each raw message must be not longer
907 # than 512 characters. From this length with have to subtract the EOL
908 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
909 # that will be prepended by the server to all of our messages.
911 # The maximum raw message length we can send is therefore 512 - 2 - 2
912 # minus the length of our hostmask.
914 max_len = 508 - myself.fullform.size
916 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
917 # will have a + or - prepended
918 if server.capabilities[:"identify-msg"]
922 # When splitting the message, we'll be prefixing the following string:
923 # (e.g. "PRIVMSG #rbot :")
924 fixed = "#{type} #{where} :"
926 # And this is what's left
927 left = max_len - fixed.size
929 truncate = opts[:truncate_text]
930 truncate = @default_send_options[:truncate_text] if truncate.size > left
931 truncate = "" if truncate.size > left
933 all_lines = messages.map { |line|
940 sub_lines = Array.new
942 sub_lines << msg.slice!(0, left)
944 lastspace = sub_lines.last.rindex(opts[:split_at])
946 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
947 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
952 line.slice(0, left - truncate.size) << truncate
954 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
959 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
960 lines = all_lines[0...opts[:max_lines]]
961 new_last = lines.last.slice(0, left - truncate.size) << truncate
962 lines.last.replace(new_last)
968 sendq "#{fixed}#{line}", chan, ring
969 delegate_sent(type, where, line)
973 # queue an arbitraty message for the server
974 def sendq(message="", chan=nil, ring=0)
976 @socket.queue(message, chan, ring)
979 # send a notice message to channel/nick +where+
980 def notice(where, message, options={})
981 return if where.kind_of?(Channel) and quiet_on?(where)
982 sendmsg "NOTICE", where, message, options
985 # say something (PRIVMSG) to channel/nick +where+
986 def say(where, message, options={})
987 return if where.kind_of?(Channel) and quiet_on?(where)
988 sendmsg "PRIVMSG", where, message, options
991 def ctcp_notice(where, command, message, options={})
992 return if where.kind_of?(Channel) and quiet_on?(where)
993 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
996 def ctcp_say(where, command, message, options={})
997 return if where.kind_of?(Channel) and quiet_on?(where)
998 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1001 # perform a CTCP action with message +message+ to channel/nick +where+
1002 def action(where, message, options={})
1003 ctcp_say(where, 'ACTION', message, options)
1006 # quick way to say "okay" (or equivalent) to +where+
1008 say where, @lang.get("okay")
1011 # set topic of channel +where+ to +topic+
1012 def topic(where, topic)
1013 sendq "TOPIC #{where} :#{topic}", where, 2
1016 def disconnect(message=nil)
1017 message = @lang.get("quit") if (!message || message.empty?)
1018 if @socket.connected?
1020 debug "Clearing socket"
1022 debug "Sending quit message"
1023 @socket.emergency_puts "QUIT :#{message}"
1024 debug "Logging quits"
1025 delegate_sent('QUIT', myself, message)
1026 debug "Flushing socket"
1028 rescue SocketError => e
1029 error "error while disconnecting socket: #{e.pretty_inspect}"
1031 debug "Shutting down socket"
1038 # disconnect from the server and cleanup all plugins and modules
1039 def shutdown(message=nil)
1040 @quit_mutex.synchronize do
1041 debug "Shutting down: #{message}"
1042 ## No we don't restore them ... let everything run through
1044 # trap("SIGINT", "DEFAULT")
1045 # trap("SIGTERM", "DEFAULT")
1046 # trap("SIGHUP", "DEFAULT")
1048 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1050 debug "\tdisconnecting..."
1052 debug "\tstopping timer..."
1054 debug "\tsaving ..."
1056 debug "\tcleaning up ..."
1057 @save_mutex.synchronize do
1060 # debug "\tstopping timers ..."
1062 # debug "Closing registries"
1064 debug "\t\tcleaning up the db environment ..."
1066 log "rbot quit (#{message})"
1070 # message:: optional IRC quit message
1071 # quit IRC, shutdown the bot
1072 def quit(message=nil)
1080 # totally shutdown and respawn the bot
1081 def restart(message=nil)
1082 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1084 sleep @config['server.reconnect_wait']
1087 # Note, this fails on Windows
1088 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1092 rescue Errno::ENOENT
1094 exec("ruby", *(@argv.unshift $0))
1095 rescue Exception => e
1101 # call the save method for all of the botmodules
1103 @save_mutex.synchronize do
1109 # call the rescan method for all of the botmodules
1111 debug "\tstopping timer..."
1113 @save_mutex.synchronize do
1120 # channel:: channel to join
1121 # key:: optional channel key if channel is +s
1123 def join(channel, key=nil)
1125 sendq "JOIN #{channel} :#{key}", channel, 2
1127 sendq "JOIN #{channel}", channel, 2
1132 def part(channel, message="")
1133 sendq "PART #{channel} :#{message}", channel, 2
1136 # attempt to change bot's nick to +name+
1138 sendq "NICK #{name}"
1142 def mode(channel, mode, target)
1143 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1147 def kick(channel, user, msg)
1148 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1151 # m:: message asking for help
1152 # topic:: optional topic help is requested for
1153 # respond to online help requests
1155 topic = nil if topic == ""
1158 helpstr = _("help topics: ")
1159 helpstr += @plugins.helptopics
1160 helpstr += _(" (help <topic> for more info)")
1162 unless(helpstr = @plugins.help(topic))
1163 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1169 # returns a string describing the current status of the bot (uptime etc)
1171 secs_up = Time.new - @startup_time
1172 uptime = Utils.secs_to_string secs_up
1173 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1174 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1176 :up => uptime, :plug => @plugins.length,
1177 :sent => @socket.lines_sent, :recv => @socket.lines_received
1181 # We want to respond to a hung server in a timely manner. If nothing was received
1182 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1183 # the server. If the PONG is not received within the user-defined timeout, we
1184 # assume we're in ping timeout and act accordingly.
1186 act_timeout = @config['server.ping_timeout']
1187 return if act_timeout <= 0
1189 if @last_rec && now > @last_rec + act_timeout
1191 # No previous PING pending, send a new one
1193 @last_ping = Time.now
1195 diff = now - @last_ping
1196 if diff > act_timeout
1197 debug "no PONG from server in #{diff} seconds, reconnecting"
1198 # the actual reconnect is handled in the main loop:
1199 raise TimeoutError, "no PONG from server in #{diff} seconds"
1205 def stop_server_pings
1206 # cancel previous PINGs and reset time of last RECV
1213 # delegate sent messages
1214 def delegate_sent(type, where, message)
1215 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1218 m = NoticeMessage.new(*args)
1220 m = PrivMessage.new(*args)
1222 m = QuitMessage.new(*args)
1224 @plugins.delegate('sent', m)