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'
106 # require 'rbot/utils'
109 require 'rbot/rfc2812'
110 require 'rbot/ircsocket'
111 require 'rbot/botuser'
113 require 'rbot/plugins'
114 # require 'rbot/channel'
115 require 'rbot/message'
116 require 'rbot/language'
117 require 'rbot/dbhash'
118 require 'rbot/registry'
119 # require 'rbot/httputil'
123 # Main bot class, which manages the various components, receives messages,
124 # handles them or passes them to plugins, and contains core functionality.
126 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
127 SOURCE_URL = "http://ruby-rbot.org"
128 # the bot's Auth data
131 # the bot's Config data
134 # the botclass for this bot (determines configdir among other things)
135 attr_reader :botclass
137 # used to perform actions periodically (saves configuration once per minute
141 # synchronize with this mutex while touching permanent data files:
142 # saving, flushing, cleaning up ...
143 attr_reader :save_mutex
145 # bot's Language data
152 # bot's object registry, plugins get an interface to this for persistant
153 # storage (hash interface tied to a bdb file, plugins use Accessors to store
154 # and restore objects in their own namespaces.)
155 attr_reader :registry
157 # bot's plugins. This is an instance of class Plugins
160 # bot's httputil help object, for fetching resources via http. Sets up
161 # proxies etc as defined by the bot configuration/environment
162 attr_accessor :httputil
164 # server we are connected to
170 # bot User in the client/server connection
176 # bot User in the client/server connection
184 ret = self.to_s[0..-2]
185 ret << ' version=' << $version.inspect
186 ret << ' botclass=' << botclass.inspect
187 ret << ' lang="' << lang.language
192 ret << ' nick=' << nick.inspect
195 ret << (server.to_s + (socket ?
196 ' [' << socket.server_uri.to_s << ']' : '')).inspect
197 unless server.channels.empty?
199 ret << server.channels.map { |c|
200 "%s%s" % [c.modes_of(nick).map { |m|
201 server.prefix_for_mode(m)
208 ret << ' plugins=' << plugins.inspect
213 # create a new Bot with botclass +botclass+
214 def initialize(botclass, params = {})
215 # Config for the core bot
216 # TODO should we split socket stuff into ircsocket, etc?
217 Config.register Config::ArrayValue.new('server.list',
218 :default => ['irc://localhost'], :wizard => true,
219 :requires_restart => true,
220 :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.")
221 Config.register Config::BooleanValue.new('server.ssl',
222 :default => false, :requires_restart => true, :wizard => true,
223 :desc => "Use SSL to connect to this server?")
224 Config.register Config::StringValue.new('server.password',
225 :default => false, :requires_restart => true,
226 :desc => "Password for connecting to this server (if required)",
228 Config.register Config::StringValue.new('server.bindhost',
229 :default => false, :requires_restart => true,
230 :desc => "Specific local host or IP for the bot to bind to (if required)",
232 Config.register Config::IntegerValue.new('server.reconnect_wait',
233 :default => 5, :validate => Proc.new{|v| v >= 0},
234 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
235 Config.register Config::FloatValue.new('server.sendq_delay',
236 :default => 2.0, :validate => Proc.new{|v| v >= 0},
237 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
238 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
239 Config.register Config::IntegerValue.new('server.sendq_burst',
240 :default => 4, :validate => Proc.new{|v| v >= 0},
241 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
242 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
243 Config.register Config::IntegerValue.new('server.ping_timeout',
244 :default => 30, :validate => Proc.new{|v| v >= 0},
245 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
247 Config.register Config::StringValue.new('irc.nick', :default => "rbot",
248 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
249 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
250 Config.register Config::StringValue.new('irc.name',
251 :default => "Ruby bot", :requires_restart => true,
252 :desc => "IRC realname the bot should use")
253 Config.register Config::BooleanValue.new('irc.name_copyright',
254 :default => true, :requires_restart => true,
255 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
256 Config.register Config::StringValue.new('irc.user', :default => "rbot",
257 :requires_restart => true,
258 :desc => "local user the bot should appear to be", :wizard => true)
259 Config.register Config::ArrayValue.new('irc.join_channels',
260 :default => [], :wizard => true,
261 :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'")
262 Config.register Config::ArrayValue.new('irc.ignore_users',
264 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
266 Config.register Config::IntegerValue.new('core.save_every',
267 :default => 60, :validate => Proc.new{|v| v >= 0},
268 :on_change => Proc.new { |bot, v|
271 @timer.reschedule(@save_timer, v)
272 @timer.unblock(@save_timer)
274 @timer.block(@save_timer)
278 @save_timer = @timer.add(v) { bot.save }
280 # Nothing to do when v == 0
283 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
285 Config.register Config::BooleanValue.new('core.run_as_daemon',
286 :default => false, :requires_restart => true,
287 :desc => "Should the bot run as a daemon?")
289 Config.register Config::StringValue.new('log.file',
290 :default => false, :requires_restart => true,
291 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
292 Config.register Config::IntegerValue.new('log.level',
293 :default => 1, :requires_restart => false,
294 :validate => Proc.new { |v| (0..5).include?(v) },
295 :on_change => Proc.new { |bot, v|
298 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
299 Config.register Config::IntegerValue.new('log.keep',
300 :default => 1, :requires_restart => true,
301 :validate => Proc.new { |v| v >= 0 },
302 :desc => "How many old console messages logfiles to keep")
303 Config.register Config::IntegerValue.new('log.max_size',
304 :default => 10, :requires_restart => true,
305 :validate => Proc.new { |v| v > 0 },
306 :desc => "Maximum console messages logfile size (in megabytes)")
308 Config.register Config::ArrayValue.new('plugins.path',
309 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
310 :requires_restart => false,
311 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
312 :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")
314 Config.register Config::EnumValue.new('send.newlines',
315 :values => ['split', 'join'], :default => 'split',
316 :on_change => Proc.new { |bot, v|
317 bot.set_default_send_options :newlines => v.to_sym
319 :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")
320 Config.register Config::StringValue.new('send.join_with',
322 :on_change => Proc.new { |bot, v|
323 bot.set_default_send_options :join_with => v.dup
325 :desc => "String used to replace newlines when send.newlines is set to join")
326 Config.register Config::IntegerValue.new('send.max_lines',
328 :validate => Proc.new { |v| v >= 0 },
329 :on_change => Proc.new { |bot, v|
330 bot.set_default_send_options :max_lines => v
332 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
333 Config.register Config::EnumValue.new('send.overlong',
334 :values => ['split', 'truncate'], :default => 'split',
335 :on_change => Proc.new { |bot, v|
336 bot.set_default_send_options :overlong => v.to_sym
338 :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")
339 Config.register Config::StringValue.new('send.split_at',
341 :on_change => Proc.new { |bot, v|
342 bot.set_default_send_options :split_at => Regexp.new(v)
344 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
345 Config.register Config::BooleanValue.new('send.purge_split',
347 :on_change => Proc.new { |bot, v|
348 bot.set_default_send_options :purge_split => v
350 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
351 Config.register Config::StringValue.new('send.truncate_text',
352 :default => "#{Reverse}...#{Reverse}",
353 :on_change => Proc.new { |bot, v|
354 bot.set_default_send_options :truncate_text => v.dup
356 :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")
358 @argv = params[:argv]
359 @run_dir = params[:run_dir] || Dir.pwd
361 unless FileTest.directory? Config::coredir
362 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
366 unless FileTest.directory? Config::datadir
367 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
371 unless botclass and not botclass.empty?
372 # We want to find a sensible default.
373 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
374 # * On Windows (at least the NT versions) we want to put our stuff in the
375 # Application Data folder.
376 # We don't use any particular O/S detection magic, exploiting the fact that
377 # Etc.getpwuid is nil on Windows
378 if Etc.getpwuid(Process::Sys.geteuid)
379 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
381 if ENV.has_key?('APPDATA')
382 botclass = ENV['APPDATA'].dup
383 botclass.gsub!("\\","/")
388 botclass = File.expand_path(botclass)
389 @botclass = botclass.gsub(/\/$/, "")
391 unless FileTest.directory? botclass
392 log "no #{botclass} directory found, creating from templates.."
393 if FileTest.exist? botclass
394 error "file #{botclass} exists but isn't a directory"
397 FileUtils.cp_r Config::datadir+'/templates', botclass
400 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
401 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
402 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
404 # Time at which the last PING was sent
406 # Time at which the last line was RECV'd from the server
409 @startup_time = Time.new
412 @config = Config.manager
413 @config.bot_associate(self)
414 rescue Exception => e
420 if @config['core.run_as_daemon']
424 @logfile = @config['log.file']
425 if @logfile.class!=String || @logfile.empty?
426 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
429 # See http://blog.humlab.umu.se/samuel/archives/000107.html
430 # for the backgrounding code
436 rescue NotImplementedError
437 warning "Could not background, fork not supported"
440 rescue Exception => e
441 warning "Could not background. #{e.pretty_inspect}"
444 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
445 log "Redirecting standard input/output/error"
447 STDIN.reopen "/dev/null"
449 # On Windows, there's not such thing as /dev/null
452 def STDOUT.write(str=nil)
456 def STDERR.write(str=nil)
457 if str.to_s.match(/:\d+: warning:/)
466 # Set the new logfile and loglevel. This must be done after the daemonizing
467 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
468 $logger.datetime_format= $dateformat
469 $logger.level = @config['log.level']
470 $logger.level = $cl_loglevel if defined? $cl_loglevel
471 $logger.level = 0 if $debug
475 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
479 @registry = Registry.new self
482 @save_mutex = Mutex.new
483 if @config['core.save_every'] > 0
484 @save_timer = @timer.add(@config['core.save_every']) { save }
488 @quit_mutex = Mutex.new
493 @lang = Language.new(self, @config['core.language'])
496 @auth = Auth::manager
497 @auth.bot_associate(self)
498 # @auth.load("#{botclass}/botusers.yaml")
499 rescue Exception => e
504 @auth.everyone.set_default_permission("*", true)
505 @auth.botowner.password= @config['auth.password']
507 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
508 @plugins = Plugins::manager
509 @plugins.bot_associate(self)
512 if @config['server.name']
513 debug "upgrading configuration (server.name => server.list)"
514 srv_uri = 'irc://' + @config['server.name']
515 srv_uri += ":#{@config['server.port']}" if @config['server.port']
516 @config.items['server.list'.to_sym].set_string(srv_uri)
517 @config.delete('server.name'.to_sym)
518 @config.delete('server.port'.to_sym)
519 debug "server.list is now #{@config['server.list'].inspect}"
522 @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
527 # Channels where we are quiet
528 # Array of channels names where the bot should be quiet
529 # '*' means all channels
533 @client[:welcome] = proc {|data|
534 irclog "joined server #{@client.server} as #{myself}", "server"
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}"
573 @config['irc.ignore_users'].each { |mask|
574 if m.source.matches?(server.new_netmask(mask))
583 @plugins.delegate "listen", m
584 @plugins.delegate("ctcp_listen", m) if m.ctcp
585 @plugins.privmsg(m) if m.address?
587 @plugins.delegate "unreplied", m
591 @client[:notice] = proc { |data|
592 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
593 # pass it off to plugins that want to hear everything
594 @plugins.delegate "listen", message
596 @client[:motd] = proc { |data|
597 data[:motd].each_line { |line|
598 irclog "MOTD: #{line}", "server"
601 @client[:nicktaken] = proc { |data|
602 new = "#{data[:nick]}_"
604 # If we're setting our nick at connection because our choice was taken,
605 # we have to fix our nick manually, because there will be no NICK message
606 # to inform us that our nick has been changed.
607 if data[:target] == '*'
608 debug "setting my connection nick to #{new}"
611 @plugins.delegate "nicktaken", data[:nick]
613 @client[:badnick] = proc {|data|
614 warning "bad nick (#{data[:nick]})"
616 @client[:ping] = proc {|data|
617 sendq "PONG #{data[:pingid]}"
619 @client[:pong] = proc {|data|
622 @client[:nick] = proc {|data|
623 # debug "Message source is #{data[:source].inspect}"
624 # debug "Bot is #{myself.inspect}"
625 source = data[:source]
628 m = NickMessage.new(self, server, source, old, new)
630 debug "my nick is now #{new}"
632 data[:is_on].each { |ch|
633 irclog "@ #{old} is now known as #{new}", ch
635 @plugins.delegate("listen", m)
636 @plugins.delegate("nick", m)
638 @client[:quit] = proc {|data|
639 source = data[:source]
640 message = data[:message]
641 m = QuitMessage.new(self, server, source, source, message)
642 data[:was_on].each { |ch|
643 irclog "@ Quit: #{source}: #{message}", ch
645 @plugins.delegate("listen", m)
646 @plugins.delegate("quit", m)
648 @client[:mode] = proc {|data|
649 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
651 @client[:join] = proc {|data|
652 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
655 @plugins.delegate("listen", m)
656 @plugins.delegate("join", m)
657 sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
659 @client[:part] = proc {|data|
660 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
663 @plugins.delegate("listen", m)
664 @plugins.delegate("part", m)
666 @client[:kick] = proc {|data|
667 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
670 @plugins.delegate("listen", m)
671 @plugins.delegate("kick", m)
673 @client[:invite] = proc {|data|
674 if data[:target] == myself
675 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
678 @client[:changetopic] = proc {|data|
679 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
682 @plugins.delegate("listen", m)
683 @plugins.delegate("topic", m)
685 @client[:topic] = proc { |data|
686 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
688 @client[:topicinfo] = proc { |data|
689 channel = data[:channel]
690 topic = channel.topic
691 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
692 m = TopicMessage.new(self, server, data[:source], channel, topic)
694 @plugins.delegate("listen", m)
695 @plugins.delegate("topic", m)
697 @client[:names] = proc { |data|
698 @plugins.delegate "names", data[:channel], data[:users]
700 @client[:unknown] = proc { |data|
701 #debug "UNKNOWN: #{data[:serverstring]}"
702 irclog data[:serverstring], ".unknown"
705 set_default_send_options :newlines => @config['send.newlines'].to_sym,
706 :join_with => @config['send.join_with'].dup,
707 :max_lines => @config['send.max_lines'],
708 :overlong => @config['send.overlong'].to_sym,
709 :split_at => Regexp.new(@config['send.split_at']),
710 :purge_split => @config['send.purge_split'],
711 :truncate_text => @config['send.truncate_text'].dup
714 def setup_plugins_path
715 @plugins.clear_botmodule_dirs
716 @plugins.add_botmodule_dir(Config::coredir + "/utils")
717 @plugins.add_botmodule_dir(Config::coredir)
718 @plugins.add_botmodule_dir("#{botclass}/plugins")
720 @config['plugins.path'].each do |_|
721 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
722 @plugins.add_botmodule_dir(path)
726 def set_default_send_options(opts={})
727 # Default send options for NOTICE and PRIVMSG
728 unless defined? @default_send_options
729 @default_send_options = {
730 :queue_channel => nil, # use default queue channel
731 :queue_ring => nil, # use default queue ring
732 :newlines => :split, # or :join
733 :join_with => ' ', # by default, use a single space
734 :max_lines => 0, # maximum number of lines to send with a single command
735 :overlong => :split, # or :truncate
736 # TODO an array of splitpoints would be preferrable for this option:
737 :split_at => /\s+/, # by default, split overlong lines at whitespace
738 :purge_split => true, # should the split string be removed?
739 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
742 @default_send_options.update opts unless opts.empty?
745 # checks if we should be quiet on a channel
746 def quiet_on?(channel)
747 return @quiet.include?('*') || @quiet.include?(channel.downcase)
750 def set_quiet(channel)
752 ch = channel.downcase.dup
753 @quiet << ch unless @quiet.include?(ch)
760 def reset_quiet(channel)
762 @quiet.delete channel.downcase
768 # things to do when we receive a signal
770 debug "received #{sig}, queueing quit"
772 quit unless @quit_mutex.locked?
773 debug "interrupted #{$interrupted} times"
781 # connect the bot to IRC
784 trap("SIGINT") { got_sig("SIGINT") }
785 trap("SIGTERM") { got_sig("SIGTERM") }
786 trap("SIGHUP") { got_sig("SIGHUP") }
787 rescue ArgumentError => e
788 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
789 rescue Exception => e
790 debug "failed to trap signals: #{e.pretty_inspect}"
793 quit if $interrupted > 0
796 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
798 quit if $interrupted > 0
800 realname = @config['irc.name'].clone || 'Ruby bot'
801 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
803 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
804 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
805 quit if $interrupted > 0
806 myself.nick = @config['irc.nick']
807 myself.user = @config['irc.user']
810 # begin event handling loop
814 quit if $interrupted > 0
818 while @socket.connected?
819 quit if $interrupted > 0
821 # Wait for messages and process them as they arrive. If nothing is
822 # received, we call the ping_server() method that will PING the
823 # server if appropriate, or raise a TimeoutError if no PONG has been
824 # received in the user-chosen timeout since the last PING sent.
826 break unless reply = @socket.gets
828 @client.process reply
834 # I despair of this. Some of my users get "connection reset by peer"
835 # exceptions that ARENT SocketError's. How am I supposed to handle
840 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
841 error "network exception: #{e.pretty_inspect}"
843 rescue BDB::Fatal => e
844 fatal "fatal bdb error: #{e.pretty_inspect}"
846 # Why restart? DB problems are serious stuff ...
847 # restart("Oops, we seem to have registry problems ...")
850 rescue Exception => e
851 error "non-net exception: #{e.pretty_inspect}"
854 fatal "unexpected exception: #{e.pretty_inspect}"
861 log "\n\nDisconnected\n\n"
863 quit if $interrupted > 0
865 log "\n\nWaiting to reconnect\n\n"
866 sleep @config['server.reconnect_wait']
870 # type:: message type
871 # where:: message target
872 # message:: message text
873 # send message +message+ of type +type+ to target +where+
874 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
875 # relevant say() or notice() methods. This one should be used for IRCd
876 # extensions you want to use in modules.
877 def sendmsg(type, where, original_message, options={})
878 opts = @default_send_options.merge(options)
880 # For starters, set up appropriate queue channels and rings
881 mchan = opts[:queue_channel]
882 mring = opts[:queue_ring]
899 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
903 messages << [multi_line.gsub("\n", opts[:join_with])]
905 multi_line.each_line { |line|
907 next unless(line.size > 0)
911 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
914 # The IRC protocol requires that each raw message must be not longer
915 # than 512 characters. From this length with have to subtract the EOL
916 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
917 # that will be prepended by the server to all of our messages.
919 # The maximum raw message length we can send is therefore 512 - 2 - 2
920 # minus the length of our hostmask.
922 max_len = 508 - myself.fullform.size
924 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
925 # will have a + or - prepended
926 if server.capabilities[:"identify-msg"]
930 # When splitting the message, we'll be prefixing the following string:
931 # (e.g. "PRIVMSG #rbot :")
932 fixed = "#{type} #{where} :"
934 # And this is what's left
935 left = max_len - fixed.size
937 truncate = opts[:truncate_text]
938 truncate = @default_send_options[:truncate_text] if truncate.size > left
939 truncate = "" if truncate.size > left
941 all_lines = messages.map { |line|
948 sub_lines = Array.new
950 sub_lines << msg.slice!(0, left)
952 lastspace = sub_lines.last.rindex(opts[:split_at])
954 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
955 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
960 line.slice(0, left - truncate.size) << truncate
962 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
967 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
968 lines = all_lines[0...opts[:max_lines]]
969 new_last = lines.last.slice(0, left - truncate.size) << truncate
970 lines.last.replace(new_last)
976 sendq "#{fixed}#{line}", chan, ring
977 log_sent(type, where, line)
981 # queue an arbitraty message for the server
982 def sendq(message="", chan=nil, ring=0)
984 @socket.queue(message, chan, ring)
987 # send a notice message to channel/nick +where+
988 def notice(where, message, options={})
989 return if where.kind_of?(Channel) and quiet_on?(where)
990 sendmsg "NOTICE", where, message, options
993 # say something (PRIVMSG) to channel/nick +where+
994 def say(where, message, options={})
995 return if where.kind_of?(Channel) and quiet_on?(where)
996 sendmsg "PRIVMSG", where, message, options
999 def ctcp_notice(where, command, message, options={})
1000 return if where.kind_of?(Channel) and quiet_on?(where)
1001 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1004 def ctcp_say(where, command, message, options={})
1005 return if where.kind_of?(Channel) and quiet_on?(where)
1006 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1009 # perform a CTCP action with message +message+ to channel/nick +where+
1010 def action(where, message, options={})
1011 ctcp_say(where, 'ACTION', message, options)
1014 # quick way to say "okay" (or equivalent) to +where+
1016 say where, @lang.get("okay")
1019 # log IRC-related message +message+ to a file determined by +where+.
1020 # +where+ can be a channel name, or a nick for private message logging
1021 def irclog(message, where="server")
1022 message = message.chomp
1023 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
1024 if where.class <= Server
1025 where_str = "server"
1027 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
1029 unless(@logs.has_key?(where_str))
1030 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
1031 @logs[where_str].sync = true
1033 @logs[where_str].puts "[#{stamp}] #{message}"
1034 #debug "[#{stamp}] <#{where}> #{message}"
1037 # set topic of channel +where+ to +topic+
1038 def topic(where, topic)
1039 sendq "TOPIC #{where} :#{topic}", where, 2
1042 def disconnect(message=nil)
1043 message = @lang.get("quit") if (!message || message.empty?)
1044 if @socket.connected?
1046 debug "Clearing socket"
1048 debug "Sending quit message"
1049 @socket.emergency_puts "QUIT :#{message}"
1050 debug "Flushing socket"
1052 rescue SocketError => e
1053 error "error while disconnecting socket: #{e.pretty_inspect}"
1055 debug "Shutting down socket"
1058 debug "Logging quits"
1059 server.channels.each { |ch|
1060 irclog "@ quit (#{message})", ch
1066 # disconnect from the server and cleanup all plugins and modules
1067 def shutdown(message=nil)
1068 @quit_mutex.synchronize do
1069 debug "Shutting down: #{message}"
1070 ## No we don't restore them ... let everything run through
1072 # trap("SIGINT", "DEFAULT")
1073 # trap("SIGTERM", "DEFAULT")
1074 # trap("SIGHUP", "DEFAULT")
1076 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1078 debug "\tdisconnecting..."
1080 debug "\tstopping timer..."
1082 debug "\tsaving ..."
1084 debug "\tcleaning up ..."
1085 @save_mutex.synchronize do
1088 # debug "\tstopping timers ..."
1090 # debug "Closing registries"
1092 debug "\t\tcleaning up the db environment ..."
1094 log "rbot quit (#{message})"
1098 # message:: optional IRC quit message
1099 # quit IRC, shutdown the bot
1100 def quit(message=nil)
1108 # totally shutdown and respawn the bot
1109 def restart(message=nil)
1110 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1112 sleep @config['server.reconnect_wait']
1115 # Note, this fails on Windows
1116 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1119 rescue Errno::ENOENT
1120 exec("ruby", *(@argv.unshift $0))
1121 rescue Exception => e
1127 # call the save method for all of the botmodules
1129 @save_mutex.synchronize do
1135 # call the rescan method for all of the botmodules
1137 debug "\tstopping timer..."
1139 @save_mutex.synchronize do
1146 # channel:: channel to join
1147 # key:: optional channel key if channel is +s
1149 def join(channel, key=nil)
1151 sendq "JOIN #{channel} :#{key}", channel, 2
1153 sendq "JOIN #{channel}", channel, 2
1158 def part(channel, message="")
1159 sendq "PART #{channel} :#{message}", channel, 2
1162 # attempt to change bot's nick to +name+
1164 sendq "NICK #{name}"
1168 def mode(channel, mode, target)
1169 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1173 def kick(channel, user, msg)
1174 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1177 # m:: message asking for help
1178 # topic:: optional topic help is requested for
1179 # respond to online help requests
1181 topic = nil if topic == ""
1184 helpstr = _("help topics: ")
1185 helpstr += @plugins.helptopics
1186 helpstr += _(" (help <topic> for more info)")
1188 unless(helpstr = @plugins.help(topic))
1189 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1195 # returns a string describing the current status of the bot (uptime etc)
1197 secs_up = Time.new - @startup_time
1198 uptime = Utils.secs_to_string secs_up
1199 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1200 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1202 :up => uptime, :plug => @plugins.length,
1203 :sent => @socket.lines_sent, :recv => @socket.lines_received
1207 # We want to respond to a hung server in a timely manner. If nothing was received
1208 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1209 # the server. If the PONG is not received within the user-defined timeout, we
1210 # assume we're in ping timeout and act accordingly.
1212 act_timeout = @config['server.ping_timeout']
1213 return if act_timeout <= 0
1215 if @last_rec && now > @last_rec + act_timeout
1217 # No previous PING pending, send a new one
1219 @last_ping = Time.now
1221 diff = now - @last_ping
1222 if diff > act_timeout
1223 debug "no PONG from server in #{diff} seconds, reconnecting"
1224 # the actual reconnect is handled in the main loop:
1225 raise TimeoutError, "no PONG from server in #{diff} seconds"
1231 def stop_server_pings
1232 # cancel previous PINGs and reset time of last RECV
1239 def irclogprivmsg(m)
1242 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.logmessage}", m.source
1244 irclog "* #{m.source} #{m.logmessage}", m.target
1248 irclog "<#{m.source}> #{m.logmessage}", m.target
1250 irclog "[#{m.source}(#{m.sourceaddress})] #{m.logmessage}", m.source
1255 # log a message. Internal use only.
1256 def log_sent(type, where, message)
1261 irclog "-=#{myself}=- #{message}", where
1263 irclog "[-=#{where}=-] #{message}", where
1268 irclog "<#{myself}> #{message}", where
1270 irclog "[msg(#{where})] #{message}", where
1277 debug "joined channel #{m.channel}"
1278 irclog "@ Joined channel #{m.channel}", m.channel
1280 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1286 debug "left channel #{m.channel}"
1287 irclog "@ Left channel #{m.channel} (#{m.logmessage})", m.channel
1289 irclog "@ #{m.source} left channel #{m.channel} (#{m.logmessage})", m.channel
1295 debug "kicked from channel #{m.channel}"
1296 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.logmessage})", m.channel
1298 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.logmessage})", m.channel
1303 if m.source == myself
1304 irclog "@ I set topic \"#{m.topic}\"", m.channel
1306 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel