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
23 unless Kernel.instance_methods.include?("pretty_inspect")
27 public :pretty_inspect
32 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
33 if self.backtrace and not self.backtrace.empty?
35 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
41 def rawlog(level, message=nil, who_pos=1)
44 if call_stack.length > who_pos
45 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
49 # Output each line. To distinguish between separate messages and multi-line
50 # messages originating at the same time, we blank #{who} after the first message
52 # Also, we output strings as-is but for other objects we use pretty_inspect
57 str = message.pretty_inspect
60 $logger.add(level, l.chomp, who)
68 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
72 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
75 def debug(message=nil, who_pos=1)
76 rawlog(Logger::Severity::DEBUG, message, who_pos)
79 def log(message=nil, who_pos=1)
80 rawlog(Logger::Severity::INFO, message, who_pos)
83 def warning(message=nil, who_pos=1)
84 rawlog(Logger::Severity::WARN, message, who_pos)
87 def error(message=nil, who_pos=1)
88 rawlog(Logger::Severity::ERROR, message, who_pos)
91 def fatal(message=nil, who_pos=1)
92 rawlog(Logger::Severity::FATAL, message, who_pos)
97 warning "warning test"
101 # The following global is used for the improved signal handling.
105 require 'rbot/rbotconfig'
106 require 'rbot/load-gettext'
107 require 'rbot/config'
108 require 'rbot/config-compat'
111 require 'rbot/rfc2812'
112 require 'rbot/ircsocket'
113 require 'rbot/botuser'
115 require 'rbot/plugins'
116 require 'rbot/message'
117 require 'rbot/language'
118 require 'rbot/dbhash'
119 require 'rbot/registry'
123 # Main bot class, which manages the various components, receives messages,
124 # handles them or passes them to plugins, and contains core functionality.
126 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
127 SOURCE_URL = "http://ruby-rbot.org"
128 # the bot's Auth data
131 # the bot's Config data
134 # the botclass for this bot (determines configdir among other things)
135 attr_reader :botclass
137 # used to perform actions periodically (saves configuration once per minute
141 # synchronize with this mutex while touching permanent data files:
142 # saving, flushing, cleaning up ...
143 attr_reader :save_mutex
145 # bot's Language data
152 # bot's object registry, plugins get an interface to this for persistant
153 # storage (hash interface tied to a bdb file, plugins use Accessors to store
154 # and restore objects in their own namespaces.)
155 attr_reader :registry
157 # bot's plugins. This is an instance of class Plugins
160 # bot's httputil help object, for fetching resources via http. Sets up
161 # proxies etc as defined by the bot configuration/environment
162 attr_accessor :httputil
164 # server we are connected to
170 # bot User in the client/server connection
176 # bot User in the client/server connection
184 ret = self.to_s[0..-2]
185 ret << ' version=' << $version.inspect
186 ret << ' botclass=' << botclass.inspect
187 ret << ' lang="' << lang.language
192 ret << ' nick=' << nick.inspect
195 ret << (server.to_s + (socket ?
196 ' [' << socket.server_uri.to_s << ']' : '')).inspect
197 unless server.channels.empty?
199 ret << server.channels.map { |c|
200 "%s%s" % [c.modes_of(nick).map { |m|
201 server.prefix_for_mode(m)
208 ret << ' plugins=' << plugins.inspect
213 # create a new Bot with botclass +botclass+
214 def initialize(botclass, params = {})
215 # Config for the core bot
216 # TODO should we split socket stuff into ircsocket, etc?
217 Config.register Config::ArrayValue.new('server.list',
218 :default => ['irc://localhost'], :wizard => true,
219 :requires_restart => true,
220 :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.")
221 Config.register Config::BooleanValue.new('server.ssl',
222 :default => false, :requires_restart => true, :wizard => true,
223 :desc => "Use SSL to connect to this server?")
224 Config.register Config::StringValue.new('server.password',
225 :default => false, :requires_restart => true,
226 :desc => "Password for connecting to this server (if required)",
228 Config.register Config::StringValue.new('server.bindhost',
229 :default => false, :requires_restart => true,
230 :desc => "Specific local host or IP for the bot to bind to (if required)",
232 Config.register Config::IntegerValue.new('server.reconnect_wait',
233 :default => 5, :validate => Proc.new{|v| v >= 0},
234 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
235 Config.register Config::FloatValue.new('server.sendq_delay',
236 :default => 2.0, :validate => Proc.new{|v| v >= 0},
237 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
238 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
239 Config.register Config::IntegerValue.new('server.sendq_burst',
240 :default => 4, :validate => Proc.new{|v| v >= 0},
241 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
242 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
243 Config.register Config::IntegerValue.new('server.ping_timeout',
244 :default => 30, :validate => Proc.new{|v| v >= 0},
245 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
247 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
248 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
249 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
250 Config.register Config::StringValue.new('irc.name',
251 :default => "Ruby bot", :requires_restart => true,
252 :desc => "IRC realname the bot should use")
253 Config.register Config::BooleanValue.new('irc.name_copyright',
254 :default => true, :requires_restart => true,
255 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
256 Config.register Config::StringValue.new('irc.user', :default => "rbot",
257 :requires_restart => true,
258 :desc => "local user the bot should appear to be", :wizard => true)
259 Config.register Config::ArrayValue.new('irc.join_channels',
260 :default => [], :wizard => true,
261 :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'")
262 Config.register Config::ArrayValue.new('irc.ignore_users',
264 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
266 Config.register Config::IntegerValue.new('core.save_every',
267 :default => 60, :validate => Proc.new{|v| v >= 0},
268 :on_change => Proc.new { |bot, v|
271 @timer.reschedule(@save_timer, v)
272 @timer.unblock(@save_timer)
274 @timer.block(@save_timer)
278 @save_timer = @timer.add(v) { bot.save }
280 # Nothing to do when v == 0
283 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
285 Config.register Config::BooleanValue.new('core.run_as_daemon',
286 :default => false, :requires_restart => true,
287 :desc => "Should the bot run as a daemon?")
289 Config.register Config::StringValue.new('log.file',
290 :default => false, :requires_restart => true,
291 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
292 Config.register Config::IntegerValue.new('log.level',
293 :default => 1, :requires_restart => false,
294 :validate => Proc.new { |v| (0..5).include?(v) },
295 :on_change => Proc.new { |bot, v|
298 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
299 Config.register Config::IntegerValue.new('log.keep',
300 :default => 1, :requires_restart => true,
301 :validate => Proc.new { |v| v >= 0 },
302 :desc => "How many old console messages logfiles to keep")
303 Config.register Config::IntegerValue.new('log.max_size',
304 :default => 10, :requires_restart => true,
305 :validate => Proc.new { |v| v > 0 },
306 :desc => "Maximum console messages logfile size (in megabytes)")
308 Config.register Config::ArrayValue.new('plugins.path',
309 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
310 :requires_restart => false,
311 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
312 :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")
314 Config.register Config::EnumValue.new('send.newlines',
315 :values => ['split', 'join'], :default => 'split',
316 :on_change => Proc.new { |bot, v|
317 bot.set_default_send_options :newlines => v.to_sym
319 :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")
320 Config.register Config::StringValue.new('send.join_with',
322 :on_change => Proc.new { |bot, v|
323 bot.set_default_send_options :join_with => v.dup
325 :desc => "String used to replace newlines when send.newlines is set to join")
326 Config.register Config::IntegerValue.new('send.max_lines',
328 :validate => Proc.new { |v| v >= 0 },
329 :on_change => Proc.new { |bot, v|
330 bot.set_default_send_options :max_lines => v
332 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
333 Config.register Config::EnumValue.new('send.overlong',
334 :values => ['split', 'truncate'], :default => 'split',
335 :on_change => Proc.new { |bot, v|
336 bot.set_default_send_options :overlong => v.to_sym
338 :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")
339 Config.register Config::StringValue.new('send.split_at',
341 :on_change => Proc.new { |bot, v|
342 bot.set_default_send_options :split_at => Regexp.new(v)
344 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
345 Config.register Config::BooleanValue.new('send.purge_split',
347 :on_change => Proc.new { |bot, v|
348 bot.set_default_send_options :purge_split => v
350 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
351 Config.register Config::StringValue.new('send.truncate_text',
352 :default => "#{Reverse}...#{Reverse}",
353 :on_change => Proc.new { |bot, v|
354 bot.set_default_send_options :truncate_text => v.dup
356 :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")
358 @argv = params[:argv]
359 @run_dir = params[:run_dir] || Dir.pwd
361 unless FileTest.directory? Config::coredir
362 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
366 unless FileTest.directory? Config::datadir
367 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
371 unless botclass and not botclass.empty?
372 # We want to find a sensible default.
373 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
374 # * On Windows (at least the NT versions) we want to put our stuff in the
375 # Application Data folder.
376 # We don't use any particular O/S detection magic, exploiting the fact that
377 # Etc.getpwuid is nil on Windows
378 if Etc.getpwuid(Process::Sys.geteuid)
379 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
381 if ENV.has_key?('APPDATA')
382 botclass = ENV['APPDATA'].dup
383 botclass.gsub!("\\","/")
388 botclass = File.expand_path(botclass)
389 @botclass = botclass.gsub(/\/$/, "")
391 unless FileTest.directory? botclass
392 log "no #{botclass} directory found, creating from templates.."
393 if FileTest.exist? botclass
394 error "file #{botclass} exists but isn't a directory"
397 FileUtils.cp_r Config::datadir+'/templates', botclass
400 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
401 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
403 # Time at which the last PING was sent
405 # Time at which the last line was RECV'd from the server
408 @startup_time = Time.new
411 @config = Config.manager
412 @config.bot_associate(self)
413 rescue Exception => e
419 if @config['core.run_as_daemon']
423 @logfile = @config['log.file']
424 if @logfile.class!=String || @logfile.empty?
425 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
428 # See http://blog.humlab.umu.se/samuel/archives/000107.html
429 # for the backgrounding code
435 rescue NotImplementedError
436 warning "Could not background, fork not supported"
439 rescue Exception => e
440 warning "Could not background. #{e.pretty_inspect}"
443 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
444 log "Redirecting standard input/output/error"
446 STDIN.reopen "/dev/null"
448 # On Windows, there's not such thing as /dev/null
451 def STDOUT.write(str=nil)
455 def STDERR.write(str=nil)
456 if str.to_s.match(/:\d+: warning:/)
465 # Set the new logfile and loglevel. This must be done after the daemonizing
466 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
467 $logger.datetime_format= $dateformat
468 $logger.level = @config['log.level']
469 $logger.level = $cl_loglevel if defined? $cl_loglevel
470 $logger.level = 0 if $debug
474 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
478 @registry = Registry.new self
481 @save_mutex = Mutex.new
482 if @config['core.save_every'] > 0
483 @save_timer = @timer.add(@config['core.save_every']) { save }
487 @quit_mutex = Mutex.new
490 @lang = Language.new(self, @config['core.language'])
493 @auth = Auth::manager
494 @auth.bot_associate(self)
495 # @auth.load("#{botclass}/botusers.yaml")
496 rescue Exception => e
501 @auth.everyone.set_default_permission("*", true)
502 @auth.botowner.password= @config['auth.password']
504 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
505 @plugins = Plugins::manager
506 @plugins.bot_associate(self)
509 if @config['server.name']
510 debug "upgrading configuration (server.name => server.list)"
511 srv_uri = 'irc://' + @config['server.name']
512 srv_uri += ":#{@config['server.port']}" if @config['server.port']
513 @config.items['server.list'.to_sym].set_string(srv_uri)
514 @config.delete('server.name'.to_sym)
515 @config.delete('server.port'.to_sym)
516 debug "server.list is now #{@config['server.list'].inspect}"
519 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
524 # Channels where we are quiet
525 # Array of channels names where the bot should be quiet
526 # '*' means all channels
530 @client[:welcome] = proc {|data|
531 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
533 @plugins.delegate("welcome", m)
534 @plugins.delegate("connect")
536 @config['irc.join_channels'].each { |c|
537 debug "autojoining channel #{c}"
538 if(c =~ /^(\S+)\s+(\S+)$/i)
546 # TODO the next two @client should go into rfc2812.rb, probably
547 # Since capabs are two-steps processes, server.supports[:capab]
548 # should be a three-state: nil, [], [....]
549 asked_for = { :"identify-msg" => false }
550 @client[:isupport] = proc { |data|
551 if server.supports[:capab] and !asked_for[:"identify-msg"]
552 sendq "CAPAB IDENTIFY-MSG"
553 asked_for[:"identify-msg"] = true
556 @client[:datastr] = proc { |data|
557 if data[:text] == "IDENTIFY-MSG"
558 server.capabilities[:"identify-msg"] = true
560 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
564 @client[:privmsg] = proc { |data|
565 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
566 # debug "Message source is #{data[:source].inspect}"
567 # debug "Message target is #{data[:target].inspect}"
568 # debug "Bot is #{myself.inspect}"
570 @config['irc.ignore_users'].each { |mask|
571 if m.source.matches?(server.new_netmask(mask))
576 @plugins.irc_delegate('privmsg', m)
578 @client[:notice] = proc { |data|
579 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
580 # pass it off to plugins that want to hear everything
581 @plugins.irc_delegate "notice", message
583 @client[:motd] = proc { |data|
584 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
585 @plugins.delegate "motd", m
587 @client[:nicktaken] = proc { |data|
588 new = "#{data[:nick]}_"
590 # If we're setting our nick at connection because our choice was taken,
591 # we have to fix our nick manually, because there will be no NICK message
592 # to inform us that our nick has been changed.
593 if data[:target] == '*'
594 debug "setting my connection nick to #{new}"
597 @plugins.delegate "nicktaken", data[:nick]
599 @client[:badnick] = proc {|data|
600 warning "bad nick (#{data[:nick]})"
602 @client[:ping] = proc {|data|
603 sendq "PONG #{data[:pingid]}"
605 @client[:pong] = proc {|data|
608 @client[:nick] = proc {|data|
609 # debug "Message source is #{data[:source].inspect}"
610 # debug "Bot is #{myself.inspect}"
611 source = data[:source]
614 m = NickMessage.new(self, server, source, old, new)
615 m.is_on = data[:is_on]
617 debug "my nick is now #{new}"
619 @plugins.irc_delegate("nick", m)
621 @client[:quit] = proc {|data|
622 source = data[:source]
623 message = data[:message]
624 m = QuitMessage.new(self, server, source, source, message)
625 m.was_on = data[:was_on]
626 @plugins.irc_delegate("quit", m)
628 @client[:mode] = proc {|data|
629 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
630 m.modes = data[:modes]
631 @plugins.delegate "modechange", m
633 @client[:join] = proc {|data|
634 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
635 @plugins.irc_delegate("join", m)
636 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
638 @client[:part] = proc {|data|
639 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
640 @plugins.irc_delegate("part", m)
642 @client[:kick] = proc {|data|
643 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
644 @plugins.irc_delegate("kick", m)
646 @client[:invite] = proc {|data|
647 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
648 @plugins.irc_delegate("invite", m)
650 @client[:changetopic] = proc {|data|
651 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
653 @plugins.irc_delegate("topic", m)
655 # @client[:topic] = proc { |data|
656 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
658 @client[:topicinfo] = proc { |data|
659 channel = data[:channel]
660 topic = channel.topic
661 m = TopicMessage.new(self, server, data[:source], channel, topic)
662 m.info_or_set = :info
663 @plugins.irc_delegate("topic", m)
665 @client[:names] = proc { |data|
666 m = NamesMessage.new(self, server, server, data[:channel])
667 m.users = data[:users]
668 @plugins.delegate "names", m
670 @client[:unknown] = proc { |data|
671 #debug "UNKNOWN: #{data[:serverstring]}"
672 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
673 @plugins.delegate "unknown_message", m
676 set_default_send_options :newlines => @config['send.newlines'].to_sym,
677 :join_with => @config['send.join_with'].dup,
678 :max_lines => @config['send.max_lines'],
679 :overlong => @config['send.overlong'].to_sym,
680 :split_at => Regexp.new(@config['send.split_at']),
681 :purge_split => @config['send.purge_split'],
682 :truncate_text => @config['send.truncate_text'].dup
685 def setup_plugins_path
686 @plugins.clear_botmodule_dirs
687 @plugins.add_botmodule_dir(Config::coredir + "/utils")
688 @plugins.add_botmodule_dir(Config::coredir)
689 @plugins.add_botmodule_dir("#{botclass}/plugins")
691 @config['plugins.path'].each do |_|
692 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
693 @plugins.add_botmodule_dir(path)
697 def set_default_send_options(opts={})
698 # Default send options for NOTICE and PRIVMSG
699 unless defined? @default_send_options
700 @default_send_options = {
701 :queue_channel => nil, # use default queue channel
702 :queue_ring => nil, # use default queue ring
703 :newlines => :split, # or :join
704 :join_with => ' ', # by default, use a single space
705 :max_lines => 0, # maximum number of lines to send with a single command
706 :overlong => :split, # or :truncate
707 # TODO an array of splitpoints would be preferrable for this option:
708 :split_at => /\s+/, # by default, split overlong lines at whitespace
709 :purge_split => true, # should the split string be removed?
710 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
713 @default_send_options.update opts unless opts.empty?
716 # checks if we should be quiet on a channel
717 def quiet_on?(channel)
718 return @quiet.include?('*') || @quiet.include?(channel.downcase)
721 def set_quiet(channel)
723 ch = channel.downcase.dup
724 @quiet << ch unless @quiet.include?(ch)
731 def reset_quiet(channel)
733 @quiet.delete channel.downcase
739 # things to do when we receive a signal
741 debug "received #{sig}, queueing quit"
743 quit unless @quit_mutex.locked?
744 debug "interrupted #{$interrupted} times"
752 # connect the bot to IRC
755 trap("SIGINT") { got_sig("SIGINT") }
756 trap("SIGTERM") { got_sig("SIGTERM") }
757 trap("SIGHUP") { got_sig("SIGHUP") }
758 rescue ArgumentError => e
759 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
760 rescue Exception => e
761 debug "failed to trap signals: #{e.pretty_inspect}"
764 quit if $interrupted > 0
767 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
769 quit if $interrupted > 0
771 realname = @config['irc.name'].clone || 'Ruby bot'
772 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
774 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
775 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
776 quit if $interrupted > 0
777 myself.nick = @config['irc.nick']
778 myself.user = @config['irc.user']
781 # begin event handling loop
785 quit if $interrupted > 0
789 while @socket.connected?
790 quit if $interrupted > 0
792 # Wait for messages and process them as they arrive. If nothing is
793 # received, we call the ping_server() method that will PING the
794 # server if appropriate, or raise a TimeoutError if no PONG has been
795 # received in the user-chosen timeout since the last PING sent.
797 break unless reply = @socket.gets
799 @client.process reply
805 # I despair of this. Some of my users get "connection reset by peer"
806 # exceptions that ARENT SocketError's. How am I supposed to handle
811 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
812 error "network exception: #{e.pretty_inspect}"
814 rescue BDB::Fatal => e
815 fatal "fatal bdb error: #{e.pretty_inspect}"
817 # Why restart? DB problems are serious stuff ...
818 # restart("Oops, we seem to have registry problems ...")
821 rescue Exception => e
822 error "non-net exception: #{e.pretty_inspect}"
825 fatal "unexpected exception: #{e.pretty_inspect}"
832 log "\n\nDisconnected\n\n"
834 quit if $interrupted > 0
836 log "\n\nWaiting to reconnect\n\n"
837 sleep @config['server.reconnect_wait']
841 # type:: message type
842 # where:: message target
843 # message:: message text
844 # send message +message+ of type +type+ to target +where+
845 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
846 # relevant say() or notice() methods. This one should be used for IRCd
847 # extensions you want to use in modules.
848 def sendmsg(type, where, original_message, options={})
849 opts = @default_send_options.merge(options)
851 # For starters, set up appropriate queue channels and rings
852 mchan = opts[:queue_channel]
853 mring = opts[:queue_ring]
870 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
874 messages << [multi_line.gsub("\n", opts[:join_with])]
876 multi_line.each_line { |line|
878 next unless(line.size > 0)
882 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
885 # The IRC protocol requires that each raw message must be not longer
886 # than 512 characters. From this length with have to subtract the EOL
887 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
888 # that will be prepended by the server to all of our messages.
890 # The maximum raw message length we can send is therefore 512 - 2 - 2
891 # minus the length of our hostmask.
893 max_len = 508 - myself.fullform.size
895 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
896 # will have a + or - prepended
897 if server.capabilities[:"identify-msg"]
901 # When splitting the message, we'll be prefixing the following string:
902 # (e.g. "PRIVMSG #rbot :")
903 fixed = "#{type} #{where} :"
905 # And this is what's left
906 left = max_len - fixed.size
908 truncate = opts[:truncate_text]
909 truncate = @default_send_options[:truncate_text] if truncate.size > left
910 truncate = "" if truncate.size > left
912 all_lines = messages.map { |line|
919 sub_lines = Array.new
921 sub_lines << msg.slice!(0, left)
923 lastspace = sub_lines.last.rindex(opts[:split_at])
925 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
926 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
931 line.slice(0, left - truncate.size) << truncate
933 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
938 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
939 lines = all_lines[0...opts[:max_lines]]
940 new_last = lines.last.slice(0, left - truncate.size) << truncate
941 lines.last.replace(new_last)
947 sendq "#{fixed}#{line}", chan, ring
948 delegate_sent(type, where, line)
952 # queue an arbitraty message for the server
953 def sendq(message="", chan=nil, ring=0)
955 @socket.queue(message, chan, ring)
958 # send a notice message to channel/nick +where+
959 def notice(where, message, options={})
960 return if where.kind_of?(Channel) and quiet_on?(where)
961 sendmsg "NOTICE", where, message, options
964 # say something (PRIVMSG) to channel/nick +where+
965 def say(where, message, options={})
966 return if where.kind_of?(Channel) and quiet_on?(where)
967 sendmsg "PRIVMSG", where, message, options
970 def ctcp_notice(where, command, message, options={})
971 return if where.kind_of?(Channel) and quiet_on?(where)
972 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
975 def ctcp_say(where, command, message, options={})
976 return if where.kind_of?(Channel) and quiet_on?(where)
977 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
980 # perform a CTCP action with message +message+ to channel/nick +where+
981 def action(where, message, options={})
982 ctcp_say(where, 'ACTION', message, options)
985 # quick way to say "okay" (or equivalent) to +where+
987 say where, @lang.get("okay")
990 # set topic of channel +where+ to +topic+
991 def topic(where, topic)
992 sendq "TOPIC #{where} :#{topic}", where, 2
995 def disconnect(message=nil)
996 message = @lang.get("quit") if (!message || message.empty?)
997 if @socket.connected?
999 debug "Clearing socket"
1001 debug "Sending quit message"
1002 @socket.emergency_puts "QUIT :#{message}"
1003 debug "Logging quits"
1004 delegate_sent('QUIT', myself, message)
1005 debug "Flushing socket"
1007 rescue SocketError => e
1008 error "error while disconnecting socket: #{e.pretty_inspect}"
1010 debug "Shutting down socket"
1017 # disconnect from the server and cleanup all plugins and modules
1018 def shutdown(message=nil)
1019 @quit_mutex.synchronize do
1020 debug "Shutting down: #{message}"
1021 ## No we don't restore them ... let everything run through
1023 # trap("SIGINT", "DEFAULT")
1024 # trap("SIGTERM", "DEFAULT")
1025 # trap("SIGHUP", "DEFAULT")
1027 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1029 debug "\tdisconnecting..."
1031 debug "\tstopping timer..."
1033 debug "\tsaving ..."
1035 debug "\tcleaning up ..."
1036 @save_mutex.synchronize do
1039 # debug "\tstopping timers ..."
1041 # debug "Closing registries"
1043 debug "\t\tcleaning up the db environment ..."
1045 log "rbot quit (#{message})"
1049 # message:: optional IRC quit message
1050 # quit IRC, shutdown the bot
1051 def quit(message=nil)
1059 # totally shutdown and respawn the bot
1060 def restart(message=nil)
1061 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1063 sleep @config['server.reconnect_wait']
1066 # Note, this fails on Windows
1067 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1070 rescue Errno::ENOENT
1071 exec("ruby", *(@argv.unshift $0))
1072 rescue Exception => e
1078 # call the save method for all of the botmodules
1080 @save_mutex.synchronize do
1086 # call the rescan method for all of the botmodules
1088 debug "\tstopping timer..."
1090 @save_mutex.synchronize do
1097 # channel:: channel to join
1098 # key:: optional channel key if channel is +s
1100 def join(channel, key=nil)
1102 sendq "JOIN #{channel} :#{key}", channel, 2
1104 sendq "JOIN #{channel}", channel, 2
1109 def part(channel, message="")
1110 sendq "PART #{channel} :#{message}", channel, 2
1113 # attempt to change bot's nick to +name+
1115 sendq "NICK #{name}"
1119 def mode(channel, mode, target)
1120 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1124 def kick(channel, user, msg)
1125 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1128 # m:: message asking for help
1129 # topic:: optional topic help is requested for
1130 # respond to online help requests
1132 topic = nil if topic == ""
1135 helpstr = _("help topics: ")
1136 helpstr += @plugins.helptopics
1137 helpstr += _(" (help <topic> for more info)")
1139 unless(helpstr = @plugins.help(topic))
1140 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1146 # returns a string describing the current status of the bot (uptime etc)
1148 secs_up = Time.new - @startup_time
1149 uptime = Utils.secs_to_string secs_up
1150 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1151 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1153 :up => uptime, :plug => @plugins.length,
1154 :sent => @socket.lines_sent, :recv => @socket.lines_received
1158 # We want to respond to a hung server in a timely manner. If nothing was received
1159 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1160 # the server. If the PONG is not received within the user-defined timeout, we
1161 # assume we're in ping timeout and act accordingly.
1163 act_timeout = @config['server.ping_timeout']
1164 return if act_timeout <= 0
1166 if @last_rec && now > @last_rec + act_timeout
1168 # No previous PING pending, send a new one
1170 @last_ping = Time.now
1172 diff = now - @last_ping
1173 if diff > act_timeout
1174 debug "no PONG from server in #{diff} seconds, reconnecting"
1175 # the actual reconnect is handled in the main loop:
1176 raise TimeoutError, "no PONG from server in #{diff} seconds"
1182 def stop_server_pings
1183 # cancel previous PINGs and reset time of last RECV
1190 # delegate sent messages
1191 def delegate_sent(type, where, message)
1192 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1195 m = NoticeMessage.new(*args)
1197 m = PrivMessage.new(*args)
1199 m = QuitMessage.new(*args)
1201 @plugins.delegate('sent', m)