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'
75 require 'rbot/rfc2812'
76 require 'rbot/keywords'
77 require 'rbot/ircsocket'
80 require 'rbot/plugins'
81 # require 'rbot/channel'
82 require 'rbot/message'
83 require 'rbot/language'
85 require 'rbot/registry'
86 require 'rbot/httputil'
90 # Main bot class, which manages the various components, receives messages,
91 # handles them or passes them to plugins, and contains core functionality.
93 # the bot's IrcAuth data
96 # the bot's BotConfig data
99 # the botclass for this bot (determines configdir among other things)
100 attr_reader :botclass
102 # used to perform actions periodically (saves configuration once per minute
106 # bot's Language data
109 # server the bot is connected to
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 # bot User in the client/server connection
132 # bot User in the client/server connection
137 # create a new IrcBot with botclass +botclass+
138 def initialize(botclass, params = {})
139 # BotConfig for the core bot
140 # TODO should we split socket stuff into ircsocket, etc?
141 BotConfig.register BotConfigStringValue.new('server.name',
142 :default => "localhost", :requires_restart => true,
143 :desc => "What server should the bot connect to?",
145 BotConfig.register BotConfigIntegerValue.new('server.port',
146 :default => 6667, :type => :integer, :requires_restart => true,
147 :desc => "What port should the bot connect to?",
148 :validate => Proc.new {|v| v > 0}, :wizard => true)
149 BotConfig.register BotConfigStringValue.new('server.password',
150 :default => false, :requires_restart => true,
151 :desc => "Password for connecting to this server (if required)",
153 BotConfig.register BotConfigStringValue.new('server.bindhost',
154 :default => false, :requires_restart => true,
155 :desc => "Specific local host or IP for the bot to bind to (if required)",
157 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
158 :default => 5, :validate => Proc.new{|v| v >= 0},
159 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
160 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
161 :default => 2.0, :validate => Proc.new{|v| v >= 0},
162 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
163 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
164 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
165 :default => 4, :validate => Proc.new{|v| v >= 0},
166 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
167 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
168 BotConfig.register BotConfigStringValue.new('server.byterate',
169 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
170 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
171 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
172 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
173 :default => 30, :validate => Proc.new{|v| v >= 0},
174 :on_change => Proc.new {|bot, v| bot.start_server_pings},
175 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
177 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
178 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
179 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
180 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
181 :requires_restart => true,
182 :desc => "local user the bot should appear to be", :wizard => true)
183 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
184 :default => [], :wizard => true,
185 :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'")
186 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
188 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
190 BotConfig.register BotConfigIntegerValue.new('core.save_every',
191 :default => 60, :validate => Proc.new{|v| v >= 0},
192 # TODO change timer via on_change proc
193 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
195 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
196 :default => false, :requires_restart => true,
197 :desc => "Should the bot run as a daemon?")
199 BotConfig.register BotConfigStringValue.new('log.file',
200 :default => false, :requires_restart => true,
201 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
202 BotConfig.register BotConfigIntegerValue.new('log.level',
203 :default => 1, :requires_restart => false,
204 :validate => Proc.new { |v| (0..5).include?(v) },
205 :on_change => Proc.new { |bot, v|
208 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
209 BotConfig.register BotConfigIntegerValue.new('log.keep',
210 :default => 1, :requires_restart => true,
211 :validate => Proc.new { |v| v >= 0 },
212 :desc => "How many old console messages logfiles to keep")
213 BotConfig.register BotConfigIntegerValue.new('log.max_size',
214 :default => 10, :requires_restart => true,
215 :validate => Proc.new { |v| v > 0 },
216 :desc => "Maximum console messages logfile size (in megabytes)")
218 @argv = params[:argv]
220 unless FileTest.directory? Config::datadir
221 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
225 unless botclass and not botclass.empty?
226 # We want to find a sensible default.
227 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
228 # * On Windows (at least the NT versions) we want to put our stuff in the
229 # Application Data folder.
230 # We don't use any particular O/S detection magic, exploiting the fact that
231 # Etc.getpwuid is nil on Windows
232 if Etc.getpwuid(Process::Sys.geteuid)
233 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
235 if ENV.has_key?('APPDATA')
236 botclass = ENV['APPDATA'].dup
237 botclass.gsub!("\\","/")
242 botclass = File.expand_path(botclass)
243 @botclass = botclass.gsub(/\/$/, "")
245 unless FileTest.directory? botclass
246 log "no #{botclass} directory found, creating from templates.."
247 if FileTest.exist? botclass
248 error "file #{botclass} exists but isn't a directory"
251 FileUtils.cp_r Config::datadir+'/templates', botclass
254 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
255 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
260 @startup_time = Time.new
261 @config = BotConfig.new(self)
263 if @config['core.run_as_daemon']
267 @logfile = @config['log.file']
268 if @logfile.class!=String || @logfile.empty?
269 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
272 # See http://blog.humlab.umu.se/samuel/archives/000107.html
273 # for the backgrounding code
279 rescue NotImplementedError
280 warning "Could not background, fork not supported"
282 warning "Could not background. #{e.inspect}"
285 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
286 log "Redirecting standard input/output/error"
288 STDIN.reopen "/dev/null"
290 # On Windows, there's not such thing as /dev/null
293 def STDOUT.write(str=nil)
295 return str.to_s.length
297 def STDERR.write(str=nil)
298 if str.to_s.match(/:\d+: warning:/)
303 return str.to_s.length
307 # Set the new logfile and loglevel. This must be done after the daemonizing
308 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
309 $logger.datetime_format= $dateformat
310 $logger.level = @config['log.level']
311 $logger.level = $cl_loglevel if $cl_loglevel
312 $logger.level = 0 if $debug
316 @registry = BotRegistry.new self
318 @timer = Timer::Timer.new(1.0) # only need per-second granularity
319 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
323 @httputil = Utils::HttpUtil.new(self)
325 @lang = Language::Language.new(@config['core.language'])
327 @keywords = Keywords.new(self)
330 @auth = IrcAuth.new(self)
333 fatal e.backtrace.join("\n")
338 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
339 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
341 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
342 @client = IrcClient.new
343 @server = @client.server
344 @myself = @client.client
345 @myself.nick = @config['irc.nick']
347 # Channels where we are quiet
348 # It's nil when we are not quiet, an empty list when we are quiet
349 # in all channels, a list of channels otherwise
353 @client[:welcome] = proc {|data|
354 irclog "joined server #{@client.server} as #{myself}", "server"
356 @plugins.delegate("connect")
358 @config['irc.join_channels'].each { |c|
359 debug "autojoining channel #{c}"
360 if(c =~ /^(\S+)\s+(\S+)$/i)
367 @client[:isupport] = proc { |data|
368 # TODO this needs to go into rfc2812.rb
369 # Since capabs are two-steps processes, server.supports[:capab]
370 # should be a three-state: nil, [], [....]
371 sendq "CAPAB IDENTIFY-MSG" if @server.supports[:capab]
373 @client[:datastr] = proc { |data|
374 # TODO this needs to go into rfc2812.rb
375 if data[:text] == "IDENTIFY-MSG"
376 @server.capabilities["identify-msg".to_sym] = true
378 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
381 @client[:privmsg] = proc { |data|
382 message = PrivMessage.new(self, @server, data[:source], data[:target], data[:message])
385 @client[:notice] = proc { |data|
386 message = NoticeMessage.new(self, @server, data[:source], data[:target], data[:message])
387 # pass it off to plugins that want to hear everything
388 @plugins.delegate "listen", message
390 @client[:motd] = proc { |data|
391 data[:motd].each_line { |line|
392 irclog "MOTD: #{line}", "server"
395 @client[:nicktaken] = proc { |data|
396 nickchg "#{data[:nick]}_"
397 @plugins.delegate "nicktaken", data[:nick]
399 @client[:badnick] = proc {|data|
400 warning "bad nick (#{data[:nick]})"
402 @client[:ping] = proc {|data|
403 @socket.queue "PONG #{data[:pingid]}"
405 @client[:pong] = proc {|data|
408 @client[:nick] = proc {|data|
409 source = data[:source]
412 m = NickMessage.new(self, @server, source, old, new)
414 debug "my nick is now #{new}"
416 data[:is_on].each { |ch|
417 irclog "@ #{data[:old]} is now known as #{data[:new]}", ch
419 @plugins.delegate("listen", m)
420 @plugins.delegate("nick", m)
422 @client[:quit] = proc {|data|
423 m = QuitMessage.new(self, @server, data[:source], data[:source], data[:message])
424 data[:was_on].each { |ch|
425 irclog "@ Quit: #{sourcenick}: #{message}", ch
427 @plugins.delegate("listen", m)
428 @plugins.delegate("quit", m)
430 @client[:mode] = proc {|data|
431 irclog "@ Mode #{data[:modestring]} by #{data[:sourcenick]}", data[:channel]
433 @client[:join] = proc {|data|
434 m = JoinMessage.new(self, @server, data[:source], data[:channel], data[:message])
437 @client[:part] = proc {|data|
438 m = PartMessage.new(self, @server, data[:source], data[:channel], data[:message])
441 @client[:kick] = proc {|data|
442 m = KickMessage.new(self, @server, data[:source], data[:target], data[:channel],data[:message])
445 @client[:invite] = proc {|data|
446 if data[:target] == myself
447 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
450 @client[:changetopic] = proc {|data|
451 channel = data[:channel]
452 source = data[:source]
455 irclog "@ I set topic \"#{topic}\"", channel
457 irclog "@ #{source} set topic \"#{topic}\"", channel
459 m = TopicMessage.new(self, @server, data[:source], data[:channel], data[:topic])
462 @plugins.delegate("listen", m)
463 @plugins.delegate("topic", m)
465 @client[:topic] = @client[:topicinfo] = proc { |data|
466 m = TopicMessage.new(self, @server, data[:source], data[:channel], data[:channel].topic)
469 @client[:names] = proc { |data|
470 @plugins.delegate "names", data[:channel], data[:users]
472 @client[:unknown] = proc { |data|
473 #debug "UNKNOWN: #{data[:serverstring]}"
474 irclog data[:serverstring], ".unknown"
478 # checks if we should be quiet on a channel
479 def quiet_on?(channel)
480 return false unless @quiet
481 return true if @quiet.empty?
482 return @quiet.include?(channel.to_s)
485 def set_quiet(channel=nil)
487 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
493 def reset_quiet(channel=nil)
495 @quiet.delete_if { |x| x == channel.to_s }
501 # things to do when we receive a signal
503 debug "received #{sig}, queueing quit"
505 debug "interrupted #{$interrupted} times"
510 elsif $interrupted >= 3
516 # connect the bot to IRC
519 trap("SIGINT") { got_sig("SIGINT") }
520 trap("SIGTERM") { got_sig("SIGTERM") }
521 trap("SIGHUP") { got_sig("SIGHUP") }
522 rescue ArgumentError => e
523 debug "failed to trap signals (#{e.inspect}): running on Windows?"
525 debug "failed to trap signals: #{e.inspect}"
528 quit if $interrupted > 0
531 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
533 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
534 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
538 # begin event handling loop
542 quit if $interrupted > 0
546 while @socket.connected?
548 break unless reply = @socket.gets
549 @client.process reply
551 quit if $interrupted > 0
554 # I despair of this. Some of my users get "connection reset by peer"
555 # exceptions that ARENT SocketError's. How am I supposed to handle
560 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
561 error "network exception: #{e.class}: #{e}"
562 debug e.backtrace.join("\n")
563 rescue BDB::Fatal => e
564 fatal "fatal bdb error: #{e.class}: #{e}"
565 fatal e.backtrace.join("\n")
567 # Why restart? DB problems are serious stuff ...
568 # restart("Oops, we seem to have registry problems ...")
571 rescue Exception => e
572 error "non-net exception: #{e.class}: #{e}"
573 error e.backtrace.join("\n")
575 fatal "unexpected exception: #{e.class}: #{e}"
576 fatal e.backtrace.join("\n")
583 if @socket.connected?
590 quit if $interrupted > 0
592 log "waiting to reconnect"
593 sleep @config['server.reconnect_wait']
597 # type:: message type
598 # where:: message target
599 # message:: message text
600 # send message +message+ of type +type+ to target +where+
601 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
602 # relevant say() or notice() methods. This one should be used for IRCd
603 # extensions you want to use in modules.
604 def sendmsg(type, where, message, chan=nil, ring=0)
605 # limit it according to the byterate, splitting the message
606 # taking into consideration the actual message length
607 # and all the extra stuff
608 # TODO allow something to do for commands that produce too many messages
609 # TODO example: math 10**10000
610 left = @socket.bytes_per - type.length - where.to_s.length - 4
612 if(left >= message.length)
613 sendq "#{type} #{where} :#{message}", chan, ring
614 log_sent(type, where, message)
617 line = message.slice!(0, left)
618 lastspace = line.rindex(/\s+/)
620 message = line.slice!(lastspace, line.length) + message
621 message.gsub!(/^\s+/, "")
623 sendq "#{type} #{where} :#{line}", chan, ring
624 log_sent(type, where, line)
625 end while(message.length > 0)
628 # queue an arbitraty message for the server
629 def sendq(message="", chan=nil, ring=0)
631 @socket.queue(message, chan, ring)
634 # send a notice message to channel/nick +where+
635 def notice(where, message, mchan="", mring=-1)
651 message.each_line { |line|
653 next unless(line.length > 0)
654 sendmsg "NOTICE", where, line, chan, ring
658 # say something (PRIVMSG) to channel/nick +where+
659 def say(where, message, mchan="", mring=-1)
675 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
677 next unless(line.length > 0)
678 unless quiet_on?(where)
679 sendmsg "PRIVMSG", where, line, chan, ring
684 # perform a CTCP action with message +message+ to channel/nick +where+
685 def action(where, message, mchan="", mring=-1)
701 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
704 irclog "* #{myself} #{message}", where
706 irclog "* #{myself}[#{where}] #{message}", $1
708 irclog "* #{myself}[#{where}] #{message}", where
712 # quick way to say "okay" (or equivalent) to +where+
714 say where, @lang.get("okay")
717 # log IRC-related message +message+ to a file determined by +where+.
718 # +where+ can be a channel name, or a nick for private message logging
719 def irclog(message, where="server")
720 message = message.chomp
721 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
722 where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
723 unless(@logs.has_key?(where))
724 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
725 @logs[where].sync = true
727 @logs[where].puts "[#{stamp}] #{message}"
728 #debug "[#{stamp}] <#{where}> #{message}"
731 # set topic of channel +where+ to +topic+
732 def topic(where, topic)
733 sendq "TOPIC #{where} :#{topic}", where, 2
736 # disconnect from the server and cleanup all plugins and modules
737 def shutdown(message = nil)
738 debug "Shutting down ..."
739 ## No we don't restore them ... let everything run through
741 # trap("SIGINT", "DEFAULT")
742 # trap("SIGTERM", "DEFAULT")
743 # trap("SIGHUP", "DEFAULT")
745 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
747 message = @lang.get("quit") if (message.nil? || message.empty?)
748 if @socket.connected?
749 debug "Clearing socket"
751 debug "Sending quit message"
752 @socket.emergency_puts "QUIT :#{message}"
753 debug "Flushing socket"
755 debug "Shutting down socket"
758 debug "Logging quits"
759 @server.channels.each { |ch|
760 irclog "@ quit (#{message})", ch
766 # debug "Closing registries"
768 debug "Cleaning up the db environment"
770 log "rbot quit (#{message})"
773 # message:: optional IRC quit message
774 # quit IRC, shutdown the bot
775 def quit(message=nil)
783 # totally shutdown and respawn the bot
784 def restart(message = false)
785 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
787 sleep @config['server.reconnect_wait']
789 # Note, this fails on Windows
793 # call the save method for bot's config, keywords, auth and all plugins
802 # call the rescan method for the bot's lang, keywords and all plugins
809 # channel:: channel to join
810 # key:: optional channel key if channel is +s
812 def join(channel, key=nil)
814 sendq "JOIN #{channel} :#{key}", channel, 2
816 sendq "JOIN #{channel}", channel, 2
821 def part(channel, message="")
822 sendq "PART #{channel} :#{message}", channel, 2
825 # attempt to change bot's nick to +name+
831 def mode(channel, mode, target)
832 sendq "MODE #{channel} #{mode} #{target}", channel, 2
835 # m:: message asking for help
836 # topic:: optional topic help is requested for
837 # respond to online help requests
839 topic = nil if topic == ""
842 helpstr = "help topics: core, auth, keywords"
843 helpstr += @plugins.helptopics
844 helpstr += " (help <topic> for more info)"
847 when /^core\s+(.+)$/i
848 helpstr = corehelp $1
851 when /^auth\s+(.+)$/i
852 helpstr = @auth.help $1
854 helpstr = @keywords.help
855 when /^keywords\s+(.+)$/i
856 helpstr = @keywords.help $1
858 unless(helpstr = @plugins.help(topic))
859 helpstr = "no help for topic #{topic}"
865 # returns a string describing the current status of the bot (uptime etc)
867 secs_up = Time.new - @startup_time
868 uptime = Utils.secs_to_string secs_up
869 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
870 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
873 # we'll ping the server every 30 seconds or so, and expect a response
874 # before the next one come around..
875 def start_server_pings
877 return unless @config['server.ping_timeout'] > 0
878 # we want to respond to a hung server within 30 secs or so
879 @ping_timer = @timer.add(30) {
880 @last_ping = Time.now
881 @socket.queue "PING :rbot"
883 @pong_timer = @timer.add(10) {
884 unless @last_ping.nil?
885 diff = Time.now - @last_ping
886 unless diff < @config['server.ping_timeout']
887 debug "no PONG from server for #{diff} seconds, reconnecting"
891 debug "couldn't shutdown connection (already shutdown?)"
894 raise TimeoutError, "no PONG from server in #{diff} seconds"
900 def stop_server_pings
902 # stop existing timers if running
903 unless @ping_timer.nil?
904 @timer.remove @ping_timer
907 unless @pong_timer.nil?
908 @timer.remove @pong_timer
915 # handle help requests for "core" topics
916 def corehelp(topic="")
919 return "quit [<message>] => quit IRC with message <message>"
921 return "restart => completely stop and restart the bot (including reconnect)"
923 return "join <channel> [<key>] => join channel <channel> with secret key <key> if specified. #{myself} also responds to invites if you have the required access level"
925 return "part <channel> => part channel <channel>"
927 return "hide => part all channels"
929 return "save => save current dynamic data and configuration"
931 return "rescan => reload modules and static facts"
933 return "nick <nick> => attempt to change nick to <nick>"
935 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
937 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
939 # return "topic <channel> <message> => set topic of <channel> to <message>"
941 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>"
943 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>"
945 return "version => describes software version"
947 return "botsnack => reward #{myself} for being good"
949 return "hello|hi|hey|yo [#{myself}] => greet the bot"
951 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
955 # handle incoming IRC PRIVMSG +m+
960 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
962 irclog "* #{m.sourcenick} #{m.message}", m.target
966 irclog "<#{m.sourcenick}> #{m.message}", m.target
968 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
972 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
974 # pass it off to plugins that want to hear everything
975 @plugins.delegate "listen", m
977 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
978 notice m.sourcenick, "\001PING #$1\001"
979 irclog "@ #{m.sourcenick} pinged me"
986 when (/^join\s+(\S+)\s+(\S+)$/i)
987 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
988 when (/^join\s+(\S+)$/i)
989 join $1 if(@auth.allow?("join", m.source, m.replyto))
991 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
992 when (/^part\s+(\S+)$/i)
993 part $1 if(@auth.allow?("join", m.source, m.replyto))
994 when (/^quit(?:\s+(.*))?$/i)
995 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
996 when (/^restart(?:\s+(.*))?$/i)
997 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
999 join 0 if(@auth.allow?("join", m.source, m.replyto))
1001 if(@auth.allow?("config", m.source, m.replyto))
1005 when (/^nick\s+(\S+)$/i)
1006 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
1007 when (/^say\s+(\S+)\s+(.*)$/i)
1008 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
1009 when (/^action\s+(\S+)\s+(.*)$/i)
1010 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
1011 # when (/^topic\s+(\S+)\s+(.*)$/i)
1012 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
1013 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
1014 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
1016 say m.replyto, "pong"
1018 if(@auth.allow?("config", m.source, m.replyto))
1019 m.reply "saving ..."
1021 m.reply "rescanning ..."
1023 m.reply "done. #{@plugins.status(true)}"
1026 if(auth.allow?("talk", m.source, m.replyto))
1030 when (/^quiet in (\S+)$/i)
1032 if(auth.allow?("talk", m.source, m.replyto))
1034 where.gsub!(/^here$/, m.target) if m.public?
1038 if(auth.allow?("talk", m.source, m.replyto))
1042 when (/^talk in (\S+)$/i)
1044 if(auth.allow?("talk", m.source, m.replyto))
1045 where.gsub!(/^here$/, m.target) if m.public?
1049 when (/^status\??$/i)
1050 m.reply status if auth.allow?("status", m.source, m.replyto)
1051 when (/^registry stats$/i)
1052 if auth.allow?("config", m.source, m.replyto)
1053 m.reply @registry.stat.inspect
1055 when (/^(help\s+)?config(\s+|$)/)
1057 when (/^(version)|(introduce yourself)$/i)
1058 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1059 when (/^help(?:\s+(.*))?$/i)
1060 say m.replyto, help($1)
1061 #TODO move these to a "chatback" plugin
1062 when (/^(botsnack|ciggie)$/i)
1063 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1064 say m.replyto, @lang.get("thanks") if(m.private?)
1065 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1066 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1067 say m.replyto, @lang.get("hello") if(m.private?)
1070 # stuff to handle when not addressed
1072 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(self.nick)}$/i)
1073 say m.replyto, @lang.get("hello_X") % m.sourcenick
1074 when (/^#{Regexp.escape(self.nick)}!*$/)
1075 say m.replyto, @lang.get("hello_X") % m.sourcenick
1077 @keywords.privmsg(m)
1082 # log a message. Internal use only.
1083 def log_sent(type, where, message)
1088 irclog "-=#{myself}=- #{message}", where
1090 irclog "[-=#{where}=-] #{message}", $1
1092 irclog "[-=#{where}=-] #{message}", where
1097 irclog "<#{myself}> #{message}", where
1099 irclog "[msg(#{where})] #{message}", $1
1101 irclog "[msg(#{where})] #{message}", where
1108 debug "joined channel #{m.channel}"
1109 irclog "@ Joined channel #{m.channel}", m.channel
1111 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1114 @plugins.delegate("listen", m)
1115 @plugins.delegate("join", m)
1120 debug "left channel #{m.channel}"
1121 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1123 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1126 # delegate to plugins
1127 @plugins.delegate("listen", m)
1128 @plugins.delegate("part", m)
1131 # respond to being kicked from a channel
1134 debug "kicked from channel #{m.channel}"
1135 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
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 debug "topic of channel #{m.channel} is now #{m.topic}"
1148 # delegate a privmsg to auth, keyword or plugin handlers
1149 def delegate_privmsg(message)
1150 [@auth, @plugins, @keywords].each {|m|
1151 break if m.privmsg(message)