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 q.seplist(self.backtrace, lambda { "\n" }) { |v| v } if self.backtrace
38 def rawlog(level, message=nil, who_pos=1)
40 if call_stack.length > who_pos
41 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
45 # Output each line. To distinguish between separate messages and multi-line
46 # messages originating at the same time, we blank #{who} after the first message
48 # Also, we output strings as-is but for other objects we use pretty_inspect
53 str = message.pretty_inspect
56 $logger.add(level, l.chomp, who)
62 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
66 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
69 def debug(message=nil, who_pos=1)
70 rawlog(Logger::Severity::DEBUG, message, who_pos)
73 def log(message=nil, who_pos=1)
74 rawlog(Logger::Severity::INFO, message, who_pos)
77 def warning(message=nil, who_pos=1)
78 rawlog(Logger::Severity::WARN, message, who_pos)
81 def error(message=nil, who_pos=1)
82 rawlog(Logger::Severity::ERROR, message, who_pos)
85 def fatal(message=nil, who_pos=1)
86 rawlog(Logger::Severity::FATAL, message, who_pos)
91 warning "warning test"
95 # The following global is used for the improved signal handling.
99 require 'rbot/rbotconfig'
100 require 'rbot/load-gettext'
101 require 'rbot/config'
102 # require 'rbot/utils'
105 require 'rbot/rfc2812'
106 require 'rbot/ircsocket'
107 require 'rbot/botuser'
109 require 'rbot/plugins'
110 # require 'rbot/channel'
111 require 'rbot/message'
112 require 'rbot/language'
113 require 'rbot/dbhash'
114 require 'rbot/registry'
115 # require 'rbot/httputil'
119 # Main bot class, which manages the various components, receives messages,
120 # handles them or passes them to plugins, and contains core functionality.
122 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
123 # the bot's Auth data
126 # the bot's BotConfig data
129 # the botclass for this bot (determines configdir among other things)
130 attr_reader :botclass
132 # used to perform actions periodically (saves configuration once per minute
136 # synchronize with this mutex while touching permanent data files:
137 # saving, flushing, cleaning up ...
138 attr_reader :save_mutex
140 # bot's Language data
147 # bot's object registry, plugins get an interface to this for persistant
148 # storage (hash interface tied to a bdb file, plugins use Accessors to store
149 # and restore objects in their own namespaces.)
150 attr_reader :registry
152 # bot's plugins. This is an instance of class Plugins
155 # bot's httputil help object, for fetching resources via http. Sets up
156 # proxies etc as defined by the bot configuration/environment
157 attr_accessor :httputil
159 # server we are connected to
165 # bot User in the client/server connection
171 # bot User in the client/server connection
176 # create a new Bot with botclass +botclass+
177 def initialize(botclass, params = {})
178 # BotConfig for the core bot
179 # TODO should we split socket stuff into ircsocket, etc?
180 BotConfig.register BotConfigArrayValue.new('server.list',
181 :default => ['irc://localhost'], :wizard => true,
182 :requires_restart => true,
183 :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.")
184 BotConfig.register BotConfigBooleanValue.new('server.ssl',
185 :default => false, :requires_restart => true, :wizard => true,
186 :desc => "Use SSL to connect to this server?")
187 BotConfig.register BotConfigStringValue.new('server.password',
188 :default => false, :requires_restart => true,
189 :desc => "Password for connecting to this server (if required)",
191 BotConfig.register BotConfigStringValue.new('server.bindhost',
192 :default => false, :requires_restart => true,
193 :desc => "Specific local host or IP for the bot to bind to (if required)",
195 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
196 :default => 5, :validate => Proc.new{|v| v >= 0},
197 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
198 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
199 :default => 2.0, :validate => Proc.new{|v| v >= 0},
200 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
201 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
202 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
203 :default => 4, :validate => Proc.new{|v| v >= 0},
204 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
205 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
206 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
207 :default => 30, :validate => Proc.new{|v| v >= 0},
208 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
210 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
211 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
212 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
213 BotConfig.register BotConfigStringValue.new('irc.name',
214 :default => "Ruby bot", :requires_restart => true,
215 :desc => "IRC realname the bot should use")
216 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
217 :default => true, :requires_restart => true,
218 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
219 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
220 :requires_restart => true,
221 :desc => "local user the bot should appear to be", :wizard => true)
222 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
223 :default => [], :wizard => true,
224 :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'")
225 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
227 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
229 BotConfig.register BotConfigIntegerValue.new('core.save_every',
230 :default => 60, :validate => Proc.new{|v| v >= 0},
231 :on_change => Proc.new { |bot, v|
234 @timer.reschedule(@save_timer, v)
235 @timer.unblock(@save_timer)
237 @timer.block(@save_timer)
241 @save_timer = @timer.add(v) { bot.save }
243 # Nothing to do when v == 0
246 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
248 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
249 :default => false, :requires_restart => true,
250 :desc => "Should the bot run as a daemon?")
252 BotConfig.register BotConfigStringValue.new('log.file',
253 :default => false, :requires_restart => true,
254 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
255 BotConfig.register BotConfigIntegerValue.new('log.level',
256 :default => 1, :requires_restart => false,
257 :validate => Proc.new { |v| (0..5).include?(v) },
258 :on_change => Proc.new { |bot, v|
261 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
262 BotConfig.register BotConfigIntegerValue.new('log.keep',
263 :default => 1, :requires_restart => true,
264 :validate => Proc.new { |v| v >= 0 },
265 :desc => "How many old console messages logfiles to keep")
266 BotConfig.register BotConfigIntegerValue.new('log.max_size',
267 :default => 10, :requires_restart => true,
268 :validate => Proc.new { |v| v > 0 },
269 :desc => "Maximum console messages logfile size (in megabytes)")
271 BotConfig.register BotConfigArrayValue.new('plugins.path',
272 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
273 :requires_restart => false,
274 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
275 :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")
277 BotConfig.register BotConfigEnumValue.new('send.newlines',
278 :values => ['split', 'join'], :default => 'split',
279 :on_change => Proc.new { |bot, v|
280 bot.set_default_send_options :newlines => v.to_sym
282 :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")
283 BotConfig.register BotConfigStringValue.new('send.join_with',
285 :on_change => Proc.new { |bot, v|
286 bot.set_default_send_options :join_with => v.dup
288 :desc => "String used to replace newlines when send.newlines is set to join")
289 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
291 :validate => Proc.new { |v| v >= 0 },
292 :on_change => Proc.new { |bot, v|
293 bot.set_default_send_options :max_lines => v
295 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
296 BotConfig.register BotConfigEnumValue.new('send.overlong',
297 :values => ['split', 'truncate'], :default => 'split',
298 :on_change => Proc.new { |bot, v|
299 bot.set_default_send_options :overlong => v.to_sym
301 :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")
302 BotConfig.register BotConfigStringValue.new('send.split_at',
304 :on_change => Proc.new { |bot, v|
305 bot.set_default_send_options :split_at => Regexp.new(v)
307 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
308 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
310 :on_change => Proc.new { |bot, v|
311 bot.set_default_send_options :purge_split => v
313 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
314 BotConfig.register BotConfigStringValue.new('send.truncate_text',
315 :default => "#{Reverse}...#{Reverse}",
316 :on_change => Proc.new { |bot, v|
317 bot.set_default_send_options :truncate_text => v.dup
319 :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")
321 @argv = params[:argv]
322 @run_dir = params[:run_dir] || Dir.pwd
324 unless FileTest.directory? Config::coredir
325 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
329 unless FileTest.directory? Config::datadir
330 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
334 unless botclass and not botclass.empty?
335 # We want to find a sensible default.
336 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
337 # * On Windows (at least the NT versions) we want to put our stuff in the
338 # Application Data folder.
339 # We don't use any particular O/S detection magic, exploiting the fact that
340 # Etc.getpwuid is nil on Windows
341 if Etc.getpwuid(Process::Sys.geteuid)
342 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
344 if ENV.has_key?('APPDATA')
345 botclass = ENV['APPDATA'].dup
346 botclass.gsub!("\\","/")
351 botclass = File.expand_path(botclass)
352 @botclass = botclass.gsub(/\/$/, "")
354 unless FileTest.directory? botclass
355 log "no #{botclass} directory found, creating from templates.."
356 if FileTest.exist? botclass
357 error "file #{botclass} exists but isn't a directory"
360 FileUtils.cp_r Config::datadir+'/templates', botclass
363 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
364 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
365 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
367 # Time at which the last PING was sent
369 # Time at which the last line was RECV'd from the server
372 @startup_time = Time.new
375 @config = BotConfig.configmanager
376 @config.bot_associate(self)
377 rescue Exception => e
383 if @config['core.run_as_daemon']
387 @logfile = @config['log.file']
388 if @logfile.class!=String || @logfile.empty?
389 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
392 # See http://blog.humlab.umu.se/samuel/archives/000107.html
393 # for the backgrounding code
399 rescue NotImplementedError
400 warning "Could not background, fork not supported"
403 rescue Exception => e
404 warning "Could not background. #{e.pretty_inspect}"
407 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
408 log "Redirecting standard input/output/error"
410 STDIN.reopen "/dev/null"
412 # On Windows, there's not such thing as /dev/null
415 def STDOUT.write(str=nil)
419 def STDERR.write(str=nil)
420 if str.to_s.match(/:\d+: warning:/)
429 # Set the new logfile and loglevel. This must be done after the daemonizing
430 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
431 $logger.datetime_format= $dateformat
432 $logger.level = @config['log.level']
433 $logger.level = $cl_loglevel if defined? $cl_loglevel
434 $logger.level = 0 if $debug
438 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
442 @registry = BotRegistry.new self
445 @save_mutex = Mutex.new
446 if @config['core.save_every'] > 0
447 @save_timer = @timer.add(@config['core.save_every']) { save }
451 @quit_mutex = Mutex.new
456 @lang = Language.new(self, @config['core.language'])
459 @auth = Auth::authmanager
460 @auth.bot_associate(self)
461 # @auth.load("#{botclass}/botusers.yaml")
462 rescue Exception => e
467 @auth.everyone.set_default_permission("*", true)
468 @auth.botowner.password= @config['auth.password']
470 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
471 @plugins = Plugins::manager
472 @plugins.bot_associate(self)
475 if @config['server.name']
476 debug "upgrading configuration (server.name => server.list)"
477 srv_uri = 'irc://' + @config['server.name']
478 srv_uri += ":#{@config['server.port']}" if @config['server.port']
479 @config.items['server.list'.to_sym].set_string(srv_uri)
480 @config.delete('server.name'.to_sym)
481 @config.delete('server.port'.to_sym)
482 debug "server.list is now #{@config['server.list'].inspect}"
485 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
490 # Channels where we are quiet
491 # Array of channels names where the bot should be quiet
492 # '*' means all channels
496 @client[:welcome] = proc {|data|
497 irclog "joined server #{@client.server} as #{myself}", "server"
499 @plugins.delegate("connect")
501 @config['irc.join_channels'].each { |c|
502 debug "autojoining channel #{c}"
503 if(c =~ /^(\S+)\s+(\S+)$/i)
511 # TODO the next two @client should go into rfc2812.rb, probably
512 # Since capabs are two-steps processes, server.supports[:capab]
513 # should be a three-state: nil, [], [....]
514 asked_for = { :"identify-msg" => false }
515 @client[:isupport] = proc { |data|
516 if server.supports[:capab] and !asked_for[:"identify-msg"]
517 sendq "CAPAB IDENTIFY-MSG"
518 asked_for[:"identify-msg"] = true
521 @client[:datastr] = proc { |data|
522 if data[:text] == "IDENTIFY-MSG"
523 server.capabilities[:"identify-msg"] = true
525 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
529 @client[:privmsg] = proc { |data|
530 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
531 # debug "Message source is #{data[:source].inspect}"
532 # debug "Message target is #{data[:target].inspect}"
533 # debug "Bot is #{myself.inspect}"
536 @config['irc.ignore_users'].each { |mask|
537 if m.source.matches?(server.new_netmask(mask))
546 @plugins.delegate "listen", m
547 @plugins.delegate("ctcp_listen", m) if m.ctcp
548 @plugins.privmsg(m) if m.address?
550 @plugins.delegate "unreplied", m
554 @client[:notice] = proc { |data|
555 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
556 # pass it off to plugins that want to hear everything
557 @plugins.delegate "listen", message
559 @client[:motd] = proc { |data|
560 data[:motd].each_line { |line|
561 irclog "MOTD: #{line}", "server"
564 @client[:nicktaken] = proc { |data|
565 new = "#{data[:nick]}_"
567 # If we're setting our nick at connection because our choice was taken,
568 # we have to fix our nick manually, because there will be no NICK message
569 # to inform us that our nick has been changed.
570 if data[:target] == '*'
571 debug "setting my connection nick to #{new}"
574 @plugins.delegate "nicktaken", data[:nick]
576 @client[:badnick] = proc {|data|
577 warning "bad nick (#{data[:nick]})"
579 @client[:ping] = proc {|data|
580 sendq "PONG #{data[:pingid]}"
582 @client[:pong] = proc {|data|
585 @client[:nick] = proc {|data|
586 # debug "Message source is #{data[:source].inspect}"
587 # debug "Bot is #{myself.inspect}"
588 source = data[:source]
591 m = NickMessage.new(self, server, source, old, new)
593 debug "my nick is now #{new}"
595 data[:is_on].each { |ch|
596 irclog "@ #{old} is now known as #{new}", ch
598 @plugins.delegate("listen", m)
599 @plugins.delegate("nick", m)
601 @client[:quit] = proc {|data|
602 source = data[:source]
603 message = data[:message]
604 m = QuitMessage.new(self, server, source, source, message)
605 data[:was_on].each { |ch|
606 irclog "@ Quit: #{source}: #{message}", ch
608 @plugins.delegate("listen", m)
609 @plugins.delegate("quit", m)
611 @client[:mode] = proc {|data|
612 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
614 @client[:join] = proc {|data|
615 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
618 @plugins.delegate("listen", m)
619 @plugins.delegate("join", m)
620 sendq "WHO #{data[:channel]}", data[:channel], 2
622 @client[:part] = proc {|data|
623 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
626 @plugins.delegate("listen", m)
627 @plugins.delegate("part", m)
629 @client[:kick] = proc {|data|
630 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
633 @plugins.delegate("listen", m)
634 @plugins.delegate("kick", m)
636 @client[:invite] = proc {|data|
637 if data[:target] == myself
638 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
641 @client[:changetopic] = proc {|data|
642 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
645 @plugins.delegate("listen", m)
646 @plugins.delegate("topic", m)
648 @client[:topic] = proc { |data|
649 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
651 @client[:topicinfo] = proc { |data|
652 channel = data[:channel]
653 topic = channel.topic
654 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
655 m = TopicMessage.new(self, server, data[:source], channel, topic)
657 @plugins.delegate("listen", m)
658 @plugins.delegate("topic", m)
660 @client[:names] = proc { |data|
661 @plugins.delegate "names", data[:channel], data[:users]
663 @client[:unknown] = proc { |data|
664 #debug "UNKNOWN: #{data[:serverstring]}"
665 irclog data[:serverstring], ".unknown"
668 set_default_send_options :newlines => @config['send.newlines'].to_sym,
669 :join_with => @config['send.join_with'].dup,
670 :max_lines => @config['send.max_lines'],
671 :overlong => @config['send.overlong'].to_sym,
672 :split_at => Regexp.new(@config['send.split_at']),
673 :purge_split => @config['send.purge_split'],
674 :truncate_text => @config['send.truncate_text'].dup
677 def setup_plugins_path
678 @plugins.clear_botmodule_dirs
679 @plugins.add_botmodule_dir(Config::coredir + "/utils")
680 @plugins.add_botmodule_dir(Config::coredir)
681 @plugins.add_botmodule_dir("#{botclass}/plugins")
683 @config['plugins.path'].each do |_|
684 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
685 @plugins.add_botmodule_dir(path)
689 def set_default_send_options(opts={})
690 # Default send options for NOTICE and PRIVMSG
691 unless defined? @default_send_options
692 @default_send_options = {
693 :queue_channel => nil, # use default queue channel
694 :queue_ring => nil, # use default queue ring
695 :newlines => :split, # or :join
696 :join_with => ' ', # by default, use a single space
697 :max_lines => 0, # maximum number of lines to send with a single command
698 :overlong => :split, # or :truncate
699 # TODO an array of splitpoints would be preferrable for this option:
700 :split_at => /\s+/, # by default, split overlong lines at whitespace
701 :purge_split => true, # should the split string be removed?
702 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
705 @default_send_options.update opts unless opts.empty?
708 # checks if we should be quiet on a channel
709 def quiet_on?(channel)
710 return @quiet.include?('*') || @quiet.include?(channel.downcase)
713 def set_quiet(channel)
715 ch = channel.downcase.dup
716 @quiet << ch unless @quiet.include?(ch)
723 def reset_quiet(channel)
725 @quiet.delete channel.downcase
731 # things to do when we receive a signal
733 debug "received #{sig}, queueing quit"
735 quit unless @quit_mutex.locked?
736 debug "interrupted #{$interrupted} times"
744 # connect the bot to IRC
747 trap("SIGINT") { got_sig("SIGINT") }
748 trap("SIGTERM") { got_sig("SIGTERM") }
749 trap("SIGHUP") { got_sig("SIGHUP") }
750 rescue ArgumentError => e
751 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
752 rescue Exception => e
753 debug "failed to trap signals: #{e.pretty_inspect}"
756 quit if $interrupted > 0
759 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
761 quit if $interrupted > 0
763 realname = @config['irc.name'].clone || 'Ruby bot'
764 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
766 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
767 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
768 quit if $interrupted > 0
769 myself.nick = @config['irc.nick']
770 myself.user = @config['irc.user']
773 # begin event handling loop
777 quit if $interrupted > 0
781 while @socket.connected?
782 quit if $interrupted > 0
784 # Wait for messages and process them as they arrive. If nothing is
785 # received, we call the ping_server() method that will PING the
786 # server if appropriate, or raise a TimeoutError if no PONG has been
787 # received in the user-chosen timeout since the last PING sent.
789 break unless reply = @socket.gets
791 @client.process reply
797 # I despair of this. Some of my users get "connection reset by peer"
798 # exceptions that ARENT SocketError's. How am I supposed to handle
803 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
804 error "network exception: #{e.pretty_inspect}"
806 rescue BDB::Fatal => e
807 fatal "fatal bdb error: #{e.pretty_inspect}"
809 # Why restart? DB problems are serious stuff ...
810 # restart("Oops, we seem to have registry problems ...")
813 rescue Exception => e
814 error "non-net exception: #{e.pretty_inspect}"
817 fatal "unexpected exception: #{e.pretty_inspect}"
824 log "\n\nDisconnected\n\n"
826 quit if $interrupted > 0
828 log "\n\nWaiting to reconnect\n\n"
829 sleep @config['server.reconnect_wait']
833 # type:: message type
834 # where:: message target
835 # message:: message text
836 # send message +message+ of type +type+ to target +where+
837 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
838 # relevant say() or notice() methods. This one should be used for IRCd
839 # extensions you want to use in modules.
840 def sendmsg(type, where, original_message, options={})
841 opts = @default_send_options.merge(options)
843 # For starters, set up appropriate queue channels and rings
844 mchan = opts[:queue_channel]
845 mring = opts[:queue_ring]
862 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
866 messages << [multi_line.gsub("\n", opts[:join_with])]
868 multi_line.each_line { |line|
870 next unless(line.size > 0)
874 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
877 # The IRC protocol requires that each raw message must be not longer
878 # than 512 characters. From this length with have to subtract the EOL
879 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
880 # that will be prepended by the server to all of our messages.
882 # The maximum raw message length we can send is therefore 512 - 2 - 2
883 # minus the length of our hostmask.
885 max_len = 508 - myself.fullform.size
887 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
888 # will have a + or - prepended
889 if server.capabilities[:"identify-msg"]
893 # When splitting the message, we'll be prefixing the following string:
894 # (e.g. "PRIVMSG #rbot :")
895 fixed = "#{type} #{where} :"
897 # And this is what's left
898 left = max_len - fixed.size
900 truncate = opts[:truncate_text]
901 truncate = @default_send_options[:truncate_text] if truncate.size > left
902 truncate = "" if truncate.size > left
904 all_lines = messages.map { |line|
911 sub_lines = Array.new
913 sub_lines << msg.slice!(0, left)
915 lastspace = sub_lines.last.rindex(opts[:split_at])
917 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
918 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
923 line.slice(0, left - truncate.size) << truncate
925 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
930 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
931 lines = all_lines[0...opts[:max_lines]]
932 new_last = lines.last.slice(0, left - truncate.size) << truncate
933 lines.last.replace(new_last)
939 sendq "#{fixed}#{line}", chan, ring
940 log_sent(type, where, line)
944 # queue an arbitraty message for the server
945 def sendq(message="", chan=nil, ring=0)
947 @socket.queue(message, chan, ring)
950 # send a notice message to channel/nick +where+
951 def notice(where, message, options={})
952 return if where.kind_of?(Channel) and quiet_on?(where)
953 sendmsg "NOTICE", where, message, options
956 # say something (PRIVMSG) to channel/nick +where+
957 def say(where, message, options={})
958 return if where.kind_of?(Channel) and quiet_on?(where)
959 sendmsg "PRIVMSG", where, message, options
962 def ctcp_notice(where, command, message, options={})
963 return if where.kind_of?(Channel) and quiet_on?(where)
964 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
967 def ctcp_say(where, command, message, options={})
968 return if where.kind_of?(Channel) and quiet_on?(where)
969 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
972 # perform a CTCP action with message +message+ to channel/nick +where+
973 def action(where, message, options={})
974 ctcp_say(where, 'ACTION', message, options)
977 # quick way to say "okay" (or equivalent) to +where+
979 say where, @lang.get("okay")
982 # log IRC-related message +message+ to a file determined by +where+.
983 # +where+ can be a channel name, or a nick for private message logging
984 def irclog(message, where="server")
985 message = message.chomp
986 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
987 if where.class <= Server
990 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
992 unless(@logs.has_key?(where_str))
993 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
994 @logs[where_str].sync = true
996 @logs[where_str].puts "[#{stamp}] #{message}"
997 #debug "[#{stamp}] <#{where}> #{message}"
1000 # set topic of channel +where+ to +topic+
1001 def topic(where, topic)
1002 sendq "TOPIC #{where} :#{topic}", where, 2
1005 def disconnect(message=nil)
1006 message = @lang.get("quit") if (!message || message.empty?)
1007 if @socket.connected?
1008 debug "Clearing socket"
1010 debug "Sending quit message"
1011 @socket.emergency_puts "QUIT :#{message}"
1012 debug "Flushing socket"
1014 debug "Shutting down socket"
1017 debug "Logging quits"
1018 server.channels.each { |ch|
1019 irclog "@ quit (#{message})", ch
1025 # disconnect from the server and cleanup all plugins and modules
1026 def shutdown(message=nil)
1027 @quit_mutex.synchronize do
1028 debug "Shutting down: #{message}"
1029 ## No we don't restore them ... let everything run through
1031 # trap("SIGINT", "DEFAULT")
1032 # trap("SIGTERM", "DEFAULT")
1033 # trap("SIGHUP", "DEFAULT")
1035 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1037 debug "\tdisconnecting..."
1039 debug "\tstopping timer..."
1041 debug "\tsaving ..."
1043 debug "\tcleaning up ..."
1044 @save_mutex.synchronize do
1047 # debug "\tstopping timers ..."
1049 # debug "Closing registries"
1051 debug "\t\tcleaning up the db environment ..."
1053 log "rbot quit (#{message})"
1057 # message:: optional IRC quit message
1058 # quit IRC, shutdown the bot
1059 def quit(message=nil)
1067 # totally shutdown and respawn the bot
1068 def restart(message=nil)
1069 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1071 sleep @config['server.reconnect_wait']
1074 # Note, this fails on Windows
1075 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1078 rescue Errno::ENOENT
1079 exec("ruby", *(@argv.unshift $0))
1080 rescue Exception => e
1086 # call the save method for all of the botmodules
1088 @save_mutex.synchronize do
1094 # call the rescan method for all of the botmodules
1096 debug "\tstopping timer..."
1098 @save_mutex.synchronize do
1105 # channel:: channel to join
1106 # key:: optional channel key if channel is +s
1108 def join(channel, key=nil)
1110 sendq "JOIN #{channel} :#{key}", channel, 2
1112 sendq "JOIN #{channel}", channel, 2
1117 def part(channel, message="")
1118 sendq "PART #{channel} :#{message}", channel, 2
1121 # attempt to change bot's nick to +name+
1123 sendq "NICK #{name}"
1127 def mode(channel, mode, target)
1128 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1132 def kick(channel, user, msg)
1133 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1136 # m:: message asking for help
1137 # topic:: optional topic help is requested for
1138 # respond to online help requests
1140 topic = nil if topic == ""
1143 helpstr = _("help topics: ")
1144 helpstr += @plugins.helptopics
1145 helpstr += _(" (help <topic> for more info)")
1147 unless(helpstr = @plugins.help(topic))
1148 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1154 # returns a string describing the current status of the bot (uptime etc)
1156 secs_up = Time.new - @startup_time
1157 uptime = Utils.secs_to_string secs_up
1158 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1159 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1161 :up => uptime, :plug => @plugins.length,
1162 :sent => @socket.lines_sent, :recv => @socket.lines_received
1166 # We want to respond to a hung server in a timely manner. If nothing was received
1167 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1168 # the server. If the PONG is not received within the user-defined timeout, we
1169 # assume we're in ping timeout and act accordingly.
1171 act_timeout = @config['server.ping_timeout']
1172 return if act_timeout <= 0
1174 if @last_rec && now > @last_rec + act_timeout
1176 # No previous PING pending, send a new one
1178 @last_ping = Time.now
1180 diff = now - @last_ping
1181 if diff > act_timeout
1182 debug "no PONG from server in #{diff} seconds, reconnecting"
1183 # the actual reconnect is handled in the main loop:
1184 raise TimeoutError, "no PONG from server in #{diff} seconds"
1190 def stop_server_pings
1191 # cancel previous PINGs and reset time of last RECV
1198 def irclogprivmsg(m)
1201 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1203 irclog "* #{m.source} #{m.message}", m.target
1207 irclog "<#{m.source}> #{m.message}", m.target
1209 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1214 # log a message. Internal use only.
1215 def log_sent(type, where, message)
1220 irclog "-=#{myself}=- #{message}", where
1222 irclog "[-=#{where}=-] #{message}", where
1227 irclog "<#{myself}> #{message}", where
1229 irclog "[msg(#{where})] #{message}", where
1236 debug "joined channel #{m.channel}"
1237 irclog "@ Joined channel #{m.channel}", m.channel
1239 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1245 debug "left channel #{m.channel}"
1246 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1248 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1254 debug "kicked from channel #{m.channel}"
1255 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1257 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1262 if m.source == myself
1263 irclog "@ I set topic \"#{m.topic}\"", m.channel
1265 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel