5 $debug = false unless $debug
6 $daemonize = false unless $daemonize
8 # TODO we should use the actual Logger class
9 def rawlog(code="", message=nil)
10 if !code || code.empty?
13 c = code.to_s[0,1].upcase + ":"
16 case call_stack.length
18 $stderr.puts "ERROR IN THE LOGGING SYSTEM, THIS CAN'T HAPPEN"
21 $stderr.puts "ERROR IN THE LOGGING SYSTEM, THIS CAN'T HAPPEN"
24 who = call_stack[1].match(%r{(?:.+)/([^/]+):(\d+)(?::(in .*))?})[1,3].join(":")
26 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
27 message.to_s.each_line { |l|
28 $stdout.puts "#{c} [#{stamp}] #{who} -- #{l}"
38 rawlog("", "\n=== #{botclass} session ended ===") if $daemonize
41 def debug(message=nil)
42 rawlog("D", message) if $debug
45 def warning(message=nil)
49 def error(message=nil)
53 # The following global is used for the improved signal handling.
57 require 'rbot/rbotconfig'
61 require 'rbot/rfc2812'
62 require 'rbot/keywords'
63 require 'rbot/ircsocket'
66 require 'rbot/plugins'
67 require 'rbot/channel'
68 require 'rbot/message'
69 require 'rbot/language'
71 require 'rbot/registry'
72 require 'rbot/httputil'
76 # Main bot class, which manages the various components, receives messages,
77 # handles them or passes them to plugins, and contains core functionality.
79 # the bot's current nickname
82 # the bot's IrcAuth data
85 # the bot's BotConfig data
88 # the botclass for this bot (determines configdir among other things)
91 # used to perform actions periodically (saves configuration once per minute
98 # capabilities info for the server
99 attr_reader :capabilities
101 # channel info for channels the bot is in
102 attr_reader :channels
107 # bot's object registry, plugins get an interface to this for persistant
108 # storage (hash interface tied to a bdb file, plugins use Accessors to store
109 # and restore objects in their own namespaces.)
110 attr_reader :registry
112 # bot's plugins. This is an instance of class Plugins
115 # bot's httputil help object, for fetching resources via http. Sets up
116 # proxies etc as defined by the bot configuration/environment
117 attr_reader :httputil
119 # create a new IrcBot with botclass +botclass+
120 def initialize(botclass, params = {})
121 # BotConfig for the core bot
122 # TODO should we split socket stuff into ircsocket, etc?
123 BotConfig.register BotConfigStringValue.new('server.name',
124 :default => "localhost", :requires_restart => true,
125 :desc => "What server should the bot connect to?",
127 BotConfig.register BotConfigIntegerValue.new('server.port',
128 :default => 6667, :type => :integer, :requires_restart => true,
129 :desc => "What port should the bot connect to?",
130 :validate => Proc.new {|v| v > 0}, :wizard => true)
131 BotConfig.register BotConfigStringValue.new('server.password',
132 :default => false, :requires_restart => true,
133 :desc => "Password for connecting to this server (if required)",
135 BotConfig.register BotConfigStringValue.new('server.bindhost',
136 :default => false, :requires_restart => true,
137 :desc => "Specific local host or IP for the bot to bind to (if required)",
139 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
140 :default => 5, :validate => Proc.new{|v| v >= 0},
141 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
142 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
143 :default => 2.0, :validate => Proc.new{|v| v >= 0},
144 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
145 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
146 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
147 :default => 4, :validate => Proc.new{|v| v >= 0},
148 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
149 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
150 BotConfig.register BotConfigStringValue.new('server.byterate',
151 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
152 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
153 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
154 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
155 :default => 30, :validate => Proc.new{|v| v >= 0},
156 :on_change => Proc.new {|bot, v| bot.start_server_pings},
157 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
159 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
160 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
161 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
162 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
163 :requires_restart => true,
164 :desc => "local user the bot should appear to be", :wizard => true)
165 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
166 :default => [], :wizard => true,
167 :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'")
168 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
170 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
172 BotConfig.register BotConfigIntegerValue.new('core.save_every',
173 :default => 60, :validate => Proc.new{|v| v >= 0},
174 # TODO change timer via on_change proc
175 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
176 # BotConfig.register BotConfigBooleanValue.new('core.debug',
177 # :default => false, :requires_restart => true,
178 # :on_change => Proc.new { |v|
179 # debug ((v ? "Enabling" : "Disabling") + " debug output.")
181 # debug (($debug ? "Enabled" : "Disabled") + " debug output.")
183 # :desc => "Should the bot produce debug output?")
184 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
185 :default => false, :requires_restart => true,
186 :desc => "Should the bot run as a daemon?")
187 BotConfig.register BotConfigStringValue.new('core.logfile',
188 :default => false, :requires_restart => true,
189 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
191 @argv = params[:argv]
193 unless FileTest.directory? Config::datadir
194 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
198 unless botclass and not botclass.empty?
199 # We want to find a sensible default.
200 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
201 # * On Windows (at least the NT versions) we want to put our stuff in the
202 # Application Data folder.
203 # We don't use any particular O/S detection magic, exploiting the fact that
204 # Etc.getpwuid is nil on Windows
205 if Etc.getpwuid(Process::Sys.geteuid)
206 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
208 if ENV.has_key?('APPDATA')
209 botclass = ENV['APPDATA'].dup
210 botclass.gsub!("\\","/")
215 botclass = File.expand_path(botclass)
216 @botclass = botclass.gsub(/\/$/, "")
218 unless FileTest.directory? botclass
219 log "no #{botclass} directory found, creating from templates.."
220 if FileTest.exist? botclass
221 error "file #{botclass} exists but isn't a directory"
224 FileUtils.cp_r Config::datadir+'/templates', botclass
227 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
228 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
233 @startup_time = Time.new
234 @config = BotConfig.new(self)
235 # background self after botconfig has a chance to run wizard
236 @logfile = @config['core.logfile']
237 if @logfile.class!=String || @logfile.empty?
238 @logfile = File.basename(botclass)+".log"
240 if @config['core.run_as_daemon']
243 # See http://blog.humlab.umu.se/samuel/archives/000107.html
244 # for the backgrounding code
250 rescue NotImplementedError
251 warning "Could not background, fork not supported"
253 warning "Could not background. #{e.inspect}"
256 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
257 log "Redirecting standard input/output/error"
259 STDIN.reopen "/dev/null"
261 # On Windows, there's not such thing as /dev/null
264 STDOUT.reopen @logfile, "a"
266 log "\n=== #{botclass} session started ==="
269 @timer = Timer::Timer.new(1.0) # only need per-second granularity
270 @registry = BotRegistry.new self
271 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
274 @httputil = Utils::HttpUtil.new(self)
275 @lang = Language::Language.new(@config['core.language'])
276 @keywords = Keywords.new(self)
277 @auth = IrcAuth.new(self)
279 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
280 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
282 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
283 @nick = @config['irc.nick']
285 @client = IrcClient.new
286 @client[:isupport] = proc { |data|
288 sendq "CAPAB IDENTIFY-MSG"
291 @client[:datastr] = proc { |data|
293 if data[:text] == "IDENTIFY-MSG"
294 @capabilities["identify-msg".to_sym] = true
296 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
299 @client[:privmsg] = proc { |data|
300 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
303 @client[:notice] = proc { |data|
304 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
305 # pass it off to plugins that want to hear everything
306 @plugins.delegate "listen", message
308 @client[:motd] = proc { |data|
309 data[:motd].each_line { |line|
310 irclog "MOTD: #{line}", "server"
313 @client[:nicktaken] = proc { |data|
314 nickchg "#{data[:nick]}_"
315 @plugins.delegate "nicktaken", data[:nick]
317 @client[:badnick] = proc {|data|
318 warning "bad nick (#{data[:nick]})"
320 @client[:ping] = proc {|data|
321 @socket.queue "PONG #{data[:pingid]}"
323 @client[:pong] = proc {|data|
326 @client[:nick] = proc {|data|
327 sourcenick = data[:sourcenick]
329 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
330 if(sourcenick == @nick)
331 debug "my nick is now #{nick}"
334 @channels.each {|k,v|
335 if(v.users.has_key?(sourcenick))
336 irclog "@ #{sourcenick} is now known as #{nick}", k
337 v.users[nick] = v.users[sourcenick]
338 v.users.delete(sourcenick)
341 @plugins.delegate("listen", m)
342 @plugins.delegate("nick", m)
344 @client[:quit] = proc {|data|
345 source = data[:source]
346 sourcenick = data[:sourcenick]
347 sourceurl = data[:sourceaddress]
348 message = data[:message]
349 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
350 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
352 @channels.each {|k,v|
353 if(v.users.has_key?(sourcenick))
354 irclog "@ Quit: #{sourcenick}: #{message}", k
355 v.users.delete(sourcenick)
359 @plugins.delegate("listen", m)
360 @plugins.delegate("quit", m)
362 @client[:mode] = proc {|data|
363 source = data[:source]
364 sourcenick = data[:sourcenick]
365 sourceurl = data[:sourceaddress]
366 channel = data[:channel]
367 targets = data[:targets]
368 modestring = data[:modestring]
369 irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
371 @client[:welcome] = proc {|data|
372 irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
373 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
374 if data[:nick] && data[:nick].length > 0
378 @plugins.delegate("connect")
380 @config['irc.join_channels'].each {|c|
381 debug "autojoining channel #{c}"
382 if(c =~ /^(\S+)\s+(\S+)$/i)
389 @client[:join] = proc {|data|
390 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
393 @client[:part] = proc {|data|
394 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
397 @client[:kick] = proc {|data|
398 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
401 @client[:invite] = proc {|data|
402 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
403 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
406 @client[:changetopic] = proc {|data|
407 channel = data[:channel]
408 sourcenick = data[:sourcenick]
410 timestamp = data[:unixtime] || Time.now.to_i
411 if(sourcenick == @nick)
412 irclog "@ I set topic \"#{topic}\"", channel
414 irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
416 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
419 @plugins.delegate("listen", m)
420 @plugins.delegate("topic", m)
422 @client[:topic] = @client[:topicinfo] = proc {|data|
423 channel = data[:channel]
424 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
427 @client[:names] = proc {|data|
428 channel = data[:channel]
430 unless(@channels[channel])
431 warning "got names for channel '#{channel}' I didn't think I was in\n"
434 @channels[channel].users.clear
436 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
438 @plugins.delegate "names", data[:channel], data[:users]
440 @client[:unknown] = proc {|data|
441 #debug "UNKNOWN: #{data[:serverstring]}"
442 irclog data[:serverstring], ".unknown"
447 debug "received #{sig}, queueing quit"
449 debug "interrupted #{$interrupted} times"
454 elsif $interrupted >= 3
460 # connect the bot to IRC
463 trap("SIGINT") { got_sig("SIGINT") }
464 trap("SIGTERM") { got_sig("SIGTERM") }
465 trap("SIGHUP") { got_sig("SIGHUP") }
466 rescue ArgumentError => e
467 debug "failed to trap signals (#{e.inspect}): running on Windows?"
469 debug "failed to trap signals: #{e.inspect}"
472 quit if $interrupted > 0
475 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
477 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
478 @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
479 @capabilities = Hash.new
483 # begin event handling loop
487 quit if $interrupted > 0
491 while @socket.connected?
493 break unless reply = @socket.gets
494 @client.process reply
496 quit if $interrupted > 0
499 # I despair of this. Some of my users get "connection reset by peer"
500 # exceptions that ARENT SocketError's. How am I supposed to handle
505 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
506 error "network exception: #{e.class}: #{e}"
507 debug e.backtrace.join("\n")
508 rescue BDB::Fatal => e
509 error "fatal bdb error: #{e.class}: #{e}"
510 error e.backtrace.join("\n")
512 restart("Oops, we seem to have registry problems ...")
513 rescue Exception => e
514 error "non-net exception: #{e.class}: #{e}"
515 error e.backtrace.join("\n")
517 error "unexpected exception: #{e.class}: #{e}"
518 error e.backtrace.join("\n")
525 if @socket.connected?
532 quit if $interrupted > 0
534 log "waiting to reconnect"
535 sleep @config['server.reconnect_wait']
539 # type:: message type
540 # where:: message target
541 # message:: message text
542 # send message +message+ of type +type+ to target +where+
543 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
544 # relevant say() or notice() methods. This one should be used for IRCd
545 # extensions you want to use in modules.
546 def sendmsg(type, where, message, chan=nil, ring=0)
547 # limit it according to the byterate, splitting the message
548 # taking into consideration the actual message length
549 # and all the extra stuff
550 # TODO allow something to do for commands that produce too many messages
551 # TODO example: math 10**10000
552 left = @socket.bytes_per - type.length - where.length - 4
554 if(left >= message.length)
555 sendq "#{type} #{where} :#{message}", chan, ring
556 log_sent(type, where, message)
559 line = message.slice!(0, left)
560 lastspace = line.rindex(/\s+/)
562 message = line.slice!(lastspace, line.length) + message
563 message.gsub!(/^\s+/, "")
565 sendq "#{type} #{where} :#{line}", chan, ring
566 log_sent(type, where, line)
567 end while(message.length > 0)
570 # queue an arbitraty message for the server
571 def sendq(message="", chan=nil, ring=0)
573 @socket.queue(message, chan, ring)
576 # send a notice message to channel/nick +where+
577 def notice(where, message, mchan=nil, mring=-1)
592 message.each_line { |line|
594 next unless(line.length > 0)
595 sendmsg "NOTICE", where, line, chan, ring
599 # say something (PRIVMSG) to channel/nick +where+
600 def say(where, message, mchan="", mring=-1)
615 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
617 next unless(line.length > 0)
618 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
619 sendmsg "PRIVMSG", where, line, chan, ring
624 # perform a CTCP action with message +message+ to channel/nick +where+
625 def action(where, message, mchan="", mring=-1)
640 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
642 irclog "* #{@nick} #{message}", where
643 elsif (where =~ /^(\S*)!.*$/)
644 irclog "* #{@nick}[#{where}] #{message}", $1
646 irclog "* #{@nick}[#{where}] #{message}", where
650 # quick way to say "okay" (or equivalent) to +where+
652 say where, @lang.get("okay")
655 # log IRC-related message +message+ to a file determined by +where+.
656 # +where+ can be a channel name, or a nick for private message logging
657 def irclog(message, where="server")
658 message = message.chomp
659 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
660 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
661 unless(@logs.has_key?(where))
662 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
663 @logs[where].sync = true
665 @logs[where].puts "[#{stamp}] #{message}"
666 #debug "[#{stamp}] <#{where}> #{message}"
669 # set topic of channel +where+ to +topic+
670 def topic(where, topic)
671 sendq "TOPIC #{where} :#{topic}", where, 2
674 # disconnect from the server and cleanup all plugins and modules
675 def shutdown(message = nil)
676 debug "Shutting down ..."
677 ## No we don't restore them ... let everything run through
679 # trap("SIGINT", "DEFAULT")
680 # trap("SIGTERM", "DEFAULT")
681 # trap("SIGHUP", "DEFAULT")
683 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
685 message = @lang.get("quit") if (message.nil? || message.empty?)
686 if @socket.connected?
687 debug "Clearing socket"
689 debug "Sending quit message"
690 @socket.emergency_puts "QUIT :#{message}"
691 debug "Flushing socket"
693 debug "Shutting down socket"
696 debug "Logging quits"
697 @channels.each_value {|v|
698 irclog "@ quit (#{message})", v.name
704 # debug "Closing registries"
706 debug "Cleaning up the db environment"
708 log "rbot quit (#{message})"
711 # message:: optional IRC quit message
712 # quit IRC, shutdown the bot
713 def quit(message=nil)
722 # totally shutdown and respawn the bot
723 def restart(message = false)
724 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
726 sleep @config['server.reconnect_wait']
728 # Note, this fails on Windows
732 # call the save method for bot's config, keywords, auth and all plugins
741 # call the rescan method for the bot's lang, keywords and all plugins
748 # channel:: channel to join
749 # key:: optional channel key if channel is +s
751 def join(channel, key=nil)
753 sendq "JOIN #{channel} :#{key}", channel, 2
755 sendq "JOIN #{channel}", channel, 2
760 def part(channel, message="")
761 sendq "PART #{channel} :#{message}", channel, 2
764 # attempt to change bot's nick to +name+
770 def mode(channel, mode, target)
771 sendq "MODE #{channel} #{mode} #{target}", channel, 2
774 # m:: message asking for help
775 # topic:: optional topic help is requested for
776 # respond to online help requests
778 topic = nil if topic == ""
781 helpstr = "help topics: core, auth, keywords"
782 helpstr += @plugins.helptopics
783 helpstr += " (help <topic> for more info)"
786 when /^core\s+(.+)$/i
787 helpstr = corehelp $1
790 when /^auth\s+(.+)$/i
791 helpstr = @auth.help $1
793 helpstr = @keywords.help
794 when /^keywords\s+(.+)$/i
795 helpstr = @keywords.help $1
797 unless(helpstr = @plugins.help(topic))
798 helpstr = "no help for topic #{topic}"
804 # returns a string describing the current status of the bot (uptime etc)
806 secs_up = Time.new - @startup_time
807 uptime = Utils.secs_to_string secs_up
808 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
809 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
812 # we'll ping the server every 30 seconds or so, and expect a response
813 # before the next one come around..
814 def start_server_pings
816 return unless @config['server.ping_timeout'] > 0
817 # we want to respond to a hung server within 30 secs or so
818 @ping_timer = @timer.add(30) {
819 @last_ping = Time.now
820 @socket.queue "PING :rbot"
822 @pong_timer = @timer.add(10) {
823 unless @last_ping.nil?
824 diff = Time.now - @last_ping
825 unless diff < @config['server.ping_timeout']
826 debug "no PONG from server for #{diff} seconds, reconnecting"
830 debug "couldn't shutdown connection (already shutdown?)"
833 raise TimeoutError, "no PONG from server in #{diff} seconds"
839 def stop_server_pings
841 # stop existing timers if running
842 unless @ping_timer.nil?
843 @timer.remove @ping_timer
846 unless @pong_timer.nil?
847 @timer.remove @pong_timer
854 # handle help requests for "core" topics
855 def corehelp(topic="")
858 return "quit [<message>] => quit IRC with message <message>"
860 return "restart => completely stop and restart the bot (including reconnect)"
862 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"
864 return "part <channel> => part channel <channel>"
866 return "hide => part all channels"
868 return "save => save current dynamic data and configuration"
870 return "rescan => reload modules and static facts"
872 return "nick <nick> => attempt to change nick to <nick>"
874 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
876 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
878 # return "topic <channel> <message> => set topic of <channel> to <message>"
880 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>"
882 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>"
884 return "version => describes software version"
886 return "botsnack => reward #{@nick} for being good"
888 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
890 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
894 # handle incoming IRC PRIVMSG +m+
899 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
901 irclog "* #{m.sourcenick} #{m.message}", m.target
905 irclog "<#{m.sourcenick}> #{m.message}", m.target
907 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
911 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
913 # pass it off to plugins that want to hear everything
914 @plugins.delegate "listen", m
916 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
917 notice m.sourcenick, "\001PING #$1\001"
918 irclog "@ #{m.sourcenick} pinged me"
925 when (/^join\s+(\S+)\s+(\S+)$/i)
926 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
927 when (/^join\s+(\S+)$/i)
928 join $1 if(@auth.allow?("join", m.source, m.replyto))
930 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
931 when (/^part\s+(\S+)$/i)
932 part $1 if(@auth.allow?("join", m.source, m.replyto))
933 when (/^quit(?:\s+(.*))?$/i)
934 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
935 when (/^restart(?:\s+(.*))?$/i)
936 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
938 join 0 if(@auth.allow?("join", m.source, m.replyto))
940 if(@auth.allow?("config", m.source, m.replyto))
944 when (/^nick\s+(\S+)$/i)
945 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
946 when (/^say\s+(\S+)\s+(.*)$/i)
947 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
948 when (/^action\s+(\S+)\s+(.*)$/i)
949 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
950 # when (/^topic\s+(\S+)\s+(.*)$/i)
951 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
952 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
953 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
955 say m.replyto, "pong"
957 if(@auth.allow?("config", m.source, m.replyto))
960 m.reply "Rescanning ..."
965 if(auth.allow?("talk", m.source, m.replyto))
967 @channels.each_value {|c| c.quiet = true }
969 when (/^quiet in (\S+)$/i)
971 if(auth.allow?("talk", m.source, m.replyto))
973 where.gsub!(/^here$/, m.target) if m.public?
974 @channels[where].quiet = true if(@channels.has_key?(where))
977 if(auth.allow?("talk", m.source, m.replyto))
978 @channels.each_value {|c| c.quiet = false }
981 when (/^talk in (\S+)$/i)
983 if(auth.allow?("talk", m.source, m.replyto))
984 where.gsub!(/^here$/, m.target) if m.public?
985 @channels[where].quiet = false if(@channels.has_key?(where))
988 when (/^status\??$/i)
989 m.reply status if auth.allow?("status", m.source, m.replyto)
990 when (/^registry stats$/i)
991 if auth.allow?("config", m.source, m.replyto)
992 m.reply @registry.stat.inspect
994 when (/^(help\s+)?config(\s+|$)/)
996 when (/^(version)|(introduce yourself)$/i)
997 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
998 when (/^help(?:\s+(.*))?$/i)
999 say m.replyto, help($1)
1000 #TODO move these to a "chatback" plugin
1001 when (/^(botsnack|ciggie)$/i)
1002 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1003 say m.replyto, @lang.get("thanks") if(m.private?)
1004 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1005 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1006 say m.replyto, @lang.get("hello") if(m.private?)
1009 # stuff to handle when not addressed
1011 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1012 say m.replyto, @lang.get("hello_X") % m.sourcenick
1013 when (/^#{Regexp.escape(@nick)}!*$/)
1014 say m.replyto, @lang.get("hello_X") % m.sourcenick
1016 @keywords.privmsg(m)
1021 # log a message. Internal use only.
1022 def log_sent(type, where, message)
1026 irclog "-=#{@nick}=- #{message}", where
1027 elsif (where =~ /(\S*)!.*/)
1028 irclog "[-=#{where}=-] #{message}", $1
1030 irclog "[-=#{where}=-] #{message}"
1034 irclog "<#{@nick}> #{message}", where
1035 elsif (where =~ /^(\S*)!.*$/)
1036 irclog "[msg(#{where})] #{message}", $1
1038 irclog "[msg(#{where})] #{message}", where
1044 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1046 debug "joined channel #{m.channel}"
1047 irclog "@ Joined channel #{m.channel}", m.channel
1049 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1050 @channels[m.channel].users[m.sourcenick] = Hash.new
1051 @channels[m.channel].users[m.sourcenick]["mode"] = ""
1054 @plugins.delegate("listen", m)
1055 @plugins.delegate("join", m)
1060 debug "left channel #{m.channel}"
1061 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1062 @channels.delete(m.channel)
1064 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1065 if @channels.has_key?(m.channel)
1066 @channels[m.channel].users.delete(m.sourcenick)
1068 warning "got part for channel '#{channel}' I didn't think I was in\n"
1073 # delegate to plugins
1074 @plugins.delegate("listen", m)
1075 @plugins.delegate("part", m)
1078 # respond to being kicked from a channel
1081 debug "kicked from channel #{m.channel}"
1082 @channels.delete(m.channel)
1083 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1085 @channels[m.channel].users.delete(m.sourcenick)
1086 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1089 @plugins.delegate("listen", m)
1090 @plugins.delegate("kick", m)
1094 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1095 @channels[m.channel].topic = m.topic if !m.topic.nil?
1096 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1097 @channels[m.channel].topic.by = m.source if !m.source.nil?
1099 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1102 # delegate a privmsg to auth, keyword or plugin handlers
1103 def delegate_privmsg(message)
1104 [@auth, @plugins, @keywords].each {|m|
1105 break if m.privmsg(message)