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 SOURCE_URL = "http://linuxbrit.co.uk"
124 # the bot's Auth data
127 # the bot's BotConfig data
130 # the botclass for this bot (determines configdir among other things)
131 attr_reader :botclass
133 # used to perform actions periodically (saves configuration once per minute
137 # synchronize with this mutex while touching permanent data files:
138 # saving, flushing, cleaning up ...
139 attr_reader :save_mutex
141 # bot's Language data
148 # bot's object registry, plugins get an interface to this for persistant
149 # storage (hash interface tied to a bdb file, plugins use Accessors to store
150 # and restore objects in their own namespaces.)
151 attr_reader :registry
153 # bot's plugins. This is an instance of class Plugins
156 # bot's httputil help object, for fetching resources via http. Sets up
157 # proxies etc as defined by the bot configuration/environment
158 attr_accessor :httputil
160 # server we are connected to
166 # bot User in the client/server connection
172 # bot User in the client/server connection
177 # create a new Bot with botclass +botclass+
178 def initialize(botclass, params = {})
179 # BotConfig for the core bot
180 # TODO should we split socket stuff into ircsocket, etc?
181 BotConfig.register BotConfigArrayValue.new('server.list',
182 :default => ['irc://localhost'], :wizard => true,
183 :requires_restart => true,
184 :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.")
185 BotConfig.register BotConfigBooleanValue.new('server.ssl',
186 :default => false, :requires_restart => true, :wizard => true,
187 :desc => "Use SSL to connect to this server?")
188 BotConfig.register BotConfigStringValue.new('server.password',
189 :default => false, :requires_restart => true,
190 :desc => "Password for connecting to this server (if required)",
192 BotConfig.register BotConfigStringValue.new('server.bindhost',
193 :default => false, :requires_restart => true,
194 :desc => "Specific local host or IP for the bot to bind to (if required)",
196 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
197 :default => 5, :validate => Proc.new{|v| v >= 0},
198 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
199 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
200 :default => 2.0, :validate => Proc.new{|v| v >= 0},
201 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
202 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
203 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
204 :default => 4, :validate => Proc.new{|v| v >= 0},
205 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
206 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
207 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
208 :default => 30, :validate => Proc.new{|v| v >= 0},
209 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
211 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
212 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
213 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
214 BotConfig.register BotConfigStringValue.new('irc.name',
215 :default => "Ruby bot", :requires_restart => true,
216 :desc => "IRC realname the bot should use")
217 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
218 :default => true, :requires_restart => true,
219 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
220 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
221 :requires_restart => true,
222 :desc => "local user the bot should appear to be", :wizard => true)
223 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
224 :default => [], :wizard => true,
225 :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'")
226 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
228 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
230 BotConfig.register BotConfigIntegerValue.new('core.save_every',
231 :default => 60, :validate => Proc.new{|v| v >= 0},
232 :on_change => Proc.new { |bot, v|
235 @timer.reschedule(@save_timer, v)
236 @timer.unblock(@save_timer)
238 @timer.block(@save_timer)
242 @save_timer = @timer.add(v) { bot.save }
244 # Nothing to do when v == 0
247 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
249 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
250 :default => false, :requires_restart => true,
251 :desc => "Should the bot run as a daemon?")
253 BotConfig.register BotConfigStringValue.new('log.file',
254 :default => false, :requires_restart => true,
255 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
256 BotConfig.register BotConfigIntegerValue.new('log.level',
257 :default => 1, :requires_restart => false,
258 :validate => Proc.new { |v| (0..5).include?(v) },
259 :on_change => Proc.new { |bot, v|
262 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
263 BotConfig.register BotConfigIntegerValue.new('log.keep',
264 :default => 1, :requires_restart => true,
265 :validate => Proc.new { |v| v >= 0 },
266 :desc => "How many old console messages logfiles to keep")
267 BotConfig.register BotConfigIntegerValue.new('log.max_size',
268 :default => 10, :requires_restart => true,
269 :validate => Proc.new { |v| v > 0 },
270 :desc => "Maximum console messages logfile size (in megabytes)")
272 BotConfig.register BotConfigArrayValue.new('plugins.path',
273 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
274 :requires_restart => false,
275 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
276 :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")
278 BotConfig.register BotConfigEnumValue.new('send.newlines',
279 :values => ['split', 'join'], :default => 'split',
280 :on_change => Proc.new { |bot, v|
281 bot.set_default_send_options :newlines => v.to_sym
283 :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")
284 BotConfig.register BotConfigStringValue.new('send.join_with',
286 :on_change => Proc.new { |bot, v|
287 bot.set_default_send_options :join_with => v.dup
289 :desc => "String used to replace newlines when send.newlines is set to join")
290 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
292 :validate => Proc.new { |v| v >= 0 },
293 :on_change => Proc.new { |bot, v|
294 bot.set_default_send_options :max_lines => v
296 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
297 BotConfig.register BotConfigEnumValue.new('send.overlong',
298 :values => ['split', 'truncate'], :default => 'split',
299 :on_change => Proc.new { |bot, v|
300 bot.set_default_send_options :overlong => v.to_sym
302 :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")
303 BotConfig.register BotConfigStringValue.new('send.split_at',
305 :on_change => Proc.new { |bot, v|
306 bot.set_default_send_options :split_at => Regexp.new(v)
308 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
309 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
311 :on_change => Proc.new { |bot, v|
312 bot.set_default_send_options :purge_split => v
314 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
315 BotConfig.register BotConfigStringValue.new('send.truncate_text',
316 :default => "#{Reverse}...#{Reverse}",
317 :on_change => Proc.new { |bot, v|
318 bot.set_default_send_options :truncate_text => v.dup
320 :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")
322 @argv = params[:argv]
323 @run_dir = params[:run_dir] || Dir.pwd
325 unless FileTest.directory? Config::coredir
326 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
330 unless FileTest.directory? Config::datadir
331 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
335 unless botclass and not botclass.empty?
336 # We want to find a sensible default.
337 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
338 # * On Windows (at least the NT versions) we want to put our stuff in the
339 # Application Data folder.
340 # We don't use any particular O/S detection magic, exploiting the fact that
341 # Etc.getpwuid is nil on Windows
342 if Etc.getpwuid(Process::Sys.geteuid)
343 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
345 if ENV.has_key?('APPDATA')
346 botclass = ENV['APPDATA'].dup
347 botclass.gsub!("\\","/")
352 botclass = File.expand_path(botclass)
353 @botclass = botclass.gsub(/\/$/, "")
355 unless FileTest.directory? botclass
356 log "no #{botclass} directory found, creating from templates.."
357 if FileTest.exist? botclass
358 error "file #{botclass} exists but isn't a directory"
361 FileUtils.cp_r Config::datadir+'/templates', botclass
364 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
365 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
366 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
368 # Time at which the last PING was sent
370 # Time at which the last line was RECV'd from the server
373 @startup_time = Time.new
376 @config = BotConfig.configmanager
377 @config.bot_associate(self)
378 rescue Exception => e
384 if @config['core.run_as_daemon']
388 @logfile = @config['log.file']
389 if @logfile.class!=String || @logfile.empty?
390 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
393 # See http://blog.humlab.umu.se/samuel/archives/000107.html
394 # for the backgrounding code
400 rescue NotImplementedError
401 warning "Could not background, fork not supported"
404 rescue Exception => e
405 warning "Could not background. #{e.pretty_inspect}"
408 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
409 log "Redirecting standard input/output/error"
411 STDIN.reopen "/dev/null"
413 # On Windows, there's not such thing as /dev/null
416 def STDOUT.write(str=nil)
420 def STDERR.write(str=nil)
421 if str.to_s.match(/:\d+: warning:/)
430 # Set the new logfile and loglevel. This must be done after the daemonizing
431 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
432 $logger.datetime_format= $dateformat
433 $logger.level = @config['log.level']
434 $logger.level = $cl_loglevel if defined? $cl_loglevel
435 $logger.level = 0 if $debug
439 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
443 @registry = BotRegistry.new self
446 @save_mutex = Mutex.new
447 if @config['core.save_every'] > 0
448 @save_timer = @timer.add(@config['core.save_every']) { save }
452 @quit_mutex = Mutex.new
457 @lang = Language.new(self, @config['core.language'])
460 @auth = Auth::authmanager
461 @auth.bot_associate(self)
462 # @auth.load("#{botclass}/botusers.yaml")
463 rescue Exception => e
468 @auth.everyone.set_default_permission("*", true)
469 @auth.botowner.password= @config['auth.password']
471 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
472 @plugins = Plugins::manager
473 @plugins.bot_associate(self)
476 if @config['server.name']
477 debug "upgrading configuration (server.name => server.list)"
478 srv_uri = 'irc://' + @config['server.name']
479 srv_uri += ":#{@config['server.port']}" if @config['server.port']
480 @config.items['server.list'.to_sym].set_string(srv_uri)
481 @config.delete('server.name'.to_sym)
482 @config.delete('server.port'.to_sym)
483 debug "server.list is now #{@config['server.list'].inspect}"
486 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
491 # Channels where we are quiet
492 # Array of channels names where the bot should be quiet
493 # '*' means all channels
497 @client[:welcome] = proc {|data|
498 irclog "joined server #{@client.server} as #{myself}", "server"
500 @plugins.delegate("connect")
502 @config['irc.join_channels'].each { |c|
503 debug "autojoining channel #{c}"
504 if(c =~ /^(\S+)\s+(\S+)$/i)
512 # TODO the next two @client should go into rfc2812.rb, probably
513 # Since capabs are two-steps processes, server.supports[:capab]
514 # should be a three-state: nil, [], [....]
515 asked_for = { :"identify-msg" => false }
516 @client[:isupport] = proc { |data|
517 if server.supports[:capab] and !asked_for[:"identify-msg"]
518 sendq "CAPAB IDENTIFY-MSG"
519 asked_for[:"identify-msg"] = true
522 @client[:datastr] = proc { |data|
523 if data[:text] == "IDENTIFY-MSG"
524 server.capabilities[:"identify-msg"] = true
526 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
530 @client[:privmsg] = proc { |data|
531 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
532 # debug "Message source is #{data[:source].inspect}"
533 # debug "Message target is #{data[:target].inspect}"
534 # debug "Bot is #{myself.inspect}"
537 @config['irc.ignore_users'].each { |mask|
538 if m.source.matches?(server.new_netmask(mask))
547 @plugins.delegate "listen", m
548 @plugins.delegate("ctcp_listen", m) if m.ctcp
549 @plugins.privmsg(m) if m.address?
551 @plugins.delegate "unreplied", m
555 @client[:notice] = proc { |data|
556 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
557 # pass it off to plugins that want to hear everything
558 @plugins.delegate "listen", message
560 @client[:motd] = proc { |data|
561 data[:motd].each_line { |line|
562 irclog "MOTD: #{line}", "server"
565 @client[:nicktaken] = proc { |data|
566 new = "#{data[:nick]}_"
568 # If we're setting our nick at connection because our choice was taken,
569 # we have to fix our nick manually, because there will be no NICK message
570 # to inform us that our nick has been changed.
571 if data[:target] == '*'
572 debug "setting my connection nick to #{new}"
575 @plugins.delegate "nicktaken", data[:nick]
577 @client[:badnick] = proc {|data|
578 warning "bad nick (#{data[:nick]})"
580 @client[:ping] = proc {|data|
581 sendq "PONG #{data[:pingid]}"
583 @client[:pong] = proc {|data|
586 @client[:nick] = proc {|data|
587 # debug "Message source is #{data[:source].inspect}"
588 # debug "Bot is #{myself.inspect}"
589 source = data[:source]
592 m = NickMessage.new(self, server, source, old, new)
594 debug "my nick is now #{new}"
596 data[:is_on].each { |ch|
597 irclog "@ #{old} is now known as #{new}", ch
599 @plugins.delegate("listen", m)
600 @plugins.delegate("nick", m)
602 @client[:quit] = proc {|data|
603 source = data[:source]
604 message = data[:message]
605 m = QuitMessage.new(self, server, source, source, message)
606 data[:was_on].each { |ch|
607 irclog "@ Quit: #{source}: #{message}", ch
609 @plugins.delegate("listen", m)
610 @plugins.delegate("quit", m)
612 @client[:mode] = proc {|data|
613 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
615 @client[:join] = proc {|data|
616 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
619 @plugins.delegate("listen", m)
620 @plugins.delegate("join", m)
621 sendq "WHO #{data[:channel]}", data[:channel], 2
623 @client[:part] = proc {|data|
624 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
627 @plugins.delegate("listen", m)
628 @plugins.delegate("part", m)
630 @client[:kick] = proc {|data|
631 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
634 @plugins.delegate("listen", m)
635 @plugins.delegate("kick", m)
637 @client[:invite] = proc {|data|
638 if data[:target] == myself
639 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
642 @client[:changetopic] = proc {|data|
643 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
646 @plugins.delegate("listen", m)
647 @plugins.delegate("topic", m)
649 @client[:topic] = proc { |data|
650 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
652 @client[:topicinfo] = proc { |data|
653 channel = data[:channel]
654 topic = channel.topic
655 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
656 m = TopicMessage.new(self, server, data[:source], channel, topic)
658 @plugins.delegate("listen", m)
659 @plugins.delegate("topic", m)
661 @client[:names] = proc { |data|
662 @plugins.delegate "names", data[:channel], data[:users]
664 @client[:unknown] = proc { |data|
665 #debug "UNKNOWN: #{data[:serverstring]}"
666 irclog data[:serverstring], ".unknown"
669 set_default_send_options :newlines => @config['send.newlines'].to_sym,
670 :join_with => @config['send.join_with'].dup,
671 :max_lines => @config['send.max_lines'],
672 :overlong => @config['send.overlong'].to_sym,
673 :split_at => Regexp.new(@config['send.split_at']),
674 :purge_split => @config['send.purge_split'],
675 :truncate_text => @config['send.truncate_text'].dup
678 def setup_plugins_path
679 @plugins.clear_botmodule_dirs
680 @plugins.add_botmodule_dir(Config::coredir + "/utils")
681 @plugins.add_botmodule_dir(Config::coredir)
682 @plugins.add_botmodule_dir("#{botclass}/plugins")
684 @config['plugins.path'].each do |_|
685 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
686 @plugins.add_botmodule_dir(path)
690 def set_default_send_options(opts={})
691 # Default send options for NOTICE and PRIVMSG
692 unless defined? @default_send_options
693 @default_send_options = {
694 :queue_channel => nil, # use default queue channel
695 :queue_ring => nil, # use default queue ring
696 :newlines => :split, # or :join
697 :join_with => ' ', # by default, use a single space
698 :max_lines => 0, # maximum number of lines to send with a single command
699 :overlong => :split, # or :truncate
700 # TODO an array of splitpoints would be preferrable for this option:
701 :split_at => /\s+/, # by default, split overlong lines at whitespace
702 :purge_split => true, # should the split string be removed?
703 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
706 @default_send_options.update opts unless opts.empty?
709 # checks if we should be quiet on a channel
710 def quiet_on?(channel)
711 return @quiet.include?('*') || @quiet.include?(channel.downcase)
714 def set_quiet(channel)
716 ch = channel.downcase.dup
717 @quiet << ch unless @quiet.include?(ch)
724 def reset_quiet(channel)
726 @quiet.delete channel.downcase
732 # things to do when we receive a signal
734 debug "received #{sig}, queueing quit"
736 quit unless @quit_mutex.locked?
737 debug "interrupted #{$interrupted} times"
745 # connect the bot to IRC
748 trap("SIGINT") { got_sig("SIGINT") }
749 trap("SIGTERM") { got_sig("SIGTERM") }
750 trap("SIGHUP") { got_sig("SIGHUP") }
751 rescue ArgumentError => e
752 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
753 rescue Exception => e
754 debug "failed to trap signals: #{e.pretty_inspect}"
757 quit if $interrupted > 0
760 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
762 quit if $interrupted > 0
764 realname = @config['irc.name'].clone || 'Ruby bot'
765 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
767 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
768 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
769 quit if $interrupted > 0
770 myself.nick = @config['irc.nick']
771 myself.user = @config['irc.user']
774 # begin event handling loop
778 quit if $interrupted > 0
782 while @socket.connected?
783 quit if $interrupted > 0
785 # Wait for messages and process them as they arrive. If nothing is
786 # received, we call the ping_server() method that will PING the
787 # server if appropriate, or raise a TimeoutError if no PONG has been
788 # received in the user-chosen timeout since the last PING sent.
790 break unless reply = @socket.gets
792 @client.process reply
798 # I despair of this. Some of my users get "connection reset by peer"
799 # exceptions that ARENT SocketError's. How am I supposed to handle
804 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
805 error "network exception: #{e.pretty_inspect}"
807 rescue BDB::Fatal => e
808 fatal "fatal bdb error: #{e.pretty_inspect}"
810 # Why restart? DB problems are serious stuff ...
811 # restart("Oops, we seem to have registry problems ...")
814 rescue Exception => e
815 error "non-net exception: #{e.pretty_inspect}"
818 fatal "unexpected exception: #{e.pretty_inspect}"
825 log "\n\nDisconnected\n\n"
827 quit if $interrupted > 0
829 log "\n\nWaiting to reconnect\n\n"
830 sleep @config['server.reconnect_wait']
834 # type:: message type
835 # where:: message target
836 # message:: message text
837 # send message +message+ of type +type+ to target +where+
838 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
839 # relevant say() or notice() methods. This one should be used for IRCd
840 # extensions you want to use in modules.
841 def sendmsg(type, where, original_message, options={})
842 opts = @default_send_options.merge(options)
844 # For starters, set up appropriate queue channels and rings
845 mchan = opts[:queue_channel]
846 mring = opts[:queue_ring]
863 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
867 messages << [multi_line.gsub("\n", opts[:join_with])]
869 multi_line.each_line { |line|
871 next unless(line.size > 0)
875 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
878 # The IRC protocol requires that each raw message must be not longer
879 # than 512 characters. From this length with have to subtract the EOL
880 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
881 # that will be prepended by the server to all of our messages.
883 # The maximum raw message length we can send is therefore 512 - 2 - 2
884 # minus the length of our hostmask.
886 max_len = 508 - myself.fullform.size
888 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
889 # will have a + or - prepended
890 if server.capabilities[:"identify-msg"]
894 # When splitting the message, we'll be prefixing the following string:
895 # (e.g. "PRIVMSG #rbot :")
896 fixed = "#{type} #{where} :"
898 # And this is what's left
899 left = max_len - fixed.size
901 truncate = opts[:truncate_text]
902 truncate = @default_send_options[:truncate_text] if truncate.size > left
903 truncate = "" if truncate.size > left
905 all_lines = messages.map { |line|
912 sub_lines = Array.new
914 sub_lines << msg.slice!(0, left)
916 lastspace = sub_lines.last.rindex(opts[:split_at])
918 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
919 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
924 line.slice(0, left - truncate.size) << truncate
926 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
931 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
932 lines = all_lines[0...opts[:max_lines]]
933 new_last = lines.last.slice(0, left - truncate.size) << truncate
934 lines.last.replace(new_last)
940 sendq "#{fixed}#{line}", chan, ring
941 log_sent(type, where, line)
945 # queue an arbitraty message for the server
946 def sendq(message="", chan=nil, ring=0)
948 @socket.queue(message, chan, ring)
951 # send a notice message to channel/nick +where+
952 def notice(where, message, options={})
953 return if where.kind_of?(Channel) and quiet_on?(where)
954 sendmsg "NOTICE", where, message, options
957 # say something (PRIVMSG) to channel/nick +where+
958 def say(where, message, options={})
959 return if where.kind_of?(Channel) and quiet_on?(where)
960 sendmsg "PRIVMSG", where, message, options
963 def ctcp_notice(where, command, message, options={})
964 return if where.kind_of?(Channel) and quiet_on?(where)
965 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
968 def ctcp_say(where, command, message, options={})
969 return if where.kind_of?(Channel) and quiet_on?(where)
970 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
973 # perform a CTCP action with message +message+ to channel/nick +where+
974 def action(where, message, options={})
975 ctcp_say(where, 'ACTION', message, options)
978 # quick way to say "okay" (or equivalent) to +where+
980 say where, @lang.get("okay")
983 # log IRC-related message +message+ to a file determined by +where+.
984 # +where+ can be a channel name, or a nick for private message logging
985 def irclog(message, where="server")
986 message = message.chomp
987 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
988 if where.class <= Server
991 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
993 unless(@logs.has_key?(where_str))
994 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
995 @logs[where_str].sync = true
997 @logs[where_str].puts "[#{stamp}] #{message}"
998 #debug "[#{stamp}] <#{where}> #{message}"
1001 # set topic of channel +where+ to +topic+
1002 def topic(where, topic)
1003 sendq "TOPIC #{where} :#{topic}", where, 2
1006 def disconnect(message=nil)
1007 message = @lang.get("quit") if (!message || message.empty?)
1008 if @socket.connected?
1009 debug "Clearing socket"
1011 debug "Sending quit message"
1012 @socket.emergency_puts "QUIT :#{message}"
1013 debug "Flushing socket"
1015 debug "Shutting down socket"
1018 debug "Logging quits"
1019 server.channels.each { |ch|
1020 irclog "@ quit (#{message})", ch
1026 # disconnect from the server and cleanup all plugins and modules
1027 def shutdown(message=nil)
1028 @quit_mutex.synchronize do
1029 debug "Shutting down: #{message}"
1030 ## No we don't restore them ... let everything run through
1032 # trap("SIGINT", "DEFAULT")
1033 # trap("SIGTERM", "DEFAULT")
1034 # trap("SIGHUP", "DEFAULT")
1036 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1038 debug "\tdisconnecting..."
1040 debug "\tstopping timer..."
1042 debug "\tsaving ..."
1044 debug "\tcleaning up ..."
1045 @save_mutex.synchronize do
1048 # debug "\tstopping timers ..."
1050 # debug "Closing registries"
1052 debug "\t\tcleaning up the db environment ..."
1054 log "rbot quit (#{message})"
1058 # message:: optional IRC quit message
1059 # quit IRC, shutdown the bot
1060 def quit(message=nil)
1068 # totally shutdown and respawn the bot
1069 def restart(message=nil)
1070 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1072 sleep @config['server.reconnect_wait']
1075 # Note, this fails on Windows
1076 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1079 rescue Errno::ENOENT
1080 exec("ruby", *(@argv.unshift $0))
1081 rescue Exception => e
1087 # call the save method for all of the botmodules
1089 @save_mutex.synchronize do
1095 # call the rescan method for all of the botmodules
1097 debug "\tstopping timer..."
1099 @save_mutex.synchronize do
1106 # channel:: channel to join
1107 # key:: optional channel key if channel is +s
1109 def join(channel, key=nil)
1111 sendq "JOIN #{channel} :#{key}", channel, 2
1113 sendq "JOIN #{channel}", channel, 2
1118 def part(channel, message="")
1119 sendq "PART #{channel} :#{message}", channel, 2
1122 # attempt to change bot's nick to +name+
1124 sendq "NICK #{name}"
1128 def mode(channel, mode, target)
1129 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1133 def kick(channel, user, msg)
1134 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1137 # m:: message asking for help
1138 # topic:: optional topic help is requested for
1139 # respond to online help requests
1141 topic = nil if topic == ""
1144 helpstr = _("help topics: ")
1145 helpstr += @plugins.helptopics
1146 helpstr += _(" (help <topic> for more info)")
1148 unless(helpstr = @plugins.help(topic))
1149 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1155 # returns a string describing the current status of the bot (uptime etc)
1157 secs_up = Time.new - @startup_time
1158 uptime = Utils.secs_to_string secs_up
1159 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1160 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1162 :up => uptime, :plug => @plugins.length,
1163 :sent => @socket.lines_sent, :recv => @socket.lines_received
1167 # We want to respond to a hung server in a timely manner. If nothing was received
1168 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1169 # the server. If the PONG is not received within the user-defined timeout, we
1170 # assume we're in ping timeout and act accordingly.
1172 act_timeout = @config['server.ping_timeout']
1173 return if act_timeout <= 0
1175 if @last_rec && now > @last_rec + act_timeout
1177 # No previous PING pending, send a new one
1179 @last_ping = Time.now
1181 diff = now - @last_ping
1182 if diff > act_timeout
1183 debug "no PONG from server in #{diff} seconds, reconnecting"
1184 # the actual reconnect is handled in the main loop:
1185 raise TimeoutError, "no PONG from server in #{diff} seconds"
1191 def stop_server_pings
1192 # cancel previous PINGs and reset time of last RECV
1199 def irclogprivmsg(m)
1202 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1204 irclog "* #{m.source} #{m.message}", m.target
1208 irclog "<#{m.source}> #{m.message}", m.target
1210 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1215 # log a message. Internal use only.
1216 def log_sent(type, where, message)
1221 irclog "-=#{myself}=- #{message}", where
1223 irclog "[-=#{where}=-] #{message}", where
1228 irclog "<#{myself}> #{message}", where
1230 irclog "[msg(#{where})] #{message}", where
1237 debug "joined channel #{m.channel}"
1238 irclog "@ Joined channel #{m.channel}", m.channel
1240 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1246 debug "left channel #{m.channel}"
1247 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1249 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1255 debug "kicked from channel #{m.channel}"
1256 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1258 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1263 if m.source == myself
1264 irclog "@ I set topic \"#{m.topic}\"", m.channel
1266 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel