12 $debug = false unless $debug
13 $daemonize = false unless $daemonize
15 $dateformat = "%Y/%m/%d %H:%M:%S"
16 $logger = Logger.new($stderr)
17 $logger.datetime_format = $dateformat
18 $logger.level = $cl_loglevel if defined? $cl_loglevel
19 $logger.level = 0 if $debug
23 unless Kernel.instance_methods.include?("pretty_inspect")
27 public :pretty_inspect
32 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
33 if self.backtrace and not self.backtrace.empty?
35 q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
41 def rawlog(level, message=nil, who_pos=1)
43 if call_stack.length > who_pos
44 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
48 # Output each line. To distinguish between separate messages and multi-line
49 # messages originating at the same time, we blank #{who} after the first message
51 # Also, we output strings as-is but for other objects we use pretty_inspect
56 str = message.pretty_inspect
59 $logger.add(level, l.chomp, who)
65 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
69 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
72 def debug(message=nil, who_pos=1)
73 rawlog(Logger::Severity::DEBUG, message, who_pos)
76 def log(message=nil, who_pos=1)
77 rawlog(Logger::Severity::INFO, message, who_pos)
80 def warning(message=nil, who_pos=1)
81 rawlog(Logger::Severity::WARN, message, who_pos)
84 def error(message=nil, who_pos=1)
85 rawlog(Logger::Severity::ERROR, message, who_pos)
88 def fatal(message=nil, who_pos=1)
89 rawlog(Logger::Severity::FATAL, message, who_pos)
94 warning "warning test"
98 # The following global is used for the improved signal handling.
102 require 'rbot/rbotconfig'
103 require 'rbot/load-gettext'
104 require 'rbot/config'
105 # require 'rbot/utils'
108 require 'rbot/rfc2812'
109 require 'rbot/ircsocket'
110 require 'rbot/botuser'
112 require 'rbot/plugins'
113 # require 'rbot/channel'
114 require 'rbot/message'
115 require 'rbot/language'
116 require 'rbot/dbhash'
117 require 'rbot/registry'
118 # require 'rbot/httputil'
122 # Main bot class, which manages the various components, receives messages,
123 # handles them or passes them to plugins, and contains core functionality.
125 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
126 SOURCE_URL = "http://linuxbrit.co.uk/rbot"
127 # the bot's Auth data
130 # the bot's BotConfig data
133 # the botclass for this bot (determines configdir among other things)
134 attr_reader :botclass
136 # used to perform actions periodically (saves configuration once per minute
140 # synchronize with this mutex while touching permanent data files:
141 # saving, flushing, cleaning up ...
142 attr_reader :save_mutex
144 # bot's Language data
151 # bot's object registry, plugins get an interface to this for persistant
152 # storage (hash interface tied to a bdb file, plugins use Accessors to store
153 # and restore objects in their own namespaces.)
154 attr_reader :registry
156 # bot's plugins. This is an instance of class Plugins
159 # bot's httputil help object, for fetching resources via http. Sets up
160 # proxies etc as defined by the bot configuration/environment
161 attr_accessor :httputil
163 # server we are connected to
169 # bot User in the client/server connection
175 # bot User in the client/server connection
180 # create a new Bot with botclass +botclass+
181 def initialize(botclass, params = {})
182 # BotConfig for the core bot
183 # TODO should we split socket stuff into ircsocket, etc?
184 BotConfig.register BotConfigArrayValue.new('server.list',
185 :default => ['irc://localhost'], :wizard => true,
186 :requires_restart => true,
187 :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.")
188 BotConfig.register BotConfigBooleanValue.new('server.ssl',
189 :default => false, :requires_restart => true, :wizard => true,
190 :desc => "Use SSL to connect to this server?")
191 BotConfig.register BotConfigStringValue.new('server.password',
192 :default => false, :requires_restart => true,
193 :desc => "Password for connecting to this server (if required)",
195 BotConfig.register BotConfigStringValue.new('server.bindhost',
196 :default => false, :requires_restart => true,
197 :desc => "Specific local host or IP for the bot to bind to (if required)",
199 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
200 :default => 5, :validate => Proc.new{|v| v >= 0},
201 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
202 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
203 :default => 2.0, :validate => Proc.new{|v| v >= 0},
204 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
205 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
206 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
207 :default => 4, :validate => Proc.new{|v| v >= 0},
208 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
209 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
210 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
211 :default => 30, :validate => Proc.new{|v| v >= 0},
212 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
214 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
215 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
216 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
217 BotConfig.register BotConfigStringValue.new('irc.name',
218 :default => "Ruby bot", :requires_restart => true,
219 :desc => "IRC realname the bot should use")
220 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
221 :default => true, :requires_restart => true,
222 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
223 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
224 :requires_restart => true,
225 :desc => "local user the bot should appear to be", :wizard => true)
226 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
227 :default => [], :wizard => true,
228 :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'")
229 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
231 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
233 BotConfig.register BotConfigIntegerValue.new('core.save_every',
234 :default => 60, :validate => Proc.new{|v| v >= 0},
235 :on_change => Proc.new { |bot, v|
238 @timer.reschedule(@save_timer, v)
239 @timer.unblock(@save_timer)
241 @timer.block(@save_timer)
245 @save_timer = @timer.add(v) { bot.save }
247 # Nothing to do when v == 0
250 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
252 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
253 :default => false, :requires_restart => true,
254 :desc => "Should the bot run as a daemon?")
256 BotConfig.register BotConfigStringValue.new('log.file',
257 :default => false, :requires_restart => true,
258 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
259 BotConfig.register BotConfigIntegerValue.new('log.level',
260 :default => 1, :requires_restart => false,
261 :validate => Proc.new { |v| (0..5).include?(v) },
262 :on_change => Proc.new { |bot, v|
265 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
266 BotConfig.register BotConfigIntegerValue.new('log.keep',
267 :default => 1, :requires_restart => true,
268 :validate => Proc.new { |v| v >= 0 },
269 :desc => "How many old console messages logfiles to keep")
270 BotConfig.register BotConfigIntegerValue.new('log.max_size',
271 :default => 10, :requires_restart => true,
272 :validate => Proc.new { |v| v > 0 },
273 :desc => "Maximum console messages logfile size (in megabytes)")
275 BotConfig.register BotConfigArrayValue.new('plugins.path',
276 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
277 :requires_restart => false,
278 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
279 :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")
281 BotConfig.register BotConfigEnumValue.new('send.newlines',
282 :values => ['split', 'join'], :default => 'split',
283 :on_change => Proc.new { |bot, v|
284 bot.set_default_send_options :newlines => v.to_sym
286 :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")
287 BotConfig.register BotConfigStringValue.new('send.join_with',
289 :on_change => Proc.new { |bot, v|
290 bot.set_default_send_options :join_with => v.dup
292 :desc => "String used to replace newlines when send.newlines is set to join")
293 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
295 :validate => Proc.new { |v| v >= 0 },
296 :on_change => Proc.new { |bot, v|
297 bot.set_default_send_options :max_lines => v
299 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
300 BotConfig.register BotConfigEnumValue.new('send.overlong',
301 :values => ['split', 'truncate'], :default => 'split',
302 :on_change => Proc.new { |bot, v|
303 bot.set_default_send_options :overlong => v.to_sym
305 :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")
306 BotConfig.register BotConfigStringValue.new('send.split_at',
308 :on_change => Proc.new { |bot, v|
309 bot.set_default_send_options :split_at => Regexp.new(v)
311 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
312 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
314 :on_change => Proc.new { |bot, v|
315 bot.set_default_send_options :purge_split => v
317 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
318 BotConfig.register BotConfigStringValue.new('send.truncate_text',
319 :default => "#{Reverse}...#{Reverse}",
320 :on_change => Proc.new { |bot, v|
321 bot.set_default_send_options :truncate_text => v.dup
323 :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")
325 @argv = params[:argv]
326 @run_dir = params[:run_dir] || Dir.pwd
328 unless FileTest.directory? Config::coredir
329 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
333 unless FileTest.directory? Config::datadir
334 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
338 unless botclass and not botclass.empty?
339 # We want to find a sensible default.
340 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
341 # * On Windows (at least the NT versions) we want to put our stuff in the
342 # Application Data folder.
343 # We don't use any particular O/S detection magic, exploiting the fact that
344 # Etc.getpwuid is nil on Windows
345 if Etc.getpwuid(Process::Sys.geteuid)
346 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
348 if ENV.has_key?('APPDATA')
349 botclass = ENV['APPDATA'].dup
350 botclass.gsub!("\\","/")
355 botclass = File.expand_path(botclass)
356 @botclass = botclass.gsub(/\/$/, "")
358 unless FileTest.directory? botclass
359 log "no #{botclass} directory found, creating from templates.."
360 if FileTest.exist? botclass
361 error "file #{botclass} exists but isn't a directory"
364 FileUtils.cp_r Config::datadir+'/templates', botclass
367 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
368 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
369 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
371 # Time at which the last PING was sent
373 # Time at which the last line was RECV'd from the server
376 @startup_time = Time.new
379 @config = BotConfig.configmanager
380 @config.bot_associate(self)
381 rescue Exception => e
387 if @config['core.run_as_daemon']
391 @logfile = @config['log.file']
392 if @logfile.class!=String || @logfile.empty?
393 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
396 # See http://blog.humlab.umu.se/samuel/archives/000107.html
397 # for the backgrounding code
403 rescue NotImplementedError
404 warning "Could not background, fork not supported"
407 rescue Exception => e
408 warning "Could not background. #{e.pretty_inspect}"
411 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
412 log "Redirecting standard input/output/error"
414 STDIN.reopen "/dev/null"
416 # On Windows, there's not such thing as /dev/null
419 def STDOUT.write(str=nil)
423 def STDERR.write(str=nil)
424 if str.to_s.match(/:\d+: warning:/)
433 # Set the new logfile and loglevel. This must be done after the daemonizing
434 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
435 $logger.datetime_format= $dateformat
436 $logger.level = @config['log.level']
437 $logger.level = $cl_loglevel if defined? $cl_loglevel
438 $logger.level = 0 if $debug
442 File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
446 @registry = BotRegistry.new self
449 @save_mutex = Mutex.new
450 if @config['core.save_every'] > 0
451 @save_timer = @timer.add(@config['core.save_every']) { save }
455 @quit_mutex = Mutex.new
460 @lang = Language.new(self, @config['core.language'])
463 @auth = Auth::authmanager
464 @auth.bot_associate(self)
465 # @auth.load("#{botclass}/botusers.yaml")
466 rescue Exception => e
471 @auth.everyone.set_default_permission("*", true)
472 @auth.botowner.password= @config['auth.password']
474 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
475 @plugins = Plugins::manager
476 @plugins.bot_associate(self)
479 if @config['server.name']
480 debug "upgrading configuration (server.name => server.list)"
481 srv_uri = 'irc://' + @config['server.name']
482 srv_uri += ":#{@config['server.port']}" if @config['server.port']
483 @config.items['server.list'.to_sym].set_string(srv_uri)
484 @config.delete('server.name'.to_sym)
485 @config.delete('server.port'.to_sym)
486 debug "server.list is now #{@config['server.list'].inspect}"
489 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
494 # Channels where we are quiet
495 # Array of channels names where the bot should be quiet
496 # '*' means all channels
500 @client[:welcome] = proc {|data|
501 irclog "joined server #{@client.server} as #{myself}", "server"
503 @plugins.delegate("connect")
505 @config['irc.join_channels'].each { |c|
506 debug "autojoining channel #{c}"
507 if(c =~ /^(\S+)\s+(\S+)$/i)
515 # TODO the next two @client should go into rfc2812.rb, probably
516 # Since capabs are two-steps processes, server.supports[:capab]
517 # should be a three-state: nil, [], [....]
518 asked_for = { :"identify-msg" => false }
519 @client[:isupport] = proc { |data|
520 if server.supports[:capab] and !asked_for[:"identify-msg"]
521 sendq "CAPAB IDENTIFY-MSG"
522 asked_for[:"identify-msg"] = true
525 @client[:datastr] = proc { |data|
526 if data[:text] == "IDENTIFY-MSG"
527 server.capabilities[:"identify-msg"] = true
529 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
533 @client[:privmsg] = proc { |data|
534 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
535 # debug "Message source is #{data[:source].inspect}"
536 # debug "Message target is #{data[:target].inspect}"
537 # debug "Bot is #{myself.inspect}"
540 @config['irc.ignore_users'].each { |mask|
541 if m.source.matches?(server.new_netmask(mask))
550 @plugins.delegate "listen", m
551 @plugins.delegate("ctcp_listen", m) if m.ctcp
552 @plugins.privmsg(m) if m.address?
554 @plugins.delegate "unreplied", m
558 @client[:notice] = proc { |data|
559 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
560 # pass it off to plugins that want to hear everything
561 @plugins.delegate "listen", message
563 @client[:motd] = proc { |data|
564 data[:motd].each_line { |line|
565 irclog "MOTD: #{line}", "server"
568 @client[:nicktaken] = proc { |data|
569 new = "#{data[:nick]}_"
571 # If we're setting our nick at connection because our choice was taken,
572 # we have to fix our nick manually, because there will be no NICK message
573 # to inform us that our nick has been changed.
574 if data[:target] == '*'
575 debug "setting my connection nick to #{new}"
578 @plugins.delegate "nicktaken", data[:nick]
580 @client[:badnick] = proc {|data|
581 warning "bad nick (#{data[:nick]})"
583 @client[:ping] = proc {|data|
584 sendq "PONG #{data[:pingid]}"
586 @client[:pong] = proc {|data|
589 @client[:nick] = proc {|data|
590 # debug "Message source is #{data[:source].inspect}"
591 # debug "Bot is #{myself.inspect}"
592 source = data[:source]
595 m = NickMessage.new(self, server, source, old, new)
597 debug "my nick is now #{new}"
599 data[:is_on].each { |ch|
600 irclog "@ #{old} is now known as #{new}", ch
602 @plugins.delegate("listen", m)
603 @plugins.delegate("nick", m)
605 @client[:quit] = proc {|data|
606 source = data[:source]
607 message = data[:message]
608 m = QuitMessage.new(self, server, source, source, message)
609 data[:was_on].each { |ch|
610 irclog "@ Quit: #{source}: #{message}", ch
612 @plugins.delegate("listen", m)
613 @plugins.delegate("quit", m)
615 @client[:mode] = proc {|data|
616 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
618 @client[:join] = proc {|data|
619 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
622 @plugins.delegate("listen", m)
623 @plugins.delegate("join", m)
624 sendq "WHO #{data[:channel]}", data[:channel], 2
626 @client[:part] = proc {|data|
627 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
630 @plugins.delegate("listen", m)
631 @plugins.delegate("part", m)
633 @client[:kick] = proc {|data|
634 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
637 @plugins.delegate("listen", m)
638 @plugins.delegate("kick", m)
640 @client[:invite] = proc {|data|
641 if data[:target] == myself
642 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
645 @client[:changetopic] = proc {|data|
646 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
649 @plugins.delegate("listen", m)
650 @plugins.delegate("topic", m)
652 @client[:topic] = proc { |data|
653 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
655 @client[:topicinfo] = proc { |data|
656 channel = data[:channel]
657 topic = channel.topic
658 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
659 m = TopicMessage.new(self, server, data[:source], channel, topic)
661 @plugins.delegate("listen", m)
662 @plugins.delegate("topic", m)
664 @client[:names] = proc { |data|
665 @plugins.delegate "names", data[:channel], data[:users]
667 @client[:unknown] = proc { |data|
668 #debug "UNKNOWN: #{data[:serverstring]}"
669 irclog data[:serverstring], ".unknown"
672 set_default_send_options :newlines => @config['send.newlines'].to_sym,
673 :join_with => @config['send.join_with'].dup,
674 :max_lines => @config['send.max_lines'],
675 :overlong => @config['send.overlong'].to_sym,
676 :split_at => Regexp.new(@config['send.split_at']),
677 :purge_split => @config['send.purge_split'],
678 :truncate_text => @config['send.truncate_text'].dup
681 def setup_plugins_path
682 @plugins.clear_botmodule_dirs
683 @plugins.add_botmodule_dir(Config::coredir + "/utils")
684 @plugins.add_botmodule_dir(Config::coredir)
685 @plugins.add_botmodule_dir("#{botclass}/plugins")
687 @config['plugins.path'].each do |_|
688 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
689 @plugins.add_botmodule_dir(path)
693 def set_default_send_options(opts={})
694 # Default send options for NOTICE and PRIVMSG
695 unless defined? @default_send_options
696 @default_send_options = {
697 :queue_channel => nil, # use default queue channel
698 :queue_ring => nil, # use default queue ring
699 :newlines => :split, # or :join
700 :join_with => ' ', # by default, use a single space
701 :max_lines => 0, # maximum number of lines to send with a single command
702 :overlong => :split, # or :truncate
703 # TODO an array of splitpoints would be preferrable for this option:
704 :split_at => /\s+/, # by default, split overlong lines at whitespace
705 :purge_split => true, # should the split string be removed?
706 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
709 @default_send_options.update opts unless opts.empty?
712 # checks if we should be quiet on a channel
713 def quiet_on?(channel)
714 return @quiet.include?('*') || @quiet.include?(channel.downcase)
717 def set_quiet(channel)
719 ch = channel.downcase.dup
720 @quiet << ch unless @quiet.include?(ch)
727 def reset_quiet(channel)
729 @quiet.delete channel.downcase
735 # things to do when we receive a signal
737 debug "received #{sig}, queueing quit"
739 quit unless @quit_mutex.locked?
740 debug "interrupted #{$interrupted} times"
748 # connect the bot to IRC
751 trap("SIGINT") { got_sig("SIGINT") }
752 trap("SIGTERM") { got_sig("SIGTERM") }
753 trap("SIGHUP") { got_sig("SIGHUP") }
754 rescue ArgumentError => e
755 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
756 rescue Exception => e
757 debug "failed to trap signals: #{e.pretty_inspect}"
760 quit if $interrupted > 0
763 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
765 quit if $interrupted > 0
767 realname = @config['irc.name'].clone || 'Ruby bot'
768 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
770 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
771 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
772 quit if $interrupted > 0
773 myself.nick = @config['irc.nick']
774 myself.user = @config['irc.user']
777 # begin event handling loop
781 quit if $interrupted > 0
785 while @socket.connected?
786 quit if $interrupted > 0
788 # Wait for messages and process them as they arrive. If nothing is
789 # received, we call the ping_server() method that will PING the
790 # server if appropriate, or raise a TimeoutError if no PONG has been
791 # received in the user-chosen timeout since the last PING sent.
793 break unless reply = @socket.gets
795 @client.process reply
801 # I despair of this. Some of my users get "connection reset by peer"
802 # exceptions that ARENT SocketError's. How am I supposed to handle
807 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
808 error "network exception: #{e.pretty_inspect}"
810 rescue BDB::Fatal => e
811 fatal "fatal bdb error: #{e.pretty_inspect}"
813 # Why restart? DB problems are serious stuff ...
814 # restart("Oops, we seem to have registry problems ...")
817 rescue Exception => e
818 error "non-net exception: #{e.pretty_inspect}"
821 fatal "unexpected exception: #{e.pretty_inspect}"
828 log "\n\nDisconnected\n\n"
830 quit if $interrupted > 0
832 log "\n\nWaiting to reconnect\n\n"
833 sleep @config['server.reconnect_wait']
837 # type:: message type
838 # where:: message target
839 # message:: message text
840 # send message +message+ of type +type+ to target +where+
841 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
842 # relevant say() or notice() methods. This one should be used for IRCd
843 # extensions you want to use in modules.
844 def sendmsg(type, where, original_message, options={})
845 opts = @default_send_options.merge(options)
847 # For starters, set up appropriate queue channels and rings
848 mchan = opts[:queue_channel]
849 mring = opts[:queue_ring]
866 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
870 messages << [multi_line.gsub("\n", opts[:join_with])]
872 multi_line.each_line { |line|
874 next unless(line.size > 0)
878 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
881 # The IRC protocol requires that each raw message must be not longer
882 # than 512 characters. From this length with have to subtract the EOL
883 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
884 # that will be prepended by the server to all of our messages.
886 # The maximum raw message length we can send is therefore 512 - 2 - 2
887 # minus the length of our hostmask.
889 max_len = 508 - myself.fullform.size
891 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
892 # will have a + or - prepended
893 if server.capabilities[:"identify-msg"]
897 # When splitting the message, we'll be prefixing the following string:
898 # (e.g. "PRIVMSG #rbot :")
899 fixed = "#{type} #{where} :"
901 # And this is what's left
902 left = max_len - fixed.size
904 truncate = opts[:truncate_text]
905 truncate = @default_send_options[:truncate_text] if truncate.size > left
906 truncate = "" if truncate.size > left
908 all_lines = messages.map { |line|
915 sub_lines = Array.new
917 sub_lines << msg.slice!(0, left)
919 lastspace = sub_lines.last.rindex(opts[:split_at])
921 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
922 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
927 line.slice(0, left - truncate.size) << truncate
929 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
934 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
935 lines = all_lines[0...opts[:max_lines]]
936 new_last = lines.last.slice(0, left - truncate.size) << truncate
937 lines.last.replace(new_last)
943 sendq "#{fixed}#{line}", chan, ring
944 log_sent(type, where, line)
948 # queue an arbitraty message for the server
949 def sendq(message="", chan=nil, ring=0)
951 @socket.queue(message, chan, ring)
954 # send a notice message to channel/nick +where+
955 def notice(where, message, options={})
956 return if where.kind_of?(Channel) and quiet_on?(where)
957 sendmsg "NOTICE", where, message, options
960 # say something (PRIVMSG) to channel/nick +where+
961 def say(where, message, options={})
962 return if where.kind_of?(Channel) and quiet_on?(where)
963 sendmsg "PRIVMSG", where, message, options
966 def ctcp_notice(where, command, message, options={})
967 return if where.kind_of?(Channel) and quiet_on?(where)
968 sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
971 def ctcp_say(where, command, message, options={})
972 return if where.kind_of?(Channel) and quiet_on?(where)
973 sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
976 # perform a CTCP action with message +message+ to channel/nick +where+
977 def action(where, message, options={})
978 ctcp_say(where, 'ACTION', message, options)
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 || 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: #{message}"
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 "\tstopping timer..."
1045 debug "\tsaving ..."
1047 debug "\tcleaning up ..."
1048 @save_mutex.synchronize do
1051 # debug "\tstopping timers ..."
1053 # debug "Closing registries"
1055 debug "\t\tcleaning up the db environment ..."
1057 log "rbot quit (#{message})"
1061 # message:: optional IRC quit message
1062 # quit IRC, shutdown the bot
1063 def quit(message=nil)
1071 # totally shutdown and respawn the bot
1072 def restart(message=nil)
1073 message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1075 sleep @config['server.reconnect_wait']
1078 # Note, this fails on Windows
1079 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1082 rescue Errno::ENOENT
1083 exec("ruby", *(@argv.unshift $0))
1084 rescue Exception => e
1090 # call the save method for all of the botmodules
1092 @save_mutex.synchronize do
1098 # call the rescan method for all of the botmodules
1100 debug "\tstopping timer..."
1102 @save_mutex.synchronize do
1109 # channel:: channel to join
1110 # key:: optional channel key if channel is +s
1112 def join(channel, key=nil)
1114 sendq "JOIN #{channel} :#{key}", channel, 2
1116 sendq "JOIN #{channel}", channel, 2
1121 def part(channel, message="")
1122 sendq "PART #{channel} :#{message}", channel, 2
1125 # attempt to change bot's nick to +name+
1127 sendq "NICK #{name}"
1131 def mode(channel, mode, target)
1132 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1136 def kick(channel, user, msg)
1137 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1140 # m:: message asking for help
1141 # topic:: optional topic help is requested for
1142 # respond to online help requests
1144 topic = nil if topic == ""
1147 helpstr = _("help topics: ")
1148 helpstr += @plugins.helptopics
1149 helpstr += _(" (help <topic> for more info)")
1151 unless(helpstr = @plugins.help(topic))
1152 helpstr = _("no help for topic %{topic}") % { :topic => topic }
1158 # returns a string describing the current status of the bot (uptime etc)
1160 secs_up = Time.new - @startup_time
1161 uptime = Utils.secs_to_string secs_up
1162 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1163 return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1165 :up => uptime, :plug => @plugins.length,
1166 :sent => @socket.lines_sent, :recv => @socket.lines_received
1170 # We want to respond to a hung server in a timely manner. If nothing was received
1171 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1172 # the server. If the PONG is not received within the user-defined timeout, we
1173 # assume we're in ping timeout and act accordingly.
1175 act_timeout = @config['server.ping_timeout']
1176 return if act_timeout <= 0
1178 if @last_rec && now > @last_rec + act_timeout
1180 # No previous PING pending, send a new one
1182 @last_ping = Time.now
1184 diff = now - @last_ping
1185 if diff > act_timeout
1186 debug "no PONG from server in #{diff} seconds, reconnecting"
1187 # the actual reconnect is handled in the main loop:
1188 raise TimeoutError, "no PONG from server in #{diff} seconds"
1194 def stop_server_pings
1195 # cancel previous PINGs and reset time of last RECV
1202 def irclogprivmsg(m)
1205 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1207 irclog "* #{m.source} #{m.message}", m.target
1211 irclog "<#{m.source}> #{m.message}", m.target
1213 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1218 # log a message. Internal use only.
1219 def log_sent(type, where, message)
1224 irclog "-=#{myself}=- #{message}", where
1226 irclog "[-=#{where}=-] #{message}", where
1231 irclog "<#{myself}> #{message}", where
1233 irclog "[msg(#{where})] #{message}", where
1240 debug "joined channel #{m.channel}"
1241 irclog "@ Joined channel #{m.channel}", m.channel
1243 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1249 debug "left channel #{m.channel}"
1250 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1252 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1258 debug "kicked from channel #{m.channel}"
1259 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1261 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1266 if m.source == myself
1267 irclog "@ I set topic \"#{m.topic}\"", m.channel
1269 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel