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