5 $debug = false unless $debug
6 $daemonize = false unless $daemonize
8 def rawlog(code="", message=nil)
9 if !code || code.empty?
12 c = code.to_s[0,1].upcase + ":"
14 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
15 message.to_s.each_line { |l|
16 $stdout.puts "#{c} [#{stamp}] #{l}"
26 log("\n=== #{botclass} session ended ===") if $daemonize
29 def debug(message=nil)
30 rawlog("D", message) if $debug
33 def warning(message=nil)
37 def error(message=nil)
41 # The following global is used for the improved signal handling.
45 require 'rbot/rbotconfig'
49 require 'rbot/rfc2812'
50 require 'rbot/keywords'
51 require 'rbot/ircsocket'
54 require 'rbot/plugins'
55 require 'rbot/channel'
56 require 'rbot/message'
57 require 'rbot/language'
59 require 'rbot/registry'
60 require 'rbot/httputil'
64 # Main bot class, which manages the various components, receives messages,
65 # handles them or passes them to plugins, and contains core functionality.
67 # the bot's current nickname
70 # the bot's IrcAuth data
73 # the bot's BotConfig data
76 # the botclass for this bot (determines configdir among other things)
79 # used to perform actions periodically (saves configuration once per minute
86 # capabilities info for the server
87 attr_reader :capabilities
89 # channel info for channels the bot is in
95 # bot's object registry, plugins get an interface to this for persistant
96 # storage (hash interface tied to a bdb file, plugins use Accessors to store
97 # and restore objects in their own namespaces.)
100 # bot's plugins. This is an instance of class Plugins
103 # bot's httputil help object, for fetching resources via http. Sets up
104 # proxies etc as defined by the bot configuration/environment
105 attr_reader :httputil
107 # create a new IrcBot with botclass +botclass+
108 def initialize(botclass, params = {})
109 # BotConfig for the core bot
110 # TODO should we split socket stuff into ircsocket, etc?
111 BotConfig.register BotConfigStringValue.new('server.name',
112 :default => "localhost", :requires_restart => true,
113 :desc => "What server should the bot connect to?",
115 BotConfig.register BotConfigIntegerValue.new('server.port',
116 :default => 6667, :type => :integer, :requires_restart => true,
117 :desc => "What port should the bot connect to?",
118 :validate => Proc.new {|v| v > 0}, :wizard => true)
119 BotConfig.register BotConfigStringValue.new('server.password',
120 :default => false, :requires_restart => true,
121 :desc => "Password for connecting to this server (if required)",
123 BotConfig.register BotConfigStringValue.new('server.bindhost',
124 :default => false, :requires_restart => true,
125 :desc => "Specific local host or IP for the bot to bind to (if required)",
127 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
128 :default => 5, :validate => Proc.new{|v| v >= 0},
129 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
130 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
131 :default => 2.0, :validate => Proc.new{|v| v >= 0},
132 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
133 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
134 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
135 :default => 4, :validate => Proc.new{|v| v >= 0},
136 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
137 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
138 BotConfig.register BotConfigStringValue.new('server.byterate',
139 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
140 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
141 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
142 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
143 :default => 10, :validate => Proc.new{|v| v >= 0},
144 :on_change => Proc.new {|bot, v| bot.start_server_pings},
145 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
147 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
148 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
149 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
150 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
151 :requires_restart => true,
152 :desc => "local user the bot should appear to be", :wizard => true)
153 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
154 :default => [], :wizard => true,
155 :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'")
156 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
158 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
160 BotConfig.register BotConfigIntegerValue.new('core.save_every',
161 :default => 60, :validate => Proc.new{|v| v >= 0},
162 # TODO change timer via on_change proc
163 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
164 # BotConfig.register BotConfigBooleanValue.new('core.debug',
165 # :default => false, :requires_restart => true,
166 # :on_change => Proc.new { |v|
167 # debug ((v ? "Enabling" : "Disabling") + " debug output.")
169 # debug (($debug ? "Enabled" : "Disabled") + " debug output.")
171 # :desc => "Should the bot produce debug output?")
172 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
173 :default => false, :requires_restart => true,
174 :desc => "Should the bot run as a daemon?")
175 BotConfig.register BotConfigStringValue.new('core.logfile',
176 :default => false, :requires_restart => true,
177 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
179 @argv = params[:argv]
181 unless FileTest.directory? Config::datadir
182 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
186 botclass = "#{Etc.getpwuid(Process::Sys.geteuid)[:dir]}/.rbot" unless botclass
187 #botclass = "#{ENV['HOME']}/.rbot" unless botclass
188 botclass = File.expand_path(botclass)
189 @botclass = botclass.gsub(/\/$/, "")
191 unless FileTest.directory? botclass
192 log "no #{botclass} directory found, creating from templates.."
193 if FileTest.exist? botclass
194 error "file #{botclass} exists but isn't a directory"
197 FileUtils.cp_r Config::datadir+'/templates', botclass
200 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
201 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
206 @startup_time = Time.new
207 @config = BotConfig.new(self)
208 # background self after botconfig has a chance to run wizard
209 @logfile = @config['core.logfile']
210 if @logfile.class!=String || @logfile.empty?
211 @logfile = File.basename(botclass)+".log"
213 if @config['core.run_as_daemon']
216 # See http://blog.humlab.umu.se/samuel/archives/000107.html
217 # for the backgrounding code
223 rescue NotImplementedError
224 warning "Could not background, fork not supported"
226 warning "Could not background. #{e.inspect}"
229 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
230 log "Redirecting standard input/output/error"
232 STDIN.reopen "/dev/null"
234 # On Windows, there's not such thing as /dev/null
237 STDOUT.reopen @logfile, "a"
239 log "\n=== #{botclass} session started ==="
242 @timer = Timer::Timer.new(1.0) # only need per-second granularity
243 @registry = BotRegistry.new self
244 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
247 @httputil = Utils::HttpUtil.new(self)
248 @lang = Language::Language.new(@config['core.language'])
249 @keywords = Keywords.new(self)
250 @auth = IrcAuth.new(self)
252 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
253 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
255 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
256 @nick = @config['irc.nick']
258 @client = IrcClient.new
259 @client[:isupport] = proc { |data|
261 sendq "CAPAB IDENTIFY-MSG"
264 @client[:datastr] = proc { |data|
266 if data[:text] == "IDENTIFY-MSG"
267 @capabilities["identify-msg".to_sym] = true
269 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
272 @client[:privmsg] = proc { |data|
273 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
276 @client[:notice] = proc { |data|
277 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
278 # pass it off to plugins that want to hear everything
279 @plugins.delegate "listen", message
281 @client[:motd] = proc { |data|
282 data[:motd].each_line { |line|
283 irclog "MOTD: #{line}", "server"
286 @client[:nicktaken] = proc { |data|
287 nickchg "#{data[:nick]}_"
288 @plugins.delegate "nicktaken", data[:nick]
290 @client[:badnick] = proc {|data|
291 warning "bad nick (#{data[:nick]})"
293 @client[:ping] = proc {|data|
294 @socket.queue "PONG #{data[:pingid]}"
296 @client[:pong] = proc {|data|
299 @client[:nick] = proc {|data|
300 sourcenick = data[:sourcenick]
302 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
303 if(sourcenick == @nick)
304 debug "my nick is now #{nick}"
307 @channels.each {|k,v|
308 if(v.users.has_key?(sourcenick))
309 irclog "@ #{sourcenick} is now known as #{nick}", k
310 v.users[nick] = v.users[sourcenick]
311 v.users.delete(sourcenick)
314 @plugins.delegate("listen", m)
315 @plugins.delegate("nick", m)
317 @client[:quit] = proc {|data|
318 source = data[:source]
319 sourcenick = data[:sourcenick]
320 sourceurl = data[:sourceaddress]
321 message = data[:message]
322 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
323 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
325 @channels.each {|k,v|
326 if(v.users.has_key?(sourcenick))
327 irclog "@ Quit: #{sourcenick}: #{message}", k
328 v.users.delete(sourcenick)
332 @plugins.delegate("listen", m)
333 @plugins.delegate("quit", m)
335 @client[:mode] = proc {|data|
336 source = data[:source]
337 sourcenick = data[:sourcenick]
338 sourceurl = data[:sourceaddress]
339 channel = data[:channel]
340 targets = data[:targets]
341 modestring = data[:modestring]
342 irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
344 @client[:welcome] = proc {|data|
345 irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
346 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
347 if data[:nick] && data[:nick].length > 0
351 @plugins.delegate("connect")
353 @config['irc.join_channels'].each {|c|
354 debug "autojoining channel #{c}"
355 if(c =~ /^(\S+)\s+(\S+)$/i)
362 @client[:join] = proc {|data|
363 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
366 @client[:part] = proc {|data|
367 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
370 @client[:kick] = proc {|data|
371 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
374 @client[:invite] = proc {|data|
375 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
376 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
379 @client[:changetopic] = proc {|data|
380 channel = data[:channel]
381 sourcenick = data[:sourcenick]
383 timestamp = data[:unixtime] || Time.now.to_i
384 if(sourcenick == @nick)
385 irclog "@ I set topic \"#{topic}\"", channel
387 irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
389 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
392 @plugins.delegate("listen", m)
393 @plugins.delegate("topic", m)
395 @client[:topic] = @client[:topicinfo] = proc {|data|
396 channel = data[:channel]
397 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
400 @client[:names] = proc {|data|
401 channel = data[:channel]
403 unless(@channels[channel])
404 warning "got names for channel '#{channel}' I didn't think I was in\n"
407 @channels[channel].users.clear
409 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
411 @plugins.delegate "names", data[:channel], data[:users]
413 @client[:unknown] = proc {|data|
414 #debug "UNKNOWN: #{data[:serverstring]}"
415 irclog data[:serverstring], ".unknown"
420 debug "received #{sig}, queueing quit"
422 debug "interrupted #{$interrupted} times"
427 elsif $interrupted >= 3
433 # connect the bot to IRC
436 trap("SIGINT") { got_sig("SIGINT") }
437 trap("SIGTERM") { got_sig("SIGTERM") }
438 trap("SIGHUP") { got_sig("SIGHUP") }
439 rescue ArgumentError => e
440 debug "failed to trap signals (#{e.inspect}): running on Windows?"
442 debug "failed to trap signals: #{e.inspect}"
445 quit if $interrupted > 0
448 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
450 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
451 @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
452 @capabilities = Hash.new
456 # begin event handling loop
460 quit if $interrupted > 0
464 while @socket.connected?
466 break unless reply = @socket.gets
467 @client.process reply
469 quit if $interrupted > 0
472 # I despair of this. Some of my users get "connection reset by peer"
473 # exceptions that ARENT SocketError's. How am I supposed to handle
478 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
479 error "network exception: #{e.class}: #{e}"
480 debug e.backtrace.join("\n")
481 rescue BDB::Fatal => e
482 error "fatal bdb error: #{e.class}: #{e}"
483 error e.backtrace.join("\n")
485 restart("Oops, we seem to have registry problems ...")
486 rescue Exception => e
487 error "non-net exception: #{e.class}: #{e}"
488 error e.backtrace.join("\n")
490 error "unexpected exception: #{e.class}: #{e}"
491 error e.backtrace.join("\n")
498 if @socket.connected?
505 quit if $interrupted > 0
507 log "waiting to reconnect"
508 sleep @config['server.reconnect_wait']
512 # type:: message type
513 # where:: message target
514 # message:: message text
515 # send message +message+ of type +type+ to target +where+
516 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
517 # relevant say() or notice() methods. This one should be used for IRCd
518 # extensions you want to use in modules.
519 def sendmsg(type, where, message, chan=nil, ring=0)
520 # limit it according to the byterate, splitting the message
521 # taking into consideration the actual message length
522 # and all the extra stuff
523 # TODO allow something to do for commands that produce too many messages
524 # TODO example: math 10**10000
525 left = @socket.bytes_per - type.length - where.length - 4
527 if(left >= message.length)
528 sendq "#{type} #{where} :#{message}", chan, ring
529 log_sent(type, where, message)
532 line = message.slice!(0, left)
533 lastspace = line.rindex(/\s+/)
535 message = line.slice!(lastspace, line.length) + message
536 message.gsub!(/^\s+/, "")
538 sendq "#{type} #{where} :#{line}", chan, ring
539 log_sent(type, where, line)
540 end while(message.length > 0)
543 # queue an arbitraty message for the server
544 def sendq(message="", chan=nil, ring=0)
546 @socket.queue(message, chan, ring)
549 # send a notice message to channel/nick +where+
550 def notice(where, message, mchan=nil, mring=-1)
565 message.each_line { |line|
567 next unless(line.length > 0)
568 sendmsg "NOTICE", where, line, chan, ring
572 # say something (PRIVMSG) to channel/nick +where+
573 def say(where, message, mchan="", mring=-1)
588 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
590 next unless(line.length > 0)
591 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
592 sendmsg "PRIVMSG", where, line, chan, ring
597 # perform a CTCP action with message +message+ to channel/nick +where+
598 def action(where, message, mchan="", mring=-1)
613 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
615 irclog "* #{@nick} #{message}", where
616 elsif (where =~ /^(\S*)!.*$/)
617 irclog "* #{@nick}[#{where}] #{message}", $1
619 irclog "* #{@nick}[#{where}] #{message}", where
623 # quick way to say "okay" (or equivalent) to +where+
625 say where, @lang.get("okay")
628 # log IRC-related message +message+ to a file determined by +where+.
629 # +where+ can be a channel name, or a nick for private message logging
630 def irclog(message, where="server")
631 message = message.chomp
632 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
633 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
634 unless(@logs.has_key?(where))
635 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
636 @logs[where].sync = true
638 @logs[where].puts "[#{stamp}] #{message}"
639 #debug "[#{stamp}] <#{where}> #{message}"
642 # set topic of channel +where+ to +topic+
643 def topic(where, topic)
644 sendq "TOPIC #{where} :#{topic}", where, 2
647 # disconnect from the server and cleanup all plugins and modules
648 def shutdown(message = nil)
649 debug "Shutting down ..."
650 ## No we don't restore them ... let everything run through
652 # trap("SIGINT", "DEFAULT")
653 # trap("SIGTERM", "DEFAULT")
654 # trap("SIGHUP", "DEFAULT")
656 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
658 message = @lang.get("quit") if (message.nil? || message.empty?)
659 if @socket.connected?
660 debug "Clearing socket"
662 debug "Sending quit message"
663 @socket.emergency_puts "QUIT :#{message}"
664 debug "Flushing socket"
666 debug "Shutting down socket"
669 debug "Logging quits"
670 @channels.each_value {|v|
671 irclog "@ quit (#{message})", v.name
677 # debug "Closing registries"
679 debug "Cleaning up the db environment"
681 log "rbot quit (#{message})"
684 # message:: optional IRC quit message
685 # quit IRC, shutdown the bot
686 def quit(message=nil)
695 # totally shutdown and respawn the bot
696 def restart(message = false)
697 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
699 sleep @config['server.reconnect_wait']
701 # Note, this fails on Windows
705 # call the save method for bot's config, keywords, auth and all plugins
714 # call the rescan method for the bot's lang, keywords and all plugins
721 # channel:: channel to join
722 # key:: optional channel key if channel is +s
724 def join(channel, key=nil)
726 sendq "JOIN #{channel} :#{key}", channel, 2
728 sendq "JOIN #{channel}", channel, 2
733 def part(channel, message="")
734 sendq "PART #{channel} :#{message}", channel, 2
737 # attempt to change bot's nick to +name+
743 def mode(channel, mode, target)
744 sendq "MODE #{channel} #{mode} #{target}", channel, 2
747 # m:: message asking for help
748 # topic:: optional topic help is requested for
749 # respond to online help requests
751 topic = nil if topic == ""
754 helpstr = "help topics: core, auth, keywords"
755 helpstr += @plugins.helptopics
756 helpstr += " (help <topic> for more info)"
759 when /^core\s+(.+)$/i
760 helpstr = corehelp $1
763 when /^auth\s+(.+)$/i
764 helpstr = @auth.help $1
766 helpstr = @keywords.help
767 when /^keywords\s+(.+)$/i
768 helpstr = @keywords.help $1
770 unless(helpstr = @plugins.help(topic))
771 helpstr = "no help for topic #{topic}"
777 # returns a string describing the current status of the bot (uptime etc)
779 secs_up = Time.new - @startup_time
780 uptime = Utils.secs_to_string secs_up
781 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
782 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
785 # we'll ping the server every 30 seconds or so, and expect a response
786 # before the next one come around..
787 def start_server_pings
789 return unless @config['server.ping_timeout'] > 0
790 # we want to respond to a hung server within 30 secs or so
791 @ping_timer = @timer.add(30) {
792 @last_ping = Time.now
793 @socket.queue "PING :rbot"
795 @pong_timer = @timer.add(10) {
796 unless @last_ping.nil?
797 diff = Time.now - @last_ping
798 unless diff < @config['server.ping_timeout']
799 debug "no PONG from server for #{diff} seconds, reconnecting"
803 debug "couldn't shutdown connection (already shutdown?)"
806 raise TimeoutError, "no PONG from server in #{diff} seconds"
812 def stop_server_pings
814 # stop existing timers if running
815 unless @ping_timer.nil?
816 @timer.remove @ping_timer
819 unless @pong_timer.nil?
820 @timer.remove @pong_timer
827 # handle help requests for "core" topics
828 def corehelp(topic="")
831 return "quit [<message>] => quit IRC with message <message>"
833 return "restart => completely stop and restart the bot (including reconnect)"
835 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"
837 return "part <channel> => part channel <channel>"
839 return "hide => part all channels"
841 return "save => save current dynamic data and configuration"
843 return "rescan => reload modules and static facts"
845 return "nick <nick> => attempt to change nick to <nick>"
847 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
849 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
851 # return "topic <channel> <message> => set topic of <channel> to <message>"
853 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>"
855 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>"
857 return "version => describes software version"
859 return "botsnack => reward #{@nick} for being good"
861 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
863 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
867 # handle incoming IRC PRIVMSG +m+
872 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
874 irclog "* #{m.sourcenick} #{m.message}", m.target
878 irclog "<#{m.sourcenick}> #{m.message}", m.target
880 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
884 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
886 # pass it off to plugins that want to hear everything
887 @plugins.delegate "listen", m
889 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
890 notice m.sourcenick, "\001PING #$1\001"
891 irclog "@ #{m.sourcenick} pinged me"
898 when (/^join\s+(\S+)\s+(\S+)$/i)
899 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
900 when (/^join\s+(\S+)$/i)
901 join $1 if(@auth.allow?("join", m.source, m.replyto))
903 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
904 when (/^part\s+(\S+)$/i)
905 part $1 if(@auth.allow?("join", m.source, m.replyto))
906 when (/^quit(?:\s+(.*))?$/i)
907 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
908 when (/^restart(?:\s+(.*))?$/i)
909 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
911 join 0 if(@auth.allow?("join", m.source, m.replyto))
913 if(@auth.allow?("config", m.source, m.replyto))
917 when (/^nick\s+(\S+)$/i)
918 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
919 when (/^say\s+(\S+)\s+(.*)$/i)
920 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
921 when (/^action\s+(\S+)\s+(.*)$/i)
922 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
923 # when (/^topic\s+(\S+)\s+(.*)$/i)
924 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
925 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
926 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
928 say m.replyto, "pong"
930 if(@auth.allow?("config", m.source, m.replyto))
933 m.reply "Rescanning ..."
938 if(auth.allow?("talk", m.source, m.replyto))
940 @channels.each_value {|c| c.quiet = true }
942 when (/^quiet in (\S+)$/i)
944 if(auth.allow?("talk", m.source, m.replyto))
946 where.gsub!(/^here$/, m.target) if m.public?
947 @channels[where].quiet = true if(@channels.has_key?(where))
950 if(auth.allow?("talk", m.source, m.replyto))
951 @channels.each_value {|c| c.quiet = false }
954 when (/^talk in (\S+)$/i)
956 if(auth.allow?("talk", m.source, m.replyto))
957 where.gsub!(/^here$/, m.target) if m.public?
958 @channels[where].quiet = false if(@channels.has_key?(where))
961 when (/^status\??$/i)
962 m.reply status if auth.allow?("status", m.source, m.replyto)
963 when (/^registry stats$/i)
964 if auth.allow?("config", m.source, m.replyto)
965 m.reply @registry.stat.inspect
967 when (/^(help\s+)?config(\s+|$)/)
969 when (/^(version)|(introduce yourself)$/i)
970 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
971 when (/^help(?:\s+(.*))?$/i)
972 say m.replyto, help($1)
973 #TODO move these to a "chatback" plugin
974 when (/^(botsnack|ciggie)$/i)
975 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
976 say m.replyto, @lang.get("thanks") if(m.private?)
977 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
978 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
979 say m.replyto, @lang.get("hello") if(m.private?)
982 # stuff to handle when not addressed
984 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
985 say m.replyto, @lang.get("hello_X") % m.sourcenick
986 when (/^#{Regexp.escape(@nick)}!*$/)
987 say m.replyto, @lang.get("hello_X") % m.sourcenick
994 # log a message. Internal use only.
995 def log_sent(type, where, message)
999 irclog "-=#{@nick}=- #{message}", where
1000 elsif (where =~ /(\S*)!.*/)
1001 irclog "[-=#{where}=-] #{message}", $1
1003 irclog "[-=#{where}=-] #{message}"
1007 irclog "<#{@nick}> #{message}", where
1008 elsif (where =~ /^(\S*)!.*$/)
1009 irclog "[msg(#{where})] #{message}", $1
1011 irclog "[msg(#{where})] #{message}", where
1017 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1019 debug "joined channel #{m.channel}"
1020 irclog "@ Joined channel #{m.channel}", m.channel
1022 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1023 @channels[m.channel].users[m.sourcenick] = Hash.new
1024 @channels[m.channel].users[m.sourcenick]["mode"] = ""
1027 @plugins.delegate("listen", m)
1028 @plugins.delegate("join", m)
1033 debug "left channel #{m.channel}"
1034 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1035 @channels.delete(m.channel)
1037 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1038 if @channels.has_key?(m.channel)
1039 @channels[m.channel].users.delete(m.sourcenick)
1041 warning "got part for channel '#{channel}' I didn't think I was in\n"
1046 # delegate to plugins
1047 @plugins.delegate("listen", m)
1048 @plugins.delegate("part", m)
1051 # respond to being kicked from a channel
1054 debug "kicked from channel #{m.channel}"
1055 @channels.delete(m.channel)
1056 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1058 @channels[m.channel].users.delete(m.sourcenick)
1059 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1062 @plugins.delegate("listen", m)
1063 @plugins.delegate("kick", m)
1067 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1068 @channels[m.channel].topic = m.topic if !m.topic.nil?
1069 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1070 @channels[m.channel].topic.by = m.source if !m.source.nil?
1072 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1075 # delegate a privmsg to auth, keyword or plugin handlers
1076 def delegate_privmsg(message)
1077 [@auth, @plugins, @keywords].each {|m|
1078 break if m.privmsg(message)