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
711 def setup_plugins_path
712 @plugins.clear_botmodule_dirs
713 @plugins.add_botmodule_dir(Config::coredir + "/utils")
714 @plugins.add_botmodule_dir(Config::coredir)
715 @plugins.add_botmodule_dir("#{botclass}/plugins")
717 @config['plugins.path'].each do |_|
718 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
719 @plugins.add_botmodule_dir(path)
723 def set_default_send_options(opts={})
724 # Default send options for NOTICE and PRIVMSG
725 unless defined? @default_send_options
726 @default_send_options = {
727 :queue_channel => nil, # use default queue channel
728 :queue_ring => nil, # use default queue ring
729 :newlines => :split, # or :join
730 :join_with => ' ', # by default, use a single space
731 :max_lines => 0, # maximum number of lines to send with a single command
732 :overlong => :split, # or :truncate
733 # TODO an array of splitpoints would be preferrable for this option:
734 :split_at => /\s+/, # by default, split overlong lines at whitespace
735 :purge_split => true, # should the split string be removed?
736 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
739 @default_send_options.update opts unless opts.empty?
742 # checks if we should be quiet on a channel
743 def quiet_on?(channel)
744 return @quiet.include?('*') || @quiet.include?(channel.downcase)
747 def set_quiet(channel)
749 ch = channel.downcase.dup
750 @quiet << ch unless @quiet.include?(ch)
757 def reset_quiet(channel)
759 @quiet.delete channel.downcase
765 # things to do when we receive a signal
766 def got_sig(sig, func=:quit)
767 debug "received #{sig}, queueing #{func}"
769 self.send(func) unless @quit_mutex.locked?
770 debug "interrupted #{$interrupted} times"
781 trap("SIGINT") { got_sig("SIGINT") }
782 trap("SIGTERM") { got_sig("SIGTERM") }
783 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
784 rescue ArgumentError => e
785 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
786 rescue Exception => e
787 debug "failed to trap signals: #{e.pretty_inspect}"
791 # connect the bot to IRC
794 quit if $interrupted > 0
797 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
799 quit if $interrupted > 0
801 realname = @config['irc.name'].clone || 'Ruby bot'
802 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
804 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
805 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
806 quit if $interrupted > 0
807 myself.nick = @config['irc.nick']
808 myself.user = @config['irc.user']
811 # begin event handling loop
815 quit if $interrupted > 0
819 while @socket.connected?
820 quit if $interrupted > 0
822 # Wait for messages and process them as they arrive. If nothing is
823 # received, we call the ping_server() method that will PING the
824 # server if appropriate, or raise a TimeoutError if no PONG has been
825 # received in the user-chosen timeout since the last PING sent.
827 break unless reply = @socket.gets
829 @client.process reply
835 # I despair of this. Some of my users get "connection reset by peer"
836 # exceptions that ARENT SocketError's. How am I supposed to handle
841 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
842 error "network exception: #{e.pretty_inspect}"
844 rescue BDB::Fatal => e
845 fatal "fatal bdb error: #{e.pretty_inspect}"
847 # Why restart? DB problems are serious stuff ...
848 # restart("Oops, we seem to have registry problems ...")
851 rescue Exception => e
852 error "non-net exception: #{e.pretty_inspect}"
855 fatal "unexpected exception: #{e.pretty_inspect}"
862 log "\n\nDisconnected\n\n"
864 quit if $interrupted > 0
866 log "\n\nWaiting to reconnect\n\n"
867 sleep @config['server.reconnect_wait']
871 # type:: message type
872 # where:: message target
873 # message:: message text
874 # send message +message+ of type +type+ to target +where+
875 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
876 # relevant say() or notice() methods. This one should be used for IRCd
877 # extensions you want to use in modules.
878 def sendmsg(type, where, original_message, options={})
879 opts = @default_send_options.merge(options)
881 # For starters, set up appropriate queue channels and rings
882 mchan = opts[:queue_channel]
883 mring = opts[:queue_ring]
900 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
904 messages << [multi_line.gsub("\n", opts[:join_with])]
906 multi_line.each_line { |line|
908 next unless(line.size > 0)
912 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
915 # The IRC protocol requires that each raw message must be not longer
916 # than 512 characters. From this length with have to subtract the EOL
917 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
918 # that will be prepended by the server to all of our messages.
920 # The maximum raw message length we can send is therefore 512 - 2 - 2
921 # minus the length of our hostmask.
923 max_len = 508 - myself.fullform.size
925 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
926 # will have a + or - prepended
927 if server.capabilities[:"identify-msg"]
931 # When splitting the message, we'll be prefixing the following string:
932 # (e.g. "PRIVMSG #rbot :")
933 fixed = "#{type} #{where} :"
935 # And this is what's left
936 left = max_len - fixed.size
938 truncate = opts[:truncate_text]
939 truncate = @default_send_options[:truncate_text] if truncate.size > left
940 truncate = "" if truncate.size > left
942 all_lines = messages.map { |line|
949 sub_lines = Array.new
951 sub_lines << msg.slice!(0, left)
953 lastspace = sub_lines.last.rindex(opts[:split_at])
955 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
956 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
961 line.slice(0, left - truncate.size) << truncate
963 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
968 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
969 lines = all_lines[0...opts[:max_lines]]
970 new_last = lines.last.slice(0, left - truncate.size) << truncate
971 lines.last.replace(new_last)
977 sendq "#{fixed}#{line}", chan, ring
978 delegate_sent(type, where, line)
982 # queue an arbitraty message for the server
983 def sendq(message="", chan=nil, ring=0)
985 @socket.queue(message, chan, ring)
988 # send a notice message to channel/nick +where+
989 def notice(where, message, options={})
990 return if where.kind_of?(Channel) and quiet_on?(where)
991 sendmsg "NOTICE", where, message, options
994 # say something (PRIVMSG) to channel/nick +where+
995 def say(where, message, options={})
996 return if where.kind_of?(Channel) and quiet_on?(where)
997 sendmsg "PRIVMSG", where, message, options
1000 def ctcp_notice(where, command, message, options={})
1001 return if where.kind_of?(Channel) and quiet_on?(where)
1002 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1005 def ctcp_say(where, command, message, options={})
1006 return if where.kind_of?(Channel) and quiet_on?(where)
1007 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1010 # perform a CTCP action with message +message+ to channel/nick +where+
1011 def action(where, message, options={})
1012 ctcp_say(where, 'ACTION', message, options)
1015 # quick way to say "okay" (or equivalent) to +where+
1017 say where, @lang.get("okay")
1020 # set topic of channel +where+ to +topic+
1021 def topic(where, topic)
1022 sendq "TOPIC #{where} :#{topic}", where, 2
1025 def disconnect(message=nil)
1026 message = @lang.get("quit") if (!message || message.empty?)
1027 if @socket.connected?
1029 debug "Clearing socket"
1031 debug "Sending quit message"
1032 @socket.emergency_puts "QUIT :#{message}"
1033 debug "Logging quits"
1034 delegate_sent('QUIT', myself, message)
1035 debug "Flushing socket"
1037 rescue SocketError => e
1038 error "error while disconnecting socket: #{e.pretty_inspect}"
1040 debug "Shutting down socket"
1047 # disconnect from the server and cleanup all plugins and modules
1048 def shutdown(message=nil)
1049 @quit_mutex.synchronize do
1050 debug "Shutting down: #{message}"
1051 ## No we don't restore them ... let everything run through
1053 # trap("SIGINT", "DEFAULT")
1054 # trap("SIGTERM", "DEFAULT")
1055 # trap("SIGHUP", "DEFAULT")
1057 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1059 debug "\tdisconnecting..."
1061 debug "\tstopping timer..."
1063 debug "\tsaving ..."
1065 debug "\tcleaning up ..."
1066 @save_mutex.synchronize do
1069 # debug "\tstopping timers ..."
1071 # debug "Closing registries"
1073 debug "\t\tcleaning up the db environment ..."
1075 log "rbot quit (#{message})"
1079 # message:: optional IRC quit message
1080 # quit IRC, shutdown the bot
1081 def quit(message=nil)
1089 # totally shutdown and respawn the bot
1090 def restart(message=nil)
1091 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1093 sleep @config['server.reconnect_wait']
1096 # Note, this fails on Windows
1097 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1101 rescue Errno::ENOENT
1103 exec("ruby", *(@argv.unshift $0))
1104 rescue Exception => e
1110 # call the save method for all of the botmodules
1112 @save_mutex.synchronize do
1118 # call the rescan method for all of the botmodules
1120 debug "\tstopping timer..."
1122 @save_mutex.synchronize do
1129 # channel:: channel to join
1130 # key:: optional channel key if channel is +s
1132 def join(channel, key=nil)
1134 sendq "JOIN #{channel} :#{key}", channel, 2
1136 sendq "JOIN #{channel}", channel, 2
1141 def part(channel, message="")
1142 sendq "PART #{channel} :#{message}", channel, 2
1145 # attempt to change bot's nick to +name+
1147 sendq "NICK #{name}"
1151 def mode(channel, mode, target)
1152 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1156 def kick(channel, user, msg)
1157 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1160 # m:: message asking for help
1161 # topic:: optional topic help is requested for
1162 # respond to online help requests
1164 topic = nil if topic == ""
1167 helpstr = _("help topics: ")
1168 helpstr += @plugins.helptopics
1169 helpstr += _(" (help <topic> for more info)")
1171 unless(helpstr = @plugins.help(topic))
1172 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1178 # returns a string describing the current status of the bot (uptime etc)
1180 secs_up = Time.new - @startup_time
1181 uptime = Utils.secs_to_string secs_up
1182 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1183 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1185 :up => uptime, :plug => @plugins.length,
1186 :sent => @socket.lines_sent, :recv => @socket.lines_received
1190 # We want to respond to a hung server in a timely manner. If nothing was received
1191 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1192 # the server. If the PONG is not received within the user-defined timeout, we
1193 # assume we're in ping timeout and act accordingly.
1195 act_timeout = @config['server.ping_timeout']
1196 return if act_timeout <= 0
1198 if @last_rec && now > @last_rec + act_timeout
1200 # No previous PING pending, send a new one
1202 @last_ping = Time.now
1204 diff = now - @last_ping
1205 if diff > act_timeout
1206 debug "no PONG from server in #{diff} seconds, reconnecting"
1207 # the actual reconnect is handled in the main loop:
1208 raise TimeoutError, "no PONG from server in #{diff} seconds"
1214 def stop_server_pings
1215 # cancel previous PINGs and reset time of last RECV
1222 # delegate sent messages
1223 def delegate_sent(type, where, message)
1224 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1227 m = NoticeMessage.new(*args)
1229 m = PrivMessage.new(*args)
1231 m = QuitMessage.new(*args)
1233 @plugins.delegate('sent', m)