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 => 30, :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 unless botclass and not botclass.empty?
187 # We want to find a sensible default.
188 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
189 # * On Windows (at least the NT versions) we want to put our stuff in the
190 # Application Data folder.
191 # We don't use any particular O/S detection magic, exploiting the fact that
192 # Etc.getpwuid is nil on Windows
193 if Etc.getpwuid(Process::Sys.geteuid)
194 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
196 if ENV.has_key?('APPDATA')
197 botclass = ENV['APPDATA'].dup
198 botclass.gsub!("\\","/")
203 botclass = File.expand_path(botclass)
204 @botclass = botclass.gsub(/\/$/, "")
206 unless FileTest.directory? botclass
207 log "no #{botclass} directory found, creating from templates.."
208 if FileTest.exist? botclass
209 error "file #{botclass} exists but isn't a directory"
212 FileUtils.cp_r Config::datadir+'/templates', botclass
215 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
216 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
221 @startup_time = Time.new
222 @config = BotConfig.new(self)
223 # background self after botconfig has a chance to run wizard
224 @logfile = @config['core.logfile']
225 if @logfile.class!=String || @logfile.empty?
226 @logfile = File.basename(botclass)+".log"
228 if @config['core.run_as_daemon']
231 # See http://blog.humlab.umu.se/samuel/archives/000107.html
232 # for the backgrounding code
238 rescue NotImplementedError
239 warning "Could not background, fork not supported"
241 warning "Could not background. #{e.inspect}"
244 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
245 log "Redirecting standard input/output/error"
247 STDIN.reopen "/dev/null"
249 # On Windows, there's not such thing as /dev/null
252 STDOUT.reopen @logfile, "a"
254 log "\n=== #{botclass} session started ==="
257 @timer = Timer::Timer.new(1.0) # only need per-second granularity
258 @registry = BotRegistry.new self
259 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
262 @httputil = Utils::HttpUtil.new(self)
263 @lang = Language::Language.new(@config['core.language'])
264 @keywords = Keywords.new(self)
265 @auth = IrcAuth.new(self)
267 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
268 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
270 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
271 @nick = @config['irc.nick']
273 @client = IrcClient.new
274 @client[:isupport] = proc { |data|
276 sendq "CAPAB IDENTIFY-MSG"
279 @client[:datastr] = proc { |data|
281 if data[:text] == "IDENTIFY-MSG"
282 @capabilities["identify-msg".to_sym] = true
284 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
287 @client[:privmsg] = proc { |data|
288 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
291 @client[:notice] = proc { |data|
292 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
293 # pass it off to plugins that want to hear everything
294 @plugins.delegate "listen", message
296 @client[:motd] = proc { |data|
297 data[:motd].each_line { |line|
298 irclog "MOTD: #{line}", "server"
301 @client[:nicktaken] = proc { |data|
302 nickchg "#{data[:nick]}_"
303 @plugins.delegate "nicktaken", data[:nick]
305 @client[:badnick] = proc {|data|
306 warning "bad nick (#{data[:nick]})"
308 @client[:ping] = proc {|data|
309 @socket.queue "PONG #{data[:pingid]}"
311 @client[:pong] = proc {|data|
314 @client[:nick] = proc {|data|
315 sourcenick = data[:sourcenick]
317 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
318 if(sourcenick == @nick)
319 debug "my nick is now #{nick}"
322 @channels.each {|k,v|
323 if(v.users.has_key?(sourcenick))
324 irclog "@ #{sourcenick} is now known as #{nick}", k
325 v.users[nick] = v.users[sourcenick]
326 v.users.delete(sourcenick)
329 @plugins.delegate("listen", m)
330 @plugins.delegate("nick", m)
332 @client[:quit] = proc {|data|
333 source = data[:source]
334 sourcenick = data[:sourcenick]
335 sourceurl = data[:sourceaddress]
336 message = data[:message]
337 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
338 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
340 @channels.each {|k,v|
341 if(v.users.has_key?(sourcenick))
342 irclog "@ Quit: #{sourcenick}: #{message}", k
343 v.users.delete(sourcenick)
347 @plugins.delegate("listen", m)
348 @plugins.delegate("quit", m)
350 @client[:mode] = proc {|data|
351 source = data[:source]
352 sourcenick = data[:sourcenick]
353 sourceurl = data[:sourceaddress]
354 channel = data[:channel]
355 targets = data[:targets]
356 modestring = data[:modestring]
357 irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
359 @client[:welcome] = proc {|data|
360 irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
361 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
362 if data[:nick] && data[:nick].length > 0
366 @plugins.delegate("connect")
368 @config['irc.join_channels'].each {|c|
369 debug "autojoining channel #{c}"
370 if(c =~ /^(\S+)\s+(\S+)$/i)
377 @client[:join] = proc {|data|
378 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
381 @client[:part] = proc {|data|
382 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
385 @client[:kick] = proc {|data|
386 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
389 @client[:invite] = proc {|data|
390 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
391 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
394 @client[:changetopic] = proc {|data|
395 channel = data[:channel]
396 sourcenick = data[:sourcenick]
398 timestamp = data[:unixtime] || Time.now.to_i
399 if(sourcenick == @nick)
400 irclog "@ I set topic \"#{topic}\"", channel
402 irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
404 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
407 @plugins.delegate("listen", m)
408 @plugins.delegate("topic", m)
410 @client[:topic] = @client[:topicinfo] = proc {|data|
411 channel = data[:channel]
412 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
415 @client[:names] = proc {|data|
416 channel = data[:channel]
418 unless(@channels[channel])
419 warning "got names for channel '#{channel}' I didn't think I was in\n"
422 @channels[channel].users.clear
424 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
426 @plugins.delegate "names", data[:channel], data[:users]
428 @client[:unknown] = proc {|data|
429 #debug "UNKNOWN: #{data[:serverstring]}"
430 irclog data[:serverstring], ".unknown"
435 debug "received #{sig}, queueing quit"
437 debug "interrupted #{$interrupted} times"
442 elsif $interrupted >= 3
448 # connect the bot to IRC
451 trap("SIGINT") { got_sig("SIGINT") }
452 trap("SIGTERM") { got_sig("SIGTERM") }
453 trap("SIGHUP") { got_sig("SIGHUP") }
454 rescue ArgumentError => e
455 debug "failed to trap signals (#{e.inspect}): running on Windows?"
457 debug "failed to trap signals: #{e.inspect}"
460 quit if $interrupted > 0
463 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
465 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
466 @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
467 @capabilities = Hash.new
471 # begin event handling loop
475 quit if $interrupted > 0
479 while @socket.connected?
481 break unless reply = @socket.gets
482 @client.process reply
484 quit if $interrupted > 0
487 # I despair of this. Some of my users get "connection reset by peer"
488 # exceptions that ARENT SocketError's. How am I supposed to handle
493 rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
494 error "network exception: #{e.class}: #{e}"
495 debug e.backtrace.join("\n")
496 rescue BDB::Fatal => e
497 error "fatal bdb error: #{e.class}: #{e}"
498 error e.backtrace.join("\n")
500 restart("Oops, we seem to have registry problems ...")
501 rescue Exception => e
502 error "non-net exception: #{e.class}: #{e}"
503 error e.backtrace.join("\n")
505 error "unexpected exception: #{e.class}: #{e}"
506 error e.backtrace.join("\n")
513 if @socket.connected?
520 quit if $interrupted > 0
522 log "waiting to reconnect"
523 sleep @config['server.reconnect_wait']
527 # type:: message type
528 # where:: message target
529 # message:: message text
530 # send message +message+ of type +type+ to target +where+
531 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
532 # relevant say() or notice() methods. This one should be used for IRCd
533 # extensions you want to use in modules.
534 def sendmsg(type, where, message, chan=nil, ring=0)
535 # limit it according to the byterate, splitting the message
536 # taking into consideration the actual message length
537 # and all the extra stuff
538 # TODO allow something to do for commands that produce too many messages
539 # TODO example: math 10**10000
540 left = @socket.bytes_per - type.length - where.length - 4
542 if(left >= message.length)
543 sendq "#{type} #{where} :#{message}", chan, ring
544 log_sent(type, where, message)
547 line = message.slice!(0, left)
548 lastspace = line.rindex(/\s+/)
550 message = line.slice!(lastspace, line.length) + message
551 message.gsub!(/^\s+/, "")
553 sendq "#{type} #{where} :#{line}", chan, ring
554 log_sent(type, where, line)
555 end while(message.length > 0)
558 # queue an arbitraty message for the server
559 def sendq(message="", chan=nil, ring=0)
561 @socket.queue(message, chan, ring)
564 # send a notice message to channel/nick +where+
565 def notice(where, message, mchan=nil, mring=-1)
580 message.each_line { |line|
582 next unless(line.length > 0)
583 sendmsg "NOTICE", where, line, chan, ring
587 # say something (PRIVMSG) to channel/nick +where+
588 def say(where, message, mchan="", mring=-1)
603 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
605 next unless(line.length > 0)
606 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
607 sendmsg "PRIVMSG", where, line, chan, ring
612 # perform a CTCP action with message +message+ to channel/nick +where+
613 def action(where, message, mchan="", mring=-1)
628 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
630 irclog "* #{@nick} #{message}", where
631 elsif (where =~ /^(\S*)!.*$/)
632 irclog "* #{@nick}[#{where}] #{message}", $1
634 irclog "* #{@nick}[#{where}] #{message}", where
638 # quick way to say "okay" (or equivalent) to +where+
640 say where, @lang.get("okay")
643 # log IRC-related message +message+ to a file determined by +where+.
644 # +where+ can be a channel name, or a nick for private message logging
645 def irclog(message, where="server")
646 message = message.chomp
647 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
648 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
649 unless(@logs.has_key?(where))
650 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
651 @logs[where].sync = true
653 @logs[where].puts "[#{stamp}] #{message}"
654 #debug "[#{stamp}] <#{where}> #{message}"
657 # set topic of channel +where+ to +topic+
658 def topic(where, topic)
659 sendq "TOPIC #{where} :#{topic}", where, 2
662 # disconnect from the server and cleanup all plugins and modules
663 def shutdown(message = nil)
664 debug "Shutting down ..."
665 ## No we don't restore them ... let everything run through
667 # trap("SIGINT", "DEFAULT")
668 # trap("SIGTERM", "DEFAULT")
669 # trap("SIGHUP", "DEFAULT")
671 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
673 message = @lang.get("quit") if (message.nil? || message.empty?)
674 if @socket.connected?
675 debug "Clearing socket"
677 debug "Sending quit message"
678 @socket.emergency_puts "QUIT :#{message}"
679 debug "Flushing socket"
681 debug "Shutting down socket"
684 debug "Logging quits"
685 @channels.each_value {|v|
686 irclog "@ quit (#{message})", v.name
692 # debug "Closing registries"
694 debug "Cleaning up the db environment"
696 log "rbot quit (#{message})"
699 # message:: optional IRC quit message
700 # quit IRC, shutdown the bot
701 def quit(message=nil)
710 # totally shutdown and respawn the bot
711 def restart(message = false)
712 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
714 sleep @config['server.reconnect_wait']
716 # Note, this fails on Windows
720 # call the save method for bot's config, keywords, auth and all plugins
729 # call the rescan method for the bot's lang, keywords and all plugins
736 # channel:: channel to join
737 # key:: optional channel key if channel is +s
739 def join(channel, key=nil)
741 sendq "JOIN #{channel} :#{key}", channel, 2
743 sendq "JOIN #{channel}", channel, 2
748 def part(channel, message="")
749 sendq "PART #{channel} :#{message}", channel, 2
752 # attempt to change bot's nick to +name+
758 def mode(channel, mode, target)
759 sendq "MODE #{channel} #{mode} #{target}", channel, 2
762 # m:: message asking for help
763 # topic:: optional topic help is requested for
764 # respond to online help requests
766 topic = nil if topic == ""
769 helpstr = "help topics: core, auth, keywords"
770 helpstr += @plugins.helptopics
771 helpstr += " (help <topic> for more info)"
774 when /^core\s+(.+)$/i
775 helpstr = corehelp $1
778 when /^auth\s+(.+)$/i
779 helpstr = @auth.help $1
781 helpstr = @keywords.help
782 when /^keywords\s+(.+)$/i
783 helpstr = @keywords.help $1
785 unless(helpstr = @plugins.help(topic))
786 helpstr = "no help for topic #{topic}"
792 # returns a string describing the current status of the bot (uptime etc)
794 secs_up = Time.new - @startup_time
795 uptime = Utils.secs_to_string secs_up
796 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
797 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
800 # we'll ping the server every 30 seconds or so, and expect a response
801 # before the next one come around..
802 def start_server_pings
804 return unless @config['server.ping_timeout'] > 0
805 # we want to respond to a hung server within 30 secs or so
806 @ping_timer = @timer.add(30) {
807 @last_ping = Time.now
808 @socket.queue "PING :rbot"
810 @pong_timer = @timer.add(10) {
811 unless @last_ping.nil?
812 diff = Time.now - @last_ping
813 unless diff < @config['server.ping_timeout']
814 debug "no PONG from server for #{diff} seconds, reconnecting"
818 debug "couldn't shutdown connection (already shutdown?)"
821 raise TimeoutError, "no PONG from server in #{diff} seconds"
827 def stop_server_pings
829 # stop existing timers if running
830 unless @ping_timer.nil?
831 @timer.remove @ping_timer
834 unless @pong_timer.nil?
835 @timer.remove @pong_timer
842 # handle help requests for "core" topics
843 def corehelp(topic="")
846 return "quit [<message>] => quit IRC with message <message>"
848 return "restart => completely stop and restart the bot (including reconnect)"
850 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"
852 return "part <channel> => part channel <channel>"
854 return "hide => part all channels"
856 return "save => save current dynamic data and configuration"
858 return "rescan => reload modules and static facts"
860 return "nick <nick> => attempt to change nick to <nick>"
862 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
864 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
866 # return "topic <channel> <message> => set topic of <channel> to <message>"
868 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>"
870 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>"
872 return "version => describes software version"
874 return "botsnack => reward #{@nick} for being good"
876 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
878 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
882 # handle incoming IRC PRIVMSG +m+
887 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
889 irclog "* #{m.sourcenick} #{m.message}", m.target
893 irclog "<#{m.sourcenick}> #{m.message}", m.target
895 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
899 @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
901 # pass it off to plugins that want to hear everything
902 @plugins.delegate "listen", m
904 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
905 notice m.sourcenick, "\001PING #$1\001"
906 irclog "@ #{m.sourcenick} pinged me"
913 when (/^join\s+(\S+)\s+(\S+)$/i)
914 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
915 when (/^join\s+(\S+)$/i)
916 join $1 if(@auth.allow?("join", m.source, m.replyto))
918 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
919 when (/^part\s+(\S+)$/i)
920 part $1 if(@auth.allow?("join", m.source, m.replyto))
921 when (/^quit(?:\s+(.*))?$/i)
922 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
923 when (/^restart(?:\s+(.*))?$/i)
924 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
926 join 0 if(@auth.allow?("join", m.source, m.replyto))
928 if(@auth.allow?("config", m.source, m.replyto))
932 when (/^nick\s+(\S+)$/i)
933 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
934 when (/^say\s+(\S+)\s+(.*)$/i)
935 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
936 when (/^action\s+(\S+)\s+(.*)$/i)
937 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
938 # when (/^topic\s+(\S+)\s+(.*)$/i)
939 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
940 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
941 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
943 say m.replyto, "pong"
945 if(@auth.allow?("config", m.source, m.replyto))
948 m.reply "Rescanning ..."
953 if(auth.allow?("talk", m.source, m.replyto))
955 @channels.each_value {|c| c.quiet = true }
957 when (/^quiet in (\S+)$/i)
959 if(auth.allow?("talk", m.source, m.replyto))
961 where.gsub!(/^here$/, m.target) if m.public?
962 @channels[where].quiet = true if(@channels.has_key?(where))
965 if(auth.allow?("talk", m.source, m.replyto))
966 @channels.each_value {|c| c.quiet = false }
969 when (/^talk in (\S+)$/i)
971 if(auth.allow?("talk", m.source, m.replyto))
972 where.gsub!(/^here$/, m.target) if m.public?
973 @channels[where].quiet = false if(@channels.has_key?(where))
976 when (/^status\??$/i)
977 m.reply status if auth.allow?("status", m.source, m.replyto)
978 when (/^registry stats$/i)
979 if auth.allow?("config", m.source, m.replyto)
980 m.reply @registry.stat.inspect
982 when (/^(help\s+)?config(\s+|$)/)
984 when (/^(version)|(introduce yourself)$/i)
985 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
986 when (/^help(?:\s+(.*))?$/i)
987 say m.replyto, help($1)
988 #TODO move these to a "chatback" plugin
989 when (/^(botsnack|ciggie)$/i)
990 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
991 say m.replyto, @lang.get("thanks") if(m.private?)
992 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
993 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
994 say m.replyto, @lang.get("hello") if(m.private?)
997 # stuff to handle when not addressed
999 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1000 say m.replyto, @lang.get("hello_X") % m.sourcenick
1001 when (/^#{Regexp.escape(@nick)}!*$/)
1002 say m.replyto, @lang.get("hello_X") % m.sourcenick
1004 @keywords.privmsg(m)
1009 # log a message. Internal use only.
1010 def log_sent(type, where, message)
1014 irclog "-=#{@nick}=- #{message}", where
1015 elsif (where =~ /(\S*)!.*/)
1016 irclog "[-=#{where}=-] #{message}", $1
1018 irclog "[-=#{where}=-] #{message}"
1022 irclog "<#{@nick}> #{message}", where
1023 elsif (where =~ /^(\S*)!.*$/)
1024 irclog "[msg(#{where})] #{message}", $1
1026 irclog "[msg(#{where})] #{message}", where
1032 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1034 debug "joined channel #{m.channel}"
1035 irclog "@ Joined channel #{m.channel}", m.channel
1037 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1038 @channels[m.channel].users[m.sourcenick] = Hash.new
1039 @channels[m.channel].users[m.sourcenick]["mode"] = ""
1042 @plugins.delegate("listen", m)
1043 @plugins.delegate("join", m)
1048 debug "left channel #{m.channel}"
1049 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1050 @channels.delete(m.channel)
1052 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1053 if @channels.has_key?(m.channel)
1054 @channels[m.channel].users.delete(m.sourcenick)
1056 warning "got part for channel '#{channel}' I didn't think I was in\n"
1061 # delegate to plugins
1062 @plugins.delegate("listen", m)
1063 @plugins.delegate("part", m)
1066 # respond to being kicked from a channel
1069 debug "kicked from channel #{m.channel}"
1070 @channels.delete(m.channel)
1071 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1073 @channels[m.channel].users.delete(m.sourcenick)
1074 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1077 @plugins.delegate("listen", m)
1078 @plugins.delegate("kick", m)
1082 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1083 @channels[m.channel].topic = m.topic if !m.topic.nil?
1084 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1085 @channels[m.channel].topic.by = m.source if !m.source.nil?
1087 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1090 # delegate a privmsg to auth, keyword or plugin handlers
1091 def delegate_privmsg(message)
1092 [@auth, @plugins, @keywords].each {|m|
1093 break if m.privmsg(message)