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