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
23 unless Kernel.instance_methods.include?("pretty_inspect")
27 public :pretty_inspect
32 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
33 if self.backtrace and not self.backtrace.empty?
35 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
41 def rawlog(level, message=nil, who_pos=1)
43 if call_stack.length > who_pos
44 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
48 # Output each line. To distinguish between separate messages and multi-line
49 # messages originating at the same time, we blank #{who} after the first message
51 # Also, we output strings as-is but for other objects we use pretty_inspect
56 str = message.pretty_inspect
59 $logger.add(level, l.chomp, who)
65 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
69 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
72 def debug(message=nil, who_pos=1)
73 rawlog(Logger::Severity::DEBUG, message, who_pos)
76 def log(message=nil, who_pos=1)
77 rawlog(Logger::Severity::INFO, message, who_pos)
80 def warning(message=nil, who_pos=1)
81 rawlog(Logger::Severity::WARN, message, who_pos)
84 def error(message=nil, who_pos=1)
85 rawlog(Logger::Severity::ERROR, message, who_pos)
88 def fatal(message=nil, who_pos=1)
89 rawlog(Logger::Severity::FATAL, message, who_pos)
94 warning "warning test"
98 # The following global is used for the improved signal handling.
102 require 'rbot/rbotconfig'
103 require 'rbot/load-gettext'
104 require 'rbot/config'
105 require 'rbot/config-compat'
108 require 'rbot/rfc2812'
109 require 'rbot/ircsocket'
110 require 'rbot/botuser'
112 require 'rbot/plugins'
113 require 'rbot/message'
114 require 'rbot/language'
115 require 'rbot/dbhash'
116 require 'rbot/registry'
120 # Main bot class, which manages the various components, receives messages,
121 # handles them or passes them to plugins, and contains core functionality.
123 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
124 SOURCE_URL = "http://ruby-rbot.org"
125 # the bot's Auth data
128 # the bot's Config data
131 # the botclass for this bot (determines configdir among other things)
132 attr_reader :botclass
134 # used to perform actions periodically (saves configuration once per minute
138 # synchronize with this mutex while touching permanent data files:
139 # saving, flushing, cleaning up ...
140 attr_reader :save_mutex
142 # bot's Language data
149 # bot's object registry, plugins get an interface to this for persistant
150 # storage (hash interface tied to a bdb file, plugins use Accessors to store
151 # and restore objects in their own namespaces.)
152 attr_reader :registry
154 # bot's plugins. This is an instance of class Plugins
157 # bot's httputil help object, for fetching resources via http. Sets up
158 # proxies etc as defined by the bot configuration/environment
159 attr_accessor :httputil
161 # server we are connected to
167 # bot User in the client/server connection
173 # bot User in the client/server connection
181 ret = self.to_s[0..-2]
182 ret << ' version=' << $version.inspect
183 ret << ' botclass=' << botclass.inspect
184 ret << ' lang="' << lang.language
189 ret << ' nick=' << nick.inspect
192 ret << (server.to_s + (socket ?
193 ' [' << socket.server_uri.to_s << ']' : '')).inspect
194 unless server.channels.empty?
196 ret << server.channels.map { |c|
197 "%s%s" % [c.modes_of(nick).map { |m|
198 server.prefix_for_mode(m)
205 ret << ' plugins=' << plugins.inspect
210 # create a new Bot with botclass +botclass+
211 def initialize(botclass, params = {})
212 # Config for the core bot
213 # TODO should we split socket stuff into ircsocket, etc?
214 Config.register Config::ArrayValue.new('server.list',
215 :default => ['irc://localhost'], :wizard => true,
216 :requires_restart => true,
217 :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.")
218 Config.register Config::BooleanValue.new('server.ssl',
219 :default => false, :requires_restart => true, :wizard => true,
220 :desc => "Use SSL to connect to this server?")
221 Config.register Config::StringValue.new('server.password',
222 :default => false, :requires_restart => true,
223 :desc => "Password for connecting to this server (if required)",
225 Config.register Config::StringValue.new('server.bindhost',
226 :default => false, :requires_restart => true,
227 :desc => "Specific local host or IP for the bot to bind to (if required)",
229 Config.register Config::IntegerValue.new('server.reconnect_wait',
230 :default => 5, :validate => Proc.new{|v| v >= 0},
231 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
232 Config.register Config::FloatValue.new('server.sendq_delay',
233 :default => 2.0, :validate => Proc.new{|v| v >= 0},
234 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
235 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
236 Config.register Config::IntegerValue.new('server.sendq_burst',
237 :default => 4, :validate => Proc.new{|v| v >= 0},
238 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
239 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
240 Config.register Config::IntegerValue.new('server.ping_timeout',
241 :default => 30, :validate => Proc.new{|v| v >= 0},
242 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
244 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
245 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
246 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
247 Config.register Config::StringValue.new('irc.name',
248 :default => "Ruby bot", :requires_restart => true,
249 :desc => "IRC realname the bot should use")
250 Config.register Config::BooleanValue.new('irc.name_copyright',
251 :default => true, :requires_restart => true,
252 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
253 Config.register Config::StringValue.new('irc.user', :default => "rbot",
254 :requires_restart => true,
255 :desc => "local user the bot should appear to be", :wizard => true)
256 Config.register Config::ArrayValue.new('irc.join_channels',
257 :default => [], :wizard => true,
258 :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'")
259 Config.register Config::ArrayValue.new('irc.ignore_users',
261 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
263 Config.register Config::IntegerValue.new('core.save_every',
264 :default => 60, :validate => Proc.new{|v| v >= 0},
265 :on_change => Proc.new { |bot, v|
268 @timer.reschedule(@save_timer, v)
269 @timer.unblock(@save_timer)
271 @timer.block(@save_timer)
275 @save_timer = @timer.add(v) { bot.save }
277 # Nothing to do when v == 0
280 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
282 Config.register Config::BooleanValue.new('core.run_as_daemon',
283 :default => false, :requires_restart => true,
284 :desc => "Should the bot run as a daemon?")
286 Config.register Config::StringValue.new('log.file',
287 :default => false, :requires_restart => true,
288 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
289 Config.register Config::IntegerValue.new('log.level',
290 :default => 1, :requires_restart => false,
291 :validate => Proc.new { |v| (0..5).include?(v) },
292 :on_change => Proc.new { |bot, v|
295 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
296 Config.register Config::IntegerValue.new('log.keep',
297 :default => 1, :requires_restart => true,
298 :validate => Proc.new { |v| v >= 0 },
299 :desc => "How many old console messages logfiles to keep")
300 Config.register Config::IntegerValue.new('log.max_size',
301 :default => 10, :requires_restart => true,
302 :validate => Proc.new { |v| v > 0 },
303 :desc => "Maximum console messages logfile size (in megabytes)")
305 Config.register Config::ArrayValue.new('plugins.path',
306 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
307 :requires_restart => false,
308 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
309 :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")
311 Config.register Config::EnumValue.new('send.newlines',
312 :values => ['split', 'join'], :default => 'split',
313 :on_change => Proc.new { |bot, v|
314 bot.set_default_send_options :newlines => v.to_sym
316 :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")
317 Config.register Config::StringValue.new('send.join_with',
319 :on_change => Proc.new { |bot, v|
320 bot.set_default_send_options :join_with => v.dup
322 :desc => "String used to replace newlines when send.newlines is set to join")
323 Config.register Config::IntegerValue.new('send.max_lines',
325 :validate => Proc.new { |v| v >= 0 },
326 :on_change => Proc.new { |bot, v|
327 bot.set_default_send_options :max_lines => v
329 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
330 Config.register Config::EnumValue.new('send.overlong',
331 :values => ['split', 'truncate'], :default => 'split',
332 :on_change => Proc.new { |bot, v|
333 bot.set_default_send_options :overlong => v.to_sym
335 :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")
336 Config.register Config::StringValue.new('send.split_at',
338 :on_change => Proc.new { |bot, v|
339 bot.set_default_send_options :split_at => Regexp.new(v)
341 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
342 Config.register Config::BooleanValue.new('send.purge_split',
344 :on_change => Proc.new { |bot, v|
345 bot.set_default_send_options :purge_split => v
347 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
348 Config.register Config::StringValue.new('send.truncate_text',
349 :default => "#{Reverse}...#{Reverse}",
350 :on_change => Proc.new { |bot, v|
351 bot.set_default_send_options :truncate_text => v.dup
353 :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")
355 @argv = params[:argv]
356 @run_dir = params[:run_dir] || Dir.pwd
358 unless FileTest.directory? Config::coredir
359 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
363 unless FileTest.directory? Config::datadir
364 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
368 unless botclass and not botclass.empty?
369 # We want to find a sensible default.
370 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
371 # * On Windows (at least the NT versions) we want to put our stuff in the
372 # Application Data folder.
373 # We don't use any particular O/S detection magic, exploiting the fact that
374 # Etc.getpwuid is nil on Windows
375 if Etc.getpwuid(Process::Sys.geteuid)
376 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
378 if ENV.has_key?('APPDATA')
379 botclass = ENV['APPDATA'].dup
380 botclass.gsub!("\\","/")
385 botclass = File.expand_path(botclass)
386 @botclass = botclass.gsub(/\/$/, "")
388 unless FileTest.directory? botclass
389 log "no #{botclass} directory found, creating from templates.."
390 if FileTest.exist? botclass
391 error "file #{botclass} exists but isn't a directory"
394 FileUtils.cp_r Config::datadir+'/templates', botclass
397 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
398 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
399 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
401 # Time at which the last PING was sent
403 # Time at which the last line was RECV'd from the server
406 @startup_time = Time.new
409 @config = Config.manager
410 @config.bot_associate(self)
411 rescue Exception => e
417 if @config['core.run_as_daemon']
421 @logfile = @config['log.file']
422 if @logfile.class!=String || @logfile.empty?
423 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
426 # See http://blog.humlab.umu.se/samuel/archives/000107.html
427 # for the backgrounding code
433 rescue NotImplementedError
434 warning "Could not background, fork not supported"
437 rescue Exception => e
438 warning "Could not background. #{e.pretty_inspect}"
441 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
442 log "Redirecting standard input/output/error"
444 STDIN.reopen "/dev/null"
446 # On Windows, there's not such thing as /dev/null
449 def STDOUT.write(str=nil)
453 def STDERR.write(str=nil)
454 if str.to_s.match(/:\d+: warning:/)
463 # Set the new logfile and loglevel. This must be done after the daemonizing
464 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
465 $logger.datetime_format= $dateformat
466 $logger.level = @config['log.level']
467 $logger.level = $cl_loglevel if defined? $cl_loglevel
468 $logger.level = 0 if $debug
472 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
476 @registry = Registry.new self
479 @save_mutex = Mutex.new
480 if @config['core.save_every'] > 0
481 @save_timer = @timer.add(@config['core.save_every']) { save }
485 @quit_mutex = Mutex.new
490 @lang = Language.new(self, @config['core.language'])
493 @auth = Auth::manager
494 @auth.bot_associate(self)
495 # @auth.load("#{botclass}/botusers.yaml")
496 rescue Exception => e
501 @auth.everyone.set_default_permission("*", true)
502 @auth.botowner.password= @config['auth.password']
504 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
505 @plugins = Plugins::manager
506 @plugins.bot_associate(self)
509 if @config['server.name']
510 debug "upgrading configuration (server.name => server.list)"
511 srv_uri = 'irc://' + @config['server.name']
512 srv_uri += ":#{@config['server.port']}" if @config['server.port']
513 @config.items['server.list'.to_sym].set_string(srv_uri)
514 @config.delete('server.name'.to_sym)
515 @config.delete('server.port'.to_sym)
516 debug "server.list is now #{@config['server.list'].inspect}"
519 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
524 # Channels where we are quiet
525 # Array of channels names where the bot should be quiet
526 # '*' means all channels
530 @client[:welcome] = proc {|data|
531 m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
533 irclog "joined server #{@client.server} as #{myself}", "server"
535 @plugins.delegate("welcome", m)
536 @plugins.delegate("connect")
538 @config['irc.join_channels'].each { |c|
539 debug "autojoining channel #{c}"
540 if(c =~ /^(\S+)\s+(\S+)$/i)
548 # TODO the next two @client should go into rfc2812.rb, probably
549 # Since capabs are two-steps processes, server.supports[:capab]
550 # should be a three-state: nil, [], [....]
551 asked_for = { :"identify-msg" => false }
552 @client[:isupport] = proc { |data|
553 if server.supports[:capab] and !asked_for[:"identify-msg"]
554 sendq "CAPAB IDENTIFY-MSG"
555 asked_for[:"identify-msg"] = true
558 @client[:datastr] = proc { |data|
559 if data[:text] == "IDENTIFY-MSG"
560 server.capabilities[:"identify-msg"] = true
562 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
566 @client[:privmsg] = proc { |data|
567 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
568 # debug "Message source is #{data[:source].inspect}"
569 # debug "Message target is #{data[:target].inspect}"
570 # debug "Bot is #{myself.inspect}"
572 @config['irc.ignore_users'].each { |mask|
573 if m.source.matches?(server.new_netmask(mask))
580 @plugins.irc_delegate('privmsg', m) unless m.ignored?
582 @client[:notice] = proc { |data|
583 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
584 # pass it off to plugins that want to hear everything
585 @plugins.delegate "listen", message
587 @client[:motd] = proc { |data|
588 data[:motd].each_line { |line|
589 irclog "MOTD: #{line}", "server"
592 @client[:nicktaken] = proc { |data|
593 new = "#{data[:nick]}_"
595 # If we're setting our nick at connection because our choice was taken,
596 # we have to fix our nick manually, because there will be no NICK message
597 # to inform us that our nick has been changed.
598 if data[:target] == '*'
599 debug "setting my connection nick to #{new}"
602 @plugins.delegate "nicktaken", data[:nick]
604 @client[:badnick] = proc {|data|
605 warning "bad nick (#{data[:nick]})"
607 @client[:ping] = proc {|data|
608 sendq "PONG #{data[:pingid]}"
610 @client[:pong] = proc {|data|
613 @client[:nick] = proc {|data|
614 # debug "Message source is #{data[:source].inspect}"
615 # debug "Bot is #{myself.inspect}"
616 source = data[:source]
619 m = NickMessage.new(self, server, source, old, new)
621 debug "my nick is now #{new}"
623 data[:is_on].each { |ch|
624 irclog "@ #{old} is now known as #{new}", ch
626 @plugins.irc_delegate("nick", m)
628 @client[:quit] = proc {|data|
629 source = data[:source]
630 message = data[:message]
631 m = QuitMessage.new(self, server, source, source, message)
632 data[:was_on].each { |ch|
633 irclog "@ Quit: #{source}: #{message}", ch
635 @plugins.irc_delegate("quit", m)
637 @client[:mode] = proc {|data|
638 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
640 @client[:join] = proc {|data|
641 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
644 @plugins.irc_delegate("join", m)
645 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
647 @client[:part] = proc {|data|
648 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
651 @plugins.irc_delegate("part", m)
653 @client[:kick] = proc {|data|
654 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
657 @plugins.irc_delegate("kick", m)
659 @client[:invite] = proc {|data|
660 m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
662 @plugins.irc_delegate("invite", m)
664 @client[:changetopic] = proc {|data|
665 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
668 @plugins.irc_delegate("topic", m)
670 @client[:topic] = proc { |data|
671 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
673 @client[:topicinfo] = proc { |data|
674 channel = data[:channel]
675 topic = channel.topic
676 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
677 m = TopicMessage.new(self, server, data[:source], channel, topic)
679 @plugins.irc_delegate("topic", m)
681 @client[:names] = proc { |data|
682 @plugins.delegate "names", data[:channel], data[:users]
684 @client[:unknown] = proc { |data|
685 #debug "UNKNOWN: #{data[:serverstring]}"
686 irclog data[:serverstring], ".unknown"
689 set_default_send_options :newlines => @config['send.newlines'].to_sym,
690 :join_with => @config['send.join_with'].dup,
691 :max_lines => @config['send.max_lines'],
692 :overlong => @config['send.overlong'].to_sym,
693 :split_at => Regexp.new(@config['send.split_at']),
694 :purge_split => @config['send.purge_split'],
695 :truncate_text => @config['send.truncate_text'].dup
698 def setup_plugins_path
699 @plugins.clear_botmodule_dirs
700 @plugins.add_botmodule_dir(Config::coredir + "/utils")
701 @plugins.add_botmodule_dir(Config::coredir)
702 @plugins.add_botmodule_dir("#{botclass}/plugins")
704 @config['plugins.path'].each do |_|
705 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
706 @plugins.add_botmodule_dir(path)
710 def set_default_send_options(opts={})
711 # Default send options for NOTICE and PRIVMSG
712 unless defined? @default_send_options
713 @default_send_options = {
714 :queue_channel => nil, # use default queue channel
715 :queue_ring => nil, # use default queue ring
716 :newlines => :split, # or :join
717 :join_with => ' ', # by default, use a single space
718 :max_lines => 0, # maximum number of lines to send with a single command
719 :overlong => :split, # or :truncate
720 # TODO an array of splitpoints would be preferrable for this option:
721 :split_at => /\s+/, # by default, split overlong lines at whitespace
722 :purge_split => true, # should the split string be removed?
723 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
726 @default_send_options.update opts unless opts.empty?
729 # checks if we should be quiet on a channel
730 def quiet_on?(channel)
731 return @quiet.include?('*') || @quiet.include?(channel.downcase)
734 def set_quiet(channel)
736 ch = channel.downcase.dup
737 @quiet << ch unless @quiet.include?(ch)
744 def reset_quiet(channel)
746 @quiet.delete channel.downcase
752 # things to do when we receive a signal
754 debug "received #{sig}, queueing quit"
756 quit unless @quit_mutex.locked?
757 debug "interrupted #{$interrupted} times"
765 # connect the bot to IRC
768 trap("SIGINT") { got_sig("SIGINT") }
769 trap("SIGTERM") { got_sig("SIGTERM") }
770 trap("SIGHUP") { got_sig("SIGHUP") }
771 rescue ArgumentError => e
772 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
773 rescue Exception => e
774 debug "failed to trap signals: #{e.pretty_inspect}"
777 quit if $interrupted > 0
780 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
782 quit if $interrupted > 0
784 realname = @config['irc.name'].clone || 'Ruby bot'
785 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
787 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
788 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
789 quit if $interrupted > 0
790 myself.nick = @config['irc.nick']
791 myself.user = @config['irc.user']
794 # begin event handling loop
798 quit if $interrupted > 0
802 while @socket.connected?
803 quit if $interrupted > 0
805 # Wait for messages and process them as they arrive. If nothing is
806 # received, we call the ping_server() method that will PING the
807 # server if appropriate, or raise a TimeoutError if no PONG has been
808 # received in the user-chosen timeout since the last PING sent.
810 break unless reply = @socket.gets
812 @client.process reply
818 # I despair of this. Some of my users get "connection reset by peer"
819 # exceptions that ARENT SocketError's. How am I supposed to handle
824 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
825 error "network exception: #{e.pretty_inspect}"
827 rescue BDB::Fatal => e
828 fatal "fatal bdb error: #{e.pretty_inspect}"
830 # Why restart? DB problems are serious stuff ...
831 # restart("Oops, we seem to have registry problems ...")
834 rescue Exception => e
835 error "non-net exception: #{e.pretty_inspect}"
838 fatal "unexpected exception: #{e.pretty_inspect}"
845 log "\n\nDisconnected\n\n"
847 quit if $interrupted > 0
849 log "\n\nWaiting to reconnect\n\n"
850 sleep @config['server.reconnect_wait']
854 # type:: message type
855 # where:: message target
856 # message:: message text
857 # send message +message+ of type +type+ to target +where+
858 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
859 # relevant say() or notice() methods. This one should be used for IRCd
860 # extensions you want to use in modules.
861 def sendmsg(type, where, original_message, options={})
862 opts = @default_send_options.merge(options)
864 # For starters, set up appropriate queue channels and rings
865 mchan = opts[:queue_channel]
866 mring = opts[:queue_ring]
883 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
887 messages << [multi_line.gsub("\n", opts[:join_with])]
889 multi_line.each_line { |line|
891 next unless(line.size > 0)
895 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
898 # The IRC protocol requires that each raw message must be not longer
899 # than 512 characters. From this length with have to subtract the EOL
900 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
901 # that will be prepended by the server to all of our messages.
903 # The maximum raw message length we can send is therefore 512 - 2 - 2
904 # minus the length of our hostmask.
906 max_len = 508 - myself.fullform.size
908 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
909 # will have a + or - prepended
910 if server.capabilities[:"identify-msg"]
914 # When splitting the message, we'll be prefixing the following string:
915 # (e.g. "PRIVMSG #rbot :")
916 fixed = "#{type} #{where} :"
918 # And this is what's left
919 left = max_len - fixed.size
921 truncate = opts[:truncate_text]
922 truncate = @default_send_options[:truncate_text] if truncate.size > left
923 truncate = "" if truncate.size > left
925 all_lines = messages.map { |line|
932 sub_lines = Array.new
934 sub_lines << msg.slice!(0, left)
936 lastspace = sub_lines.last.rindex(opts[:split_at])
938 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
939 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
944 line.slice(0, left - truncate.size) << truncate
946 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
951 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
952 lines = all_lines[0...opts[:max_lines]]
953 new_last = lines.last.slice(0, left - truncate.size) << truncate
954 lines.last.replace(new_last)
960 sendq "#{fixed}#{line}", chan, ring
961 log_sent(type, where, line)
965 # queue an arbitraty message for the server
966 def sendq(message="", chan=nil, ring=0)
968 @socket.queue(message, chan, ring)
971 # send a notice message to channel/nick +where+
972 def notice(where, message, options={})
973 return if where.kind_of?(Channel) and quiet_on?(where)
974 sendmsg "NOTICE", where, message, options
977 # say something (PRIVMSG) to channel/nick +where+
978 def say(where, message, options={})
979 return if where.kind_of?(Channel) and quiet_on?(where)
980 sendmsg "PRIVMSG", where, message, options
983 def ctcp_notice(where, command, message, options={})
984 return if where.kind_of?(Channel) and quiet_on?(where)
985 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
988 def ctcp_say(where, command, message, options={})
989 return if where.kind_of?(Channel) and quiet_on?(where)
990 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
993 # perform a CTCP action with message +message+ to channel/nick +where+
994 def action(where, message, options={})
995 ctcp_say(where, 'ACTION', message, options)
998 # quick way to say "okay" (or equivalent) to +where+
1000 say where, @lang.get("okay")
1003 # log IRC-related message +message+ to a file determined by +where+.
1004 # +where+ can be a channel name, or a nick for private message logging
1005 def irclog(message, where="server")
1006 message = message.chomp
1007 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
1008 if where.class <= Server
1009 where_str = "server"
1011 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
1013 unless(@logs.has_key?(where_str))
1014 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
1015 @logs[where_str].sync = true
1017 @logs[where_str].puts "[#{stamp}] #{message}"
1018 #debug "[#{stamp}] <#{where}> #{message}"
1021 # set topic of channel +where+ to +topic+
1022 def topic(where, topic)
1023 sendq "TOPIC #{where} :#{topic}", where, 2
1026 def disconnect(message=nil)
1027 message = @lang.get("quit") if (!message || message.empty?)
1028 if @socket.connected?
1030 debug "Clearing socket"
1032 debug "Sending quit message"
1033 @socket.emergency_puts "QUIT :#{message}"
1034 debug "Flushing socket"
1036 rescue SocketError => e
1037 error "error while disconnecting socket: #{e.pretty_inspect}"
1039 debug "Shutting down socket"
1042 debug "Logging quits"
1043 server.channels.each { |ch|
1044 irclog "@ quit (#{message})", ch
1050 # disconnect from the server and cleanup all plugins and modules
1051 def shutdown(message=nil)
1052 @quit_mutex.synchronize do
1053 debug "Shutting down: #{message}"
1054 ## No we don't restore them ... let everything run through
1056 # trap("SIGINT", "DEFAULT")
1057 # trap("SIGTERM", "DEFAULT")
1058 # trap("SIGHUP", "DEFAULT")
1060 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1062 debug "\tdisconnecting..."
1064 debug "\tstopping timer..."
1066 debug "\tsaving ..."
1068 debug "\tcleaning up ..."
1069 @save_mutex.synchronize do
1072 # debug "\tstopping timers ..."
1074 # debug "Closing registries"
1076 debug "\t\tcleaning up the db environment ..."
1078 log "rbot quit (#{message})"
1082 # message:: optional IRC quit message
1083 # quit IRC, shutdown the bot
1084 def quit(message=nil)
1092 # totally shutdown and respawn the bot
1093 def restart(message=nil)
1094 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1096 sleep @config['server.reconnect_wait']
1099 # Note, this fails on Windows
1100 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1103 rescue Errno::ENOENT
1104 exec("ruby", *(@argv.unshift $0))
1105 rescue Exception => e
1111 # call the save method for all of the botmodules
1113 @save_mutex.synchronize do
1119 # call the rescan method for all of the botmodules
1121 debug "\tstopping timer..."
1123 @save_mutex.synchronize do
1130 # channel:: channel to join
1131 # key:: optional channel key if channel is +s
1133 def join(channel, key=nil)
1135 sendq "JOIN #{channel} :#{key}", channel, 2
1137 sendq "JOIN #{channel}", channel, 2
1142 def part(channel, message="")
1143 sendq "PART #{channel} :#{message}", channel, 2
1146 # attempt to change bot's nick to +name+
1148 sendq "NICK #{name}"
1152 def mode(channel, mode, target)
1153 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1157 def kick(channel, user, msg)
1158 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1161 # m:: message asking for help
1162 # topic:: optional topic help is requested for
1163 # respond to online help requests
1165 topic = nil if topic == ""
1168 helpstr = _("help topics: ")
1169 helpstr += @plugins.helptopics
1170 helpstr += _(" (help <topic> for more info)")
1172 unless(helpstr = @plugins.help(topic))
1173 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1179 # returns a string describing the current status of the bot (uptime etc)
1181 secs_up = Time.new - @startup_time
1182 uptime = Utils.secs_to_string secs_up
1183 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1184 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1186 :up => uptime, :plug => @plugins.length,
1187 :sent => @socket.lines_sent, :recv => @socket.lines_received
1191 # We want to respond to a hung server in a timely manner. If nothing was received
1192 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1193 # the server. If the PONG is not received within the user-defined timeout, we
1194 # assume we're in ping timeout and act accordingly.
1196 act_timeout = @config['server.ping_timeout']
1197 return if act_timeout <= 0
1199 if @last_rec && now > @last_rec + act_timeout
1201 # No previous PING pending, send a new one
1203 @last_ping = Time.now
1205 diff = now - @last_ping
1206 if diff > act_timeout
1207 debug "no PONG from server in #{diff} seconds, reconnecting"
1208 # the actual reconnect is handled in the main loop:
1209 raise TimeoutError, "no PONG from server in #{diff} seconds"
1215 def stop_server_pings
1216 # cancel previous PINGs and reset time of last RECV
1223 def irclogprivmsg(m)
1226 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.logmessage}", m.source
1228 irclog "* #{m.source} #{m.logmessage}", m.target
1232 irclog "<#{m.source}> #{m.logmessage}", m.target
1234 irclog "[#{m.source}(#{m.sourceaddress})] #{m.logmessage}", m.source
1239 # log a message. Internal use only.
1240 def log_sent(type, where, message)
1245 irclog "-=#{myself}=- #{message}", where
1247 irclog "[-=#{where}=-] #{message}", where
1252 irclog "<#{myself}> #{message}", where
1254 irclog "[msg(#{where})] #{message}", where
1261 debug "joined channel #{m.channel}"
1262 irclog "@ Joined channel #{m.channel}", m.channel
1264 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1270 debug "left channel #{m.channel}"
1271 irclog "@ Left channel #{m.channel} (#{m.logmessage})", m.channel
1273 irclog "@ #{m.source} left channel #{m.channel} (#{m.logmessage})", m.channel
1279 debug "kicked from channel #{m.channel}"
1280 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.logmessage})", m.channel
1282 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.logmessage})", m.channel
1287 if m.source == myself
1288 irclog "@ I set topic \"#{m.topic}\"", m.channel
1290 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel