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 @registry = BotRegistry.new self
434 @timer = Timer::Timer.new(1.0) # only need per-second granularity
435 @save_mutex = Mutex.new
436 if @config['core.save_every'] > 0
437 @save_timer = @timer.add(@config['core.save_every']) { save }
441 @quit_mutex = Mutex.new
446 @lang = Language::Language.new(self, @config['core.language'])
449 @auth = Auth::authmanager
450 @auth.bot_associate(self)
451 # @auth.load("#{botclass}/botusers.yaml")
452 rescue Exception => e
457 @auth.everyone.set_default_permission("*", true)
458 @auth.botowner.password= @config['auth.password']
460 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
461 @plugins = Plugins::manager
462 @plugins.bot_associate(self)
465 if @config['server.name']
466 debug "upgrading configuration (server.name => server.list)"
467 srv_uri = 'irc://' + @config['server.name']
468 srv_uri += ":#{@config['server.port']}" if @config['server.port']
469 @config.items['server.list'.to_sym].set_string(srv_uri)
470 @config.delete('server.name'.to_sym)
471 @config.delete('server.port'.to_sym)
472 debug "server.list is now #{@config['server.list'].inspect}"
475 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
480 # Channels where we are quiet
481 # Array of channels names where the bot should be quiet
482 # '*' means all channels
486 @client[:welcome] = proc {|data|
487 irclog "joined server #{@client.server} as #{myself}", "server"
489 @plugins.delegate("connect")
491 @config['irc.join_channels'].each { |c|
492 debug "autojoining channel #{c}"
493 if(c =~ /^(\S+)\s+(\S+)$/i)
501 # TODO the next two @client should go into rfc2812.rb, probably
502 # Since capabs are two-steps processes, server.supports[:capab]
503 # should be a three-state: nil, [], [....]
504 asked_for = { :"identify-msg" => false }
505 @client[:isupport] = proc { |data|
506 if server.supports[:capab] and !asked_for[:"identify-msg"]
507 sendq "CAPAB IDENTIFY-MSG"
508 asked_for[:"identify-msg"] = true
511 @client[:datastr] = proc { |data|
512 if data[:text] == "IDENTIFY-MSG"
513 server.capabilities[:"identify-msg"] = true
515 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
519 @client[:privmsg] = proc { |data|
520 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
521 # debug "Message source is #{data[:source].inspect}"
522 # debug "Message target is #{data[:target].inspect}"
523 # debug "Bot is #{myself.inspect}"
526 @config['irc.ignore_users'].each { |mask|
527 if m.source.matches?(server.new_netmask(mask))
536 @plugins.delegate "listen", m
537 @plugins.privmsg(m) if m.address?
539 @plugins.delegate "unreplied", m
543 @client[:notice] = proc { |data|
544 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
545 # pass it off to plugins that want to hear everything
546 @plugins.delegate "listen", message
548 @client[:motd] = proc { |data|
549 data[:motd].each_line { |line|
550 irclog "MOTD: #{line}", "server"
553 @client[:nicktaken] = proc { |data|
554 new = "#{data[:nick]}_"
556 # If we're setting our nick at connection because our choice was taken,
557 # we have to fix our nick manually, because there will be no NICK message
558 # to inform us that our nick has been changed.
559 if data[:target] == '*'
560 debug "setting my connection nick to #{new}"
563 @plugins.delegate "nicktaken", data[:nick]
565 @client[:badnick] = proc {|data|
566 arning "bad nick (#{data[:nick]})"
568 @client[:ping] = proc {|data|
569 sendq "PONG #{data[:pingid]}"
571 @client[:pong] = proc {|data|
574 @client[:nick] = proc {|data|
575 # debug "Message source is #{data[:source].inspect}"
576 # debug "Bot is #{myself.inspect}"
577 source = data[:source]
580 m = NickMessage.new(self, server, source, old, new)
582 debug "my nick is now #{new}"
584 data[:is_on].each { |ch|
585 irclog "@ #{old} is now known as #{new}", ch
587 @plugins.delegate("listen", m)
588 @plugins.delegate("nick", m)
590 @client[:quit] = proc {|data|
591 source = data[:source]
592 message = data[:message]
593 m = QuitMessage.new(self, server, source, source, message)
594 data[:was_on].each { |ch|
595 irclog "@ Quit: #{source}: #{message}", ch
597 @plugins.delegate("listen", m)
598 @plugins.delegate("quit", m)
600 @client[:mode] = proc {|data|
601 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
603 @client[:join] = proc {|data|
604 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
607 @plugins.delegate("listen", m)
608 @plugins.delegate("join", m)
610 @client[:part] = proc {|data|
611 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
614 @plugins.delegate("listen", m)
615 @plugins.delegate("part", m)
617 @client[:kick] = proc {|data|
618 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
621 @plugins.delegate("listen", m)
622 @plugins.delegate("kick", m)
624 @client[:invite] = proc {|data|
625 if data[:target] == myself
626 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
629 @client[:changetopic] = proc {|data|
630 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
633 @plugins.delegate("listen", m)
634 @plugins.delegate("topic", m)
636 @client[:topic] = proc { |data|
637 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
639 @client[:topicinfo] = proc { |data|
640 channel = data[:channel]
641 topic = channel.topic
642 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
643 m = TopicMessage.new(self, server, data[:source], channel, topic)
645 @plugins.delegate("listen", m)
646 @plugins.delegate("topic", m)
648 @client[:names] = proc { |data|
649 @plugins.delegate "names", data[:channel], data[:users]
651 @client[:unknown] = proc { |data|
652 #debug "UNKNOWN: #{data[:serverstring]}"
653 irclog data[:serverstring], ".unknown"
656 set_default_send_options :newlines => @config['send.newlines'].to_sym,
657 :join_with => @config['send.join_with'].dup,
658 :max_lines => @config['send.max_lines'],
659 :overlong => @config['send.overlong'].to_sym,
660 :split_at => Regexp.new(@config['send.split_at']),
661 :purge_split => @config['send.purge_split'],
662 :truncate_text => @config['send.truncate_text'].dup
665 def setup_plugins_path
666 @plugins.clear_botmodule_dirs
667 @plugins.add_botmodule_dir(Config::coredir + "/utils")
668 @plugins.add_botmodule_dir(Config::coredir)
669 @plugins.add_botmodule_dir("#{botclass}/plugins")
671 @config['plugins.path'].each do |_|
672 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
673 @plugins.add_botmodule_dir(path)
677 def set_default_send_options(opts={})
678 # Default send options for NOTICE and PRIVMSG
679 unless defined? @default_send_options
680 @default_send_options = {
681 :queue_channel => nil, # use default queue channel
682 :queue_ring => nil, # use default queue ring
683 :newlines => :split, # or :join
684 :join_with => ' ', # by default, use a single space
685 :max_lines => 0, # maximum number of lines to send with a single command
686 :overlong => :split, # or :truncate
687 # TODO an array of splitpoints would be preferrable for this option:
688 :split_at => /\s+/, # by default, split overlong lines at whitespace
689 :purge_split => true, # should the split string be removed?
690 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
693 @default_send_options.update opts unless opts.empty?
696 # checks if we should be quiet on a channel
697 def quiet_on?(channel)
698 return @quiet.include?('*') || @quiet.include?(channel.downcase)
701 def set_quiet(channel)
703 ch = channel.downcase.dup
704 @quiet << ch unless @quiet.include?(ch)
711 def reset_quiet(channel)
713 @quiet.delete channel.downcase
719 # things to do when we receive a signal
721 debug "received #{sig}, queueing quit"
723 quit unless @quit_mutex.locked?
724 debug "interrupted #{$interrupted} times"
732 # connect the bot to IRC
735 trap("SIGINT") { got_sig("SIGINT") }
736 trap("SIGTERM") { got_sig("SIGTERM") }
737 trap("SIGHUP") { got_sig("SIGHUP") }
738 rescue ArgumentError => e
739 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
740 rescue Exception => e
741 debug "failed to trap signals: #{e.pretty_inspect}"
744 quit if $interrupted > 0
747 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
749 quit if $interrupted > 0
751 realname = @config['irc.name'].clone || 'Ruby bot'
752 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
754 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
755 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
756 quit if $interrupted > 0
757 myself.nick = @config['irc.nick']
758 myself.user = @config['irc.user']
761 # begin event handling loop
765 quit if $interrupted > 0
770 while @socket.connected?
771 quit if $interrupted > 0
773 # Wait for messages and process them as they arrive. If nothing is
774 # received, we call the ping_server() method that will PING the
775 # server if appropriate, or raise a TimeoutError if no PONG has been
776 # received in the user-chosen timeout since the last PING sent.
778 break unless reply = @socket.gets
780 @client.process reply
786 # I despair of this. Some of my users get "connection reset by peer"
787 # exceptions that ARENT SocketError's. How am I supposed to handle
792 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
793 error "network exception: #{e.pretty_inspect}"
795 rescue BDB::Fatal => e
796 fatal "fatal bdb error: #{e.pretty_inspect}"
798 # Why restart? DB problems are serious stuff ...
799 # restart("Oops, we seem to have registry problems ...")
802 rescue Exception => e
803 error "non-net exception: #{e.pretty_inspect}"
806 fatal "unexpected exception: #{e.pretty_inspect}"
813 log "\n\nDisconnected\n\n"
815 quit if $interrupted > 0
817 log "\n\nWaiting to reconnect\n\n"
818 sleep @config['server.reconnect_wait']
822 # type:: message type
823 # where:: message target
824 # message:: message text
825 # send message +message+ of type +type+ to target +where+
826 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
827 # relevant say() or notice() methods. This one should be used for IRCd
828 # extensions you want to use in modules.
829 def sendmsg(type, where, original_message, options={})
830 opts = @default_send_options.merge(options)
832 # For starters, set up appropriate queue channels and rings
833 mchan = opts[:queue_channel]
834 mring = opts[:queue_ring]
851 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
855 messages << [multi_line.gsub("\n", opts[:join_with])]
857 multi_line.each_line { |line|
859 next unless(line.size > 0)
863 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
866 # The IRC protocol requires that each raw message must be not longer
867 # than 512 characters. From this length with have to subtract the EOL
868 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
869 # that will be prepended by the server to all of our messages.
871 # The maximum raw message length we can send is therefore 512 - 2 - 2
872 # minus the length of our hostmask.
874 max_len = 508 - myself.fullform.size
876 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
877 # will have a + or - prepended
878 if server.capabilities[:"identify-msg"]
882 # When splitting the message, we'll be prefixing the following string:
883 # (e.g. "PRIVMSG #rbot :")
884 fixed = "#{type} #{where} :"
886 # And this is what's left
887 left = max_len - fixed.size
889 truncate = opts[:truncate_text]
890 truncate = @default_send_options[:truncate_text] if truncate.size > left
891 truncate = "" if truncate.size > left
893 all_lines = messages.map { |line|
900 sub_lines = Array.new
902 sub_lines << msg.slice!(0, left)
904 lastspace = sub_lines.last.rindex(opts[:split_at])
906 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
907 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
912 line.slice(0, left - truncate.size) << truncate
914 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
919 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
920 lines = all_lines[0...opts[:max_lines]]
921 new_last = lines.last.slice(0, left - truncate.size) << truncate
922 lines.last.replace(new_last)
928 sendq "#{fixed}#{line}", chan, ring
929 log_sent(type, where, line)
933 # queue an arbitraty message for the server
934 def sendq(message="", chan=nil, ring=0)
936 @socket.queue(message, chan, ring)
939 # send a notice message to channel/nick +where+
940 def notice(where, message, options={})
941 return if where.kind_of?(Channel) and quiet_on?(where)
942 sendmsg "NOTICE", where, message, options
945 # say something (PRIVMSG) to channel/nick +where+
946 def say(where, message, options={})
947 return if where.kind_of?(Channel) and quiet_on?(where)
948 sendmsg "PRIVMSG", where, message, options
951 # perform a CTCP action with message +message+ to channel/nick +where+
952 def action(where, message, options={})
953 return if where.kind_of?(Channel) and quiet_on?(where)
954 mchan = options.fetch(:queue_channel, nil)
955 mring = options.fetch(:queue_ring, nil)
971 # FIXME doesn't check message length. Can we make this exploit sendmsg?
972 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
975 irclog "* #{myself} #{message}", where
977 irclog "* #{myself}[#{where}] #{message}", where
981 # quick way to say "okay" (or equivalent) to +where+
983 say where, @lang.get("okay")
986 # log IRC-related message +message+ to a file determined by +where+.
987 # +where+ can be a channel name, or a nick for private message logging
988 def irclog(message, where="server")
989 message = message.chomp
990 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
991 if where.class <= Server
994 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
996 unless(@logs.has_key?(where_str))
997 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
998 @logs[where_str].sync = true
1000 @logs[where_str].puts "[#{stamp}] #{message}"
1001 #debug "[#{stamp}] <#{where}> #{message}"
1004 # set topic of channel +where+ to +topic+
1005 def topic(where, topic)
1006 sendq "TOPIC #{where} :#{topic}", where, 2
1009 def disconnect(message = nil)
1010 message = @lang.get("quit") if (message.nil? || message.empty?)
1011 if @socket.connected?
1012 debug "Clearing socket"
1014 debug "Sending quit message"
1015 @socket.emergency_puts "QUIT :#{message}"
1016 debug "Flushing socket"
1018 debug "Shutting down socket"
1021 debug "Logging quits"
1022 server.channels.each { |ch|
1023 irclog "@ quit (#{message})", ch
1029 # disconnect from the server and cleanup all plugins and modules
1030 def shutdown(message = nil)
1031 @quit_mutex.synchronize do
1032 debug "Shutting down:"
1033 ## No we don't restore them ... let everything run through
1035 # trap("SIGINT", "DEFAULT")
1036 # trap("SIGTERM", "DEFAULT")
1037 # trap("SIGHUP", "DEFAULT")
1039 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1041 debug "\tdisconnecting..."
1043 debug "\tsaving ..."
1045 debug "\tcleaning up ..."
1046 @save_mutex.synchronize do
1049 debug "\tstopping timers ..."
1051 # debug "Closing registries"
1053 debug "\t\tcleaning up the db environment ..."
1055 log "rbot quit (#{message})"
1059 # message:: optional IRC quit message
1060 # quit IRC, shutdown the bot
1061 def quit(message=nil)
1069 # totally shutdown and respawn the bot
1070 def restart(message = false)
1071 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1073 sleep @config['server.reconnect_wait']
1076 # Note, this fails on Windows
1077 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1080 rescue Errno::ENOENT
1081 exec("ruby", *(@argv.unshift $0))
1082 rescue Exception => e
1088 # call the save method for all of the botmodules
1090 @save_mutex.synchronize do
1096 # call the rescan method for all of the botmodules
1098 @save_mutex.synchronize do
1104 # channel:: channel to join
1105 # key:: optional channel key if channel is +s
1107 def join(channel, key=nil)
1109 sendq "JOIN #{channel} :#{key}", channel, 2
1111 sendq "JOIN #{channel}", channel, 2
1116 def part(channel, message="")
1117 sendq "PART #{channel} :#{message}", channel, 2
1120 # attempt to change bot's nick to +name+
1122 sendq "NICK #{name}"
1126 def mode(channel, mode, target)
1127 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1131 def kick(channel, user, msg)
1132 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1135 # m:: message asking for help
1136 # topic:: optional topic help is requested for
1137 # respond to online help requests
1139 topic = nil if topic == ""
1142 helpstr = "help topics: "
1143 helpstr += @plugins.helptopics
1144 helpstr += " (help <topic> for more info)"
1146 unless(helpstr = @plugins.help(topic))
1147 helpstr = "no help for topic #{topic}"
1153 # returns a string describing the current status of the bot (uptime etc)
1155 secs_up = Time.new - @startup_time
1156 uptime = Utils.secs_to_string secs_up
1157 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1158 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1161 # We want to respond to a hung server in a timely manner. If nothing was received
1162 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1163 # the server. If the PONG is not received within the user-defined timeout, we
1164 # assume we're in ping timeout and act accordingly.
1166 act_timeout = @config['server.ping_timeout']
1167 return if act_timeout <= 0
1169 if @last_rec && now > @last_rec + act_timeout
1171 # No previous PING pending, send a new one
1173 @last_ping = Time.now
1175 diff = now - @last_ping
1176 if diff > act_timeout
1177 debug "no PONG from server in #{diff} seconds, reconnecting"
1178 # the actual reconnect is handled in the main loop:
1179 raise TimeoutError, "no PONG from server in #{diff} seconds"
1185 def stop_server_pings
1186 # cancel previous PINGs and reset time of last RECV
1193 def irclogprivmsg(m)
1196 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1198 irclog "* #{m.source} #{m.message}", m.target
1202 irclog "<#{m.source}> #{m.message}", m.target
1204 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1209 # log a message. Internal use only.
1210 def log_sent(type, where, message)
1215 irclog "-=#{myself}=- #{message}", where
1217 irclog "[-=#{where}=-] #{message}", where
1222 irclog "<#{myself}> #{message}", where
1224 irclog "[msg(#{where})] #{message}", where
1231 debug "joined channel #{m.channel}"
1232 irclog "@ Joined channel #{m.channel}", m.channel
1234 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1240 debug "left channel #{m.channel}"
1241 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1243 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1249 debug "kicked from channel #{m.channel}"
1250 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1252 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1257 if m.source == myself
1258 irclog "@ I set topic \"#{m.topic}\"", m.channel
1260 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel