]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
167cc0bcedcc1ab16575ee682dec5bea1729cc3a
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 require 'thread'
2 require 'etc'
3 require 'fileutils'
4
5 $debug = false unless $debug
6 # print +message+ if debugging is enabled
7 def debug(message=nil)
8   print "DEBUG: #{message}\n" if($debug && message)
9   #yield
10 end
11
12 # these first
13 require 'rbot/rbotconfig'
14 require 'rbot/config'
15 require 'rbot/utils'
16
17 require 'rbot/rfc2812'
18 require 'rbot/keywords'
19 require 'rbot/ircsocket'
20 require 'rbot/auth'
21 require 'rbot/timer'
22 require 'rbot/plugins'
23 require 'rbot/channel'
24 require 'rbot/message'
25 require 'rbot/language'
26 require 'rbot/dbhash'
27 require 'rbot/registry'
28 require 'rbot/httputil'
29
30 module Irc
31
32 # Main bot class, which manages the various components, receives messages,
33 # handles them or passes them to plugins, and contains core functionality.
34 class IrcBot
35   # the bot's current nickname
36   attr_reader :nick
37   
38   # the bot's IrcAuth data
39   attr_reader :auth
40   
41   # the bot's BotConfig data
42   attr_reader :config
43   
44   # the botclass for this bot (determines configdir among other things)
45   attr_reader :botclass
46   
47   # used to perform actions periodically (saves configuration once per minute
48   # by default)
49   attr_reader :timer
50   
51   # bot's Language data
52   attr_reader :lang
53
54   # channel info for channels the bot is in
55   attr_reader :channels
56
57   # bot's irc socket
58   attr_reader :socket
59
60   # bot's object registry, plugins get an interface to this for persistant
61   # storage (hash interface tied to a bdb file, plugins use Accessors to store
62   # and restore objects in their own namespaces.)
63   attr_reader :registry
64
65   # bot's httputil help object, for fetching resources via http. Sets up
66   # proxies etc as defined by the bot configuration/environment
67   attr_reader :httputil
68
69   # create a new IrcBot with botclass +botclass+
70   def initialize(botclass, params = {})
71     # BotConfig for the core bot
72     BotConfig.register BotConfigStringValue.new('server.name',
73       :default => "localhost", :requires_restart => true,
74       :desc => "What server should the bot connect to?",
75       :wizard => true)
76     BotConfig.register BotConfigIntegerValue.new('server.port',
77       :default => 6667, :type => :integer, :requires_restart => true,
78       :desc => "What port should the bot connect to?", 
79       :validate => Proc.new {|v| v > 0}, :wizard => true)
80     BotConfig.register BotConfigStringValue.new('server.password',
81       :default => false, :requires_restart => true,
82       :desc => "Password for connecting to this server (if required)",
83       :wizard => true)
84     BotConfig.register BotConfigStringValue.new('server.bindhost',
85       :default => false, :requires_restart => true,
86       :desc => "Specific local host or IP for the bot to bind to (if required)",
87       :wizard => true)
88     BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
89       :default => 5, :validate => Proc.new{|v| v >= 0},
90       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
91     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
92       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
93       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
94     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
95       :requires_restart => true,
96       :desc => "local user the bot should appear to be", :wizard => true)
97     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
98       :default => [], :wizard => true,
99       :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'")
100     BotConfig.register BotConfigIntegerValue.new('core.save_every',
101       :default => 60, :validate => Proc.new{|v| v >= 0},
102       # TODO change timer via on_change proc
103       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example")
104     BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
105       :default => 2.0, :validate => Proc.new{|v| v >= 0},
106       :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
107       :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
108     BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
109       :default => 4, :validate => Proc.new{|v| v >= 0},
110       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines, with non-burst limits of 512 bytes/2 seconds",
111       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
112     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
113       :default => 10, :validate => Proc.new{|v| v >= 0},
114       :on_change => Proc.new {|bot, v| bot.start_server_pings},
115       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
116
117     @argv = params[:argv]
118
119     unless FileTest.directory? Config::datadir
120       puts "data directory '#{Config::datadir}' not found, did you setup.rb?"
121       exit 2
122     end
123     
124     #botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass
125     botclass = "#{ENV['HOME']}/.rbot" unless botclass
126     @botclass = botclass.gsub(/\/$/, "")
127
128     unless FileTest.directory? botclass
129       puts "no #{botclass} directory found, creating from templates.."
130       if FileTest.exist? botclass
131         puts "Error: file #{botclass} exists but isn't a directory"
132         exit 2
133       end
134       FileUtils.cp_r Config::datadir+'/templates', botclass
135     end
136     
137     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
138
139     @ping_timer = nil
140     @pong_timer = nil
141     @last_ping = nil
142     @startup_time = Time.new
143     @config = BotConfig.new(self)
144 # TODO background self after botconfig has a chance to run wizard
145     @timer = Timer::Timer.new(1.0) # only need per-second granularity
146     @registry = BotRegistry.new self
147     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
148     @channels = Hash.new
149     @logs = Hash.new
150     @httputil = Utils::HttpUtil.new(self)
151     @lang = Language::Language.new(@config['core.language'])
152     @keywords = Keywords.new(self)
153     @auth = IrcAuth.new(self)
154
155     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
156     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
157
158     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
159     @nick = @config['irc.nick']
160
161     @client = IrcClient.new
162     @client[:privmsg] = proc { |data|
163       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
164       onprivmsg(message)
165     }
166     @client[:notice] = proc { |data|
167       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
168       # pass it off to plugins that want to hear everything
169       @plugins.delegate "listen", message
170     }
171     @client[:motd] = proc { |data|
172       data[:motd].each_line { |line|
173         log "MOTD: #{line}", "server"
174       }
175     }
176     @client[:nicktaken] = proc { |data| 
177       nickchg "#{data[:nick]}_"
178     }
179     @client[:badnick] = proc {|data| 
180       puts "WARNING, bad nick (#{data[:nick]})"
181     }
182     @client[:ping] = proc {|data|
183       # (jump the queue for pongs)
184       @socket.puts "PONG #{data[:pingid]}"
185     }
186     @client[:pong] = proc {|data|
187       @last_ping = nil
188     }
189     @client[:nick] = proc {|data|
190       sourcenick = data[:sourcenick]
191       nick = data[:nick]
192       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
193       if(sourcenick == @nick)
194         debug "my nick is now #{nick}"
195         @nick = nick
196       end
197       @channels.each {|k,v|
198         if(v.users.has_key?(sourcenick))
199           log "@ #{sourcenick} is now known as #{nick}", k
200           v.users[nick] = v.users[sourcenick]
201           v.users.delete(sourcenick)
202         end
203       }
204       @plugins.delegate("listen", m)
205       @plugins.delegate("nick", m)
206     }
207     @client[:quit] = proc {|data|
208       source = data[:source]
209       sourcenick = data[:sourcenick]
210       sourceurl = data[:sourceaddress]
211       message = data[:message]
212       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
213       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
214       else
215         @channels.each {|k,v|
216           if(v.users.has_key?(sourcenick))
217             log "@ Quit: #{sourcenick}: #{message}", k
218             v.users.delete(sourcenick)
219           end
220         }
221       end
222       @plugins.delegate("listen", m)
223       @plugins.delegate("quit", m)
224     }
225     @client[:mode] = proc {|data|
226       source = data[:source]
227       sourcenick = data[:sourcenick]
228       sourceurl = data[:sourceaddress]
229       channel = data[:channel]
230       targets = data[:targets]
231       modestring = data[:modestring]
232       log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
233     }
234     @client[:welcome] = proc {|data|
235       log "joined server #{data[:source]} as #{data[:nick]}", "server"
236       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
237       if data[:nick] && data[:nick].length > 0
238         @nick = data[:nick]
239       end
240
241       @plugins.delegate("connect")
242
243       @config['irc.join_channels'].each {|c|
244         debug "autojoining channel #{c}"
245         if(c =~ /^(\S+)\s+(\S+)$/i)
246           join $1, $2
247         else
248           join c if(c)
249         end
250       }
251     }
252     @client[:join] = proc {|data|
253       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
254       onjoin(m)
255     }
256     @client[:part] = proc {|data|
257       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
258       onpart(m)
259     }
260     @client[:kick] = proc {|data|
261       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message]) 
262       onkick(m)
263     }
264     @client[:invite] = proc {|data|
265       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
266         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
267       end
268     }
269     @client[:changetopic] = proc {|data|
270       channel = data[:channel]
271       sourcenick = data[:sourcenick]
272       topic = data[:topic]
273       timestamp = data[:unixtime] || Time.now.to_i
274       if(sourcenick == @nick)
275         log "@ I set topic \"#{topic}\"", channel
276       else
277         log "@ #{sourcenick} set topic \"#{topic}\"", channel
278       end
279       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
280
281       ontopic(m)
282       @plugins.delegate("listen", m)
283       @plugins.delegate("topic", m)
284     }
285     @client[:topic] = @client[:topicinfo] = proc {|data|
286       channel = data[:channel]
287       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
288         ontopic(m)
289     }
290     @client[:names] = proc {|data|
291       channel = data[:channel]
292       users = data[:users]
293       unless(@channels[channel])
294         puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
295         exit 2
296       end
297       @channels[channel].users.clear
298       users.each {|u|
299         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
300       }
301     }
302     @client[:unknown] = proc {|data|
303       #debug "UNKNOWN: #{data[:serverstring]}"
304       log data[:serverstring], ":unknown"
305     }
306   end
307
308   # connect the bot to IRC
309   def connect
310     begin
311       trap("SIGINT") { quit }
312       trap("SIGTERM") { quit }
313       trap("SIGHUP") { quit }
314     rescue
315       debug "failed to trap signals, probably running on windows?"
316     end
317     begin
318       @socket.connect
319     rescue => e
320       raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
321     end
322     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
323     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
324     start_server_pings
325   end
326
327   # begin event handling loop
328   def mainloop
329     while true
330       begin
331       connect
332       @timer.start
333       
334         while true
335           if @socket.select
336             break unless reply = @socket.gets
337             @client.process reply
338           end
339         end
340       # I despair of this. Some of my users get "connection reset by peer"
341       # exceptions that ARENT SocketError's. How am I supposed to handle
342       # that?
343       #rescue TimeoutError, SocketError => e
344       rescue SystemExit
345         exit 0
346       rescue Exception => e
347         puts "network exception: connection closed: #{e.inspect}"
348         puts e.backtrace.join("\n")
349         @socket.shutdown # now we reconnect
350       rescue => e
351         puts "unexpected exception: connection closed: #{e.inspect}"
352         puts e.backtrace.join("\n")
353         exit 2
354       end
355       
356       puts "disconnected"
357       @last_ping = nil
358       @channels.clear
359       @socket.clearq
360       
361       puts "waiting to reconnect"
362       sleep @config['server.reconnect_wait']
363     end
364   end
365   
366   # type:: message type
367   # where:: message target
368   # message:: message text
369   # send message +message+ of type +type+ to target +where+
370   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
371   # relevant say() or notice() methods. This one should be used for IRCd
372   # extensions you want to use in modules.
373   def sendmsg(type, where, message)
374     # limit it 440 chars + CRLF.. so we have to split long lines
375     left = 440 - type.length - where.length - 3
376     begin
377       if(left >= message.length)
378         sendq("#{type} #{where} :#{message}")
379         log_sent(type, where, message)
380         return
381       end
382       line = message.slice!(0, left)
383       lastspace = line.rindex(/\s+/)
384       if(lastspace)
385         message = line.slice!(lastspace, line.length) + message
386         message.gsub!(/^\s+/, "")
387       end
388       sendq("#{type} #{where} :#{line}")
389       log_sent(type, where, line)
390     end while(message.length > 0)
391   end
392
393   # queue an arbitraty message for the server
394   def sendq(message="")
395     # temporary
396     @socket.queue(message)
397   end
398
399   # send a notice message to channel/nick +where+
400   def notice(where, message)
401     message.each_line { |line|
402       line.chomp!
403       next unless(line.length > 0)
404       sendmsg("NOTICE", where, line)
405     }
406   end
407
408   # say something (PRIVMSG) to channel/nick +where+
409   def say(where, message)
410     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
411       line.chomp!
412       next unless(line.length > 0)
413       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
414         sendmsg("PRIVMSG", where, line)
415       end
416     }
417   end
418
419   # perform a CTCP action with message +message+ to channel/nick +where+
420   def action(where, message)
421     sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
422     if(where =~ /^#/)
423       log "* #{@nick} #{message}", where
424     elsif (where =~ /^(\S*)!.*$/)
425          log "* #{@nick}[#{where}] #{message}", $1
426     else
427          log "* #{@nick}[#{where}] #{message}", where
428     end
429   end
430
431   # quick way to say "okay" (or equivalent) to +where+
432   def okay(where)
433     say where, @lang.get("okay")
434   end
435
436   # log message +message+ to a file determined by +where+. +where+ can be a
437   # channel name, or a nick for private message logging
438   def log(message, where="server")
439     message.chomp!
440     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
441     unless(@logs.has_key?(where))
442       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
443       @logs[where].sync = true
444     end
445     @logs[where].puts "[#{stamp}] #{message}"
446     #debug "[#{stamp}] <#{where}> #{message}"
447   end
448   
449   # set topic of channel +where+ to +topic+
450   def topic(where, topic)
451     sendq "TOPIC #{where} :#{topic}"
452   end
453
454   # disconnect from the server and cleanup all plugins and modules
455   def shutdown(message = nil)
456     begin
457       trap("SIGINT", "DEFAULT")
458       trap("SIGTERM", "DEFAULT")
459       trap("SIGHUP", "DEFAULT")
460     rescue
461       debug "failed to trap signals, probably running on windows?"
462     end
463     message = @lang.get("quit") if (message.nil? || message.empty?)
464     @socket.clearq
465     save
466     @plugins.cleanup
467     @channels.each_value {|v|
468       log "@ quit (#{message})", v.name
469     }
470     @registry.close
471     @socket.puts "QUIT :#{message}"
472     @socket.flush
473     @socket.shutdown
474     puts "rbot quit (#{message})"
475   end
476   
477   # message:: optional IRC quit message
478   # quit IRC, shutdown the bot
479   def quit(message=nil)
480     begin
481       shutdown(message)
482     ensure
483       exit 0
484     end
485   end
486
487   # totally shutdown and respawn the bot
488   def restart(message = false)
489     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
490     shutdown(msg)
491     sleep @config['server.reconnect_wait']
492     # now we re-exec
493     exec($0, *@argv)
494   end
495
496   # call the save method for bot's config, keywords, auth and all plugins
497   def save
498     @registry.flush
499     @config.save
500     @keywords.save
501     @auth.save
502     @plugins.save
503   end
504
505   # call the rescan method for the bot's lang, keywords and all plugins
506   def rescan
507     @lang.rescan
508     @plugins.rescan
509     @keywords.rescan
510   end
511   
512   # channel:: channel to join
513   # key::     optional channel key if channel is +s
514   # join a channel
515   def join(channel, key=nil)
516     if(key)
517       sendq "JOIN #{channel} :#{key}"
518     else
519       sendq "JOIN #{channel}"
520     end
521   end
522
523   # part a channel
524   def part(channel, message="")
525     sendq "PART #{channel} :#{message}"
526   end
527
528   # attempt to change bot's nick to +name+
529   def nickchg(name)
530       sendq "NICK #{name}"
531   end
532
533   # changing mode
534   def mode(channel, mode, target)
535       sendq "MODE #{channel} #{mode} #{target}"
536   end
537   
538   # m::     message asking for help
539   # topic:: optional topic help is requested for
540   # respond to online help requests
541   def help(topic=nil)
542     topic = nil if topic == ""
543     case topic
544     when nil
545       helpstr = "help topics: core, auth, keywords"
546       helpstr += @plugins.helptopics
547       helpstr += " (help <topic> for more info)"
548     when /^core$/i
549       helpstr = corehelp
550     when /^core\s+(.+)$/i
551       helpstr = corehelp $1
552     when /^auth$/i
553       helpstr = @auth.help
554     when /^auth\s+(.+)$/i
555       helpstr = @auth.help $1
556     when /^keywords$/i
557       helpstr = @keywords.help
558     when /^keywords\s+(.+)$/i
559       helpstr = @keywords.help $1
560     else
561       unless(helpstr = @plugins.help(topic))
562         helpstr = "no help for topic #{topic}"
563       end
564     end
565     return helpstr
566   end
567
568   # returns a string describing the current status of the bot (uptime etc)
569   def status
570     secs_up = Time.new - @startup_time
571     uptime = Utils.secs_to_string secs_up
572     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
573   end
574
575   # we'll ping the server every 30 seconds or so, and expect a response
576   # before the next one come around..
577   def start_server_pings
578     @last_ping = nil
579     # stop existing timers if running
580     unless @ping_timer.nil?
581       @timer.remove @ping_timer
582       @ping_timer = nil
583     end
584     unless @pong_timer.nil?
585       @timer.remove @pong_timer
586       @pong_timer = nil
587     end
588     return unless @config['server.ping_timeout'] > 0
589     # we want to respond to a hung server within 30 secs or so
590     @ping_timer = @timer.add(30) {
591       @last_ping = Time.now
592       @socket.puts "PING :rbot"
593     }
594     @pong_timer = @timer.add(10) {
595       unless @last_ping.nil?
596         diff = Time.now - @last_ping
597         unless diff < @config['server.ping_timeout']
598           debug "no PONG from server for #{diff} seconds, reconnecting"
599           begin
600             @socket.shutdown
601           rescue
602             debug "couldn't shutdown connection (already shutdown?)"
603           end
604           @last_ping = nil
605         end
606       end
607     }
608   end
609
610   private
611
612   # handle help requests for "core" topics
613   def corehelp(topic="")
614     case topic
615       when "quit"
616         return "quit [<message>] => quit IRC with message <message>"
617       when "restart"
618         return "restart => completely stop and restart the bot (including reconnect)"
619       when "join"
620         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"
621       when "part"
622         return "part <channel> => part channel <channel>"
623       when "hide"
624         return "hide => part all channels"
625       when "save"
626         return "save => save current dynamic data and configuration"
627       when "rescan"
628         return "rescan => reload modules and static facts"
629       when "nick"
630         return "nick <nick> => attempt to change nick to <nick>"
631       when "say"
632         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
633       when "action"
634         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
635       when "topic"
636         return "topic <channel> <message> => set topic of <channel> to <message>"
637       when "quiet"
638         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>"
639       when "talk"
640         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>"
641       when "version"
642         return "version => describes software version"
643       when "botsnack"
644         return "botsnack => reward #{@nick} for being good"
645       when "hello"
646         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
647       else
648         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
649     end
650   end
651
652   # handle incoming IRC PRIVMSG +m+
653   def onprivmsg(m)
654     # log it first
655     if(m.action?)
656       if(m.private?)
657         log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
658       else
659         log "* #{m.sourcenick} #{m.message}", m.target
660       end
661     else
662       if(m.public?)
663         log "<#{m.sourcenick}> #{m.message}", m.target
664       else
665         log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
666       end
667     end
668
669     # pass it off to plugins that want to hear everything
670     @plugins.delegate "listen", m
671
672     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
673       notice m.sourcenick, "\001PING #$1\001"
674       log "@ #{m.sourcenick} pinged me"
675       return
676     end
677
678     if(m.address?)
679       case m.message
680         when (/^join\s+(\S+)\s+(\S+)$/i)
681           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
682         when (/^join\s+(\S+)$/i)
683           join $1 if(@auth.allow?("join", m.source, m.replyto))
684         when (/^part$/i)
685           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
686         when (/^part\s+(\S+)$/i)
687           part $1 if(@auth.allow?("join", m.source, m.replyto))
688         when (/^quit(?:\s+(.*))?$/i)
689           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
690         when (/^restart(?:\s+(.*))?$/i)
691           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
692         when (/^hide$/i)
693           join 0 if(@auth.allow?("join", m.source, m.replyto))
694         when (/^save$/i)
695           if(@auth.allow?("config", m.source, m.replyto))
696             save
697             m.okay
698           end
699         when (/^nick\s+(\S+)$/i)
700           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
701         when (/^say\s+(\S+)\s+(.*)$/i)
702           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
703         when (/^action\s+(\S+)\s+(.*)$/i)
704           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
705         when (/^topic\s+(\S+)\s+(.*)$/i)
706           topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
707         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
708           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
709         when (/^ping$/i)
710           say m.replyto, "pong"
711         when (/^rescan$/i)
712           if(@auth.allow?("config", m.source, m.replyto))
713             m.okay
714             rescan
715           end
716         when (/^quiet$/i)
717           if(auth.allow?("talk", m.source, m.replyto))
718             m.okay
719             @channels.each_value {|c| c.quiet = true }
720           end
721         when (/^quiet in (\S+)$/i)
722           where = $1
723           if(auth.allow?("talk", m.source, m.replyto))
724             m.okay
725             where.gsub!(/^here$/, m.target) if m.public?
726             @channels[where].quiet = true if(@channels.has_key?(where))
727           end
728         when (/^talk$/i)
729           if(auth.allow?("talk", m.source, m.replyto))
730             @channels.each_value {|c| c.quiet = false }
731             m.okay
732           end
733         when (/^talk in (\S+)$/i)
734           where = $1
735           if(auth.allow?("talk", m.source, m.replyto))
736             where.gsub!(/^here$/, m.target) if m.public?
737             @channels[where].quiet = false if(@channels.has_key?(where))
738             m.okay
739           end
740         when (/^status\??$/i)
741           m.reply status if auth.allow?("status", m.source, m.replyto)
742         when (/^registry stats$/i)
743           if auth.allow?("config", m.source, m.replyto)
744             m.reply @registry.stat.inspect
745           end
746         when (/^(help\s+)?config(\s+|$)/)
747           @config.privmsg(m)
748         when (/^(version)|(introduce yourself)$/i)
749           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
750         when (/^help(?:\s+(.*))?$/i)
751           say m.replyto, help($1)
752           #TODO move these to a "chatback" plugin
753         when (/^(botsnack|ciggie)$/i)
754           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
755           say m.replyto, @lang.get("thanks") if(m.private?)
756         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
757           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
758           say m.replyto, @lang.get("hello") if(m.private?)
759         else
760           delegate_privmsg(m)
761       end
762     else
763       # stuff to handle when not addressed
764       case m.message
765         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
766           say m.replyto, @lang.get("hello_X") % m.sourcenick
767         when (/^#{Regexp.escape(@nick)}!*$/)
768           say m.replyto, @lang.get("hello_X") % m.sourcenick
769         else
770           @keywords.privmsg(m)
771       end
772     end
773   end
774
775   # log a message. Internal use only.
776   def log_sent(type, where, message)
777     case type
778       when "NOTICE"
779         if(where =~ /^#/)
780           log "-=#{@nick}=- #{message}", where
781         elsif (where =~ /(\S*)!.*/)
782              log "[-=#{where}=-] #{message}", $1
783         else
784              log "[-=#{where}=-] #{message}"
785         end
786       when "PRIVMSG"
787         if(where =~ /^#/)
788           log "<#{@nick}> #{message}", where
789         elsif (where =~ /^(\S*)!.*$/)
790           log "[msg(#{where})] #{message}", $1
791         else
792           log "[msg(#{where})] #{message}", where
793         end
794     end
795   end
796
797   def onjoin(m)
798     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
799     if(m.address?)
800       debug "joined channel #{m.channel}"
801       log "@ Joined channel #{m.channel}", m.channel
802     else
803       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
804       @channels[m.channel].users[m.sourcenick] = Hash.new
805       @channels[m.channel].users[m.sourcenick]["mode"] = ""
806     end
807
808     @plugins.delegate("listen", m)
809     @plugins.delegate("join", m)
810   end
811
812   def onpart(m)
813     if(m.address?)
814       debug "left channel #{m.channel}"
815       log "@ Left channel #{m.channel} (#{m.message})", m.channel
816       @channels.delete(m.channel)
817     else
818       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
819       @channels[m.channel].users.delete(m.sourcenick)
820     end
821     
822     # delegate to plugins
823     @plugins.delegate("listen", m)
824     @plugins.delegate("part", m)
825   end
826
827   # respond to being kicked from a channel
828   def onkick(m)
829     if(m.address?)
830       debug "kicked from channel #{m.channel}"
831       @channels.delete(m.channel)
832       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
833     else
834       @channels[m.channel].users.delete(m.sourcenick)
835       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
836     end
837
838     @plugins.delegate("listen", m)
839     @plugins.delegate("kick", m)
840   end
841
842   def ontopic(m)
843     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
844     @channels[m.channel].topic = m.topic if !m.topic.nil?
845     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
846     @channels[m.channel].topic.by = m.source if !m.source.nil?
847
848           debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
849   end
850
851   # delegate a privmsg to auth, keyword or plugin handlers
852   def delegate_privmsg(message)
853     [@auth, @plugins, @keywords].each {|m|
854       break if m.privmsg(message)
855     }
856   end
857 end
858
859 end