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?
79 def restart_logger(newlogger = false)
82 $logger = newlogger if newlogger
84 $log_thread = Thread.new do
86 while ls = $log_queue.pop
87 ls.each { |l| $logger.add(*l) }
95 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
100 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
104 def debug(message=nil, who_pos=1)
105 rawlog(Logger::Severity::DEBUG, message, who_pos)
108 def log(message=nil, who_pos=1)
109 rawlog(Logger::Severity::INFO, message, who_pos)
112 def warning(message=nil, who_pos=1)
113 rawlog(Logger::Severity::WARN, message, who_pos)
116 def error(message=nil, who_pos=1)
117 rawlog(Logger::Severity::ERROR, message, who_pos)
120 def fatal(message=nil, who_pos=1)
121 rawlog(Logger::Severity::FATAL, message, who_pos)
126 warning "warning test"
130 # The following global is used for the improved signal handling.
134 require 'rbot/rbotconfig'
135 require 'rbot/load-gettext'
136 require 'rbot/config'
137 require 'rbot/config-compat'
140 require 'rbot/rfc2812'
141 require 'rbot/ircsocket'
142 require 'rbot/botuser'
144 require 'rbot/plugins'
145 require 'rbot/message'
146 require 'rbot/language'
147 require 'rbot/dbhash'
148 require 'rbot/registry'
152 # Main bot class, which manages the various components, receives messages,
153 # handles them or passes them to plugins, and contains core functionality.
155 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
156 SOURCE_URL = "http://ruby-rbot.org"
157 # the bot's Auth data
160 # the bot's Config data
163 # the botclass for this bot (determines configdir among other things)
164 attr_reader :botclass
166 # used to perform actions periodically (saves configuration once per minute
170 # synchronize with this mutex while touching permanent data files:
171 # saving, flushing, cleaning up ...
172 attr_reader :save_mutex
174 # bot's Language data
181 # bot's object registry, plugins get an interface to this for persistant
182 # storage (hash interface tied to a bdb file, plugins use Accessors to store
183 # and restore objects in their own namespaces.)
184 attr_reader :registry
186 # bot's plugins. This is an instance of class Plugins
189 # bot's httputil help object, for fetching resources via http. Sets up
190 # proxies etc as defined by the bot configuration/environment
191 attr_accessor :httputil
193 # server we are connected to
199 # bot User in the client/server connection
205 # bot User in the client/server connection
213 ret = self.to_s[0..-2]
214 ret << ' version=' << $version.inspect
215 ret << ' botclass=' << botclass.inspect
216 ret << ' lang="' << lang.language
221 ret << ' nick=' << nick.inspect
224 ret << (server.to_s + (socket ?
225 ' [' << socket.server_uri.to_s << ']' : '')).inspect
226 unless server.channels.empty?
228 ret << server.channels.map { |c|
229 "%s%s" % [c.modes_of(nick).map { |m|
230 server.prefix_for_mode(m)
237 ret << ' plugins=' << plugins.inspect
242 # create a new Bot with botclass +botclass+
243 def initialize(botclass, params = {})
244 # Config for the core bot
245 # TODO should we split socket stuff into ircsocket, etc?
246 Config.register Config::ArrayValue.new('server.list',
247 :default => ['irc://localhost'], :wizard => true,
248 :requires_restart => true,
249 :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.")
250 Config.register Config::BooleanValue.new('server.ssl',
251 :default => false, :requires_restart => true, :wizard => true,
252 :desc => "Use SSL to connect to this server?")
253 Config.register Config::StringValue.new('server.password',
254 :default => false, :requires_restart => true,
255 :desc => "Password for connecting to this server (if required)",
257 Config.register Config::StringValue.new('server.bindhost',
258 :default => false, :requires_restart => true,
259 :desc => "Specific local host or IP for the bot to bind to (if required)",
261 Config.register Config::IntegerValue.new('server.reconnect_wait',
262 :default => 5, :validate => Proc.new{|v| v >= 0},
263 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
264 Config.register Config::FloatValue.new('server.sendq_delay',
265 :default => 2.0, :validate => Proc.new{|v| v >= 0},
266 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
267 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
268 Config.register Config::IntegerValue.new('server.sendq_burst',
269 :default => 4, :validate => Proc.new{|v| v >= 0},
270 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
271 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
272 Config.register Config::IntegerValue.new('server.ping_timeout',
273 :default => 30, :validate => Proc.new{|v| v >= 0},
274 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
275 Config.register Config::ArrayValue.new('server.nocolor_modes',
276 :default => ['c'], :wizard => false,
277 :requires_restart => false,
278 :desc => "List of channel modes that require messages to be without colors")
280 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
281 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
282 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
283 Config.register Config::StringValue.new('irc.name',
284 :default => "Ruby bot", :requires_restart => true,
285 :desc => "IRC realname the bot should use")
286 Config.register Config::BooleanValue.new('irc.name_copyright',
287 :default => true, :requires_restart => true,
288 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
289 Config.register Config::StringValue.new('irc.user', :default => "rbot",
290 :requires_restart => true,
291 :desc => "local user the bot should appear to be", :wizard => true)
292 Config.register Config::ArrayValue.new('irc.join_channels',
293 :default => [], :wizard => true,
294 :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'")
295 Config.register Config::ArrayValue.new('irc.ignore_users',
297 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
299 Config.register Config::IntegerValue.new('core.save_every',
300 :default => 60, :validate => Proc.new{|v| v >= 0},
301 :on_change => Proc.new { |bot, v|
304 @timer.reschedule(@save_timer, v)
305 @timer.unblock(@save_timer)
307 @timer.block(@save_timer)
311 @save_timer = @timer.add(v) { bot.save }
313 # Nothing to do when v == 0
316 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
318 Config.register Config::BooleanValue.new('core.run_as_daemon',
319 :default => false, :requires_restart => true,
320 :desc => "Should the bot run as a daemon?")
322 Config.register Config::StringValue.new('log.file',
323 :default => false, :requires_restart => true,
324 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
325 Config.register Config::IntegerValue.new('log.level',
326 :default => 1, :requires_restart => false,
327 :validate => Proc.new { |v| (0..5).include?(v) },
328 :on_change => Proc.new { |bot, v|
331 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
332 Config.register Config::IntegerValue.new('log.keep',
333 :default => 1, :requires_restart => true,
334 :validate => Proc.new { |v| v >= 0 },
335 :desc => "How many old console messages logfiles to keep")
336 Config.register Config::IntegerValue.new('log.max_size',
337 :default => 10, :requires_restart => true,
338 :validate => Proc.new { |v| v > 0 },
339 :desc => "Maximum console messages logfile size (in megabytes)")
341 Config.register Config::ArrayValue.new('plugins.path',
342 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
343 :requires_restart => false,
344 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
345 :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")
347 Config.register Config::EnumValue.new('send.newlines',
348 :values => ['split', 'join'], :default => 'split',
349 :on_change => Proc.new { |bot, v|
350 bot.set_default_send_options :newlines => v.to_sym
352 :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")
353 Config.register Config::StringValue.new('send.join_with',
355 :on_change => Proc.new { |bot, v|
356 bot.set_default_send_options :join_with => v.dup
358 :desc => "String used to replace newlines when send.newlines is set to join")
359 Config.register Config::IntegerValue.new('send.max_lines',
361 :validate => Proc.new { |v| v >= 0 },
362 :on_change => Proc.new { |bot, v|
363 bot.set_default_send_options :max_lines => v
365 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
366 Config.register Config::EnumValue.new('send.overlong',
367 :values => ['split', 'truncate'], :default => 'split',
368 :on_change => Proc.new { |bot, v|
369 bot.set_default_send_options :overlong => v.to_sym
371 :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")
372 Config.register Config::StringValue.new('send.split_at',
374 :on_change => Proc.new { |bot, v|
375 bot.set_default_send_options :split_at => Regexp.new(v)
377 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
378 Config.register Config::BooleanValue.new('send.purge_split',
380 :on_change => Proc.new { |bot, v|
381 bot.set_default_send_options :purge_split => v
383 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
384 Config.register Config::StringValue.new('send.truncate_text',
385 :default => "#{Reverse}...#{Reverse}",
386 :on_change => Proc.new { |bot, v|
387 bot.set_default_send_options :truncate_text => v.dup
389 :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")
391 @argv = params[:argv]
392 @run_dir = params[:run_dir] || Dir.pwd
394 unless FileTest.directory? Config::coredir
395 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
399 unless FileTest.directory? Config::datadir
400 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
404 unless botclass and not botclass.empty?
405 # We want to find a sensible default.
406 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
407 # * On Windows (at least the NT versions) we want to put our stuff in the
408 # Application Data folder.
409 # We don't use any particular O/S detection magic, exploiting the fact that
410 # Etc.getpwuid is nil on Windows
411 if Etc.getpwuid(Process::Sys.geteuid)
412 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
414 if ENV.has_key?('APPDATA')
415 botclass = ENV['APPDATA'].dup
416 botclass.gsub!("\\","/")
421 botclass = File.expand_path(botclass)
422 @botclass = botclass.gsub(/\/$/, "")
424 if FileTest.directory? botclass
425 # compare the templates dir with the current botclass, and fill it in with
427 # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
429 template = File.join Config::datadir, 'templates'
430 # note that we use the */** pattern because we don't want to match
431 # keywords.rbot, which gets deleted on load and would therefore be missing always
432 missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
434 dest = File.join(botclass, f)
435 FileUtils.mkdir_p File.dirname dest
436 FileUtils.cp File.join(template, f), dest
439 log "no #{botclass} directory found, creating from templates.."
440 if FileTest.exist? botclass
441 error "file #{botclass} exists but isn't a directory"
444 FileUtils.cp_r Config::datadir+'/templates', botclass
447 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
448 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
450 # Time at which the last PING was sent
452 # Time at which the last line was RECV'd from the server
455 @startup_time = Time.new
458 @config = Config.manager
459 @config.bot_associate(self)
460 rescue Exception => e
466 if @config['core.run_as_daemon']
470 @logfile = @config['log.file']
471 if @logfile.class!=String || @logfile.empty?
472 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
473 debug "Using `#{@logfile}' as debug log"
476 # See http://blog.humlab.umu.se/samuel/archives/000107.html
477 # for the backgrounding code
483 rescue NotImplementedError
484 warning "Could not background, fork not supported"
487 rescue Exception => e
488 warning "Could not background. #{e.pretty_inspect}"
491 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
494 logger = Logger.new(@logfile,
496 @config['log.max_size']*1024*1024)
497 logger.datetime_format= $dateformat
498 logger.level = @config['log.level']
499 logger.level = $cl_loglevel if defined? $cl_loglevel
500 logger.level = 0 if $debug
502 restart_logger(logger)
507 log "Redirecting standard input/output/error"
508 [$stdin, $stdout, $stderr].each do |fd|
510 fd.reopen "/dev/null"
512 # On Windows, there's not such thing as /dev/null
517 def $stdout.write(str=nil)
521 def $stdout.write(str=nil)
522 if str.to_s.match(/:\d+: warning:/)
531 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
535 @registry = Registry.new self
538 @save_mutex = Mutex.new
539 if @config['core.save_every'] > 0
540 @save_timer = @timer.add(@config['core.save_every']) { save }
544 @quit_mutex = Mutex.new
547 @lang = Language.new(self, @config['core.language'])
550 @auth = Auth::manager
551 @auth.bot_associate(self)
552 # @auth.load("#{botclass}/botusers.yaml")
553 rescue Exception => e
558 @auth.everyone.set_default_permission("*", true)
559 @auth.botowner.password= @config['auth.password']
561 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
562 @plugins = Plugins::manager
563 @plugins.bot_associate(self)
566 if @config['server.name']
567 debug "upgrading configuration (server.name => server.list)"
568 srv_uri = 'irc://' + @config['server.name']
569 srv_uri += ":#{@config['server.port']}" if @config['server.port']
570 @config.items['server.list'.to_sym].set_string(srv_uri)
571 @config.delete('server.name'.to_sym)
572 @config.delete('server.port'.to_sym)
573 debug "server.list is now #{@config['server.list'].inspect}"
576 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
581 # Channels where we are quiet
582 # Array of channels names where the bot should be quiet
583 # '*' means all channels
587 @client[:welcome] = proc {|data|
588 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
590 @plugins.delegate("welcome", m)
591 @plugins.delegate("connect")
593 @config['irc.join_channels'].each { |c|
594 debug "autojoining channel #{c}"
595 if(c =~ /^(\S+)\s+(\S+)$/i)
603 # TODO the next two @client should go into rfc2812.rb, probably
604 # Since capabs are two-steps processes, server.supports[:capab]
605 # should be a three-state: nil, [], [....]
606 asked_for = { :"identify-msg" => false }
607 @client[:isupport] = proc { |data|
608 if server.supports[:capab] and !asked_for[:"identify-msg"]
609 sendq "CAPAB IDENTIFY-MSG"
610 asked_for[:"identify-msg"] = true
613 @client[:datastr] = proc { |data|
614 if data[:text] == "IDENTIFY-MSG"
615 server.capabilities[:"identify-msg"] = true
617 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
621 @client[:privmsg] = proc { |data|
622 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
623 # debug "Message source is #{data[:source].inspect}"
624 # debug "Message target is #{data[:target].inspect}"
625 # debug "Bot is #{myself.inspect}"
627 @config['irc.ignore_users'].each { |mask|
628 if m.source.matches?(server.new_netmask(mask))
633 @plugins.irc_delegate('privmsg', m)
635 @client[:notice] = proc { |data|
636 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
637 # pass it off to plugins that want to hear everything
638 @plugins.irc_delegate "notice", message
640 @client[:motd] = proc { |data|
641 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
642 @plugins.delegate "motd", m
644 @client[:nicktaken] = proc { |data|
645 new = "#{data[:nick]}_"
647 # If we're setting our nick at connection because our choice was taken,
648 # we have to fix our nick manually, because there will be no NICK message
649 # to inform us that our nick has been changed.
650 if data[:target] == '*'
651 debug "setting my connection nick to #{new}"
654 @plugins.delegate "nicktaken", data[:nick]
656 @client[:badnick] = proc {|data|
657 warning "bad nick (#{data[:nick]})"
659 @client[:ping] = proc {|data|
660 sendq "PONG #{data[:pingid]}"
662 @client[:pong] = proc {|data|
665 @client[:nick] = proc {|data|
666 # debug "Message source is #{data[:source].inspect}"
667 # debug "Bot is #{myself.inspect}"
668 source = data[:source]
671 m = NickMessage.new(self, server, source, old, new)
672 m.is_on = data[:is_on]
674 debug "my nick is now #{new}"
676 @plugins.irc_delegate("nick", m)
678 @client[:quit] = proc {|data|
679 source = data[:source]
680 message = data[:message]
681 m = QuitMessage.new(self, server, source, source, message)
682 m.was_on = data[:was_on]
683 @plugins.irc_delegate("quit", m)
685 @client[:mode] = proc {|data|
686 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
687 m.modes = data[:modes]
688 @plugins.delegate "modechange", m
690 @client[:join] = proc {|data|
691 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
692 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
693 @plugins.irc_delegate("join", m)
694 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
696 @client[:part] = proc {|data|
697 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
698 @plugins.irc_delegate("part", m)
700 @client[:kick] = proc {|data|
701 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
702 @plugins.irc_delegate("kick", m)
704 @client[:invite] = proc {|data|
705 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
706 @plugins.irc_delegate("invite", m)
708 @client[:changetopic] = proc {|data|
709 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
711 @plugins.irc_delegate("topic", m)
713 # @client[:topic] = proc { |data|
714 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
716 @client[:topicinfo] = proc { |data|
717 channel = data[:channel]
718 topic = channel.topic
719 m = TopicMessage.new(self, server, data[:source], channel, topic)
720 m.info_or_set = :info
721 @plugins.irc_delegate("topic", m)
723 @client[:names] = proc { |data|
724 m = NamesMessage.new(self, server, server, data[:channel])
725 m.users = data[:users]
726 @plugins.delegate "names", m
728 @client[:unknown] = proc { |data|
729 #debug "UNKNOWN: #{data[:serverstring]}"
730 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
731 @plugins.delegate "unknown_message", m
734 set_default_send_options :newlines => @config['send.newlines'].to_sym,
735 :join_with => @config['send.join_with'].dup,
736 :max_lines => @config['send.max_lines'],
737 :overlong => @config['send.overlong'].to_sym,
738 :split_at => Regexp.new(@config['send.split_at']),
739 :purge_split => @config['send.purge_split'],
740 :truncate_text => @config['send.truncate_text'].dup
745 def setup_plugins_path
746 @plugins.clear_botmodule_dirs
747 @plugins.add_botmodule_dir(Config::coredir + "/utils")
748 @plugins.add_botmodule_dir(Config::coredir)
749 @plugins.add_botmodule_dir("#{botclass}/plugins")
751 @config['plugins.path'].each do |_|
752 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
753 @plugins.add_botmodule_dir(path)
757 def set_default_send_options(opts={})
758 # Default send options for NOTICE and PRIVMSG
759 unless defined? @default_send_options
760 @default_send_options = {
761 :queue_channel => nil, # use default queue channel
762 :queue_ring => nil, # use default queue ring
763 :newlines => :split, # or :join
764 :join_with => ' ', # by default, use a single space
765 :max_lines => 0, # maximum number of lines to send with a single command
766 :overlong => :split, # or :truncate
767 # TODO an array of splitpoints would be preferrable for this option:
768 :split_at => /\s+/, # by default, split overlong lines at whitespace
769 :purge_split => true, # should the split string be removed?
770 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
773 @default_send_options.update opts unless opts.empty?
776 # checks if we should be quiet on a channel
777 def quiet_on?(channel)
778 return @quiet.include?('*') || @quiet.include?(channel.downcase)
781 def set_quiet(channel = nil)
783 ch = channel.downcase.dup
791 def reset_quiet(channel = nil)
793 @quiet.delete channel.downcase
799 # things to do when we receive a signal
800 def got_sig(sig, func=:quit)
801 debug "received #{sig}, queueing #{func}"
803 self.send(func) unless @quit_mutex.locked?
804 debug "interrupted #{$interrupted} times"
815 trap("SIGINT") { got_sig("SIGINT") }
816 trap("SIGTERM") { got_sig("SIGTERM") }
817 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
818 rescue ArgumentError => e
819 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
820 rescue Exception => e
821 debug "failed to trap signals: #{e.pretty_inspect}"
825 # connect the bot to IRC
828 quit if $interrupted > 0
831 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
833 quit if $interrupted > 0
835 realname = @config['irc.name'].clone || 'Ruby bot'
836 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
838 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
839 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
840 quit if $interrupted > 0
841 myself.nick = @config['irc.nick']
842 myself.user = @config['irc.user']
845 # begin event handling loop
849 quit if $interrupted > 0
853 while @socket.connected?
854 quit if $interrupted > 0
856 # Wait for messages and process them as they arrive. If nothing is
857 # received, we call the ping_server() method that will PING the
858 # server if appropriate, or raise a TimeoutError if no PONG has been
859 # received in the user-chosen timeout since the last PING sent.
861 break unless reply = @socket.gets
863 @client.process reply
869 # I despair of this. Some of my users get "connection reset by peer"
870 # exceptions that ARENT SocketError's. How am I supposed to handle
875 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
876 error "network exception: #{e.pretty_inspect}"
878 rescue BDB::Fatal => e
879 fatal "fatal bdb error: #{e.pretty_inspect}"
881 # Why restart? DB problems are serious stuff ...
882 # restart("Oops, we seem to have registry problems ...")
885 rescue Exception => e
886 error "non-net exception: #{e.pretty_inspect}"
889 fatal "unexpected exception: #{e.pretty_inspect}"
896 log "\n\nDisconnected\n\n"
898 quit if $interrupted > 0
900 log "\n\nWaiting to reconnect\n\n"
901 sleep @config['server.reconnect_wait']
905 # type:: message type
906 # where:: message target
907 # message:: message text
908 # send message +message+ of type +type+ to target +where+
909 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
910 # relevant say() or notice() methods. This one should be used for IRCd
911 # extensions you want to use in modules.
912 def sendmsg(type, where, original_message, options={})
913 opts = @default_send_options.merge(options)
915 # For starters, set up appropriate queue channels and rings
916 mchan = opts[:queue_channel]
917 mring = opts[:queue_ring]
934 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
936 # if target is a channel with nocolor modes, strip colours
937 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
938 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
944 messages << [multi_line.gsub("\n", opts[:join_with])]
946 multi_line.each_line { |line|
948 next unless(line.size > 0)
952 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
955 # The IRC protocol requires that each raw message must be not longer
956 # than 512 characters. From this length with have to subtract the EOL
957 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
958 # that will be prepended by the server to all of our messages.
960 # The maximum raw message length we can send is therefore 512 - 2 - 2
961 # minus the length of our hostmask.
963 max_len = 508 - myself.fullform.size
965 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
966 # will have a + or - prepended
967 if server.capabilities[:"identify-msg"]
971 # When splitting the message, we'll be prefixing the following string:
972 # (e.g. "PRIVMSG #rbot :")
973 fixed = "#{type} #{where} :"
975 # And this is what's left
976 left = max_len - fixed.size
978 truncate = opts[:truncate_text]
979 truncate = @default_send_options[:truncate_text] if truncate.size > left
980 truncate = "" if truncate.size > left
982 all_lines = messages.map { |line|
989 sub_lines = Array.new
991 sub_lines << msg.slice!(0, left)
993 lastspace = sub_lines.last.rindex(opts[:split_at])
995 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
996 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1001 line.slice(0, left - truncate.size) << truncate
1003 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1008 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1009 lines = all_lines[0...opts[:max_lines]]
1010 new_last = lines.last.slice(0, left - truncate.size) << truncate
1011 lines.last.replace(new_last)
1017 sendq "#{fixed}#{line}", chan, ring
1018 delegate_sent(type, where, line)
1022 # queue an arbitraty message for the server
1023 def sendq(message="", chan=nil, ring=0)
1025 @socket.queue(message, chan, ring)
1028 # send a notice message to channel/nick +where+
1029 def notice(where, message, options={})
1030 return if where.kind_of?(Channel) and quiet_on?(where)
1031 sendmsg "NOTICE", where, message, options
1034 # say something (PRIVMSG) to channel/nick +where+
1035 def say(where, message, options={})
1036 return if where.kind_of?(Channel) and quiet_on?(where)
1037 sendmsg "PRIVMSG", where, message, options
1040 def ctcp_notice(where, command, message, options={})
1041 return if where.kind_of?(Channel) and quiet_on?(where)
1042 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1045 def ctcp_say(where, command, message, options={})
1046 return if where.kind_of?(Channel) and quiet_on?(where)
1047 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1050 # perform a CTCP action with message +message+ to channel/nick +where+
1051 def action(where, message, options={})
1052 ctcp_say(where, 'ACTION', message, options)
1055 # quick way to say "okay" (or equivalent) to +where+
1057 say where, @lang.get("okay")
1060 # set topic of channel +where+ to +topic+
1061 # can also be used to retrieve the topic of channel +where+
1062 # by omitting the last argument
1063 def topic(where, topic=nil)
1065 sendq "TOPIC #{where}", where, 2
1067 sendq "TOPIC #{where} :#{topic}", where, 2
1071 def disconnect(message=nil)
1072 message = @lang.get("quit") if (!message || message.empty?)
1073 if @socket.connected?
1075 debug "Clearing socket"
1077 debug "Sending quit message"
1078 @socket.emergency_puts "QUIT :#{message}"
1079 debug "Logging quits"
1080 delegate_sent('QUIT', myself, message)
1081 debug "Flushing socket"
1083 rescue SocketError => e
1084 error "error while disconnecting socket: #{e.pretty_inspect}"
1086 debug "Shutting down socket"
1093 # disconnect from the server and cleanup all plugins and modules
1094 def shutdown(message=nil)
1095 @quit_mutex.synchronize do
1096 debug "Shutting down: #{message}"
1097 ## No we don't restore them ... let everything run through
1099 # trap("SIGINT", "DEFAULT")
1100 # trap("SIGTERM", "DEFAULT")
1101 # trap("SIGHUP", "DEFAULT")
1103 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1105 debug "\tdisconnecting..."
1107 debug "\tstopping timer..."
1109 debug "\tsaving ..."
1111 debug "\tcleaning up ..."
1112 @save_mutex.synchronize do
1115 # debug "\tstopping timers ..."
1117 # debug "Closing registries"
1119 debug "\t\tcleaning up the db environment ..."
1121 log "rbot quit (#{message})"
1125 # message:: optional IRC quit message
1126 # quit IRC, shutdown the bot
1127 def quit(message=nil)
1135 # totally shutdown and respawn the bot
1136 def restart(message=nil)
1137 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1139 sleep @config['server.reconnect_wait']
1142 # Note, this fails on Windows
1143 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1147 rescue Errno::ENOENT
1149 exec("ruby", *(@argv.unshift $0))
1150 rescue Exception => e
1156 # call the save method for all of the botmodules
1158 @save_mutex.synchronize do
1164 # call the rescan method for all of the botmodules
1166 debug "\tstopping timer..."
1168 @save_mutex.synchronize do
1175 # channel:: channel to join
1176 # key:: optional channel key if channel is +s
1178 def join(channel, key=nil)
1180 sendq "JOIN #{channel} :#{key}", channel, 2
1182 sendq "JOIN #{channel}", channel, 2
1187 def part(channel, message="")
1188 sendq "PART #{channel} :#{message}", channel, 2
1191 # attempt to change bot's nick to +name+
1193 sendq "NICK #{name}"
1197 def mode(channel, mode, target=nil)
1198 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1202 def kick(channel, user, msg)
1203 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1206 # m:: message asking for help
1207 # topic:: optional topic help is requested for
1208 # respond to online help requests
1210 topic = nil if topic == ""
1213 helpstr = _("help topics: ")
1214 helpstr += @plugins.helptopics
1215 helpstr += _(" (help <topic> for more info)")
1217 unless(helpstr = @plugins.help(topic))
1218 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1224 # returns a string describing the current status of the bot (uptime etc)
1226 secs_up = Time.new - @startup_time
1227 uptime = Utils.secs_to_string secs_up
1228 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1229 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1231 :up => uptime, :plug => @plugins.length,
1232 :sent => @socket.lines_sent, :recv => @socket.lines_received
1236 # We want to respond to a hung server in a timely manner. If nothing was received
1237 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1238 # the server. If the PONG is not received within the user-defined timeout, we
1239 # assume we're in ping timeout and act accordingly.
1241 act_timeout = @config['server.ping_timeout']
1242 return if act_timeout <= 0
1244 if @last_rec && now > @last_rec + act_timeout
1246 # No previous PING pending, send a new one
1248 @last_ping = Time.now
1250 diff = now - @last_ping
1251 if diff > act_timeout
1252 debug "no PONG from server in #{diff} seconds, reconnecting"
1253 # the actual reconnect is handled in the main loop:
1254 raise TimeoutError, "no PONG from server in #{diff} seconds"
1260 def stop_server_pings
1261 # cancel previous PINGs and reset time of last RECV
1268 # delegate sent messages
1269 def delegate_sent(type, where, message)
1270 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1273 m = NoticeMessage.new(*args)
1275 m = PrivMessage.new(*args)
1277 m = QuitMessage.new(*args)
1279 @plugins.delegate('sent', m)