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