7 $debug = false unless $debug
8 $daemonize = false unless $daemonize
10 $dateformat = "%Y/%m/%d %H:%M:%S"
11 $logger = Logger.new($stderr)
12 $logger.datetime_format = $dateformat
13 $logger.level = $cl_loglevel if $cl_loglevel
14 $logger.level = 0 if $debug
16 def rawlog(level, message=nil, who_pos=1)
18 if call_stack.length > who_pos
19 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
23 # Output each line. To distinguish between separate messages and multi-line
24 # messages originating at the same time, we blank #{who} after the first message
26 message.to_s.each_line { |l|
27 $logger.add(level, l.chomp, who)
33 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
37 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
40 def debug(message=nil, who_pos=1)
41 rawlog(Logger::Severity::DEBUG, message, who_pos)
44 def log(message=nil, who_pos=1)
45 rawlog(Logger::Severity::INFO, message, who_pos)
48 def warning(message=nil, who_pos=1)
49 rawlog(Logger::Severity::WARN, message, who_pos)
52 def error(message=nil, who_pos=1)
53 rawlog(Logger::Severity::ERROR, message, who_pos)
56 def fatal(message=nil, who_pos=1)
57 rawlog(Logger::Severity::FATAL, message, who_pos)
62 warning "warning test"
66 # The following global is used for the improved signal handling.
70 require 'rbot/rbotconfig'
74 require 'rbot/rfc2812'
75 require 'rbot/keywords'
76 require 'rbot/ircsocket'
79 require 'rbot/plugins'
80 require 'rbot/channel'
81 require 'rbot/message'
82 require 'rbot/language'
84 require 'rbot/registry'
85 require 'rbot/httputil'
89 # Main bot class, which manages the various components, receives messages,
90 # handles them or passes them to plugins, and contains core functionality.
92 # the bot's current nickname
95 # the bot's IrcAuth data
98 # the bot's BotConfig data
101 # the botclass for this bot (determines configdir among other things)
102 attr_reader :botclass
104 # used to perform actions periodically (saves configuration once per minute
108 # bot's Language data
111 # capabilities info for the server
112 attr_reader :capabilities
114 # channel info for channels the bot is in
115 attr_reader :channels
120 # bot's object registry, plugins get an interface to this for persistant
121 # storage (hash interface tied to a bdb file, plugins use Accessors to store
122 # and restore objects in their own namespaces.)
123 attr_reader :registry
125 # bot's plugins. This is an instance of class Plugins
128 # bot's httputil help object, for fetching resources via http. Sets up
129 # proxies etc as defined by the bot configuration/environment
130 attr_reader :httputil
132 # create a new IrcBot with botclass +botclass+
133 def initialize(botclass, params = {})
134 # BotConfig for the core bot
135 # TODO should we split socket stuff into ircsocket, etc?
136 BotConfig.register BotConfigStringValue.new('server.name',
137 :default => "localhost", :requires_restart => true,
138 :desc => "What server should the bot connect to?",
140 BotConfig.register BotConfigIntegerValue.new('server.port',
141 :default => 6667, :type => :integer, :requires_restart => true,
142 :desc => "What port should the bot connect to?",
143 :validate => Proc.new {|v| v > 0}, :wizard => true)
144 BotConfig.register BotConfigStringValue.new('server.password',
145 :default => false, :requires_restart => true,
146 :desc => "Password for connecting to this server (if required)",
148 BotConfig.register BotConfigStringValue.new('server.bindhost',
149 :default => false, :requires_restart => true,
150 :desc => "Specific local host or IP for the bot to bind to (if required)",
152 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
153 :default => 5, :validate => Proc.new{|v| v >= 0},
154 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
155 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
156 :default => 2.0, :validate => Proc.new{|v| v >= 0},
157 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
158 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
159 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
160 :default => 4, :validate => Proc.new{|v| v >= 0},
161 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
162 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
163 BotConfig.register BotConfigStringValue.new('server.byterate',
164 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
165 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
166 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
167 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
168 :default => 30, :validate => Proc.new{|v| v >= 0},
169 :on_change => Proc.new {|bot, v| bot.start_server_pings},
170 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
172 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
173 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
174 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
175 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
176 :requires_restart => true,
177 :desc => "local user the bot should appear to be", :wizard => true)
178 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
179 :default => [], :wizard => true,
180 :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'")
181 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
183 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
185 BotConfig.register BotConfigIntegerValue.new('core.save_every',
186 :default => 60, :validate => Proc.new{|v| v >= 0},
187 # TODO change timer via on_change proc
188 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
190 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
191 :default => false, :requires_restart => true,
192 :desc => "Should the bot run as a daemon?")
194 BotConfig.register BotConfigStringValue.new('log.file',
195 :default => false, :requires_restart => true,
196 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
197 BotConfig.register BotConfigIntegerValue.new('log.level',
198 :default => 1, :requires_restart => false,
199 :validate => Proc.new { |v| (0..5).include?(v) },
200 :on_change => Proc.new { |bot, v|
203 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
204 BotConfig.register BotConfigIntegerValue.new('log.keep',
205 :default => 1, :requires_restart => true,
206 :validate => Proc.new { |v| v >= 0 },
207 :desc => "How many old console messages logfiles to keep")
208 BotConfig.register BotConfigIntegerValue.new('log.max_size',
209 :default => 10, :requires_restart => true,
210 :validate => Proc.new { |v| v > 0 },
211 :desc => "Maximum console messages logfile size (in megabytes)")
213 @argv = params[:argv]
215 unless FileTest.directory? Config::datadir
216 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
220 unless botclass and not botclass.empty?
221 # We want to find a sensible default.
222 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
223 # * On Windows (at least the NT versions) we want to put our stuff in the
224 # Application Data folder.
225 # We don't use any particular O/S detection magic, exploiting the fact that
226 # Etc.getpwuid is nil on Windows
227 if Etc.getpwuid(Process::Sys.geteuid)
228 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
230 if ENV.has_key?('APPDATA')
231 botclass = ENV['APPDATA'].dup
232 botclass.gsub!("\\","/")
237 botclass = File.expand_path(botclass)
238 @botclass = botclass.gsub(/\/$/, "")
240 unless FileTest.directory? botclass
241 log "no #{botclass} directory found, creating from templates.."
242 if FileTest.exist? botclass
243 error "file #{botclass} exists but isn't a directory"
246 FileUtils.cp_r Config::datadir+'/templates', botclass
249 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
250 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
255 @startup_time = Time.new
256 @config = BotConfig.new(self)
258 if @config['core.run_as_daemon']
262 @logfile = @config['log.file']
263 if @logfile.class!=String || @logfile.empty?
264 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
267 # See http://blog.humlab.umu.se/samuel/archives/000107.html
268 # for the backgrounding code
274 rescue NotImplementedError
275 warning "Could not background, fork not supported"
277 warning "Could not background. #{e.inspect}"
280 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
281 log "Redirecting standard input/output/error"
283 STDIN.reopen "/dev/null"
285 # On Windows, there's not such thing as /dev/null
288 def STDOUT.write(str=nil)
290 return str.to_s.length
292 def STDERR.write(str=nil)
293 if str.to_s.match(/:\d+: warning:/)
298 return str.to_s.length
302 # Set the new logfile and loglevel. This must be done after the daemonizing
303 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
304 $logger.datetime_format= $dateformat
305 $logger.level = @config['log.level']
306 $logger.level = $cl_loglevel if $cl_loglevel
307 $logger.level = 0 if $debug
311 @timer = Timer::Timer.new(1.0) # only need per-second granularity
312 @registry = BotRegistry.new self
313 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
316 @httputil = Utils::HttpUtil.new(self)
317 @lang = Language::Language.new(@config['core.language'])
318 @keywords = Keywords.new(self)
320 @auth = IrcAuth.new(self)
323 fatal e.backtrace.join("\n")
328 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
329 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
331 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
332 @nick = @config['irc.nick']
334 @client = IrcClient.new
335 @client[:isupport] = proc { |data|
337 sendq "CAPAB IDENTIFY-MSG"
340 @client[:datastr] = proc { |data|
342 if data[:text] == "IDENTIFY-MSG"
343 @capabilities["identify-msg".to_sym] = true
345 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
348 @client[:privmsg] = proc { |data|
349 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
352 @client[:notice] = proc { |data|
353 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
354 # pass it off to plugins that want to hear everything
355 @plugins.delegate "listen", message
357 @client[:motd] = proc { |data|
358 data[:motd].each_line { |line|
359 irclog "MOTD: #{line}", "server"
362 @client[:nicktaken] = proc { |data|
363 nickchg "#{data[:nick]}_"
364 @plugins.delegate "nicktaken", data[:nick]
366 @client[:badnick] = proc {|data|
367 warning "bad nick (#{data[:nick]})"
369 @client[:ping] = proc {|data|
370 @socket.queue "PONG #{data[:pingid]}"
372 @client[:pong] = proc {|data|
375 @client[:nick] = proc {|data|
376 sourcenick = data[:sourcenick]
378 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
379 if(sourcenick == @nick)
380 debug "my nick is now #{nick}"
383 @channels.each {|k,v|
384 if(v.users.has_key?(sourcenick))
385 irclog "@ #{sourcenick} is now known as #{nick}", k
386 v.users[nick] = v.users[sourcenick]
387 v.users.delete(sourcenick)
390 @plugins.delegate("listen", m)
391 @plugins.delegate("nick", m)
393 @client[:quit] = proc {|data|
394 source = data[:source]
395 sourcenick = data[:sourcenick]
396 sourceurl = data[:sourceaddress]
397 message = data[:message]
398 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
399 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
401 @channels.each {|k,v|
402 if(v.users.has_key?(sourcenick))
403 irclog "@ Quit: #{sourcenick}: #{message}", k
404 v.users.delete(sourcenick)
408 @plugins.delegate("listen", m)
409 @plugins.delegate("quit", m)
411 @client[:mode] = proc {|data|
412 source = data[:source]
413 sourcenick = data[:sourcenick]
414 sourceurl = data[:sourceaddress]
415 channel = data[:channel]
416 targets = data[:targets]
417 modestring = data[:modestring]
418 irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
420 @client[:welcome] = proc {|data|
421 irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
422 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
423 if data[:nick] && data[:nick].length > 0
427 @plugins.delegate("connect")
429 @config['irc.join_channels'].each {|c|
430 debug "autojoining channel #{c}"
431 if(c =~ /^(\S+)\s+(\S+)$/i)
438 @client[:join] = proc {|data|
439 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
442 @client[:part] = proc {|data|
443 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
446 @client[:kick] = proc {|data|
447 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
450 @client[:invite] = proc {|data|
451 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
452 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
455 @client[:changetopic] = proc {|data|
456 channel = data[:channel]
457 sourcenick = data[:sourcenick]
459 timestamp = data[:unixtime] || Time.now.to_i
460 if(sourcenick == @nick)
461 irclog "@ I set topic \"#{topic}\"", channel
463 irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
465 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
468 @plugins.delegate("listen", m)
469 @plugins.delegate("topic", m)
471 @client[:topic] = @client[:topicinfo] = proc {|data|
472 channel = data[:channel]
473 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
476 @client[:names] = proc {|data|
477 channel = data[:channel]
479 unless(@channels[channel])
480 warning "got names for channel '#{channel}' I didn't think I was in\n"
483 @channels[channel].users.clear
485 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
487 @plugins.delegate "names", data[:channel], data[:users]
489 @client[:unknown] = proc {|data|
490 #debug "UNKNOWN: #{data[:serverstring]}"
491 irclog data[:serverstring], ".unknown"
496 debug "received #{sig}, queueing quit"
498 debug "interrupted #{$interrupted} times"
503 elsif $interrupted >= 3
509 # connect the bot to IRC
512 trap("SIGINT") { got_sig("SIGINT") }
513 trap("SIGTERM") { got_sig("SIGTERM") }
514 trap("SIGHUP") { got_sig("SIGHUP") }
515 rescue ArgumentError => e
516 debug "failed to trap signals (#{e.inspect}): running on Windows?"
518 debug "failed to trap signals: #{e.inspect}"
521 quit if $interrupted > 0
524 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
526 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
527 @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
528 @capabilities = Hash.new
532 # begin event handling loop
536 quit if $interrupted > 0
540 while @socket.connected?
542 break unless reply = @socket.gets
543 @client.process reply
545 quit if $interrupted > 0
548 # I despair of this. Some of my users get "connection reset by peer"
549 # exceptions that ARENT SocketError's. How am I supposed to handle
554 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
555 error "network exception: #{e.class}: #{e}"
556 debug e.backtrace.join("\n")
557 rescue BDB::Fatal => e
558 fatal "fatal bdb error: #{e.class}: #{e}"
559 fatal e.backtrace.join("\n")
561 # Why restart? DB problems are serious stuff ...
562 # restart("Oops, we seem to have registry problems ...")
565 rescue Exception => e
566 error "non-net exception: #{e.class}: #{e}"
567 error e.backtrace.join("\n")
569 fatal "unexpected exception: #{e.class}: #{e}"
570 fatal e.backtrace.join("\n")
577 if @socket.connected?
584 quit if $interrupted > 0
586 log "waiting to reconnect"
587 sleep @config['server.reconnect_wait']
591 # type:: message type
592 # where:: message target
593 # message:: message text
594 # send message +message+ of type +type+ to target +where+
595 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
596 # relevant say() or notice() methods. This one should be used for IRCd
597 # extensions you want to use in modules.
598 def sendmsg(type, where, message, chan=nil, ring=0)
599 # limit it according to the byterate, splitting the message
600 # taking into consideration the actual message length
601 # and all the extra stuff
602 # TODO allow something to do for commands that produce too many messages
603 # TODO example: math 10**10000
604 left = @socket.bytes_per - type.length - where.length - 4
606 if(left >= message.length)
607 sendq "#{type} #{where} :#{message}", chan, ring
608 log_sent(type, where, message)
611 line = message.slice!(0, left)
612 lastspace = line.rindex(/\s+/)
614 message = line.slice!(lastspace, line.length) + message
615 message.gsub!(/^\s+/, "")
617 sendq "#{type} #{where} :#{line}", chan, ring
618 log_sent(type, where, line)
619 end while(message.length > 0)
622 # queue an arbitraty message for the server
623 def sendq(message="", chan=nil, ring=0)
625 @socket.queue(message, chan, ring)
628 # send a notice message to channel/nick +where+
629 def notice(where, message, mchan=nil, mring=-1)
644 message.each_line { |line|
646 next unless(line.length > 0)
647 sendmsg "NOTICE", where, line, chan, ring
651 # say something (PRIVMSG) to channel/nick +where+
652 def say(where, message, mchan="", mring=-1)
667 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
669 next unless(line.length > 0)
670 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
671 sendmsg "PRIVMSG", where, line, chan, ring
676 # perform a CTCP action with message +message+ to channel/nick +where+
677 def action(where, message, mchan="", mring=-1)
692 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
694 irclog "* #{@nick} #{message}", where
695 elsif (where =~ /^(\S*)!.*$/)
696 irclog "* #{@nick}[#{where}] #{message}", $1
698 irclog "* #{@nick}[#{where}] #{message}", where
702 # quick way to say "okay" (or equivalent) to +where+
704 say where, @lang.get("okay")
707 # log IRC-related message +message+ to a file determined by +where+.
708 # +where+ can be a channel name, or a nick for private message logging
709 def irclog(message, where="server")
710 message = message.chomp
711 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
712 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
713 unless(@logs.has_key?(where))
714 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
715 @logs[where].sync = true
717 @logs[where].puts "[#{stamp}] #{message}"
718 #debug "[#{stamp}] <#{where}> #{message}"
721 # set topic of channel +where+ to +topic+
722 def topic(where, topic)
723 sendq "TOPIC #{where} :#{topic}", where, 2
726 # disconnect from the server and cleanup all plugins and modules
727 def shutdown(message = nil)
728 debug "Shutting down ..."
729 ## No we don't restore them ... let everything run through
731 # trap("SIGINT", "DEFAULT")
732 # trap("SIGTERM", "DEFAULT")
733 # trap("SIGHUP", "DEFAULT")
735 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
737 message = @lang.get("quit") if (message.nil? || message.empty?)
738 if @socket.connected?
739 debug "Clearing socket"
741 debug "Sending quit message"
742 @socket.emergency_puts "QUIT :#{message}"
743 debug "Flushing socket"
745 debug "Shutting down socket"
748 debug "Logging quits"
749 @channels.each_value {|v|
750 irclog "@ quit (#{message})", v.name
756 # debug "Closing registries"
758 debug "Cleaning up the db environment"
760 log "rbot quit (#{message})"
763 # message:: optional IRC quit message
764 # quit IRC, shutdown the bot
765 def quit(message=nil)
773 # totally shutdown and respawn the bot
774 def restart(message = false)
775 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
777 sleep @config['server.reconnect_wait']
779 # Note, this fails on Windows
783 # call the save method for bot's config, keywords, auth and all plugins
792 # call the rescan method for the bot's lang, keywords and all plugins
799 # channel:: channel to join
800 # key:: optional channel key if channel is +s
802 def join(channel, key=nil)
804 sendq "JOIN #{channel} :#{key}", channel, 2
806 sendq "JOIN #{channel}", channel, 2
811 def part(channel, message="")
812 sendq "PART #{channel} :#{message}", channel, 2
815 # attempt to change bot's nick to +name+
821 def mode(channel, mode, target)
822 sendq "MODE #{channel} #{mode} #{target}", channel, 2
825 # m:: message asking for help
826 # topic:: optional topic help is requested for
827 # respond to online help requests
829 topic = nil if topic == ""
832 helpstr = "help topics: core, auth, keywords"
833 helpstr += @plugins.helptopics
834 helpstr += " (help <topic> for more info)"
837 when /^core\s+(.+)$/i
838 helpstr = corehelp $1
841 when /^auth\s+(.+)$/i
842 helpstr = @auth.help $1
844 helpstr = @keywords.help
845 when /^keywords\s+(.+)$/i
846 helpstr = @keywords.help $1
848 unless(helpstr = @plugins.help(topic))
849 helpstr = "no help for topic #{topic}"
855 # returns a string describing the current status of the bot (uptime etc)
857 secs_up = Time.new - @startup_time
858 uptime = Utils.secs_to_string secs_up
859 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
860 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
863 # we'll ping the server every 30 seconds or so, and expect a response
864 # before the next one come around..
865 def start_server_pings
867 return unless @config['server.ping_timeout'] > 0
868 # we want to respond to a hung server within 30 secs or so
869 @ping_timer = @timer.add(30) {
870 @last_ping = Time.now
871 @socket.queue "PING :rbot"
873 @pong_timer = @timer.add(10) {
874 unless @last_ping.nil?
875 diff = Time.now - @last_ping
876 unless diff < @config['server.ping_timeout']
877 debug "no PONG from server for #{diff} seconds, reconnecting"
881 debug "couldn't shutdown connection (already shutdown?)"
884 raise TimeoutError, "no PONG from server in #{diff} seconds"
890 def stop_server_pings
892 # stop existing timers if running
893 unless @ping_timer.nil?
894 @timer.remove @ping_timer
897 unless @pong_timer.nil?
898 @timer.remove @pong_timer
905 # handle help requests for "core" topics
906 def corehelp(topic="")
909 return "quit [<message>] => quit IRC with message <message>"
911 return "restart => completely stop and restart the bot (including reconnect)"
913 return "join <channel> [<key>] => join channel <channel> with secret key <key> if specified. #{@nick} also responds to invites if you have the required access level"
915 return "part <channel> => part channel <channel>"
917 return "hide => part all channels"
919 return "save => save current dynamic data and configuration"
921 return "rescan => reload modules and static facts"
923 return "nick <nick> => attempt to change nick to <nick>"
925 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
927 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
929 # return "topic <channel> <message> => set topic of <channel> to <message>"
931 return "quiet [in here|<channel>] => with no arguments, stop speaking in all channels, if \"in here\", stop speaking in this channel, or stop speaking in <channel>"
933 return "talk [in here|<channel>] => with no arguments, resume speaking in all channels, if \"in here\", resume speaking in this channel, or resume speaking in <channel>"
935 return "version => describes software version"
937 return "botsnack => reward #{@nick} for being good"
939 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
941 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
945 # handle incoming IRC PRIVMSG +m+
950 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
952 irclog "* #{m.sourcenick} #{m.message}", m.target
956 irclog "<#{m.sourcenick}> #{m.message}", m.target
958 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
962 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
964 # pass it off to plugins that want to hear everything
965 @plugins.delegate "listen", m
967 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
968 notice m.sourcenick, "\001PING #$1\001"
969 irclog "@ #{m.sourcenick} pinged me"
976 when (/^join\s+(\S+)\s+(\S+)$/i)
977 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
978 when (/^join\s+(\S+)$/i)
979 join $1 if(@auth.allow?("join", m.source, m.replyto))
981 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
982 when (/^part\s+(\S+)$/i)
983 part $1 if(@auth.allow?("join", m.source, m.replyto))
984 when (/^quit(?:\s+(.*))?$/i)
985 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
986 when (/^restart(?:\s+(.*))?$/i)
987 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
989 join 0 if(@auth.allow?("join", m.source, m.replyto))
991 if(@auth.allow?("config", m.source, m.replyto))
995 when (/^nick\s+(\S+)$/i)
996 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
997 when (/^say\s+(\S+)\s+(.*)$/i)
998 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
999 when (/^action\s+(\S+)\s+(.*)$/i)
1000 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
1001 # when (/^topic\s+(\S+)\s+(.*)$/i)
1002 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
1003 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
1004 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
1006 say m.replyto, "pong"
1008 if(@auth.allow?("config", m.source, m.replyto))
1009 m.reply "saving ..."
1011 m.reply "rescanning ..."
1013 m.reply "done. #{@plugins.status(true)}"
1016 if(auth.allow?("talk", m.source, m.replyto))
1018 @channels.each_value {|c| c.quiet = true }
1020 when (/^quiet in (\S+)$/i)
1022 if(auth.allow?("talk", m.source, m.replyto))
1024 where.gsub!(/^here$/, m.target) if m.public?
1025 @channels[where].quiet = true if(@channels.has_key?(where))
1028 if(auth.allow?("talk", m.source, m.replyto))
1029 @channels.each_value {|c| c.quiet = false }
1032 when (/^talk in (\S+)$/i)
1034 if(auth.allow?("talk", m.source, m.replyto))
1035 where.gsub!(/^here$/, m.target) if m.public?
1036 @channels[where].quiet = false if(@channels.has_key?(where))
1039 when (/^status\??$/i)
1040 m.reply status if auth.allow?("status", m.source, m.replyto)
1041 when (/^registry stats$/i)
1042 if auth.allow?("config", m.source, m.replyto)
1043 m.reply @registry.stat.inspect
1045 when (/^(help\s+)?config(\s+|$)/)
1047 when (/^(version)|(introduce yourself)$/i)
1048 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1049 when (/^help(?:\s+(.*))?$/i)
1050 say m.replyto, help($1)
1051 #TODO move these to a "chatback" plugin
1052 when (/^(botsnack|ciggie)$/i)
1053 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1054 say m.replyto, @lang.get("thanks") if(m.private?)
1055 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1056 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1057 say m.replyto, @lang.get("hello") if(m.private?)
1060 # stuff to handle when not addressed
1062 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1063 say m.replyto, @lang.get("hello_X") % m.sourcenick
1064 when (/^#{Regexp.escape(@nick)}!*$/)
1065 say m.replyto, @lang.get("hello_X") % m.sourcenick
1067 @keywords.privmsg(m)
1072 # log a message. Internal use only.
1073 def log_sent(type, where, message)
1077 irclog "-=#{@nick}=- #{message}", where
1078 elsif (where =~ /(\S*)!.*/)
1079 irclog "[-=#{where}=-] #{message}", $1
1081 irclog "[-=#{where}=-] #{message}"
1085 irclog "<#{@nick}> #{message}", where
1086 elsif (where =~ /^(\S*)!.*$/)
1087 irclog "[msg(#{where})] #{message}", $1
1089 irclog "[msg(#{where})] #{message}", where
1095 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1097 debug "joined channel #{m.channel}"
1098 irclog "@ Joined channel #{m.channel}", m.channel
1100 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1101 @channels[m.channel].users[m.sourcenick] = Hash.new
1102 @channels[m.channel].users[m.sourcenick]["mode"] = ""
1105 @plugins.delegate("listen", m)
1106 @plugins.delegate("join", m)
1111 debug "left channel #{m.channel}"
1112 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1113 @channels.delete(m.channel)
1115 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1116 if @channels.has_key?(m.channel)
1117 @channels[m.channel].users.delete(m.sourcenick)
1119 warning "got part for channel '#{channel}' I didn't think I was in\n"
1124 # delegate to plugins
1125 @plugins.delegate("listen", m)
1126 @plugins.delegate("part", m)
1129 # respond to being kicked from a channel
1132 debug "kicked from channel #{m.channel}"
1133 @channels.delete(m.channel)
1134 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1136 @channels[m.channel].users.delete(m.sourcenick)
1137 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1140 @plugins.delegate("listen", m)
1141 @plugins.delegate("kick", m)
1145 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1146 @channels[m.channel].topic = m.topic if !m.topic.nil?
1147 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1148 @channels[m.channel].topic.by = m.source if !m.source.nil?
1150 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1153 # delegate a privmsg to auth, keyword or plugin handlers
1154 def delegate_privmsg(message)
1155 [@auth, @plugins, @keywords].each {|m|
1156 break if m.privmsg(message)