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 l = $log_queue.pop
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
67 $log_queue.push [level, l.chomp, who]
73 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
77 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
81 def debug(message=nil, who_pos=1)
82 rawlog(Logger::Severity::DEBUG, message, who_pos)
85 def log(message=nil, who_pos=1)
86 rawlog(Logger::Severity::INFO, message, who_pos)
89 def warning(message=nil, who_pos=1)
90 rawlog(Logger::Severity::WARN, message, who_pos)
93 def error(message=nil, who_pos=1)
94 rawlog(Logger::Severity::ERROR, message, who_pos)
97 def fatal(message=nil, who_pos=1)
98 rawlog(Logger::Severity::FATAL, message, who_pos)
103 warning "warning test"
107 # The following global is used for the improved signal handling.
111 require 'rbot/rbotconfig'
112 require 'rbot/load-gettext'
113 require 'rbot/config'
114 require 'rbot/config-compat'
117 require 'rbot/rfc2812'
118 require 'rbot/ircsocket'
119 require 'rbot/botuser'
121 require 'rbot/plugins'
122 require 'rbot/message'
123 require 'rbot/language'
124 require 'rbot/dbhash'
125 require 'rbot/registry'
129 # Main bot class, which manages the various components, receives messages,
130 # handles them or passes them to plugins, and contains core functionality.
132 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
133 SOURCE_URL = "http://ruby-rbot.org"
134 # the bot's Auth data
137 # the bot's Config data
140 # the botclass for this bot (determines configdir among other things)
141 attr_reader :botclass
143 # used to perform actions periodically (saves configuration once per minute
147 # synchronize with this mutex while touching permanent data files:
148 # saving, flushing, cleaning up ...
149 attr_reader :save_mutex
151 # bot's Language data
158 # bot's object registry, plugins get an interface to this for persistant
159 # storage (hash interface tied to a bdb file, plugins use Accessors to store
160 # and restore objects in their own namespaces.)
161 attr_reader :registry
163 # bot's plugins. This is an instance of class Plugins
166 # bot's httputil help object, for fetching resources via http. Sets up
167 # proxies etc as defined by the bot configuration/environment
168 attr_accessor :httputil
170 # server we are connected to
176 # bot User in the client/server connection
182 # bot User in the client/server connection
190 ret = self.to_s[0..-2]
191 ret << ' version=' << $version.inspect
192 ret << ' botclass=' << botclass.inspect
193 ret << ' lang="' << lang.language
198 ret << ' nick=' << nick.inspect
201 ret << (server.to_s + (socket ?
202 ' [' << socket.server_uri.to_s << ']' : '')).inspect
203 unless server.channels.empty?
205 ret << server.channels.map { |c|
206 "%s%s" % [c.modes_of(nick).map { |m|
207 server.prefix_for_mode(m)
214 ret << ' plugins=' << plugins.inspect
219 # create a new Bot with botclass +botclass+
220 def initialize(botclass, params = {})
221 # Config for the core bot
222 # TODO should we split socket stuff into ircsocket, etc?
223 Config.register Config::ArrayValue.new('server.list',
224 :default => ['irc://localhost'], :wizard => true,
225 :requires_restart => true,
226 :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.")
227 Config.register Config::BooleanValue.new('server.ssl',
228 :default => false, :requires_restart => true, :wizard => true,
229 :desc => "Use SSL to connect to this server?")
230 Config.register Config::StringValue.new('server.password',
231 :default => false, :requires_restart => true,
232 :desc => "Password for connecting to this server (if required)",
234 Config.register Config::StringValue.new('server.bindhost',
235 :default => false, :requires_restart => true,
236 :desc => "Specific local host or IP for the bot to bind to (if required)",
238 Config.register Config::IntegerValue.new('server.reconnect_wait',
239 :default => 5, :validate => Proc.new{|v| v >= 0},
240 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
241 Config.register Config::FloatValue.new('server.sendq_delay',
242 :default => 2.0, :validate => Proc.new{|v| v >= 0},
243 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
244 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
245 Config.register Config::IntegerValue.new('server.sendq_burst',
246 :default => 4, :validate => Proc.new{|v| v >= 0},
247 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
248 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
249 Config.register Config::IntegerValue.new('server.ping_timeout',
250 :default => 30, :validate => Proc.new{|v| v >= 0},
251 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
253 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
254 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
255 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
256 Config.register Config::StringValue.new('irc.name',
257 :default => "Ruby bot", :requires_restart => true,
258 :desc => "IRC realname the bot should use")
259 Config.register Config::BooleanValue.new('irc.name_copyright',
260 :default => true, :requires_restart => true,
261 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
262 Config.register Config::StringValue.new('irc.user', :default => "rbot",
263 :requires_restart => true,
264 :desc => "local user the bot should appear to be", :wizard => true)
265 Config.register Config::ArrayValue.new('irc.join_channels',
266 :default => [], :wizard => true,
267 :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'")
268 Config.register Config::ArrayValue.new('irc.ignore_users',
270 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
272 Config.register Config::IntegerValue.new('core.save_every',
273 :default => 60, :validate => Proc.new{|v| v >= 0},
274 :on_change => Proc.new { |bot, v|
277 @timer.reschedule(@save_timer, v)
278 @timer.unblock(@save_timer)
280 @timer.block(@save_timer)
284 @save_timer = @timer.add(v) { bot.save }
286 # Nothing to do when v == 0
289 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
291 Config.register Config::BooleanValue.new('core.run_as_daemon',
292 :default => false, :requires_restart => true,
293 :desc => "Should the bot run as a daemon?")
295 Config.register Config::StringValue.new('log.file',
296 :default => false, :requires_restart => true,
297 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
298 Config.register Config::IntegerValue.new('log.level',
299 :default => 1, :requires_restart => false,
300 :validate => Proc.new { |v| (0..5).include?(v) },
301 :on_change => Proc.new { |bot, v|
304 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
305 Config.register Config::IntegerValue.new('log.keep',
306 :default => 1, :requires_restart => true,
307 :validate => Proc.new { |v| v >= 0 },
308 :desc => "How many old console messages logfiles to keep")
309 Config.register Config::IntegerValue.new('log.max_size',
310 :default => 10, :requires_restart => true,
311 :validate => Proc.new { |v| v > 0 },
312 :desc => "Maximum console messages logfile size (in megabytes)")
314 Config.register Config::ArrayValue.new('plugins.path',
315 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
316 :requires_restart => false,
317 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
318 :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")
320 Config.register Config::EnumValue.new('send.newlines',
321 :values => ['split', 'join'], :default => 'split',
322 :on_change => Proc.new { |bot, v|
323 bot.set_default_send_options :newlines => v.to_sym
325 :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")
326 Config.register Config::StringValue.new('send.join_with',
328 :on_change => Proc.new { |bot, v|
329 bot.set_default_send_options :join_with => v.dup
331 :desc => "String used to replace newlines when send.newlines is set to join")
332 Config.register Config::IntegerValue.new('send.max_lines',
334 :validate => Proc.new { |v| v >= 0 },
335 :on_change => Proc.new { |bot, v|
336 bot.set_default_send_options :max_lines => v
338 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
339 Config.register Config::EnumValue.new('send.overlong',
340 :values => ['split', 'truncate'], :default => 'split',
341 :on_change => Proc.new { |bot, v|
342 bot.set_default_send_options :overlong => v.to_sym
344 :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")
345 Config.register Config::StringValue.new('send.split_at',
347 :on_change => Proc.new { |bot, v|
348 bot.set_default_send_options :split_at => Regexp.new(v)
350 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
351 Config.register Config::BooleanValue.new('send.purge_split',
353 :on_change => Proc.new { |bot, v|
354 bot.set_default_send_options :purge_split => v
356 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
357 Config.register Config::StringValue.new('send.truncate_text',
358 :default => "#{Reverse}...#{Reverse}",
359 :on_change => Proc.new { |bot, v|
360 bot.set_default_send_options :truncate_text => v.dup
362 :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")
364 @argv = params[:argv]
365 @run_dir = params[:run_dir] || Dir.pwd
367 unless FileTest.directory? Config::coredir
368 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
372 unless FileTest.directory? Config::datadir
373 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
377 unless botclass and not botclass.empty?
378 # We want to find a sensible default.
379 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
380 # * On Windows (at least the NT versions) we want to put our stuff in the
381 # Application Data folder.
382 # We don't use any particular O/S detection magic, exploiting the fact that
383 # Etc.getpwuid is nil on Windows
384 if Etc.getpwuid(Process::Sys.geteuid)
385 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
387 if ENV.has_key?('APPDATA')
388 botclass = ENV['APPDATA'].dup
389 botclass.gsub!("\\","/")
394 botclass = File.expand_path(botclass)
395 @botclass = botclass.gsub(/\/$/, "")
397 unless FileTest.directory? botclass
398 log "no #{botclass} directory found, creating from templates.."
399 if FileTest.exist? botclass
400 error "file #{botclass} exists but isn't a directory"
403 FileUtils.cp_r Config::datadir+'/templates', botclass
406 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
407 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
409 # Time at which the last PING was sent
411 # Time at which the last line was RECV'd from the server
414 @startup_time = Time.new
417 @config = Config.manager
418 @config.bot_associate(self)
419 rescue Exception => e
425 if @config['core.run_as_daemon']
429 @logfile = @config['log.file']
430 if @logfile.class!=String || @logfile.empty?
431 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
434 # See http://blog.humlab.umu.se/samuel/archives/000107.html
435 # for the backgrounding code
441 rescue NotImplementedError
442 warning "Could not background, fork not supported"
445 rescue Exception => e
446 warning "Could not background. #{e.pretty_inspect}"
449 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
450 log "Redirecting standard input/output/error"
452 STDIN.reopen "/dev/null"
454 # On Windows, there's not such thing as /dev/null
457 def STDOUT.write(str=nil)
461 def STDERR.write(str=nil)
462 if str.to_s.match(/:\d+: warning:/)
471 # Set the new logfile and loglevel. This must be done after the daemonizing
472 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
473 $logger.datetime_format= $dateformat
474 $logger.level = @config['log.level']
475 $logger.level = $cl_loglevel if defined? $cl_loglevel
476 $logger.level = 0 if $debug
480 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
484 @registry = Registry.new self
487 @save_mutex = Mutex.new
488 if @config['core.save_every'] > 0
489 @save_timer = @timer.add(@config['core.save_every']) { save }
493 @quit_mutex = Mutex.new
496 @lang = Language.new(self, @config['core.language'])
499 @auth = Auth::manager
500 @auth.bot_associate(self)
501 # @auth.load("#{botclass}/botusers.yaml")
502 rescue Exception => e
507 @auth.everyone.set_default_permission("*", true)
508 @auth.botowner.password= @config['auth.password']
510 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
511 @plugins = Plugins::manager
512 @plugins.bot_associate(self)
515 if @config['server.name']
516 debug "upgrading configuration (server.name => server.list)"
517 srv_uri = 'irc://' + @config['server.name']
518 srv_uri += ":#{@config['server.port']}" if @config['server.port']
519 @config.items['server.list'.to_sym].set_string(srv_uri)
520 @config.delete('server.name'.to_sym)
521 @config.delete('server.port'.to_sym)
522 debug "server.list is now #{@config['server.list'].inspect}"
525 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
530 # Channels where we are quiet
531 # Array of channels names where the bot should be quiet
532 # '*' means all channels
536 @client[:welcome] = proc {|data|
537 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
539 @plugins.delegate("welcome", m)
540 @plugins.delegate("connect")
542 @config['irc.join_channels'].each { |c|
543 debug "autojoining channel #{c}"
544 if(c =~ /^(\S+)\s+(\S+)$/i)
552 # TODO the next two @client should go into rfc2812.rb, probably
553 # Since capabs are two-steps processes, server.supports[:capab]
554 # should be a three-state: nil, [], [....]
555 asked_for = { :"identify-msg" => false }
556 @client[:isupport] = proc { |data|
557 if server.supports[:capab] and !asked_for[:"identify-msg"]
558 sendq "CAPAB IDENTIFY-MSG"
559 asked_for[:"identify-msg"] = true
562 @client[:datastr] = proc { |data|
563 if data[:text] == "IDENTIFY-MSG"
564 server.capabilities[:"identify-msg"] = true
566 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
570 @client[:privmsg] = proc { |data|
571 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
572 # debug "Message source is #{data[:source].inspect}"
573 # debug "Message target is #{data[:target].inspect}"
574 # debug "Bot is #{myself.inspect}"
576 @config['irc.ignore_users'].each { |mask|
577 if m.source.matches?(server.new_netmask(mask))
582 @plugins.irc_delegate('privmsg', m)
584 @client[:notice] = proc { |data|
585 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
586 # pass it off to plugins that want to hear everything
587 @plugins.irc_delegate "notice", message
589 @client[:motd] = proc { |data|
590 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
591 @plugins.delegate "motd", m
593 @client[:nicktaken] = proc { |data|
594 new = "#{data[:nick]}_"
596 # If we're setting our nick at connection because our choice was taken,
597 # we have to fix our nick manually, because there will be no NICK message
598 # to inform us that our nick has been changed.
599 if data[:target] == '*'
600 debug "setting my connection nick to #{new}"
603 @plugins.delegate "nicktaken", data[:nick]
605 @client[:badnick] = proc {|data|
606 warning "bad nick (#{data[:nick]})"
608 @client[:ping] = proc {|data|
609 sendq "PONG #{data[:pingid]}"
611 @client[:pong] = proc {|data|
614 @client[:nick] = proc {|data|
615 # debug "Message source is #{data[:source].inspect}"
616 # debug "Bot is #{myself.inspect}"
617 source = data[:source]
620 m = NickMessage.new(self, server, source, old, new)
621 m.is_on = data[:is_on]
623 debug "my nick is now #{new}"
625 @plugins.irc_delegate("nick", m)
627 @client[:quit] = proc {|data|
628 source = data[:source]
629 message = data[:message]
630 m = QuitMessage.new(self, server, source, source, message)
631 m.was_on = data[:was_on]
632 @plugins.irc_delegate("quit", m)
634 @client[:mode] = proc {|data|
635 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
636 m.modes = data[:modes]
637 @plugins.delegate "modechange", m
639 @client[:join] = proc {|data|
640 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
641 @plugins.irc_delegate("join", m)
642 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
644 @client[:part] = proc {|data|
645 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
646 @plugins.irc_delegate("part", m)
648 @client[:kick] = proc {|data|
649 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
650 @plugins.irc_delegate("kick", m)
652 @client[:invite] = proc {|data|
653 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
654 @plugins.irc_delegate("invite", m)
656 @client[:changetopic] = proc {|data|
657 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
659 @plugins.irc_delegate("topic", m)
661 # @client[:topic] = proc { |data|
662 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
664 @client[:topicinfo] = proc { |data|
665 channel = data[:channel]
666 topic = channel.topic
667 m = TopicMessage.new(self, server, data[:source], channel, topic)
668 m.info_or_set = :info
669 @plugins.irc_delegate("topic", m)
671 @client[:names] = proc { |data|
672 m = NamesMessage.new(self, server, server, data[:channel])
673 m.users = data[:users]
674 @plugins.delegate "names", m
676 @client[:unknown] = proc { |data|
677 #debug "UNKNOWN: #{data[:serverstring]}"
678 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
679 @plugins.delegate "unknown_message", m
682 set_default_send_options :newlines => @config['send.newlines'].to_sym,
683 :join_with => @config['send.join_with'].dup,
684 :max_lines => @config['send.max_lines'],
685 :overlong => @config['send.overlong'].to_sym,
686 :split_at => Regexp.new(@config['send.split_at']),
687 :purge_split => @config['send.purge_split'],
688 :truncate_text => @config['send.truncate_text'].dup
691 def setup_plugins_path
692 @plugins.clear_botmodule_dirs
693 @plugins.add_botmodule_dir(Config::coredir + "/utils")
694 @plugins.add_botmodule_dir(Config::coredir)
695 @plugins.add_botmodule_dir("#{botclass}/plugins")
697 @config['plugins.path'].each do |_|
698 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
699 @plugins.add_botmodule_dir(path)
703 def set_default_send_options(opts={})
704 # Default send options for NOTICE and PRIVMSG
705 unless defined? @default_send_options
706 @default_send_options = {
707 :queue_channel => nil, # use default queue channel
708 :queue_ring => nil, # use default queue ring
709 :newlines => :split, # or :join
710 :join_with => ' ', # by default, use a single space
711 :max_lines => 0, # maximum number of lines to send with a single command
712 :overlong => :split, # or :truncate
713 # TODO an array of splitpoints would be preferrable for this option:
714 :split_at => /\s+/, # by default, split overlong lines at whitespace
715 :purge_split => true, # should the split string be removed?
716 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
719 @default_send_options.update opts unless opts.empty?
722 # checks if we should be quiet on a channel
723 def quiet_on?(channel)
724 return @quiet.include?('*') || @quiet.include?(channel.downcase)
727 def set_quiet(channel)
729 ch = channel.downcase.dup
730 @quiet << ch unless @quiet.include?(ch)
737 def reset_quiet(channel)
739 @quiet.delete channel.downcase
745 # things to do when we receive a signal
747 debug "received #{sig}, queueing quit"
749 quit unless @quit_mutex.locked?
750 debug "interrupted #{$interrupted} times"
758 # connect the bot to IRC
761 trap("SIGINT") { got_sig("SIGINT") }
762 trap("SIGTERM") { got_sig("SIGTERM") }
763 trap("SIGHUP") { got_sig("SIGHUP") }
764 rescue ArgumentError => e
765 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
766 rescue Exception => e
767 debug "failed to trap signals: #{e.pretty_inspect}"
770 quit if $interrupted > 0
773 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
775 quit if $interrupted > 0
777 realname = @config['irc.name'].clone || 'Ruby bot'
778 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
780 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
781 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
782 quit if $interrupted > 0
783 myself.nick = @config['irc.nick']
784 myself.user = @config['irc.user']
787 # begin event handling loop
791 quit if $interrupted > 0
795 while @socket.connected?
796 quit if $interrupted > 0
798 # Wait for messages and process them as they arrive. If nothing is
799 # received, we call the ping_server() method that will PING the
800 # server if appropriate, or raise a TimeoutError if no PONG has been
801 # received in the user-chosen timeout since the last PING sent.
803 break unless reply = @socket.gets
805 @client.process reply
811 # I despair of this. Some of my users get "connection reset by peer"
812 # exceptions that ARENT SocketError's. How am I supposed to handle
817 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
818 error "network exception: #{e.pretty_inspect}"
820 rescue BDB::Fatal => e
821 fatal "fatal bdb error: #{e.pretty_inspect}"
823 # Why restart? DB problems are serious stuff ...
824 # restart("Oops, we seem to have registry problems ...")
827 rescue Exception => e
828 error "non-net exception: #{e.pretty_inspect}"
831 fatal "unexpected exception: #{e.pretty_inspect}"
838 log "\n\nDisconnected\n\n"
840 quit if $interrupted > 0
842 log "\n\nWaiting to reconnect\n\n"
843 sleep @config['server.reconnect_wait']
847 # type:: message type
848 # where:: message target
849 # message:: message text
850 # send message +message+ of type +type+ to target +where+
851 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
852 # relevant say() or notice() methods. This one should be used for IRCd
853 # extensions you want to use in modules.
854 def sendmsg(type, where, original_message, options={})
855 opts = @default_send_options.merge(options)
857 # For starters, set up appropriate queue channels and rings
858 mchan = opts[:queue_channel]
859 mring = opts[:queue_ring]
876 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
880 messages << [multi_line.gsub("\n", opts[:join_with])]
882 multi_line.each_line { |line|
884 next unless(line.size > 0)
888 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
891 # The IRC protocol requires that each raw message must be not longer
892 # than 512 characters. From this length with have to subtract the EOL
893 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
894 # that will be prepended by the server to all of our messages.
896 # The maximum raw message length we can send is therefore 512 - 2 - 2
897 # minus the length of our hostmask.
899 max_len = 508 - myself.fullform.size
901 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
902 # will have a + or - prepended
903 if server.capabilities[:"identify-msg"]
907 # When splitting the message, we'll be prefixing the following string:
908 # (e.g. "PRIVMSG #rbot :")
909 fixed = "#{type} #{where} :"
911 # And this is what's left
912 left = max_len - fixed.size
914 truncate = opts[:truncate_text]
915 truncate = @default_send_options[:truncate_text] if truncate.size > left
916 truncate = "" if truncate.size > left
918 all_lines = messages.map { |line|
925 sub_lines = Array.new
927 sub_lines << msg.slice!(0, left)
929 lastspace = sub_lines.last.rindex(opts[:split_at])
931 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
932 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
937 line.slice(0, left - truncate.size) << truncate
939 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
944 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
945 lines = all_lines[0...opts[:max_lines]]
946 new_last = lines.last.slice(0, left - truncate.size) << truncate
947 lines.last.replace(new_last)
953 sendq "#{fixed}#{line}", chan, ring
954 delegate_sent(type, where, line)
958 # queue an arbitraty message for the server
959 def sendq(message="", chan=nil, ring=0)
961 @socket.queue(message, chan, ring)
964 # send a notice message to channel/nick +where+
965 def notice(where, message, options={})
966 return if where.kind_of?(Channel) and quiet_on?(where)
967 sendmsg "NOTICE", where, message, options
970 # say something (PRIVMSG) to channel/nick +where+
971 def say(where, message, options={})
972 return if where.kind_of?(Channel) and quiet_on?(where)
973 sendmsg "PRIVMSG", where, message, options
976 def ctcp_notice(where, command, message, options={})
977 return if where.kind_of?(Channel) and quiet_on?(where)
978 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
981 def ctcp_say(where, command, message, options={})
982 return if where.kind_of?(Channel) and quiet_on?(where)
983 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
986 # perform a CTCP action with message +message+ to channel/nick +where+
987 def action(where, message, options={})
988 ctcp_say(where, 'ACTION', message, options)
991 # quick way to say "okay" (or equivalent) to +where+
993 say where, @lang.get("okay")
996 # set topic of channel +where+ to +topic+
997 def topic(where, topic)
998 sendq "TOPIC #{where} :#{topic}", where, 2
1001 def disconnect(message=nil)
1002 message = @lang.get("quit") if (!message || message.empty?)
1003 if @socket.connected?
1005 debug "Clearing socket"
1007 debug "Sending quit message"
1008 @socket.emergency_puts "QUIT :#{message}"
1009 debug "Logging quits"
1010 delegate_sent('QUIT', myself, message)
1011 debug "Flushing socket"
1013 rescue SocketError => e
1014 error "error while disconnecting socket: #{e.pretty_inspect}"
1016 debug "Shutting down socket"
1023 # disconnect from the server and cleanup all plugins and modules
1024 def shutdown(message=nil)
1025 @quit_mutex.synchronize do
1026 debug "Shutting down: #{message}"
1027 ## No we don't restore them ... let everything run through
1029 # trap("SIGINT", "DEFAULT")
1030 # trap("SIGTERM", "DEFAULT")
1031 # trap("SIGHUP", "DEFAULT")
1033 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1035 debug "\tdisconnecting..."
1037 debug "\tstopping timer..."
1039 debug "\tsaving ..."
1041 debug "\tcleaning up ..."
1042 @save_mutex.synchronize do
1045 # debug "\tstopping timers ..."
1047 # debug "Closing registries"
1049 debug "\t\tcleaning up the db environment ..."
1051 log "rbot quit (#{message})"
1055 # message:: optional IRC quit message
1056 # quit IRC, shutdown the bot
1057 def quit(message=nil)
1065 # totally shutdown and respawn the bot
1066 def restart(message=nil)
1067 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1069 sleep @config['server.reconnect_wait']
1072 # Note, this fails on Windows
1073 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1076 rescue Errno::ENOENT
1077 exec("ruby", *(@argv.unshift $0))
1078 rescue Exception => e
1084 # call the save method for all of the botmodules
1086 @save_mutex.synchronize do
1092 # call the rescan method for all of the botmodules
1094 debug "\tstopping timer..."
1096 @save_mutex.synchronize do
1103 # channel:: channel to join
1104 # key:: optional channel key if channel is +s
1106 def join(channel, key=nil)
1108 sendq "JOIN #{channel} :#{key}", channel, 2
1110 sendq "JOIN #{channel}", channel, 2
1115 def part(channel, message="")
1116 sendq "PART #{channel} :#{message}", channel, 2
1119 # attempt to change bot's nick to +name+
1121 sendq "NICK #{name}"
1125 def mode(channel, mode, target)
1126 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1130 def kick(channel, user, msg)
1131 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1134 # m:: message asking for help
1135 # topic:: optional topic help is requested for
1136 # respond to online help requests
1138 topic = nil if topic == ""
1141 helpstr = _("help topics: ")
1142 helpstr += @plugins.helptopics
1143 helpstr += _(" (help <topic> for more info)")
1145 unless(helpstr = @plugins.help(topic))
1146 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1152 # returns a string describing the current status of the bot (uptime etc)
1154 secs_up = Time.new - @startup_time
1155 uptime = Utils.secs_to_string secs_up
1156 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1157 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1159 :up => uptime, :plug => @plugins.length,
1160 :sent => @socket.lines_sent, :recv => @socket.lines_received
1164 # We want to respond to a hung server in a timely manner. If nothing was received
1165 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1166 # the server. If the PONG is not received within the user-defined timeout, we
1167 # assume we're in ping timeout and act accordingly.
1169 act_timeout = @config['server.ping_timeout']
1170 return if act_timeout <= 0
1172 if @last_rec && now > @last_rec + act_timeout
1174 # No previous PING pending, send a new one
1176 @last_ping = Time.now
1178 diff = now - @last_ping
1179 if diff > act_timeout
1180 debug "no PONG from server in #{diff} seconds, reconnecting"
1181 # the actual reconnect is handled in the main loop:
1182 raise TimeoutError, "no PONG from server in #{diff} seconds"
1188 def stop_server_pings
1189 # cancel previous PINGs and reset time of last RECV
1196 # delegate sent messages
1197 def delegate_sent(type, where, message)
1198 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1201 m = NoticeMessage.new(*args)
1203 m = PrivMessage.new(*args)
1205 m = QuitMessage.new(*args)
1207 @plugins.delegate('sent', m)