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
210 # nick wanted by the bot. This defaults to the irc.nick config value,
211 # but may be overridden by a manual !nick command
213 @wanted_nick || config['irc.nick']
216 # set the nick wanted by the bot
218 if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
221 @wanted_nick = wn.to_s.dup
229 ret = self.to_s[0..-2]
230 ret << ' version=' << $version.inspect
231 ret << ' botclass=' << botclass.inspect
232 ret << ' lang="' << lang.language
237 ret << ' nick=' << nick.inspect
240 ret << (server.to_s + (socket ?
241 ' [' << socket.server_uri.to_s << ']' : '')).inspect
242 unless server.channels.empty?
244 ret << server.channels.map { |c|
245 "%s%s" % [c.modes_of(nick).map { |m|
246 server.prefix_for_mode(m)
253 ret << ' plugins=' << plugins.inspect
258 # create a new Bot with botclass +botclass+
259 def initialize(botclass, params = {})
260 # Config for the core bot
261 # TODO should we split socket stuff into ircsocket, etc?
262 Config.register Config::ArrayValue.new('server.list',
263 :default => ['irc://localhost'], :wizard => true,
264 :requires_restart => true,
265 :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.")
266 Config.register Config::BooleanValue.new('server.ssl',
267 :default => false, :requires_restart => true, :wizard => true,
268 :desc => "Use SSL to connect to this server?")
269 Config.register Config::StringValue.new('server.password',
270 :default => false, :requires_restart => true,
271 :desc => "Password for connecting to this server (if required)",
273 Config.register Config::StringValue.new('server.bindhost',
274 :default => false, :requires_restart => true,
275 :desc => "Specific local host or IP for the bot to bind to (if required)",
277 Config.register Config::IntegerValue.new('server.reconnect_wait',
278 :default => 5, :validate => Proc.new{|v| v >= 0},
279 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
280 Config.register Config::IntegerValue.new('server.ping_timeout',
281 :default => 30, :validate => Proc.new{|v| v >= 0},
282 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
283 Config.register Config::ArrayValue.new('server.nocolor_modes',
284 :default => ['c'], :wizard => false,
285 :requires_restart => false,
286 :desc => "List of channel modes that require messages to be without colors")
288 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
289 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
290 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
291 Config.register Config::StringValue.new('irc.name',
292 :default => "Ruby bot", :requires_restart => true,
293 :desc => "IRC realname the bot should use")
294 Config.register Config::BooleanValue.new('irc.name_copyright',
295 :default => true, :requires_restart => true,
296 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
297 Config.register Config::StringValue.new('irc.user', :default => "rbot",
298 :requires_restart => true,
299 :desc => "local user the bot should appear to be", :wizard => true)
300 Config.register Config::ArrayValue.new('irc.join_channels',
301 :default => [], :wizard => true,
302 :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'")
303 Config.register Config::ArrayValue.new('irc.ignore_users',
305 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
307 Config.register Config::IntegerValue.new('core.save_every',
308 :default => 60, :validate => Proc.new{|v| v >= 0},
309 :on_change => Proc.new { |bot, v|
312 @timer.reschedule(@save_timer, v)
313 @timer.unblock(@save_timer)
315 @timer.block(@save_timer)
319 @save_timer = @timer.add(v) { bot.save }
321 # Nothing to do when v == 0
324 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
326 Config.register Config::BooleanValue.new('core.run_as_daemon',
327 :default => false, :requires_restart => true,
328 :desc => "Should the bot run as a daemon?")
330 Config.register Config::StringValue.new('log.file',
331 :default => false, :requires_restart => true,
332 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
333 Config.register Config::IntegerValue.new('log.level',
334 :default => 1, :requires_restart => false,
335 :validate => Proc.new { |v| (0..5).include?(v) },
336 :on_change => Proc.new { |bot, v|
339 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
340 Config.register Config::IntegerValue.new('log.keep',
341 :default => 1, :requires_restart => true,
342 :validate => Proc.new { |v| v >= 0 },
343 :desc => "How many old console messages logfiles to keep")
344 Config.register Config::IntegerValue.new('log.max_size',
345 :default => 10, :requires_restart => true,
346 :validate => Proc.new { |v| v > 0 },
347 :desc => "Maximum console messages logfile size (in megabytes)")
349 Config.register Config::ArrayValue.new('plugins.path',
350 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
351 :requires_restart => false,
352 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
353 :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")
355 Config.register Config::EnumValue.new('send.newlines',
356 :values => ['split', 'join'], :default => 'split',
357 :on_change => Proc.new { |bot, v|
358 bot.set_default_send_options :newlines => v.to_sym
360 :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")
361 Config.register Config::StringValue.new('send.join_with',
363 :on_change => Proc.new { |bot, v|
364 bot.set_default_send_options :join_with => v.dup
366 :desc => "String used to replace newlines when send.newlines is set to join")
367 Config.register Config::IntegerValue.new('send.max_lines',
369 :validate => Proc.new { |v| v >= 0 },
370 :on_change => Proc.new { |bot, v|
371 bot.set_default_send_options :max_lines => v
373 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
374 Config.register Config::EnumValue.new('send.overlong',
375 :values => ['split', 'truncate'], :default => 'split',
376 :on_change => Proc.new { |bot, v|
377 bot.set_default_send_options :overlong => v.to_sym
379 :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")
380 Config.register Config::StringValue.new('send.split_at',
382 :on_change => Proc.new { |bot, v|
383 bot.set_default_send_options :split_at => Regexp.new(v)
385 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
386 Config.register Config::BooleanValue.new('send.purge_split',
388 :on_change => Proc.new { |bot, v|
389 bot.set_default_send_options :purge_split => v
391 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
392 Config.register Config::StringValue.new('send.truncate_text',
393 :default => "#{Reverse}...#{Reverse}",
394 :on_change => Proc.new { |bot, v|
395 bot.set_default_send_options :truncate_text => v.dup
397 :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")
399 @argv = params[:argv]
400 @run_dir = params[:run_dir] || Dir.pwd
402 unless FileTest.directory? Config::coredir
403 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
407 unless FileTest.directory? Config::datadir
408 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
412 unless botclass and not botclass.empty?
413 # We want to find a sensible default.
414 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
415 # * On Windows (at least the NT versions) we want to put our stuff in the
416 # Application Data folder.
417 # We don't use any particular O/S detection magic, exploiting the fact that
418 # Etc.getpwuid is nil on Windows
419 if Etc.getpwuid(Process::Sys.geteuid)
420 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
422 if ENV.has_key?('APPDATA')
423 botclass = ENV['APPDATA'].dup
424 botclass.gsub!("\\","/")
429 botclass = File.expand_path(botclass)
430 @botclass = botclass.gsub(/\/$/, "")
432 if FileTest.directory? botclass
433 # compare the templates dir with the current botclass, and fill it in with
435 # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
437 template = File.join Config::datadir, 'templates'
438 # note that we use the */** pattern because we don't want to match
439 # keywords.rbot, which gets deleted on load and would therefore be missing always
440 missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
442 dest = File.join(botclass, f)
443 FileUtils.mkdir_p File.dirname dest
444 FileUtils.cp File.join(template, f), dest
447 log "no #{botclass} directory found, creating from templates.."
448 if FileTest.exist? botclass
449 error "file #{botclass} exists but isn't a directory"
452 FileUtils.cp_r Config::datadir+'/templates', botclass
455 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
456 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
458 # Time at which the last PING was sent
460 # Time at which the last line was RECV'd from the server
463 @startup_time = Time.new
466 @config = Config.manager
467 @config.bot_associate(self)
468 rescue Exception => e
474 if @config['core.run_as_daemon']
478 @logfile = @config['log.file']
479 if @logfile.class!=String || @logfile.empty?
480 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
481 debug "Using `#{@logfile}' as debug log"
484 # See http://blog.humlab.umu.se/samuel/archives/000107.html
485 # for the backgrounding code
491 rescue NotImplementedError
492 warning "Could not background, fork not supported"
495 rescue Exception => e
496 warning "Could not background. #{e.pretty_inspect}"
499 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
502 logger = Logger.new(@logfile,
504 @config['log.max_size']*1024*1024)
505 logger.datetime_format= $dateformat
506 logger.level = @config['log.level']
507 logger.level = $cl_loglevel if defined? $cl_loglevel
508 logger.level = 0 if $debug
510 restart_logger(logger)
515 log "Redirecting standard input/output/error"
516 [$stdin, $stdout, $stderr].each do |fd|
518 fd.reopen "/dev/null"
520 # On Windows, there's not such thing as /dev/null
525 def $stdout.write(str=nil)
529 def $stdout.write(str=nil)
530 if str.to_s.match(/:\d+: warning:/)
539 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
543 @registry = Registry.new self
546 @save_mutex = Mutex.new
547 if @config['core.save_every'] > 0
548 @save_timer = @timer.add(@config['core.save_every']) { save }
552 @quit_mutex = Mutex.new
555 @lang = Language.new(self, @config['core.language'])
558 @auth = Auth::manager
559 @auth.bot_associate(self)
560 # @auth.load("#{botclass}/botusers.yaml")
561 rescue Exception => e
566 @auth.everyone.set_default_permission("*", true)
567 @auth.botowner.password= @config['auth.password']
569 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
570 @plugins = Plugins::manager
571 @plugins.bot_associate(self)
574 if @config['server.name']
575 debug "upgrading configuration (server.name => server.list)"
576 srv_uri = 'irc://' + @config['server.name']
577 srv_uri += ":#{@config['server.port']}" if @config['server.port']
578 @config.items['server.list'.to_sym].set_string(srv_uri)
579 @config.delete('server.name'.to_sym)
580 @config.delete('server.port'.to_sym)
581 debug "server.list is now #{@config['server.list'].inspect}"
584 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'])
589 # Channels where we are quiet
590 # Array of channels names where the bot should be quiet
591 # '*' means all channels
595 # the nick we want, if it's different from the irc.nick config value
596 # (e.g. as set by a !nick command)
599 @client[:welcome] = proc {|data|
600 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
602 @plugins.delegate("welcome", m)
603 @plugins.delegate("connect")
606 # TODO the next two @client should go into rfc2812.rb, probably
607 # Since capabs are two-steps processes, server.supports[:capab]
608 # should be a three-state: nil, [], [....]
609 asked_for = { :"identify-msg" => false }
610 @client[:isupport] = proc { |data|
611 if server.supports[:capab] and !asked_for[:"identify-msg"]
612 sendq "CAPAB IDENTIFY-MSG"
613 asked_for[:"identify-msg"] = true
616 @client[:datastr] = proc { |data|
617 if data[:text] == "IDENTIFY-MSG"
618 server.capabilities[:"identify-msg"] = true
620 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
624 @client[:privmsg] = proc { |data|
625 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
626 # debug "Message source is #{data[:source].inspect}"
627 # debug "Message target is #{data[:target].inspect}"
628 # debug "Bot is #{myself.inspect}"
630 @config['irc.ignore_users'].each { |mask|
631 if m.source.matches?(server.new_netmask(mask))
636 @plugins.irc_delegate('privmsg', m)
638 @client[:notice] = proc { |data|
639 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
640 # pass it off to plugins that want to hear everything
641 @plugins.irc_delegate "notice", message
643 @client[:motd] = proc { |data|
644 m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
645 @plugins.delegate "motd", m
647 @client[:nicktaken] = proc { |data|
648 new = "#{data[:nick]}_"
650 # If we're setting our nick at connection because our choice was taken,
651 # we have to fix our nick manually, because there will be no NICK message
652 # to inform us that our nick has been changed.
653 if data[:target] == '*'
654 debug "setting my connection nick to #{new}"
657 @plugins.delegate "nicktaken", data[:nick]
659 @client[:badnick] = proc {|data|
660 warning "bad nick (#{data[:nick]})"
662 @client[:ping] = proc {|data|
663 sendq "PONG #{data[:pingid]}"
665 @client[:pong] = proc {|data|
668 @client[:nick] = proc {|data|
669 # debug "Message source is #{data[:source].inspect}"
670 # debug "Bot is #{myself.inspect}"
671 source = data[:source]
674 m = NickMessage.new(self, server, source, old, new)
675 m.is_on = data[:is_on]
677 debug "my nick is now #{new}"
679 @plugins.irc_delegate("nick", m)
681 @client[:quit] = proc {|data|
682 source = data[:source]
683 message = data[:message]
684 m = QuitMessage.new(self, server, source, source, message)
685 m.was_on = data[:was_on]
686 @plugins.irc_delegate("quit", m)
688 @client[:mode] = proc {|data|
689 m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
690 m.modes = data[:modes]
691 @plugins.delegate "modechange", m
693 @client[:whois] = proc {|data|
694 source = data[:source]
695 target = server.get_user(data[:whois][:nick])
696 m = WhoisMessage.new(self, server, source, target, data[:whois])
697 @plugins.delegate "whois", m
699 @client[:join] = proc {|data|
700 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
701 sendq("MODE #{data[:channel]}", nil, 0) if m.address?
702 @plugins.irc_delegate("join", m)
703 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
705 @client[:part] = proc {|data|
706 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
707 @plugins.irc_delegate("part", m)
709 @client[:kick] = proc {|data|
710 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
711 @plugins.irc_delegate("kick", m)
713 @client[:invite] = proc {|data|
714 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
715 @plugins.irc_delegate("invite", m)
717 @client[:changetopic] = proc {|data|
718 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
720 @plugins.irc_delegate("topic", m)
722 # @client[:topic] = proc { |data|
723 # irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
725 @client[:topicinfo] = proc { |data|
726 channel = data[:channel]
727 topic = channel.topic
728 m = TopicMessage.new(self, server, data[:source], channel, topic)
729 m.info_or_set = :info
730 @plugins.irc_delegate("topic", m)
732 @client[:names] = proc { |data|
733 m = NamesMessage.new(self, server, server, data[:channel])
734 m.users = data[:users]
735 @plugins.delegate "names", m
737 @client[:unknown] = proc { |data|
738 #debug "UNKNOWN: #{data[:serverstring]}"
739 m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
740 @plugins.delegate "unknown_message", m
743 set_default_send_options :newlines => @config['send.newlines'].to_sym,
744 :join_with => @config['send.join_with'].dup,
745 :max_lines => @config['send.max_lines'],
746 :overlong => @config['send.overlong'].to_sym,
747 :split_at => Regexp.new(@config['send.split_at']),
748 :purge_split => @config['send.purge_split'],
749 :truncate_text => @config['send.truncate_text'].dup
754 def setup_plugins_path
755 @plugins.clear_botmodule_dirs
756 @plugins.add_botmodule_dir(Config::coredir + "/utils")
757 @plugins.add_botmodule_dir(Config::coredir)
758 @plugins.add_botmodule_dir("#{botclass}/plugins")
760 @config['plugins.path'].each do |_|
761 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
762 @plugins.add_botmodule_dir(path)
766 def set_default_send_options(opts={})
767 # Default send options for NOTICE and PRIVMSG
768 unless defined? @default_send_options
769 @default_send_options = {
770 :queue_channel => nil, # use default queue channel
771 :queue_ring => nil, # use default queue ring
772 :newlines => :split, # or :join
773 :join_with => ' ', # by default, use a single space
774 :max_lines => 0, # maximum number of lines to send with a single command
775 :overlong => :split, # or :truncate
776 # TODO an array of splitpoints would be preferrable for this option:
777 :split_at => /\s+/, # by default, split overlong lines at whitespace
778 :purge_split => true, # should the split string be removed?
779 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
782 @default_send_options.update opts unless opts.empty?
785 # checks if we should be quiet on a channel
786 def quiet_on?(channel)
787 return @quiet.include?('*') || @quiet.include?(channel.downcase)
790 def set_quiet(channel = nil)
792 ch = channel.downcase.dup
800 def reset_quiet(channel = nil)
802 @quiet.delete channel.downcase
808 # things to do when we receive a signal
809 def got_sig(sig, func=:quit)
810 debug "received #{sig}, queueing #{func}"
812 self.send(func) unless @quit_mutex.locked?
813 debug "interrupted #{$interrupted} times"
824 trap("SIGINT") { got_sig("SIGINT") }
825 trap("SIGTERM") { got_sig("SIGTERM") }
826 trap("SIGHUP") { got_sig("SIGHUP", :restart) }
827 rescue ArgumentError => e
828 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
829 rescue Exception => e
830 debug "failed to trap signals: #{e.pretty_inspect}"
834 # connect the bot to IRC
837 quit if $interrupted > 0
840 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
842 quit if $interrupted > 0
844 realname = @config['irc.name'].clone || 'Ruby bot'
845 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
847 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
848 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
849 quit if $interrupted > 0
850 myself.nick = @config['irc.nick']
851 myself.user = @config['irc.user']
854 # begin event handling loop
858 quit if $interrupted > 0
862 while @socket.connected?
863 quit if $interrupted > 0
865 # Wait for messages and process them as they arrive. If nothing is
866 # received, we call the ping_server() method that will PING the
867 # server if appropriate, or raise a TimeoutError if no PONG has been
868 # received in the user-chosen timeout since the last PING sent.
870 break unless reply = @socket.gets
872 @client.process reply
878 # I despair of this. Some of my users get "connection reset by peer"
879 # exceptions that ARENT SocketError's. How am I supposed to handle
884 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
885 error "network exception: #{e.pretty_inspect}"
887 rescue BDB::Fatal => e
888 fatal "fatal bdb error: #{e.pretty_inspect}"
890 # Why restart? DB problems are serious stuff ...
891 # restart("Oops, we seem to have registry problems ...")
894 rescue Exception => e
895 error "non-net exception: #{e.pretty_inspect}"
898 fatal "unexpected exception: #{e.pretty_inspect}"
905 log "\n\nDisconnected\n\n"
907 quit if $interrupted > 0
909 log "\n\nWaiting to reconnect\n\n"
910 sleep @config['server.reconnect_wait']
914 # type:: message type
915 # where:: message target
916 # message:: message text
917 # send message +message+ of type +type+ to target +where+
918 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
919 # relevant say() or notice() methods. This one should be used for IRCd
920 # extensions you want to use in modules.
921 def sendmsg(type, where, original_message, options={})
922 opts = @default_send_options.merge(options)
924 # For starters, set up appropriate queue channels and rings
925 mchan = opts[:queue_channel]
926 mring = opts[:queue_ring]
943 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
945 # if target is a channel with nocolor modes, strip colours
946 if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
947 multi_line.replace BasicUserMessage.strip_formatting(multi_line)
953 messages << [multi_line.gsub("\n", opts[:join_with])]
955 multi_line.each_line { |line|
957 next unless(line.size > 0)
961 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
964 # The IRC protocol requires that each raw message must be not longer
965 # than 512 characters. From this length with have to subtract the EOL
966 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
967 # that will be prepended by the server to all of our messages.
969 # The maximum raw message length we can send is therefore 512 - 2 - 2
970 # minus the length of our hostmask.
972 max_len = 508 - myself.fullform.size
974 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
975 # will have a + or - prepended
976 if server.capabilities[:"identify-msg"]
980 # When splitting the message, we'll be prefixing the following string:
981 # (e.g. "PRIVMSG #rbot :")
982 fixed = "#{type} #{where} :"
984 # And this is what's left
985 left = max_len - fixed.size
987 truncate = opts[:truncate_text]
988 truncate = @default_send_options[:truncate_text] if truncate.size > left
989 truncate = "" if truncate.size > left
991 all_lines = messages.map { |line|
998 sub_lines = Array.new
1000 sub_lines << msg.slice!(0, left)
1002 lastspace = sub_lines.last.rindex(opts[:split_at])
1004 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1005 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1007 end until msg.empty?
1010 line.slice(0, left - truncate.size) << truncate
1012 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1017 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1018 lines = all_lines[0...opts[:max_lines]]
1019 new_last = lines.last.slice(0, left - truncate.size) << truncate
1020 lines.last.replace(new_last)
1026 sendq "#{fixed}#{line}", chan, ring
1027 delegate_sent(type, where, line)
1031 # queue an arbitraty message for the server
1032 def sendq(message="", chan=nil, ring=0)
1034 @socket.queue(message, chan, ring)
1037 # send a notice message to channel/nick +where+
1038 def notice(where, message, options={})
1039 return if where.kind_of?(Channel) and quiet_on?(where)
1040 sendmsg "NOTICE", where, message, options
1043 # say something (PRIVMSG) to channel/nick +where+
1044 def say(where, message, options={})
1045 return if where.kind_of?(Channel) and quiet_on?(where)
1046 sendmsg "PRIVMSG", where, message, options
1049 def ctcp_notice(where, command, message, options={})
1050 return if where.kind_of?(Channel) and quiet_on?(where)
1051 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1054 def ctcp_say(where, command, message, options={})
1055 return if where.kind_of?(Channel) and quiet_on?(where)
1056 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1059 # perform a CTCP action with message +message+ to channel/nick +where+
1060 def action(where, message, options={})
1061 ctcp_say(where, 'ACTION', message, options)
1064 # quick way to say "okay" (or equivalent) to +where+
1066 say where, @lang.get("okay")
1069 # set topic of channel +where+ to +topic+
1070 # can also be used to retrieve the topic of channel +where+
1071 # by omitting the last argument
1072 def topic(where, topic=nil)
1074 sendq "TOPIC #{where}", where, 2
1076 sendq "TOPIC #{where} :#{topic}", where, 2
1080 def disconnect(message=nil)
1081 message = @lang.get("quit") if (!message || message.empty?)
1082 if @socket.connected?
1084 debug "Clearing socket"
1086 debug "Sending quit message"
1087 @socket.emergency_puts "QUIT :#{message}"
1088 debug "Logging quits"
1089 delegate_sent('QUIT', myself, message)
1090 debug "Flushing socket"
1092 rescue SocketError => e
1093 error "error while disconnecting socket: #{e.pretty_inspect}"
1095 debug "Shutting down socket"
1102 # disconnect from the server and cleanup all plugins and modules
1103 def shutdown(message=nil)
1104 @quit_mutex.synchronize do
1105 debug "Shutting down: #{message}"
1106 ## No we don't restore them ... let everything run through
1108 # trap("SIGINT", "DEFAULT")
1109 # trap("SIGTERM", "DEFAULT")
1110 # trap("SIGHUP", "DEFAULT")
1112 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1114 debug "\tdisconnecting..."
1116 debug "\tstopping timer..."
1118 debug "\tsaving ..."
1120 debug "\tcleaning up ..."
1121 @save_mutex.synchronize do
1124 # debug "\tstopping timers ..."
1126 # debug "Closing registries"
1128 debug "\t\tcleaning up the db environment ..."
1130 log "rbot quit (#{message})"
1134 # message:: optional IRC quit message
1135 # quit IRC, shutdown the bot
1136 def quit(message=nil)
1144 # totally shutdown and respawn the bot
1145 def restart(message=nil)
1146 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1148 sleep @config['server.reconnect_wait']
1151 # Note, this fails on Windows
1152 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1156 rescue Errno::ENOENT
1158 exec("ruby", *(@argv.unshift $0))
1159 rescue Exception => e
1165 # call the save method for all of the botmodules
1167 @save_mutex.synchronize do
1173 # call the rescan method for all of the botmodules
1175 debug "\tstopping timer..."
1177 @save_mutex.synchronize do
1184 # channel:: channel to join
1185 # key:: optional channel key if channel is +s
1187 def join(channel, key=nil)
1189 sendq "JOIN #{channel} :#{key}", channel, 2
1191 sendq "JOIN #{channel}", channel, 2
1196 def part(channel, message="")
1197 sendq "PART #{channel} :#{message}", channel, 2
1200 # attempt to change bot's nick to +name+
1202 sendq "NICK #{name}"
1206 def mode(channel, mode, target=nil)
1207 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1211 def whois(nick, target=nil)
1212 sendq "WHOIS #{target} #{nick}", nil, 0
1216 def kick(channel, user, msg)
1217 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1220 # m:: message asking for help
1221 # topic:: optional topic help is requested for
1222 # respond to online help requests
1224 topic = nil if topic == ""
1227 helpstr = _("help topics: ")
1228 helpstr += @plugins.helptopics
1229 helpstr += _(" (help <topic> for more info)")
1231 unless(helpstr = @plugins.help(topic))
1232 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1238 # returns a string describing the current status of the bot (uptime etc)
1240 secs_up = Time.new - @startup_time
1241 uptime = Utils.secs_to_string secs_up
1242 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1243 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1245 :up => uptime, :plug => @plugins.length,
1246 :sent => @socket.lines_sent, :recv => @socket.lines_received
1250 # We want to respond to a hung server in a timely manner. If nothing was received
1251 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1252 # the server. If the PONG is not received within the user-defined timeout, we
1253 # assume we're in ping timeout and act accordingly.
1255 act_timeout = @config['server.ping_timeout']
1256 return if act_timeout <= 0
1258 if @last_rec && now > @last_rec + act_timeout
1260 # No previous PING pending, send a new one
1262 @last_ping = Time.now
1264 diff = now - @last_ping
1265 if diff > act_timeout
1266 debug "no PONG from server in #{diff} seconds, reconnecting"
1267 # the actual reconnect is handled in the main loop:
1268 raise TimeoutError, "no PONG from server in #{diff} seconds"
1274 def stop_server_pings
1275 # cancel previous PINGs and reset time of last RECV
1282 # delegate sent messages
1283 def delegate_sent(type, where, message)
1284 args = [self, server, myself, server.user_or_channel(where.to_s), message]
1287 m = NoticeMessage.new(*args)
1289 m = PrivMessage.new(*args)
1291 m = QuitMessage.new(*args)
1293 @plugins.delegate('sent', m)