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