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
24 while ls = $log_queue.pop
25 ls.each { |l| $logger.add(*l) }
31 unless Kernel.instance_methods.include?("pretty_inspect")
35 public :pretty_inspect
40 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
41 if self.backtrace and not self.backtrace.empty?
43 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
49 def rawlog(level, message=nil, who_pos=1)
51 if call_stack.length > who_pos
52 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
56 # Output each line. To distinguish between separate messages and multi-line
57 # messages originating at the same time, we blank #{who} after the first message
59 # Also, we output strings as-is but for other objects we use pretty_inspect
64 str = message.pretty_inspect
68 qmsg.push [level, l.chomp, who]
75 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
79 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
83 def debug(message=nil, who_pos=1)
84 rawlog(Logger::Severity::DEBUG, message, who_pos)
87 def log(message=nil, who_pos=1)
88 rawlog(Logger::Severity::INFO, message, who_pos)
91 def warning(message=nil, who_pos=1)
92 rawlog(Logger::Severity::WARN, message, who_pos)
95 def error(message=nil, who_pos=1)
96 rawlog(Logger::Severity::ERROR, message, who_pos)
99 def fatal(message=nil, who_pos=1)
100 rawlog(Logger::Severity::FATAL, message, who_pos)
105 warning "warning test"
109 # The following global is used for the improved signal handling.
113 require 'rbot/rbotconfig'
114 require 'rbot/load-gettext'
115 require 'rbot/config'
116 require 'rbot/config-compat'
119 require 'rbot/rfc2812'
120 require 'rbot/ircsocket'
121 require 'rbot/botuser'
123 require 'rbot/plugins'
124 require 'rbot/message'
125 require 'rbot/language'
126 require 'rbot/dbhash'
127 require 'rbot/registry'
131 # Main bot class, which manages the various components, receives messages,
132 # handles them or passes them to plugins, and contains core functionality.
134 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
135 SOURCE_URL = "http://ruby-rbot.org"
136 # the bot's Auth data
139 # the bot's Config data
142 # the botclass for this bot (determines configdir among other things)
143 attr_reader :botclass
145 # used to perform actions periodically (saves configuration once per minute
149 # synchronize with this mutex while touching permanent data files:
150 # saving, flushing, cleaning up ...
151 attr_reader :save_mutex
153 # bot's Language data
160 # bot's object registry, plugins get an interface to this for persistant
161 # storage (hash interface tied to a bdb file, plugins use Accessors to store
162 # and restore objects in their own namespaces.)
163 attr_reader :registry
165 # bot's plugins. This is an instance of class Plugins
168 # bot's httputil help object, for fetching resources via http. Sets up
169 # proxies etc as defined by the bot configuration/environment
170 attr_accessor :httputil
172 # server we are connected to
178 # bot User in the client/server connection
184 # bot User in the client/server connection
192 ret = self.to_s[0..-2]
193 ret << ' version=' << $version.inspect
194 ret << ' botclass=' << botclass.inspect
195 ret << ' lang="' << lang.language
200 ret << ' nick=' << nick.inspect
203 ret << (server.to_s + (socket ?
204 ' [' << socket.server_uri.to_s << ']' : '')).inspect
205 unless server.channels.empty?
207 ret << server.channels.map { |c|
208 "%s%s" % [c.modes_of(nick).map { |m|
209 server.prefix_for_mode(m)
216 ret << ' plugins=' << plugins.inspect
221 # create a new Bot with botclass +botclass+
222 def initialize(botclass, params = {})
223 # Config for the core bot
224 # TODO should we split socket stuff into ircsocket, etc?
225 Config.register Config::ArrayValue.new('server.list',
226 :default => ['irc://localhost'], :wizard => true,
227 :requires_restart => true,
228 :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.")
229 Config.register Config::BooleanValue.new('server.ssl',
230 :default => false, :requires_restart => true, :wizard => true,
231 :desc => "Use SSL to connect to this server?")
232 Config.register Config::StringValue.new('server.password',
233 :default => false, :requires_restart => true,
234 :desc => "Password for connecting to this server (if required)",
236 Config.register Config::StringValue.new('server.bindhost',
237 :default => false, :requires_restart => true,
238 :desc => "Specific local host or IP for the bot to bind to (if required)",
240 Config.register Config::IntegerValue.new('server.reconnect_wait',
241 :default => 5, :validate => Proc.new{|v| v >= 0},
242 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
243 Config.register Config::FloatValue.new('server.sendq_delay',
244 :default => 2.0, :validate => Proc.new{|v| v >= 0},
245 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
246 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
247 Config.register Config::IntegerValue.new('server.sendq_burst',
248 :default => 4, :validate => Proc.new{|v| v >= 0},
249 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
250 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
251 Config.register Config::IntegerValue.new('server.ping_timeout',
252 :default => 30, :validate => Proc.new{|v| v >= 0},
253 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
255 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
256 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
257 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
258 Config.register Config::StringValue.new('irc.name',
259 :default => "Ruby bot", :requires_restart => true,
260 :desc => "IRC realname the bot should use")
261 Config.register Config::BooleanValue.new('irc.name_copyright',
262 :default => true, :requires_restart => true,
263 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
264 Config.register Config::StringValue.new('irc.user', :default => "rbot",
265 :requires_restart => true,
266 :desc => "local user the bot should appear to be", :wizard => true)
267 Config.register Config::ArrayValue.new('irc.join_channels',
268 :default => [], :wizard => true,
269 :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'")
270 Config.register Config::ArrayValue.new('irc.ignore_users',
272 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
274 Config.register Config::IntegerValue.new('core.save_every',
275 :default => 60, :validate => Proc.new{|v| v >= 0},
276 :on_change => Proc.new { |bot, v|
279 @timer.reschedule(@save_timer, v)
280 @timer.unblock(@save_timer)
282 @timer.block(@save_timer)
286 @save_timer = @timer.add(v) { bot.save }
288 # Nothing to do when v == 0
291 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
293 Config.register Config::BooleanValue.new('core.run_as_daemon',
294 :default => false, :requires_restart => true,
295 :desc => "Should the bot run as a daemon?")
297 Config.register Config::StringValue.new('log.file',
298 :default => false, :requires_restart => true,
299 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
300 Config.register Config::IntegerValue.new('log.level',
301 :default => 1, :requires_restart => false,
302 :validate => Proc.new { |v| (0..5).include?(v) },
303 :on_change => Proc.new { |bot, v|
306 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
307 Config.register Config::IntegerValue.new('log.keep',
308 :default => 1, :requires_restart => true,
309 :validate => Proc.new { |v| v >= 0 },
310 :desc => "How many old console messages logfiles to keep")
311 Config.register Config::IntegerValue.new('log.max_size',
312 :default => 10, :requires_restart => true,
313 :validate => Proc.new { |v| v > 0 },
314 :desc => "Maximum console messages logfile size (in megabytes)")
316 Config.register Config::ArrayValue.new('plugins.path',
317 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
318 :requires_restart => false,
319 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
320 :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")
322 Config.register Config::EnumValue.new('send.newlines',
323 :values => ['split', 'join'], :default => 'split',
324 :on_change => Proc.new { |bot, v|
325 bot.set_default_send_options :newlines => v.to_sym
327 :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")
328 Config.register Config::StringValue.new('send.join_with',
330 :on_change => Proc.new { |bot, v|
331 bot.set_default_send_options :join_with => v.dup
333 :desc => "String used to replace newlines when send.newlines is set to join")
334 Config.register Config::IntegerValue.new('send.max_lines',
336 :validate => Proc.new { |v| v >= 0 },
337 :on_change => Proc.new { |bot, v|
338 bot.set_default_send_options :max_lines => v
340 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
341 Config.register Config::EnumValue.new('send.overlong',
342 :values => ['split', 'truncate'], :default => 'split',
343 :on_change => Proc.new { |bot, v|
344 bot.set_default_send_options :overlong => v.to_sym
346 :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")
347 Config.register Config::StringValue.new('send.split_at',
349 :on_change => Proc.new { |bot, v|
350 bot.set_default_send_options :split_at => Regexp.new(v)
352 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
353 Config.register Config::BooleanValue.new('send.purge_split',
355 :on_change => Proc.new { |bot, v|
356 bot.set_default_send_options :purge_split => v
358 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
359 Config.register Config::StringValue.new('send.truncate_text',
360 :default => "#{Reverse}...#{Reverse}",
361 :on_change => Proc.new { |bot, v|
362 bot.set_default_send_options :truncate_text => v.dup
364 :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")
366 @argv = params[:argv]
367 @run_dir = params[:run_dir] || Dir.pwd
369 unless FileTest.directory? Config::coredir
370 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
374 unless FileTest.directory? Config::datadir
375 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
379 unless botclass and not botclass.empty?
380 # We want to find a sensible default.
381 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
382 # * On Windows (at least the NT versions) we want to put our stuff in the
383 # Application Data folder.
384 # We don't use any particular O/S detection magic, exploiting the fact that
385 # Etc.getpwuid is nil on Windows
386 if Etc.getpwuid(Process::Sys.geteuid)
387 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
389 if ENV.has_key?('APPDATA')
390 botclass = ENV['APPDATA'].dup
391 botclass.gsub!("\\","/")
396 botclass = File.expand_path(botclass)
397 @botclass = botclass.gsub(/\/$/, "")
399 unless FileTest.directory? botclass
400 log "no #{botclass} directory found, creating from templates.."
401 if FileTest.exist? botclass
402 error "file #{botclass} exists but isn't a directory"
405 FileUtils.cp_r Config::datadir+'/templates', botclass
408 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
409 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
411 # Time at which the last PING was sent
413 # Time at which the last line was RECV'd from the server
416 @startup_time = Time.new
419 @config = Config.manager
420 @config.bot_associate(self)
421 rescue Exception => e
427 if @config['core.run_as_daemon']
431 @logfile = @config['log.file']
432 if @logfile.class!=String || @logfile.empty?
433 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
436 # See http://blog.humlab.umu.se/samuel/archives/000107.html
437 # for the backgrounding code
443 rescue NotImplementedError
444 warning "Could not background, fork not supported"
447 rescue Exception => e
448 warning "Could not background. #{e.pretty_inspect}"
451 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
452 log "Redirecting standard input/output/error"
454 STDIN.reopen "/dev/null"
456 # On Windows, there's not such thing as /dev/null
459 def STDOUT.write(str=nil)
463 def STDERR.write(str=nil)
464 if str.to_s.match(/:\d+: warning:/)
473 # Set the new logfile and loglevel. This must be done after the daemonizing
474 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
475 $logger.datetime_format= $dateformat
476 $logger.level = @config['log.level']
477 $logger.level = $cl_loglevel if defined? $cl_loglevel
478 $logger.level = 0 if $debug
482 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
486 @registry = Registry.new self
489 @save_mutex = Mutex.new
490 if @config['core.save_every'] > 0
491 @save_timer = @timer.add(@config['core.save_every']) { save }
495 @quit_mutex = Mutex.new
498 @lang = Language.new(self, @config['core.language'])
501 @auth = Auth::manager
502 @auth.bot_associate(self)
503 # @auth.load("#{botclass}/botusers.yaml")
504 rescue Exception => e
509 @auth.everyone.set_default_permission("*", true)
510 @auth.botowner.password= @config['auth.password']
512 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
513 @plugins = Plugins::manager
514 @plugins.bot_associate(self)
517 if @config['server.name']
518 debug "upgrading configuration (server.name => server.list)"
519 srv_uri = 'irc://' + @config['server.name']
520 srv_uri += ":#{@config['server.port']}" if @config['server.port']
521 @config.items['server.list'.to_sym].set_string(srv_uri)
522 @config.delete('server.name'.to_sym)
523 @config.delete('server.port'.to_sym)
524 debug "server.list is now #{@config['server.list'].inspect}"
527 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
532 # Channels where we are quiet
533 # Array of channels names where the bot should be quiet
534 # '*' means all channels
538 @client[:welcome] = proc {|data|
539 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
541 @plugins.delegate("welcome", m)
542 @plugins.delegate("connect")
544 @config['irc.join_channels'].each { |c|
545 debug "autojoining channel #{c}"
546 if(c =~ /^(\S+)\s+(\S+)$/i)
554 # TODO the next two @client should go into rfc2812.rb, probably
555 # Since capabs are two-steps processes, server.supports[:capab]
556 # should be a three-state: nil, [], [....]
557 asked_for = { :"identify-msg" => false }
558 @client[:isupport] = proc { |data|
559 if server.supports[:capab] and !asked_for[:"identify-msg"]
560 sendq "CAPAB IDENTIFY-MSG"
561 asked_for[:"identify-msg"] = true
564 @client[:datastr] = proc { |data|
565 if data[:text] == "IDENTIFY-MSG"
566 server.capabilities[:"identify-msg"] = true
568 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
572 @client[:privmsg] = proc { |data|
573 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
574 # debug "Message source is #{data[:source].inspect}"
575 # debug "Message target is #{data[:target].inspect}"
576 # debug "Bot is #{myself.inspect}"
578 @config['irc.ignore_users'].each { |mask|
579 if m.source.matches?(server.new_netmask(mask))
584 @plugins.irc_delegate('privmsg', m)
586 @client[:notice] = proc { |data|
587 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
588 # pass it off to plugins that want to hear everything
589 @plugins.irc_delegate "notice", message
591 @client[:motd] = proc { |data|
592 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
593 @plugins.delegate "motd", m
595 @client[:nicktaken] = proc { |data|
596 new = "#{data[:nick]}_"
598 # If we're setting our nick at connection because our choice was taken,
599 # we have to fix our nick manually, because there will be no NICK message
600 # to inform us that our nick has been changed.
601 if data[:target] == '*'
602 debug "setting my connection nick to #{new}"
605 @plugins.delegate "nicktaken", data[:nick]
607 @client[:badnick] = proc {|data|
608 warning "bad nick (#{data[:nick]})"
610 @client[:ping] = proc {|data|
611 sendq "PONG #{data[:pingid]}"
613 @client[:pong] = proc {|data|
616 @client[:nick] = proc {|data|
617 # debug "Message source is #{data[:source].inspect}"
618 # debug "Bot is #{myself.inspect}"
619 source = data[:source]
622 m = NickMessage.new(self, server, source, old, new)
623 m.is_on = data[:is_on]
625 debug "my nick is now #{new}"
627 @plugins.irc_delegate("nick", m)
629 @client[:quit] = proc {|data|
630 source = data[:source]
631 message = data[:message]
632 m = QuitMessage.new(self, server, source, source, message)
633 m.was_on = data[:was_on]
634 @plugins.irc_delegate("quit", m)
636 @client[:mode] = proc {|data|
637 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
638 m.modes = data[:modes]
639 @plugins.delegate "modechange", m
641 @client[:join] = proc {|data|
642 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
643 @plugins.irc_delegate("join", m)
644 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
646 @client[:part] = proc {|data|
647 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
648 @plugins.irc_delegate("part", m)
650 @client[:kick] = proc {|data|
651 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
652 @plugins.irc_delegate("kick", m)
654 @client[:invite] = proc {|data|
655 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
656 @plugins.irc_delegate("invite", m)
658 @client[:changetopic] = proc {|data|
659 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
661 @plugins.irc_delegate("topic", m)
663 # @client[:topic] = proc { |data|
664 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
666 @client[:topicinfo] = proc { |data|
667 channel = data[:channel]
668 topic = channel.topic
669 m = TopicMessage.new(self, server, data[:source], channel, topic)
670 m.info_or_set = :info
671 @plugins.irc_delegate("topic", m)
673 @client[:names] = proc { |data|
674 m = NamesMessage.new(self, server, server, data[:channel])
675 m.users = data[:users]
676 @plugins.delegate "names", m
678 @client[:unknown] = proc { |data|
679 #debug "UNKNOWN: #{data[:serverstring]}"
680 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
681 @plugins.delegate "unknown_message", m
684 set_default_send_options :newlines => @config['send.newlines'].to_sym,
685 :join_with => @config['send.join_with'].dup,
686 :max_lines => @config['send.max_lines'],
687 :overlong => @config['send.overlong'].to_sym,
688 :split_at => Regexp.new(@config['send.split_at']),
689 :purge_split => @config['send.purge_split'],
690 :truncate_text => @config['send.truncate_text'].dup
693 def setup_plugins_path
694 @plugins.clear_botmodule_dirs
695 @plugins.add_botmodule_dir(Config::coredir + "/utils")
696 @plugins.add_botmodule_dir(Config::coredir)
697 @plugins.add_botmodule_dir("#{botclass}/plugins")
699 @config['plugins.path'].each do |_|
700 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
701 @plugins.add_botmodule_dir(path)
705 def set_default_send_options(opts={})
706 # Default send options for NOTICE and PRIVMSG
707 unless defined? @default_send_options
708 @default_send_options = {
709 :queue_channel => nil, # use default queue channel
710 :queue_ring => nil, # use default queue ring
711 :newlines => :split, # or :join
712 :join_with => ' ', # by default, use a single space
713 :max_lines => 0, # maximum number of lines to send with a single command
714 :overlong => :split, # or :truncate
715 # TODO an array of splitpoints would be preferrable for this option:
716 :split_at => /\s+/, # by default, split overlong lines at whitespace
717 :purge_split => true, # should the split string be removed?
718 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
721 @default_send_options.update opts unless opts.empty?
724 # checks if we should be quiet on a channel
725 def quiet_on?(channel)
726 return @quiet.include?('*') || @quiet.include?(channel.downcase)
729 def set_quiet(channel)
731 ch = channel.downcase.dup
732 @quiet << ch unless @quiet.include?(ch)
739 def reset_quiet(channel)
741 @quiet.delete channel.downcase
747 # things to do when we receive a signal
749 debug "received #{sig}, queueing quit"
751 quit unless @quit_mutex.locked?
752 debug "interrupted #{$interrupted} times"
760 # connect the bot to IRC
763 trap("SIGINT") { got_sig("SIGINT") }
764 trap("SIGTERM") { got_sig("SIGTERM") }
765 trap("SIGHUP") { got_sig("SIGHUP") }
766 rescue ArgumentError => e
767 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
768 rescue Exception => e
769 debug "failed to trap signals: #{e.pretty_inspect}"
772 quit if $interrupted > 0
775 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
777 quit if $interrupted > 0
779 realname = @config['irc.name'].clone || 'Ruby bot'
780 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
782 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
783 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
784 quit if $interrupted > 0
785 myself.nick = @config['irc.nick']
786 myself.user = @config['irc.user']
789 # begin event handling loop
793 quit if $interrupted > 0
797 while @socket.connected?
798 quit if $interrupted > 0
800 # Wait for messages and process them as they arrive. If nothing is
801 # received, we call the ping_server() method that will PING the
802 # server if appropriate, or raise a TimeoutError if no PONG has been
803 # received in the user-chosen timeout since the last PING sent.
805 break unless reply = @socket.gets
807 @client.process reply
813 # I despair of this. Some of my users get "connection reset by peer"
814 # exceptions that ARENT SocketError's. How am I supposed to handle
819 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
820 error "network exception: #{e.pretty_inspect}"
822 rescue BDB::Fatal => e
823 fatal "fatal bdb error: #{e.pretty_inspect}"
825 # Why restart? DB problems are serious stuff ...
826 # restart("Oops, we seem to have registry problems ...")
829 rescue Exception => e
830 error "non-net exception: #{e.pretty_inspect}"
833 fatal "unexpected exception: #{e.pretty_inspect}"
840 log "\n\nDisconnected\n\n"
842 quit if $interrupted > 0
844 log "\n\nWaiting to reconnect\n\n"
845 sleep @config['server.reconnect_wait']
849 # type:: message type
850 # where:: message target
851 # message:: message text
852 # send message +message+ of type +type+ to target +where+
853 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
854 # relevant say() or notice() methods. This one should be used for IRCd
855 # extensions you want to use in modules.
856 def sendmsg(type, where, original_message, options={})
857 opts = @default_send_options.merge(options)
859 # For starters, set up appropriate queue channels and rings
860 mchan = opts[:queue_channel]
861 mring = opts[:queue_ring]
878 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
882 messages << [multi_line.gsub("\n", opts[:join_with])]
884 multi_line.each_line { |line|
886 next unless(line.size > 0)
890 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
893 # The IRC protocol requires that each raw message must be not longer
894 # than 512 characters. From this length with have to subtract the EOL
895 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
896 # that will be prepended by the server to all of our messages.
898 # The maximum raw message length we can send is therefore 512 - 2 - 2
899 # minus the length of our hostmask.
901 max_len = 508 - myself.fullform.size
903 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
904 # will have a + or - prepended
905 if server.capabilities[:"identify-msg"]
909 # When splitting the message, we'll be prefixing the following string:
910 # (e.g. "PRIVMSG #rbot :")
911 fixed = "#{type} #{where} :"
913 # And this is what's left
914 left = max_len - fixed.size
916 truncate = opts[:truncate_text]
917 truncate = @default_send_options[:truncate_text] if truncate.size > left
918 truncate = "" if truncate.size > left
920 all_lines = messages.map { |line|
927 sub_lines = Array.new
929 sub_lines << msg.slice!(0, left)
931 lastspace = sub_lines.last.rindex(opts[:split_at])
933 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
934 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
939 line.slice(0, left - truncate.size) << truncate
941 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
946 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
947 lines = all_lines[0...opts[:max_lines]]
948 new_last = lines.last.slice(0, left - truncate.size) << truncate
949 lines.last.replace(new_last)
955 sendq "#{fixed}#{line}", chan, ring
956 delegate_sent(type, where, line)
960 # queue an arbitraty message for the server
961 def sendq(message="", chan=nil, ring=0)
963 @socket.queue(message, chan, ring)
966 # send a notice message to channel/nick +where+
967 def notice(where, message, options={})
968 return if where.kind_of?(Channel) and quiet_on?(where)
969 sendmsg "NOTICE", where, message, options
972 # say something (PRIVMSG) to channel/nick +where+
973 def say(where, message, options={})
974 return if where.kind_of?(Channel) and quiet_on?(where)
975 sendmsg "PRIVMSG", where, message, options
978 def ctcp_notice(where, command, message, options={})
979 return if where.kind_of?(Channel) and quiet_on?(where)
980 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
983 def ctcp_say(where, command, message, options={})
984 return if where.kind_of?(Channel) and quiet_on?(where)
985 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
988 # perform a CTCP action with message +message+ to channel/nick +where+
989 def action(where, message, options={})
990 ctcp_say(where, 'ACTION', message, options)
993 # quick way to say "okay" (or equivalent) to +where+
995 say where, @lang.get("okay")
998 # set topic of channel +where+ to +topic+
999 def topic(where, topic)
1000 sendq "TOPIC #{where} :#{topic}", where, 2
1003 def disconnect(message=nil)
1004 message = @lang.get("quit") if (!message || message.empty?)
1005 if @socket.connected?
1007 debug "Clearing socket"
1009 debug "Sending quit message"
1010 @socket.emergency_puts "QUIT :#{message}"
1011 debug "Logging quits"
1012 delegate_sent('QUIT', myself, message)
1013 debug "Flushing socket"
1015 rescue SocketError => e
1016 error "error while disconnecting socket: #{e.pretty_inspect}"
1018 debug "Shutting down socket"
1025 # disconnect from the server and cleanup all plugins and modules
1026 def shutdown(message=nil)
1027 @quit_mutex.synchronize do
1028 debug "Shutting down: #{message}"
1029 ## No we don't restore them ... let everything run through
1031 # trap("SIGINT", "DEFAULT")
1032 # trap("SIGTERM", "DEFAULT")
1033 # trap("SIGHUP", "DEFAULT")
1035 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1037 debug "\tdisconnecting..."
1039 debug "\tstopping timer..."
1041 debug "\tsaving ..."
1043 debug "\tcleaning up ..."
1044 @save_mutex.synchronize do
1047 # debug "\tstopping timers ..."
1049 # debug "Closing registries"
1051 debug "\t\tcleaning up the db environment ..."
1053 log "rbot quit (#{message})"
1057 # message:: optional IRC quit message
1058 # quit IRC, shutdown the bot
1059 def quit(message=nil)
1067 # totally shutdown and respawn the bot
1068 def restart(message=nil)
1069 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1071 sleep @config['server.reconnect_wait']
1074 # Note, this fails on Windows
1075 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1078 rescue Errno::ENOENT
1079 exec("ruby", *(@argv.unshift $0))
1080 rescue Exception => e
1086 # call the save method for all of the botmodules
1088 @save_mutex.synchronize do
1094 # call the rescan method for all of the botmodules
1096 debug "\tstopping timer..."
1098 @save_mutex.synchronize do
1105 # channel:: channel to join
1106 # key:: optional channel key if channel is +s
1108 def join(channel, key=nil)
1110 sendq "JOIN #{channel} :#{key}", channel, 2
1112 sendq "JOIN #{channel}", channel, 2
1117 def part(channel, message="")
1118 sendq "PART #{channel} :#{message}", channel, 2
1121 # attempt to change bot's nick to +name+
1123 sendq "NICK #{name}"
1127 def mode(channel, mode, target)
1128 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1132 def kick(channel, user, msg)
1133 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1136 # m:: message asking for help
1137 # topic:: optional topic help is requested for
1138 # respond to online help requests
1140 topic = nil if topic == ""
1143 helpstr = _("help topics: ")
1144 helpstr += @plugins.helptopics
1145 helpstr += _(" (help <topic> for more info)")
1147 unless(helpstr = @plugins.help(topic))
1148 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1154 # returns a string describing the current status of the bot (uptime etc)
1156 secs_up = Time.new - @startup_time
1157 uptime = Utils.secs_to_string secs_up
1158 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1159 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1161 :up => uptime, :plug => @plugins.length,
1162 :sent => @socket.lines_sent, :recv => @socket.lines_received
1166 # We want to respond to a hung server in a timely manner. If nothing was received
1167 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1168 # the server. If the PONG is not received within the user-defined timeout, we
1169 # assume we're in ping timeout and act accordingly.
1171 act_timeout = @config['server.ping_timeout']
1172 return if act_timeout <= 0
1174 if @last_rec && now > @last_rec + act_timeout
1176 # No previous PING pending, send a new one
1178 @last_ping = Time.now
1180 diff = now - @last_ping
1181 if diff > act_timeout
1182 debug "no PONG from server in #{diff} seconds, reconnecting"
1183 # the actual reconnect is handled in the main loop:
1184 raise TimeoutError, "no PONG from server in #{diff} seconds"
1190 def stop_server_pings
1191 # cancel previous PINGs and reset time of last RECV
1198 # delegate sent messages
1199 def delegate_sent(type, where, message)
1200 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1203 m = NoticeMessage.new(*args)
1205 m = PrivMessage.new(*args)
1207 m = QuitMessage.new(*args)
1209 @plugins.delegate('sent', m)