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"
466 [$stdin, $stdout, $stderr].each do |fd|
468 fd.reopen "/dev/null"
470 # On Windows, there's not such thing as /dev/null
475 def $stdout.write(str=nil)
479 def $stdout.write(str=nil)
480 if str.to_s.match(/:\d+: warning:/)
489 # Set the new logfile and loglevel. This must be done after the daemonizing
490 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
491 $logger.datetime_format= $dateformat
492 $logger.level = @config['log.level']
493 $logger.level = $cl_loglevel if defined? $cl_loglevel
494 $logger.level = 0 if $debug
498 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
502 @registry = Registry.new self
505 @save_mutex = Mutex.new
506 if @config['core.save_every'] > 0
507 @save_timer = @timer.add(@config['core.save_every']) { save }
511 @quit_mutex = Mutex.new
514 @lang = Language.new(self, @config['core.language'])
517 @auth = Auth::manager
518 @auth.bot_associate(self)
519 # @auth.load("#{botclass}/botusers.yaml")
520 rescue Exception => e
525 @auth.everyone.set_default_permission("*", true)
526 @auth.botowner.password= @config['auth.password']
528 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
529 @plugins = Plugins::manager
530 @plugins.bot_associate(self)
533 if @config['server.name']
534 debug "upgrading configuration (server.name => server.list)"
535 srv_uri = 'irc://' + @config['server.name']
536 srv_uri += ":#{@config['server.port']}" if @config['server.port']
537 @config.items['server.list'.to_sym].set_string(srv_uri)
538 @config.delete('server.name'.to_sym)
539 @config.delete('server.port'.to_sym)
540 debug "server.list is now #{@config['server.list'].inspect}"
543 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
548 # Channels where we are quiet
549 # Array of channels names where the bot should be quiet
550 # '*' means all channels
554 @client[:welcome] = proc {|data|
555 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
557 @plugins.delegate("welcome", m)
558 @plugins.delegate("connect")
560 @config['irc.join_channels'].each { |c|
561 debug "autojoining channel #{c}"
562 if(c =~ /^(\S+)\s+(\S+)$/i)
570 # TODO the next two @client should go into rfc2812.rb, probably
571 # Since capabs are two-steps processes, server.supports[:capab]
572 # should be a three-state: nil, [], [....]
573 asked_for = { :"identify-msg" => false }
574 @client[:isupport] = proc { |data|
575 if server.supports[:capab] and !asked_for[:"identify-msg"]
576 sendq "CAPAB IDENTIFY-MSG"
577 asked_for[:"identify-msg"] = true
580 @client[:datastr] = proc { |data|
581 if data[:text] == "IDENTIFY-MSG"
582 server.capabilities[:"identify-msg"] = true
584 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
588 @client[:privmsg] = proc { |data|
589 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
590 # debug "Message source is #{data[:source].inspect}"
591 # debug "Message target is #{data[:target].inspect}"
592 # debug "Bot is #{myself.inspect}"
594 @config['irc.ignore_users'].each { |mask|
595 if m.source.matches?(server.new_netmask(mask))
600 @plugins.irc_delegate('privmsg', m)
602 @client[:notice] = proc { |data|
603 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
604 # pass it off to plugins that want to hear everything
605 @plugins.irc_delegate "notice", message
607 @client[:motd] = proc { |data|
608 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
609 @plugins.delegate "motd", m
611 @client[:nicktaken] = proc { |data|
612 new = "#{data[:nick]}_"
614 # If we're setting our nick at connection because our choice was taken,
615 # we have to fix our nick manually, because there will be no NICK message
616 # to inform us that our nick has been changed.
617 if data[:target] == '*'
618 debug "setting my connection nick to #{new}"
621 @plugins.delegate "nicktaken", data[:nick]
623 @client[:badnick] = proc {|data|
624 warning "bad nick (#{data[:nick]})"
626 @client[:ping] = proc {|data|
627 sendq "PONG #{data[:pingid]}"
629 @client[:pong] = proc {|data|
632 @client[:nick] = proc {|data|
633 # debug "Message source is #{data[:source].inspect}"
634 # debug "Bot is #{myself.inspect}"
635 source = data[:source]
638 m = NickMessage.new(self, server, source, old, new)
639 m.is_on = data[:is_on]
641 debug "my nick is now #{new}"
643 @plugins.irc_delegate("nick", m)
645 @client[:quit] = proc {|data|
646 source = data[:source]
647 message = data[:message]
648 m = QuitMessage.new(self, server, source, source, message)
649 m.was_on = data[:was_on]
650 @plugins.irc_delegate("quit", m)
652 @client[:mode] = proc {|data|
653 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
654 m.modes = data[:modes]
655 @plugins.delegate "modechange", m
657 @client[:join] = proc {|data|
658 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
659 @plugins.irc_delegate("join", m)
660 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
662 @client[:part] = proc {|data|
663 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
664 @plugins.irc_delegate("part", m)
666 @client[:kick] = proc {|data|
667 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
668 @plugins.irc_delegate("kick", m)
670 @client[:invite] = proc {|data|
671 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
672 @plugins.irc_delegate("invite", m)
674 @client[:changetopic] = proc {|data|
675 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
677 @plugins.irc_delegate("topic", m)
679 # @client[:topic] = proc { |data|
680 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
682 @client[:topicinfo] = proc { |data|
683 channel = data[:channel]
684 topic = channel.topic
685 m = TopicMessage.new(self, server, data[:source], channel, topic)
686 m.info_or_set = :info
687 @plugins.irc_delegate("topic", m)
689 @client[:names] = proc { |data|
690 m = NamesMessage.new(self, server, server, data[:channel])
691 m.users = data[:users]
692 @plugins.delegate "names", m
694 @client[:unknown] = proc { |data|
695 #debug "UNKNOWN: #{data[:serverstring]}"
696 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
697 @plugins.delegate "unknown_message", m
700 set_default_send_options :newlines => @config['send.newlines'].to_sym,
701 :join_with => @config['send.join_with'].dup,
702 :max_lines => @config['send.max_lines'],
703 :overlong => @config['send.overlong'].to_sym,
704 :split_at => Regexp.new(@config['send.split_at']),
705 :purge_split => @config['send.purge_split'],
706 :truncate_text => @config['send.truncate_text'].dup
709 def setup_plugins_path
710 @plugins.clear_botmodule_dirs
711 @plugins.add_botmodule_dir(Config::coredir + "/utils")
712 @plugins.add_botmodule_dir(Config::coredir)
713 @plugins.add_botmodule_dir("#{botclass}/plugins")
715 @config['plugins.path'].each do |_|
716 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
717 @plugins.add_botmodule_dir(path)
721 def set_default_send_options(opts={})
722 # Default send options for NOTICE and PRIVMSG
723 unless defined? @default_send_options
724 @default_send_options = {
725 :queue_channel => nil, # use default queue channel
726 :queue_ring => nil, # use default queue ring
727 :newlines => :split, # or :join
728 :join_with => ' ', # by default, use a single space
729 :max_lines => 0, # maximum number of lines to send with a single command
730 :overlong => :split, # or :truncate
731 # TODO an array of splitpoints would be preferrable for this option:
732 :split_at => /\s+/, # by default, split overlong lines at whitespace
733 :purge_split => true, # should the split string be removed?
734 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
737 @default_send_options.update opts unless opts.empty?
740 # checks if we should be quiet on a channel
741 def quiet_on?(channel)
742 return @quiet.include?('*') || @quiet.include?(channel.downcase)
745 def set_quiet(channel)
747 ch = channel.downcase.dup
748 @quiet << ch unless @quiet.include?(ch)
755 def reset_quiet(channel)
757 @quiet.delete channel.downcase
763 # things to do when we receive a signal
764 def got_sig(sig, func=:quit)
765 debug "received #{sig}, queueing #{func}"
767 self.send(func) unless @quit_mutex.locked?
768 debug "interrupted #{$interrupted} times"
776 # connect the bot to IRC
779 trap("SIGINT") { got_sig("SIGINT") }
780 trap("SIGTERM") { got_sig("SIGTERM") }
781 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
782 rescue ArgumentError => e
783 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
784 rescue Exception => e
785 debug "failed to trap signals: #{e.pretty_inspect}"
788 quit if $interrupted > 0
791 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
793 quit if $interrupted > 0
795 realname = @config['irc.name'].clone || 'Ruby bot'
796 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
798 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
799 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
800 quit if $interrupted > 0
801 myself.nick = @config['irc.nick']
802 myself.user = @config['irc.user']
805 # begin event handling loop
809 quit if $interrupted > 0
813 while @socket.connected?
814 quit if $interrupted > 0
816 # Wait for messages and process them as they arrive. If nothing is
817 # received, we call the ping_server() method that will PING the
818 # server if appropriate, or raise a TimeoutError if no PONG has been
819 # received in the user-chosen timeout since the last PING sent.
821 break unless reply = @socket.gets
823 @client.process reply
829 # I despair of this. Some of my users get "connection reset by peer"
830 # exceptions that ARENT SocketError's. How am I supposed to handle
835 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
836 error "network exception: #{e.pretty_inspect}"
838 rescue BDB::Fatal => e
839 fatal "fatal bdb error: #{e.pretty_inspect}"
841 # Why restart? DB problems are serious stuff ...
842 # restart("Oops, we seem to have registry problems ...")
845 rescue Exception => e
846 error "non-net exception: #{e.pretty_inspect}"
849 fatal "unexpected exception: #{e.pretty_inspect}"
856 log "\n\nDisconnected\n\n"
858 quit if $interrupted > 0
860 log "\n\nWaiting to reconnect\n\n"
861 sleep @config['server.reconnect_wait']
865 # type:: message type
866 # where:: message target
867 # message:: message text
868 # send message +message+ of type +type+ to target +where+
869 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
870 # relevant say() or notice() methods. This one should be used for IRCd
871 # extensions you want to use in modules.
872 def sendmsg(type, where, original_message, options={})
873 opts = @default_send_options.merge(options)
875 # For starters, set up appropriate queue channels and rings
876 mchan = opts[:queue_channel]
877 mring = opts[:queue_ring]
894 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
898 messages << [multi_line.gsub("\n", opts[:join_with])]
900 multi_line.each_line { |line|
902 next unless(line.size > 0)
906 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
909 # The IRC protocol requires that each raw message must be not longer
910 # than 512 characters. From this length with have to subtract the EOL
911 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
912 # that will be prepended by the server to all of our messages.
914 # The maximum raw message length we can send is therefore 512 - 2 - 2
915 # minus the length of our hostmask.
917 max_len = 508 - myself.fullform.size
919 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
920 # will have a + or - prepended
921 if server.capabilities[:"identify-msg"]
925 # When splitting the message, we'll be prefixing the following string:
926 # (e.g. "PRIVMSG #rbot :")
927 fixed = "#{type} #{where} :"
929 # And this is what's left
930 left = max_len - fixed.size
932 truncate = opts[:truncate_text]
933 truncate = @default_send_options[:truncate_text] if truncate.size > left
934 truncate = "" if truncate.size > left
936 all_lines = messages.map { |line|
943 sub_lines = Array.new
945 sub_lines << msg.slice!(0, left)
947 lastspace = sub_lines.last.rindex(opts[:split_at])
949 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
950 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
955 line.slice(0, left - truncate.size) << truncate
957 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
962 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
963 lines = all_lines[0...opts[:max_lines]]
964 new_last = lines.last.slice(0, left - truncate.size) << truncate
965 lines.last.replace(new_last)
971 sendq "#{fixed}#{line}", chan, ring
972 delegate_sent(type, where, line)
976 # queue an arbitraty message for the server
977 def sendq(message="", chan=nil, ring=0)
979 @socket.queue(message, chan, ring)
982 # send a notice message to channel/nick +where+
983 def notice(where, message, options={})
984 return if where.kind_of?(Channel) and quiet_on?(where)
985 sendmsg "NOTICE", where, message, options
988 # say something (PRIVMSG) to channel/nick +where+
989 def say(where, message, options={})
990 return if where.kind_of?(Channel) and quiet_on?(where)
991 sendmsg "PRIVMSG", where, message, options
994 def ctcp_notice(where, command, message, options={})
995 return if where.kind_of?(Channel) and quiet_on?(where)
996 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
999 def ctcp_say(where, command, message, options={})
1000 return if where.kind_of?(Channel) and quiet_on?(where)
1001 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1004 # perform a CTCP action with message +message+ to channel/nick +where+
1005 def action(where, message, options={})
1006 ctcp_say(where, 'ACTION', message, options)
1009 # quick way to say "okay" (or equivalent) to +where+
1011 say where, @lang.get("okay")
1014 # set topic of channel +where+ to +topic+
1015 def topic(where, topic)
1016 sendq "TOPIC #{where} :#{topic}", where, 2
1019 def disconnect(message=nil)
1020 message = @lang.get("quit") if (!message || message.empty?)
1021 if @socket.connected?
1023 debug "Clearing socket"
1025 debug "Sending quit message"
1026 @socket.emergency_puts "QUIT :#{message}"
1027 debug "Logging quits"
1028 delegate_sent('QUIT', myself, message)
1029 debug "Flushing socket"
1031 rescue SocketError => e
1032 error "error while disconnecting socket: #{e.pretty_inspect}"
1034 debug "Shutting down socket"
1041 # disconnect from the server and cleanup all plugins and modules
1042 def shutdown(message=nil)
1043 @quit_mutex.synchronize do
1044 debug "Shutting down: #{message}"
1045 ## No we don't restore them ... let everything run through
1047 # trap("SIGINT", "DEFAULT")
1048 # trap("SIGTERM", "DEFAULT")
1049 # trap("SIGHUP", "DEFAULT")
1051 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1053 debug "\tdisconnecting..."
1055 debug "\tstopping timer..."
1057 debug "\tsaving ..."
1059 debug "\tcleaning up ..."
1060 @save_mutex.synchronize do
1063 # debug "\tstopping timers ..."
1065 # debug "Closing registries"
1067 debug "\t\tcleaning up the db environment ..."
1069 log "rbot quit (#{message})"
1073 # message:: optional IRC quit message
1074 # quit IRC, shutdown the bot
1075 def quit(message=nil)
1083 # totally shutdown and respawn the bot
1084 def restart(message=nil)
1085 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1087 sleep @config['server.reconnect_wait']
1090 # Note, this fails on Windows
1091 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1095 rescue Errno::ENOENT
1097 exec("ruby", *(@argv.unshift $0))
1098 rescue Exception => e
1104 # call the save method for all of the botmodules
1106 @save_mutex.synchronize do
1112 # call the rescan method for all of the botmodules
1114 debug "\tstopping timer..."
1116 @save_mutex.synchronize do
1123 # channel:: channel to join
1124 # key:: optional channel key if channel is +s
1126 def join(channel, key=nil)
1128 sendq "JOIN #{channel} :#{key}", channel, 2
1130 sendq "JOIN #{channel}", channel, 2
1135 def part(channel, message="")
1136 sendq "PART #{channel} :#{message}", channel, 2
1139 # attempt to change bot's nick to +name+
1141 sendq "NICK #{name}"
1145 def mode(channel, mode, target)
1146 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1150 def kick(channel, user, msg)
1151 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1154 # m:: message asking for help
1155 # topic:: optional topic help is requested for
1156 # respond to online help requests
1158 topic = nil if topic == ""
1161 helpstr = _("help topics: ")
1162 helpstr += @plugins.helptopics
1163 helpstr += _(" (help <topic> for more info)")
1165 unless(helpstr = @plugins.help(topic))
1166 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1172 # returns a string describing the current status of the bot (uptime etc)
1174 secs_up = Time.new - @startup_time
1175 uptime = Utils.secs_to_string secs_up
1176 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1177 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1179 :up => uptime, :plug => @plugins.length,
1180 :sent => @socket.lines_sent, :recv => @socket.lines_received
1184 # We want to respond to a hung server in a timely manner. If nothing was received
1185 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1186 # the server. If the PONG is not received within the user-defined timeout, we
1187 # assume we're in ping timeout and act accordingly.
1189 act_timeout = @config['server.ping_timeout']
1190 return if act_timeout <= 0
1192 if @last_rec && now > @last_rec + act_timeout
1194 # No previous PING pending, send a new one
1196 @last_ping = Time.now
1198 diff = now - @last_ping
1199 if diff > act_timeout
1200 debug "no PONG from server in #{diff} seconds, reconnecting"
1201 # the actual reconnect is handled in the main loop:
1202 raise TimeoutError, "no PONG from server in #{diff} seconds"
1208 def stop_server_pings
1209 # cancel previous PINGs and reset time of last RECV
1216 # delegate sent messages
1217 def delegate_sent(type, where, message)
1218 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1221 m = NoticeMessage.new(*args)
1223 m = PrivMessage.new(*args)
1225 m = QuitMessage.new(*args)
1227 @plugins.delegate('sent', m)