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 message.to_s.each_line { |l|
24 $logger.add(level, l.chomp, who)
30 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
34 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
37 def debug(message=nil, who_pos=1)
38 rawlog(Logger::Severity::DEBUG, message, who_pos)
41 def log(message=nil, who_pos=1)
42 rawlog(Logger::Severity::INFO, message, who_pos)
45 def warning(message=nil, who_pos=1)
46 rawlog(Logger::Severity::WARN, message, who_pos)
49 def error(message=nil, who_pos=1)
50 rawlog(Logger::Severity::ERROR, message, who_pos)
53 def fatal(message=nil, who_pos=1)
54 rawlog(Logger::Severity::FATAL, message, who_pos)
59 warning "warning test"
63 # The following global is used for the improved signal handling.
67 require 'rbot/rbotconfig'
71 require 'rbot/rfc2812'
72 require 'rbot/keywords'
73 require 'rbot/ircsocket'
76 require 'rbot/plugins'
77 require 'rbot/channel'
78 require 'rbot/message'
79 require 'rbot/language'
81 require 'rbot/registry'
82 require 'rbot/httputil'
86 # Main bot class, which manages the various components, receives messages,
87 # handles them or passes them to plugins, and contains core functionality.
89 # the bot's current nickname
92 # the bot's IrcAuth data
95 # the bot's BotConfig data
98 # the botclass for this bot (determines configdir among other things)
101 # used to perform actions periodically (saves configuration once per minute
105 # bot's Language data
108 # capabilities info for the server
109 attr_reader :capabilities
111 # channel info for channels the bot is in
112 attr_reader :channels
117 # bot's object registry, plugins get an interface to this for persistant
118 # storage (hash interface tied to a bdb file, plugins use Accessors to store
119 # and restore objects in their own namespaces.)
120 attr_reader :registry
122 # bot's plugins. This is an instance of class Plugins
125 # bot's httputil help object, for fetching resources via http. Sets up
126 # proxies etc as defined by the bot configuration/environment
127 attr_reader :httputil
129 # create a new IrcBot with botclass +botclass+
130 def initialize(botclass, params = {})
131 # BotConfig for the core bot
132 # TODO should we split socket stuff into ircsocket, etc?
133 BotConfig.register BotConfigStringValue.new('server.name',
134 :default => "localhost", :requires_restart => true,
135 :desc => "What server should the bot connect to?",
137 BotConfig.register BotConfigIntegerValue.new('server.port',
138 :default => 6667, :type => :integer, :requires_restart => true,
139 :desc => "What port should the bot connect to?",
140 :validate => Proc.new {|v| v > 0}, :wizard => true)
141 BotConfig.register BotConfigStringValue.new('server.password',
142 :default => false, :requires_restart => true,
143 :desc => "Password for connecting to this server (if required)",
145 BotConfig.register BotConfigStringValue.new('server.bindhost',
146 :default => false, :requires_restart => true,
147 :desc => "Specific local host or IP for the bot to bind to (if required)",
149 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
150 :default => 5, :validate => Proc.new{|v| v >= 0},
151 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
152 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
153 :default => 2.0, :validate => Proc.new{|v| v >= 0},
154 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
155 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
156 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
157 :default => 4, :validate => Proc.new{|v| v >= 0},
158 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
159 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
160 BotConfig.register BotConfigStringValue.new('server.byterate',
161 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
162 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
163 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
164 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
165 :default => 30, :validate => Proc.new{|v| v >= 0},
166 :on_change => Proc.new {|bot, v| bot.start_server_pings},
167 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
169 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
170 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
171 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
172 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
173 :requires_restart => true,
174 :desc => "local user the bot should appear to be", :wizard => true)
175 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
176 :default => [], :wizard => true,
177 :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'")
178 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
180 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
182 BotConfig.register BotConfigIntegerValue.new('core.save_every',
183 :default => 60, :validate => Proc.new{|v| v >= 0},
184 # TODO change timer via on_change proc
185 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
187 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
188 :default => false, :requires_restart => true,
189 :desc => "Should the bot run as a daemon?")
191 BotConfig.register BotConfigStringValue.new('log.file',
192 :default => false, :requires_restart => true,
193 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
194 BotConfig.register BotConfigIntegerValue.new('log.level',
195 :default => 1, :requires_restart => false,
196 :validate => Proc.new { |v| (0..5).include?(v) },
197 :on_change => Proc.new { |bot, v|
200 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
201 BotConfig.register BotConfigIntegerValue.new('log.keep',
202 :default => 1, :requires_restart => true,
203 :validate => Proc.new { |v| v >= 0 },
204 :desc => "How many old console messages logfiles to keep")
205 BotConfig.register BotConfigIntegerValue.new('log.max_size',
206 :default => 10, :requires_restart => true,
207 :validate => Proc.new { |v| v > 0 },
208 :desc => "Maximum console messages logfile size (in megabytes)")
210 @argv = params[:argv]
212 unless FileTest.directory? Config::datadir
213 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
217 unless botclass and not botclass.empty?
218 # We want to find a sensible default.
219 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
220 # * On Windows (at least the NT versions) we want to put our stuff in the
221 # Application Data folder.
222 # We don't use any particular O/S detection magic, exploiting the fact that
223 # Etc.getpwuid is nil on Windows
224 if Etc.getpwuid(Process::Sys.geteuid)
225 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
227 if ENV.has_key?('APPDATA')
228 botclass = ENV['APPDATA'].dup
229 botclass.gsub!("\\","/")
234 botclass = File.expand_path(botclass)
235 @botclass = botclass.gsub(/\/$/, "")
237 unless FileTest.directory? botclass
238 log "no #{botclass} directory found, creating from templates.."
239 if FileTest.exist? botclass
240 error "file #{botclass} exists but isn't a directory"
243 FileUtils.cp_r Config::datadir+'/templates', botclass
246 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
247 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
252 @startup_time = Time.new
253 @config = BotConfig.new(self)
255 if @config['core.run_as_daemon']
259 @logfile = @config['log.file']
260 if @logfile.class!=String || @logfile.empty?
261 @logfile = File.basename(botclass)+".log"
264 # See http://blog.humlab.umu.se/samuel/archives/000107.html
265 # for the backgrounding code
271 rescue NotImplementedError
272 warning "Could not background, fork not supported"
274 warning "Could not background. #{e.inspect}"
277 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
278 log "Redirecting standard input/output/error"
280 STDIN.reopen "/dev/null"
282 # On Windows, there's not such thing as /dev/null
285 def STDOUT.write(str=nil)
287 return str.to_s.length
289 def STDERR.write(str=nil)
290 if str.to_s.match(/:\d+: warning:/)
295 return str.to_s.length
299 # Set the new logfile and loglevel. This must be done after the daemonizing
301 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
302 $logger.datetime_format= $dateformat
303 $logger.level = @config['log.level']
304 $logger.level = $cl_loglevel if $cl_loglevel
305 $logger.level = 0 if $debug
309 @timer = Timer::Timer.new(1.0) # only need per-second granularity
310 @registry = BotRegistry.new self
311 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
314 @httputil = Utils::HttpUtil.new(self)
315 @lang = Language::Language.new(@config['core.language'])
316 @keywords = Keywords.new(self)
317 @auth = IrcAuth.new(self)
319 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
320 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
322 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
323 @nick = @config['irc.nick']
325 @client = IrcClient.new
326 @client[:isupport] = proc { |data|
328 sendq "CAPAB IDENTIFY-MSG"
331 @client[:datastr] = proc { |data|
333 if data[:text] == "IDENTIFY-MSG"
334 @capabilities["identify-msg".to_sym] = true
336 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
339 @client[:privmsg] = proc { |data|
340 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
343 @client[:notice] = proc { |data|
344 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
345 # pass it off to plugins that want to hear everything
346 @plugins.delegate "listen", message
348 @client[:motd] = proc { |data|
349 data[:motd].each_line { |line|
350 irclog "MOTD: #{line}", "server"
353 @client[:nicktaken] = proc { |data|
354 nickchg "#{data[:nick]}_"
355 @plugins.delegate "nicktaken", data[:nick]
357 @client[:badnick] = proc {|data|
358 warning "bad nick (#{data[:nick]})"
360 @client[:ping] = proc {|data|
361 @socket.queue "PONG #{data[:pingid]}"
363 @client[:pong] = proc {|data|
366 @client[:nick] = proc {|data|
367 sourcenick = data[:sourcenick]
369 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
370 if(sourcenick == @nick)
371 debug "my nick is now #{nick}"
374 @channels.each {|k,v|
375 if(v.users.has_key?(sourcenick))
376 irclog "@ #{sourcenick} is now known as #{nick}", k
377 v.users[nick] = v.users[sourcenick]
378 v.users.delete(sourcenick)
381 @plugins.delegate("listen", m)
382 @plugins.delegate("nick", m)
384 @client[:quit] = proc {|data|
385 source = data[:source]
386 sourcenick = data[:sourcenick]
387 sourceurl = data[:sourceaddress]
388 message = data[:message]
389 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
390 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
392 @channels.each {|k,v|
393 if(v.users.has_key?(sourcenick))
394 irclog "@ Quit: #{sourcenick}: #{message}", k
395 v.users.delete(sourcenick)
399 @plugins.delegate("listen", m)
400 @plugins.delegate("quit", m)
402 @client[:mode] = proc {|data|
403 source = data[:source]
404 sourcenick = data[:sourcenick]
405 sourceurl = data[:sourceaddress]
406 channel = data[:channel]
407 targets = data[:targets]
408 modestring = data[:modestring]
409 irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
411 @client[:welcome] = proc {|data|
412 irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
413 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
414 if data[:nick] && data[:nick].length > 0
418 @plugins.delegate("connect")
420 @config['irc.join_channels'].each {|c|
421 debug "autojoining channel #{c}"
422 if(c =~ /^(\S+)\s+(\S+)$/i)
429 @client[:join] = proc {|data|
430 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
433 @client[:part] = proc {|data|
434 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
437 @client[:kick] = proc {|data|
438 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
441 @client[:invite] = proc {|data|
442 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
443 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
446 @client[:changetopic] = proc {|data|
447 channel = data[:channel]
448 sourcenick = data[:sourcenick]
450 timestamp = data[:unixtime] || Time.now.to_i
451 if(sourcenick == @nick)
452 irclog "@ I set topic \"#{topic}\"", channel
454 irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
456 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
459 @plugins.delegate("listen", m)
460 @plugins.delegate("topic", m)
462 @client[:topic] = @client[:topicinfo] = proc {|data|
463 channel = data[:channel]
464 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
467 @client[:names] = proc {|data|
468 channel = data[:channel]
470 unless(@channels[channel])
471 warning "got names for channel '#{channel}' I didn't think I was in\n"
474 @channels[channel].users.clear
476 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
478 @plugins.delegate "names", data[:channel], data[:users]
480 @client[:unknown] = proc {|data|
481 #debug "UNKNOWN: #{data[:serverstring]}"
482 irclog data[:serverstring], ".unknown"
487 debug "received #{sig}, queueing quit"
489 debug "interrupted #{$interrupted} times"
494 elsif $interrupted >= 3
500 # connect the bot to IRC
503 trap("SIGINT") { got_sig("SIGINT") }
504 trap("SIGTERM") { got_sig("SIGTERM") }
505 trap("SIGHUP") { got_sig("SIGHUP") }
506 rescue ArgumentError => e
507 debug "failed to trap signals (#{e.inspect}): running on Windows?"
509 debug "failed to trap signals: #{e.inspect}"
512 quit if $interrupted > 0
515 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
517 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
518 @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
519 @capabilities = Hash.new
523 # begin event handling loop
527 quit if $interrupted > 0
531 while @socket.connected?
533 break unless reply = @socket.gets
534 @client.process reply
536 quit if $interrupted > 0
539 # I despair of this. Some of my users get "connection reset by peer"
540 # exceptions that ARENT SocketError's. How am I supposed to handle
545 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
546 error "network exception: #{e.class}: #{e}"
547 debug e.backtrace.join("\n")
548 rescue BDB::Fatal => e
549 error "fatal bdb error: #{e.class}: #{e}"
550 error e.backtrace.join("\n")
552 restart("Oops, we seem to have registry problems ...")
553 rescue Exception => e
554 error "non-net exception: #{e.class}: #{e}"
555 error e.backtrace.join("\n")
557 error "unexpected exception: #{e.class}: #{e}"
558 error e.backtrace.join("\n")
565 if @socket.connected?
572 quit if $interrupted > 0
574 log "waiting to reconnect"
575 sleep @config['server.reconnect_wait']
579 # type:: message type
580 # where:: message target
581 # message:: message text
582 # send message +message+ of type +type+ to target +where+
583 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
584 # relevant say() or notice() methods. This one should be used for IRCd
585 # extensions you want to use in modules.
586 def sendmsg(type, where, message, chan=nil, ring=0)
587 # limit it according to the byterate, splitting the message
588 # taking into consideration the actual message length
589 # and all the extra stuff
590 # TODO allow something to do for commands that produce too many messages
591 # TODO example: math 10**10000
592 left = @socket.bytes_per - type.length - where.length - 4
594 if(left >= message.length)
595 sendq "#{type} #{where} :#{message}", chan, ring
596 log_sent(type, where, message)
599 line = message.slice!(0, left)
600 lastspace = line.rindex(/\s+/)
602 message = line.slice!(lastspace, line.length) + message
603 message.gsub!(/^\s+/, "")
605 sendq "#{type} #{where} :#{line}", chan, ring
606 log_sent(type, where, line)
607 end while(message.length > 0)
610 # queue an arbitraty message for the server
611 def sendq(message="", chan=nil, ring=0)
613 @socket.queue(message, chan, ring)
616 # send a notice message to channel/nick +where+
617 def notice(where, message, mchan=nil, mring=-1)
632 message.each_line { |line|
634 next unless(line.length > 0)
635 sendmsg "NOTICE", where, line, chan, ring
639 # say something (PRIVMSG) to channel/nick +where+
640 def say(where, message, mchan="", mring=-1)
655 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
657 next unless(line.length > 0)
658 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
659 sendmsg "PRIVMSG", where, line, chan, ring
664 # perform a CTCP action with message +message+ to channel/nick +where+
665 def action(where, message, mchan="", mring=-1)
680 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
682 irclog "* #{@nick} #{message}", where
683 elsif (where =~ /^(\S*)!.*$/)
684 irclog "* #{@nick}[#{where}] #{message}", $1
686 irclog "* #{@nick}[#{where}] #{message}", where
690 # quick way to say "okay" (or equivalent) to +where+
692 say where, @lang.get("okay")
695 # log IRC-related message +message+ to a file determined by +where+.
696 # +where+ can be a channel name, or a nick for private message logging
697 def irclog(message, where="server")
698 message = message.chomp
699 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
700 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
701 unless(@logs.has_key?(where))
702 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
703 @logs[where].sync = true
705 @logs[where].puts "[#{stamp}] #{message}"
706 #debug "[#{stamp}] <#{where}> #{message}"
709 # set topic of channel +where+ to +topic+
710 def topic(where, topic)
711 sendq "TOPIC #{where} :#{topic}", where, 2
714 # disconnect from the server and cleanup all plugins and modules
715 def shutdown(message = nil)
716 debug "Shutting down ..."
717 ## No we don't restore them ... let everything run through
719 # trap("SIGINT", "DEFAULT")
720 # trap("SIGTERM", "DEFAULT")
721 # trap("SIGHUP", "DEFAULT")
723 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
725 message = @lang.get("quit") if (message.nil? || message.empty?)
726 if @socket.connected?
727 debug "Clearing socket"
729 debug "Sending quit message"
730 @socket.emergency_puts "QUIT :#{message}"
731 debug "Flushing socket"
733 debug "Shutting down socket"
736 debug "Logging quits"
737 @channels.each_value {|v|
738 irclog "@ quit (#{message})", v.name
744 # debug "Closing registries"
746 debug "Cleaning up the db environment"
748 log "rbot quit (#{message})"
751 # message:: optional IRC quit message
752 # quit IRC, shutdown the bot
753 def quit(message=nil)
761 # totally shutdown and respawn the bot
762 def restart(message = false)
763 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
765 sleep @config['server.reconnect_wait']
767 # Note, this fails on Windows
771 # call the save method for bot's config, keywords, auth and all plugins
780 # call the rescan method for the bot's lang, keywords and all plugins
787 # channel:: channel to join
788 # key:: optional channel key if channel is +s
790 def join(channel, key=nil)
792 sendq "JOIN #{channel} :#{key}", channel, 2
794 sendq "JOIN #{channel}", channel, 2
799 def part(channel, message="")
800 sendq "PART #{channel} :#{message}", channel, 2
803 # attempt to change bot's nick to +name+
809 def mode(channel, mode, target)
810 sendq "MODE #{channel} #{mode} #{target}", channel, 2
813 # m:: message asking for help
814 # topic:: optional topic help is requested for
815 # respond to online help requests
817 topic = nil if topic == ""
820 helpstr = "help topics: core, auth, keywords"
821 helpstr += @plugins.helptopics
822 helpstr += " (help <topic> for more info)"
825 when /^core\s+(.+)$/i
826 helpstr = corehelp $1
829 when /^auth\s+(.+)$/i
830 helpstr = @auth.help $1
832 helpstr = @keywords.help
833 when /^keywords\s+(.+)$/i
834 helpstr = @keywords.help $1
836 unless(helpstr = @plugins.help(topic))
837 helpstr = "no help for topic #{topic}"
843 # returns a string describing the current status of the bot (uptime etc)
845 secs_up = Time.new - @startup_time
846 uptime = Utils.secs_to_string secs_up
847 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
848 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
851 # we'll ping the server every 30 seconds or so, and expect a response
852 # before the next one come around..
853 def start_server_pings
855 return unless @config['server.ping_timeout'] > 0
856 # we want to respond to a hung server within 30 secs or so
857 @ping_timer = @timer.add(30) {
858 @last_ping = Time.now
859 @socket.queue "PING :rbot"
861 @pong_timer = @timer.add(10) {
862 unless @last_ping.nil?
863 diff = Time.now - @last_ping
864 unless diff < @config['server.ping_timeout']
865 debug "no PONG from server for #{diff} seconds, reconnecting"
869 debug "couldn't shutdown connection (already shutdown?)"
872 raise TimeoutError, "no PONG from server in #{diff} seconds"
878 def stop_server_pings
880 # stop existing timers if running
881 unless @ping_timer.nil?
882 @timer.remove @ping_timer
885 unless @pong_timer.nil?
886 @timer.remove @pong_timer
893 # handle help requests for "core" topics
894 def corehelp(topic="")
897 return "quit [<message>] => quit IRC with message <message>"
899 return "restart => completely stop and restart the bot (including reconnect)"
901 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"
903 return "part <channel> => part channel <channel>"
905 return "hide => part all channels"
907 return "save => save current dynamic data and configuration"
909 return "rescan => reload modules and static facts"
911 return "nick <nick> => attempt to change nick to <nick>"
913 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
915 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
917 # return "topic <channel> <message> => set topic of <channel> to <message>"
919 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>"
921 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>"
923 return "version => describes software version"
925 return "botsnack => reward #{@nick} for being good"
927 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
929 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
933 # handle incoming IRC PRIVMSG +m+
938 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
940 irclog "* #{m.sourcenick} #{m.message}", m.target
944 irclog "<#{m.sourcenick}> #{m.message}", m.target
946 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
950 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
952 # pass it off to plugins that want to hear everything
953 @plugins.delegate "listen", m
955 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
956 notice m.sourcenick, "\001PING #$1\001"
957 irclog "@ #{m.sourcenick} pinged me"
964 when (/^join\s+(\S+)\s+(\S+)$/i)
965 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
966 when (/^join\s+(\S+)$/i)
967 join $1 if(@auth.allow?("join", m.source, m.replyto))
969 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
970 when (/^part\s+(\S+)$/i)
971 part $1 if(@auth.allow?("join", m.source, m.replyto))
972 when (/^quit(?:\s+(.*))?$/i)
973 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
974 when (/^restart(?:\s+(.*))?$/i)
975 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
977 join 0 if(@auth.allow?("join", m.source, m.replyto))
979 if(@auth.allow?("config", m.source, m.replyto))
983 when (/^nick\s+(\S+)$/i)
984 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
985 when (/^say\s+(\S+)\s+(.*)$/i)
986 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
987 when (/^action\s+(\S+)\s+(.*)$/i)
988 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
989 # when (/^topic\s+(\S+)\s+(.*)$/i)
990 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
991 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
992 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
994 say m.replyto, "pong"
996 if(@auth.allow?("config", m.source, m.replyto))
999 m.reply "Rescanning ..."
1004 if(auth.allow?("talk", m.source, m.replyto))
1006 @channels.each_value {|c| c.quiet = true }
1008 when (/^quiet in (\S+)$/i)
1010 if(auth.allow?("talk", m.source, m.replyto))
1012 where.gsub!(/^here$/, m.target) if m.public?
1013 @channels[where].quiet = true if(@channels.has_key?(where))
1016 if(auth.allow?("talk", m.source, m.replyto))
1017 @channels.each_value {|c| c.quiet = false }
1020 when (/^talk in (\S+)$/i)
1022 if(auth.allow?("talk", m.source, m.replyto))
1023 where.gsub!(/^here$/, m.target) if m.public?
1024 @channels[where].quiet = false if(@channels.has_key?(where))
1027 when (/^status\??$/i)
1028 m.reply status if auth.allow?("status", m.source, m.replyto)
1029 when (/^registry stats$/i)
1030 if auth.allow?("config", m.source, m.replyto)
1031 m.reply @registry.stat.inspect
1033 when (/^(help\s+)?config(\s+|$)/)
1035 when (/^(version)|(introduce yourself)$/i)
1036 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1037 when (/^help(?:\s+(.*))?$/i)
1038 say m.replyto, help($1)
1039 #TODO move these to a "chatback" plugin
1040 when (/^(botsnack|ciggie)$/i)
1041 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1042 say m.replyto, @lang.get("thanks") if(m.private?)
1043 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1044 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1045 say m.replyto, @lang.get("hello") if(m.private?)
1048 # stuff to handle when not addressed
1050 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1051 say m.replyto, @lang.get("hello_X") % m.sourcenick
1052 when (/^#{Regexp.escape(@nick)}!*$/)
1053 say m.replyto, @lang.get("hello_X") % m.sourcenick
1055 @keywords.privmsg(m)
1060 # log a message. Internal use only.
1061 def log_sent(type, where, message)
1065 irclog "-=#{@nick}=- #{message}", where
1066 elsif (where =~ /(\S*)!.*/)
1067 irclog "[-=#{where}=-] #{message}", $1
1069 irclog "[-=#{where}=-] #{message}"
1073 irclog "<#{@nick}> #{message}", where
1074 elsif (where =~ /^(\S*)!.*$/)
1075 irclog "[msg(#{where})] #{message}", $1
1077 irclog "[msg(#{where})] #{message}", where
1083 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1085 debug "joined channel #{m.channel}"
1086 irclog "@ Joined channel #{m.channel}", m.channel
1088 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1089 @channels[m.channel].users[m.sourcenick] = Hash.new
1090 @channels[m.channel].users[m.sourcenick]["mode"] = ""
1093 @plugins.delegate("listen", m)
1094 @plugins.delegate("join", m)
1099 debug "left channel #{m.channel}"
1100 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1101 @channels.delete(m.channel)
1103 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1104 if @channels.has_key?(m.channel)
1105 @channels[m.channel].users.delete(m.sourcenick)
1107 warning "got part for channel '#{channel}' I didn't think I was in\n"
1112 # delegate to plugins
1113 @plugins.delegate("listen", m)
1114 @plugins.delegate("part", m)
1117 # respond to being kicked from a channel
1120 debug "kicked from channel #{m.channel}"
1121 @channels.delete(m.channel)
1122 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1124 @channels[m.channel].users.delete(m.sourcenick)
1125 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1128 @plugins.delegate("listen", m)
1129 @plugins.delegate("kick", m)
1133 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1134 @channels[m.channel].topic = m.topic if !m.topic.nil?
1135 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1136 @channels[m.channel].topic.by = m.source if !m.source.nil?
1138 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1141 # delegate a privmsg to auth, keyword or plugin handlers
1142 def delegate_privmsg(message)
1143 [@auth, @plugins, @keywords].each {|m|
1144 break if m.privmsg(message)