7 $debug = false unless $debug
8 $daemonize = false unless $daemonize
10 $dateformat = "%Y/%m/%d %H:%M:%S"
11 $logger = Logger.new($stderr)
12 $logger.datetime_format = $dateformat
13 $logger.level = $cl_loglevel if $cl_loglevel
14 $logger.level = 0 if $debug
18 unless Kernel.instance_methods.include?("pretty_inspect")
22 public :pretty_inspect
27 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
28 q.seplist(self.backtrace, lambda { "\n" }) { |v| v } if self.backtrace
33 def rawlog(level, message=nil, who_pos=1)
35 if call_stack.length > who_pos
36 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
40 # Output each line. To distinguish between separate messages and multi-line
41 # messages originating at the same time, we blank #{who} after the first message
43 # Also, we output strings as-is but for other objects we use pretty_inspect
48 str = message.pretty_inspect
51 $logger.add(level, l.chomp, who)
57 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
61 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
64 def debug(message=nil, who_pos=1)
65 rawlog(Logger::Severity::DEBUG, message, who_pos)
68 def log(message=nil, who_pos=1)
69 rawlog(Logger::Severity::INFO, message, who_pos)
72 def warning(message=nil, who_pos=1)
73 rawlog(Logger::Severity::WARN, message, who_pos)
76 def error(message=nil, who_pos=1)
77 rawlog(Logger::Severity::ERROR, message, who_pos)
80 def fatal(message=nil, who_pos=1)
81 rawlog(Logger::Severity::FATAL, message, who_pos)
86 warning "warning test"
90 # The following global is used for the improved signal handling.
94 require 'rbot/rbotconfig'
96 # require 'rbot/utils'
99 require 'rbot/rfc2812'
100 require 'rbot/ircsocket'
101 require 'rbot/botuser'
103 require 'rbot/plugins'
104 # require 'rbot/channel'
105 require 'rbot/message'
106 require 'rbot/language'
107 require 'rbot/dbhash'
108 require 'rbot/registry'
109 # require 'rbot/httputil'
113 # Main bot class, which manages the various components, receives messages,
114 # handles them or passes them to plugins, and contains core functionality.
116 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
117 # the bot's Auth data
120 # the bot's BotConfig data
123 # the botclass for this bot (determines configdir among other things)
124 attr_reader :botclass
126 # used to perform actions periodically (saves configuration once per minute
130 # synchronize with this mutex while touching permanent data files:
131 # saving, flushing, cleaning up ...
132 attr_reader :save_mutex
134 # bot's Language data
141 # bot's object registry, plugins get an interface to this for persistant
142 # storage (hash interface tied to a bdb file, plugins use Accessors to store
143 # and restore objects in their own namespaces.)
144 attr_reader :registry
146 # bot's plugins. This is an instance of class Plugins
149 # bot's httputil help object, for fetching resources via http. Sets up
150 # proxies etc as defined by the bot configuration/environment
151 attr_accessor :httputil
153 # server we are connected to
159 # bot User in the client/server connection
165 # bot User in the client/server connection
170 # create a new Bot with botclass +botclass+
171 def initialize(botclass, params = {})
172 # BotConfig for the core bot
173 # TODO should we split socket stuff into ircsocket, etc?
174 BotConfig.register BotConfigArrayValue.new('server.list',
175 :default => ['irc://localhost'], :wizard => true,
176 :requires_restart => true,
177 :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.")
178 BotConfig.register BotConfigBooleanValue.new('server.ssl',
179 :default => false, :requires_restart => true, :wizard => true,
180 :desc => "Use SSL to connect to this server?")
181 BotConfig.register BotConfigStringValue.new('server.password',
182 :default => false, :requires_restart => true,
183 :desc => "Password for connecting to this server (if required)",
185 BotConfig.register BotConfigStringValue.new('server.bindhost',
186 :default => false, :requires_restart => true,
187 :desc => "Specific local host or IP for the bot to bind to (if required)",
189 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
190 :default => 5, :validate => Proc.new{|v| v >= 0},
191 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
192 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
193 :default => 2.0, :validate => Proc.new{|v| v >= 0},
194 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
195 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
196 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
197 :default => 4, :validate => Proc.new{|v| v >= 0},
198 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
199 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
200 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
201 :default => 30, :validate => Proc.new{|v| v >= 0},
202 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
204 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
205 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
206 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
207 BotConfig.register BotConfigStringValue.new('irc.name',
208 :default => "Ruby bot", :requires_restart => true,
209 :desc => "IRC realname the bot should use")
210 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
211 :default => true, :requires_restart => true,
212 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
213 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
214 :requires_restart => true,
215 :desc => "local user the bot should appear to be", :wizard => true)
216 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
217 :default => [], :wizard => true,
218 :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'")
219 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
221 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
223 BotConfig.register BotConfigIntegerValue.new('core.save_every',
224 :default => 60, :validate => Proc.new{|v| v >= 0},
225 :on_change => Proc.new { |bot, v|
228 @timer.reschedule(@save_timer, v)
229 @timer.unblock(@save_timer)
231 @timer.block(@save_timer)
235 @save_timer = @timer.add(v) { bot.save }
237 # Nothing to do when v == 0
240 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
242 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
243 :default => false, :requires_restart => true,
244 :desc => "Should the bot run as a daemon?")
246 BotConfig.register BotConfigStringValue.new('log.file',
247 :default => false, :requires_restart => true,
248 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
249 BotConfig.register BotConfigIntegerValue.new('log.level',
250 :default => 1, :requires_restart => false,
251 :validate => Proc.new { |v| (0..5).include?(v) },
252 :on_change => Proc.new { |bot, v|
255 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
256 BotConfig.register BotConfigIntegerValue.new('log.keep',
257 :default => 1, :requires_restart => true,
258 :validate => Proc.new { |v| v >= 0 },
259 :desc => "How many old console messages logfiles to keep")
260 BotConfig.register BotConfigIntegerValue.new('log.max_size',
261 :default => 10, :requires_restart => true,
262 :validate => Proc.new { |v| v > 0 },
263 :desc => "Maximum console messages logfile size (in megabytes)")
265 BotConfig.register BotConfigArrayValue.new('plugins.path',
266 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
267 :requires_restart => false,
268 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
269 :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")
271 BotConfig.register BotConfigEnumValue.new('send.newlines',
272 :values => ['split', 'join'], :default => 'split',
273 :on_change => Proc.new { |bot, v|
274 bot.set_default_send_options :newlines => v.to_sym
276 :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")
277 BotConfig.register BotConfigStringValue.new('send.join_with',
279 :on_change => Proc.new { |bot, v|
280 bot.set_default_send_options :join_with => v.dup
282 :desc => "String used to replace newlines when send.newlines is set to join")
283 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
285 :validate => Proc.new { |v| v >= 0 },
286 :on_change => Proc.new { |bot, v|
287 bot.set_default_send_options :max_lines => v
289 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
290 BotConfig.register BotConfigEnumValue.new('send.overlong',
291 :values => ['split', 'truncate'], :default => 'split',
292 :on_change => Proc.new { |bot, v|
293 bot.set_default_send_options :overlong => v.to_sym
295 :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")
296 BotConfig.register BotConfigStringValue.new('send.split_at',
298 :on_change => Proc.new { |bot, v|
299 bot.set_default_send_options :split_at => Regexp.new(v)
301 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
302 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
304 :on_change => Proc.new { |bot, v|
305 bot.set_default_send_options :purge_split => v
307 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
308 BotConfig.register BotConfigStringValue.new('send.truncate_text',
309 :default => "#{Reverse}...#{Reverse}",
310 :on_change => Proc.new { |bot, v|
311 bot.set_default_send_options :truncate_text => v.dup
313 :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")
315 @argv = params[:argv]
316 @run_dir = params[:run_dir] || Dir.pwd
318 unless FileTest.directory? Config::coredir
319 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
323 unless FileTest.directory? Config::datadir
324 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
328 unless botclass and not botclass.empty?
329 # We want to find a sensible default.
330 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
331 # * On Windows (at least the NT versions) we want to put our stuff in the
332 # Application Data folder.
333 # We don't use any particular O/S detection magic, exploiting the fact that
334 # Etc.getpwuid is nil on Windows
335 if Etc.getpwuid(Process::Sys.geteuid)
336 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
338 if ENV.has_key?('APPDATA')
339 botclass = ENV['APPDATA'].dup
340 botclass.gsub!("\\","/")
345 botclass = File.expand_path(botclass)
346 @botclass = botclass.gsub(/\/$/, "")
348 unless FileTest.directory? botclass
349 log "no #{botclass} directory found, creating from templates.."
350 if FileTest.exist? botclass
351 error "file #{botclass} exists but isn't a directory"
354 FileUtils.cp_r Config::datadir+'/templates', botclass
357 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
358 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
359 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
361 # Time at which the last PING was sent
363 # Time at which the last line was RECV'd from the server
366 @startup_time = Time.new
369 @config = BotConfig.configmanager
370 @config.bot_associate(self)
371 rescue Exception => e
377 if @config['core.run_as_daemon']
381 @logfile = @config['log.file']
382 if @logfile.class!=String || @logfile.empty?
383 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
386 # See http://blog.humlab.umu.se/samuel/archives/000107.html
387 # for the backgrounding code
393 rescue NotImplementedError
394 warning "Could not background, fork not supported"
397 rescue Exception => e
398 warning "Could not background. #{e.pretty_inspect}"
401 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
402 log "Redirecting standard input/output/error"
404 STDIN.reopen "/dev/null"
406 # On Windows, there's not such thing as /dev/null
409 def STDOUT.write(str=nil)
413 def STDERR.write(str=nil)
414 if str.to_s.match(/:\d+: warning:/)
423 # Set the new logfile and loglevel. This must be done after the daemonizing
424 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
425 $logger.datetime_format= $dateformat
426 $logger.level = @config['log.level']
427 $logger.level = $cl_loglevel if $cl_loglevel
428 $logger.level = 0 if $debug
432 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
436 @registry = BotRegistry.new self
438 @timer = Timer::Timer.new(1.0) # only need per-second granularity
439 @save_mutex = Mutex.new
440 if @config['core.save_every'] > 0
441 @save_timer = @timer.add(@config['core.save_every']) { save }
445 @quit_mutex = Mutex.new
450 @lang = Language::Language.new(self, @config['core.language'])
453 @auth = Auth::authmanager
454 @auth.bot_associate(self)
455 # @auth.load("#{botclass}/botusers.yaml")
456 rescue Exception => e
461 @auth.everyone.set_default_permission("*", true)
462 @auth.botowner.password= @config['auth.password']
464 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
465 @plugins = Plugins::manager
466 @plugins.bot_associate(self)
469 if @config['server.name']
470 debug "upgrading configuration (server.name => server.list)"
471 srv_uri = 'irc://' + @config['server.name']
472 srv_uri += ":#{@config['server.port']}" if @config['server.port']
473 @config.items['server.list'.to_sym].set_string(srv_uri)
474 @config.delete('server.name'.to_sym)
475 @config.delete('server.port'.to_sym)
476 debug "server.list is now #{@config['server.list'].inspect}"
479 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
484 # Channels where we are quiet
485 # Array of channels names where the bot should be quiet
486 # '*' means all channels
490 @client[:welcome] = proc {|data|
491 irclog "joined server #{@client.server} as #{myself}", "server"
493 @plugins.delegate("connect")
495 @config['irc.join_channels'].each { |c|
496 debug "autojoining channel #{c}"
497 if(c =~ /^(\S+)\s+(\S+)$/i)
505 # TODO the next two @client should go into rfc2812.rb, probably
506 # Since capabs are two-steps processes, server.supports[:capab]
507 # should be a three-state: nil, [], [....]
508 asked_for = { :"identify-msg" => false }
509 @client[:isupport] = proc { |data|
510 if server.supports[:capab] and !asked_for[:"identify-msg"]
511 sendq "CAPAB IDENTIFY-MSG"
512 asked_for[:"identify-msg"] = true
515 @client[:datastr] = proc { |data|
516 if data[:text] == "IDENTIFY-MSG"
517 server.capabilities[:"identify-msg"] = true
519 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
523 @client[:privmsg] = proc { |data|
524 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
525 # debug "Message source is #{data[:source].inspect}"
526 # debug "Message target is #{data[:target].inspect}"
527 # debug "Bot is #{myself.inspect}"
530 @config['irc.ignore_users'].each { |mask|
531 if m.source.matches?(server.new_netmask(mask))
540 @plugins.delegate "listen", m
541 @plugins.privmsg(m) if m.address?
543 @plugins.delegate "unreplied", m
547 @client[:notice] = proc { |data|
548 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
549 # pass it off to plugins that want to hear everything
550 @plugins.delegate "listen", message
552 @client[:motd] = proc { |data|
553 data[:motd].each_line { |line|
554 irclog "MOTD: #{line}", "server"
557 @client[:nicktaken] = proc { |data|
558 new = "#{data[:nick]}_"
560 # If we're setting our nick at connection because our choice was taken,
561 # we have to fix our nick manually, because there will be no NICK message
562 # to inform us that our nick has been changed.
563 if data[:target] == '*'
564 debug "setting my connection nick to #{new}"
567 @plugins.delegate "nicktaken", data[:nick]
569 @client[:badnick] = proc {|data|
570 arning "bad nick (#{data[:nick]})"
572 @client[:ping] = proc {|data|
573 sendq "PONG #{data[:pingid]}"
575 @client[:pong] = proc {|data|
578 @client[:nick] = proc {|data|
579 # debug "Message source is #{data[:source].inspect}"
580 # debug "Bot is #{myself.inspect}"
581 source = data[:source]
584 m = NickMessage.new(self, server, source, old, new)
586 debug "my nick is now #{new}"
588 data[:is_on].each { |ch|
589 irclog "@ #{old} is now known as #{new}", ch
591 @plugins.delegate("listen", m)
592 @plugins.delegate("nick", m)
594 @client[:quit] = proc {|data|
595 source = data[:source]
596 message = data[:message]
597 m = QuitMessage.new(self, server, source, source, message)
598 data[:was_on].each { |ch|
599 irclog "@ Quit: #{source}: #{message}", ch
601 @plugins.delegate("listen", m)
602 @plugins.delegate("quit", m)
604 @client[:mode] = proc {|data|
605 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
607 @client[:join] = proc {|data|
608 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
611 @plugins.delegate("listen", m)
612 @plugins.delegate("join", m)
614 @client[:part] = proc {|data|
615 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
618 @plugins.delegate("listen", m)
619 @plugins.delegate("part", m)
621 @client[:kick] = proc {|data|
622 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
625 @plugins.delegate("listen", m)
626 @plugins.delegate("kick", m)
628 @client[:invite] = proc {|data|
629 if data[:target] == myself
630 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
633 @client[:changetopic] = proc {|data|
634 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
637 @plugins.delegate("listen", m)
638 @plugins.delegate("topic", m)
640 @client[:topic] = proc { |data|
641 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
643 @client[:topicinfo] = proc { |data|
644 channel = data[:channel]
645 topic = channel.topic
646 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
647 m = TopicMessage.new(self, server, data[:source], channel, topic)
649 @plugins.delegate("listen", m)
650 @plugins.delegate("topic", m)
652 @client[:names] = proc { |data|
653 @plugins.delegate "names", data[:channel], data[:users]
655 @client[:unknown] = proc { |data|
656 #debug "UNKNOWN: #{data[:serverstring]}"
657 irclog data[:serverstring], ".unknown"
660 set_default_send_options :newlines => @config['send.newlines'].to_sym,
661 :join_with => @config['send.join_with'].dup,
662 :max_lines => @config['send.max_lines'],
663 :overlong => @config['send.overlong'].to_sym,
664 :split_at => Regexp.new(@config['send.split_at']),
665 :purge_split => @config['send.purge_split'],
666 :truncate_text => @config['send.truncate_text'].dup
669 def setup_plugins_path
670 @plugins.clear_botmodule_dirs
671 @plugins.add_botmodule_dir(Config::coredir + "/utils")
672 @plugins.add_botmodule_dir(Config::coredir)
673 @plugins.add_botmodule_dir("#{botclass}/plugins")
675 @config['plugins.path'].each do |_|
676 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
677 @plugins.add_botmodule_dir(path)
681 def set_default_send_options(opts={})
682 # Default send options for NOTICE and PRIVMSG
683 unless defined? @default_send_options
684 @default_send_options = {
685 :queue_channel => nil, # use default queue channel
686 :queue_ring => nil, # use default queue ring
687 :newlines => :split, # or :join
688 :join_with => ' ', # by default, use a single space
689 :max_lines => 0, # maximum number of lines to send with a single command
690 :overlong => :split, # or :truncate
691 # TODO an array of splitpoints would be preferrable for this option:
692 :split_at => /\s+/, # by default, split overlong lines at whitespace
693 :purge_split => true, # should the split string be removed?
694 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
697 @default_send_options.update opts unless opts.empty?
700 # checks if we should be quiet on a channel
701 def quiet_on?(channel)
702 return @quiet.include?('*') || @quiet.include?(channel.downcase)
705 def set_quiet(channel)
707 ch = channel.downcase.dup
708 @quiet << ch unless @quiet.include?(ch)
715 def reset_quiet(channel)
717 @quiet.delete channel.downcase
723 # things to do when we receive a signal
725 debug "received #{sig}, queueing quit"
727 quit unless @quit_mutex.locked?
728 debug "interrupted #{$interrupted} times"
736 # connect the bot to IRC
739 trap("SIGINT") { got_sig("SIGINT") }
740 trap("SIGTERM") { got_sig("SIGTERM") }
741 trap("SIGHUP") { got_sig("SIGHUP") }
742 rescue ArgumentError => e
743 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
744 rescue Exception => e
745 debug "failed to trap signals: #{e.pretty_inspect}"
748 quit if $interrupted > 0
751 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
753 quit if $interrupted > 0
755 realname = @config['irc.name'].clone || 'Ruby bot'
756 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
758 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
759 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
760 quit if $interrupted > 0
761 myself.nick = @config['irc.nick']
762 myself.user = @config['irc.user']
765 # begin event handling loop
769 quit if $interrupted > 0
774 while @socket.connected?
775 quit if $interrupted > 0
777 # Wait for messages and process them as they arrive. If nothing is
778 # received, we call the ping_server() method that will PING the
779 # server if appropriate, or raise a TimeoutError if no PONG has been
780 # received in the user-chosen timeout since the last PING sent.
782 break unless reply = @socket.gets
784 @client.process reply
790 # I despair of this. Some of my users get "connection reset by peer"
791 # exceptions that ARENT SocketError's. How am I supposed to handle
796 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
797 error "network exception: #{e.pretty_inspect}"
799 rescue BDB::Fatal => e
800 fatal "fatal bdb error: #{e.pretty_inspect}"
802 # Why restart? DB problems are serious stuff ...
803 # restart("Oops, we seem to have registry problems ...")
806 rescue Exception => e
807 error "non-net exception: #{e.pretty_inspect}"
810 fatal "unexpected exception: #{e.pretty_inspect}"
817 log "\n\nDisconnected\n\n"
819 quit if $interrupted > 0
821 log "\n\nWaiting to reconnect\n\n"
822 sleep @config['server.reconnect_wait']
826 # type:: message type
827 # where:: message target
828 # message:: message text
829 # send message +message+ of type +type+ to target +where+
830 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
831 # relevant say() or notice() methods. This one should be used for IRCd
832 # extensions you want to use in modules.
833 def sendmsg(type, where, original_message, options={})
834 opts = @default_send_options.merge(options)
836 # For starters, set up appropriate queue channels and rings
837 mchan = opts[:queue_channel]
838 mring = opts[:queue_ring]
855 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
859 messages << [multi_line.gsub("\n", opts[:join_with])]
861 multi_line.each_line { |line|
863 next unless(line.size > 0)
867 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
870 # The IRC protocol requires that each raw message must be not longer
871 # than 512 characters. From this length with have to subtract the EOL
872 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
873 # that will be prepended by the server to all of our messages.
875 # The maximum raw message length we can send is therefore 512 - 2 - 2
876 # minus the length of our hostmask.
878 max_len = 508 - myself.fullform.size
880 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
881 # will have a + or - prepended
882 if server.capabilities[:"identify-msg"]
886 # When splitting the message, we'll be prefixing the following string:
887 # (e.g. "PRIVMSG #rbot :")
888 fixed = "#{type} #{where} :"
890 # And this is what's left
891 left = max_len - fixed.size
893 truncate = opts[:truncate_text]
894 truncate = @default_send_options[:truncate_text] if truncate.size > left
895 truncate = "" if truncate.size > left
897 all_lines = messages.map { |line|
904 sub_lines = Array.new
906 sub_lines << msg.slice!(0, left)
908 lastspace = sub_lines.last.rindex(opts[:split_at])
910 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
911 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
916 line.slice(0, left - truncate.size) << truncate
918 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
923 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
924 lines = all_lines[0...opts[:max_lines]]
925 new_last = lines.last.slice(0, left - truncate.size) << truncate
926 lines.last.replace(new_last)
932 sendq "#{fixed}#{line}", chan, ring
933 log_sent(type, where, line)
937 # queue an arbitraty message for the server
938 def sendq(message="", chan=nil, ring=0)
940 @socket.queue(message, chan, ring)
943 # send a notice message to channel/nick +where+
944 def notice(where, message, options={})
945 return if where.kind_of?(Channel) and quiet_on?(where)
946 sendmsg "NOTICE", where, message, options
949 # say something (PRIVMSG) to channel/nick +where+
950 def say(where, message, options={})
951 return if where.kind_of?(Channel) and quiet_on?(where)
952 sendmsg "PRIVMSG", where, message, options
955 # perform a CTCP action with message +message+ to channel/nick +where+
956 def action(where, message, options={})
957 return if where.kind_of?(Channel) and quiet_on?(where)
958 mchan = options.fetch(:queue_channel, nil)
959 mring = options.fetch(:queue_ring, nil)
975 # FIXME doesn't check message length. Can we make this exploit sendmsg?
976 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
979 irclog "* #{myself} #{message}", where
981 irclog "* #{myself}[#{where}] #{message}", where
985 # quick way to say "okay" (or equivalent) to +where+
987 say where, @lang.get("okay")
990 # log IRC-related message +message+ to a file determined by +where+.
991 # +where+ can be a channel name, or a nick for private message logging
992 def irclog(message, where="server")
993 message = message.chomp
994 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
995 if where.class <= Server
998 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
1000 unless(@logs.has_key?(where_str))
1001 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
1002 @logs[where_str].sync = true
1004 @logs[where_str].puts "[#{stamp}] #{message}"
1005 #debug "[#{stamp}] <#{where}> #{message}"
1008 # set topic of channel +where+ to +topic+
1009 def topic(where, topic)
1010 sendq "TOPIC #{where} :#{topic}", where, 2
1013 def disconnect(message = nil)
1014 message = @lang.get("quit") if (message.nil? || message.empty?)
1015 if @socket.connected?
1016 debug "Clearing socket"
1018 debug "Sending quit message"
1019 @socket.emergency_puts "QUIT :#{message}"
1020 debug "Flushing socket"
1022 debug "Shutting down socket"
1025 debug "Logging quits"
1026 server.channels.each { |ch|
1027 irclog "@ quit (#{message})", ch
1033 # disconnect from the server and cleanup all plugins and modules
1034 def shutdown(message = nil)
1035 @quit_mutex.synchronize do
1036 debug "Shutting down:"
1037 ## No we don't restore them ... let everything run through
1039 # trap("SIGINT", "DEFAULT")
1040 # trap("SIGTERM", "DEFAULT")
1041 # trap("SIGHUP", "DEFAULT")
1043 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1045 debug "\tdisconnecting..."
1047 debug "\tsaving ..."
1049 debug "\tcleaning up ..."
1050 @save_mutex.synchronize do
1053 debug "\tstopping timers ..."
1055 # debug "Closing registries"
1057 debug "\t\tcleaning up the db environment ..."
1059 log "rbot quit (#{message})"
1063 # message:: optional IRC quit message
1064 # quit IRC, shutdown the bot
1065 def quit(message=nil)
1073 # totally shutdown and respawn the bot
1074 def restart(message = false)
1075 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1077 sleep @config['server.reconnect_wait']
1080 # Note, this fails on Windows
1081 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1084 rescue Errno::ENOENT
1085 exec("ruby", *(@argv.unshift $0))
1086 rescue Exception => e
1092 # call the save method for all of the botmodules
1094 @save_mutex.synchronize do
1100 # call the rescan method for all of the botmodules
1102 @save_mutex.synchronize do
1108 # channel:: channel to join
1109 # key:: optional channel key if channel is +s
1111 def join(channel, key=nil)
1113 sendq "JOIN #{channel} :#{key}", channel, 2
1115 sendq "JOIN #{channel}", channel, 2
1120 def part(channel, message="")
1121 sendq "PART #{channel} :#{message}", channel, 2
1124 # attempt to change bot's nick to +name+
1126 sendq "NICK #{name}"
1130 def mode(channel, mode, target)
1131 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1135 def kick(channel, user, msg)
1136 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1139 # m:: message asking for help
1140 # topic:: optional topic help is requested for
1141 # respond to online help requests
1143 topic = nil if topic == ""
1146 helpstr = "help topics: "
1147 helpstr += @plugins.helptopics
1148 helpstr += " (help <topic> for more info)"
1150 unless(helpstr = @plugins.help(topic))
1151 helpstr = "no help for topic #{topic}"
1157 # returns a string describing the current status of the bot (uptime etc)
1159 secs_up = Time.new - @startup_time
1160 uptime = Utils.secs_to_string secs_up
1161 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1162 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1165 # We want to respond to a hung server in a timely manner. If nothing was received
1166 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1167 # the server. If the PONG is not received within the user-defined timeout, we
1168 # assume we're in ping timeout and act accordingly.
1170 act_timeout = @config['server.ping_timeout']
1171 return if act_timeout <= 0
1173 if @last_rec && now > @last_rec + act_timeout
1175 # No previous PING pending, send a new one
1177 @last_ping = Time.now
1179 diff = now - @last_ping
1180 if diff > act_timeout
1181 debug "no PONG from server in #{diff} seconds, reconnecting"
1182 # the actual reconnect is handled in the main loop:
1183 raise TimeoutError, "no PONG from server in #{diff} seconds"
1189 def stop_server_pings
1190 # cancel previous PINGs and reset time of last RECV
1197 def irclogprivmsg(m)
1200 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1202 irclog "* #{m.source} #{m.message}", m.target
1206 irclog "<#{m.source}> #{m.message}", m.target
1208 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1213 # log a message. Internal use only.
1214 def log_sent(type, where, message)
1219 irclog "-=#{myself}=- #{message}", where
1221 irclog "[-=#{where}=-] #{message}", where
1226 irclog "<#{myself}> #{message}", where
1228 irclog "[msg(#{where})] #{message}", where
1235 debug "joined channel #{m.channel}"
1236 irclog "@ Joined channel #{m.channel}", m.channel
1238 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1244 debug "left channel #{m.channel}"
1245 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1247 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1253 debug "kicked from channel #{m.channel}"
1254 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1256 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1261 if m.source == myself
1262 irclog "@ I set topic \"#{m.topic}\"", m.channel
1264 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel