]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
d435ac4c23a862cc9598ce16a5188b094751c69a
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 require 'thread'
2
3 require 'etc'
4 require 'fileutils'
5 require 'logger'
6
7 $debug = false unless $debug
8 $daemonize = false unless $daemonize
9
10 $dateformat = "%Y/%m/%d %H:%M:%S"
11 $logger = Logger.new($stderr)
12 $logger.datetime_format = $dateformat
13 $logger.level = $cl_loglevel if $cl_loglevel
14 $logger.level = 0 if $debug
15
16 def rawlog(level, message=nil, who_pos=1)
17   call_stack = caller
18   if call_stack.length > who_pos
19     who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
20   else
21     who = "(unknown)"
22   end
23   message.to_s.each_line { |l|
24     $logger.add(level, l.chomp, who)
25     who.gsub!(/./," ")
26   }
27 end
28
29 def log_session_start
30   $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
31 end
32
33 def log_session_end
34   $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
35 end
36
37 def debug(message=nil, who_pos=1)
38   rawlog(Logger::Severity::DEBUG, message, who_pos)
39 end
40
41 def log(message=nil, who_pos=1)
42   rawlog(Logger::Severity::INFO, message, who_pos)
43 end
44
45 def warning(message=nil, who_pos=1)
46   rawlog(Logger::Severity::WARN, message, who_pos)
47 end
48
49 def error(message=nil, who_pos=1)
50   rawlog(Logger::Severity::ERROR, message, who_pos)
51 end
52
53 def fatal(message=nil, who_pos=1)
54   rawlog(Logger::Severity::FATAL, message, who_pos)
55 end
56
57 debug "debug test"
58 log "log test"
59 warning "warning test"
60 error "error test"
61 fatal "fatal test"
62
63 # The following global is used for the improved signal handling.
64 $interrupted = 0
65
66 # these first
67 require 'rbot/rbotconfig'
68 require 'rbot/config'
69 require 'rbot/utils'
70
71 require 'rbot/rfc2812'
72 require 'rbot/keywords'
73 require 'rbot/ircsocket'
74 require 'rbot/auth'
75 require 'rbot/timer'
76 require 'rbot/plugins'
77 require 'rbot/channel'
78 require 'rbot/message'
79 require 'rbot/language'
80 require 'rbot/dbhash'
81 require 'rbot/registry'
82 require 'rbot/httputil'
83
84 module Irc
85
86 # Main bot class, which manages the various components, receives messages,
87 # handles them or passes them to plugins, and contains core functionality.
88 class IrcBot
89   # the bot's current nickname
90   attr_reader :nick
91
92   # the bot's IrcAuth data
93   attr_reader :auth
94
95   # the bot's BotConfig data
96   attr_reader :config
97
98   # the botclass for this bot (determines configdir among other things)
99   attr_reader :botclass
100
101   # used to perform actions periodically (saves configuration once per minute
102   # by default)
103   attr_reader :timer
104
105   # bot's Language data
106   attr_reader :lang
107
108   # capabilities info for the server
109   attr_reader :capabilities
110
111   # channel info for channels the bot is in
112   attr_reader :channels
113
114   # bot's irc socket
115   attr_reader :socket
116
117   # bot's object registry, plugins get an interface to this for persistant
118   # storage (hash interface tied to a bdb file, plugins use Accessors to store
119   # and restore objects in their own namespaces.)
120   attr_reader :registry
121
122   # bot's plugins. This is an instance of class Plugins
123   attr_reader :plugins
124
125   # bot's httputil help object, for fetching resources via http. Sets up
126   # proxies etc as defined by the bot configuration/environment
127   attr_reader :httputil
128
129   # create a new IrcBot with botclass +botclass+
130   def initialize(botclass, params = {})
131     # BotConfig for the core bot
132     # TODO should we split socket stuff into ircsocket, etc?
133     BotConfig.register BotConfigStringValue.new('server.name',
134       :default => "localhost", :requires_restart => true,
135       :desc => "What server should the bot connect to?",
136       :wizard => true)
137     BotConfig.register BotConfigIntegerValue.new('server.port',
138       :default => 6667, :type => :integer, :requires_restart => true,
139       :desc => "What port should the bot connect to?",
140       :validate => Proc.new {|v| v > 0}, :wizard => true)
141     BotConfig.register BotConfigStringValue.new('server.password',
142       :default => false, :requires_restart => true,
143       :desc => "Password for connecting to this server (if required)",
144       :wizard => true)
145     BotConfig.register BotConfigStringValue.new('server.bindhost',
146       :default => false, :requires_restart => true,
147       :desc => "Specific local host or IP for the bot to bind to (if required)",
148       :wizard => true)
149     BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
150       :default => 5, :validate => Proc.new{|v| v >= 0},
151       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
152     BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
153       :default => 2.0, :validate => Proc.new{|v| v >= 0},
154       :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
155       :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
156     BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
157       :default => 4, :validate => Proc.new{|v| v >= 0},
158       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
159       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
160     BotConfig.register BotConfigStringValue.new('server.byterate',
161       :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
162       :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
163       :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
164     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
165       :default => 30, :validate => Proc.new{|v| v >= 0},
166       :on_change => Proc.new {|bot, v| bot.start_server_pings},
167       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
168
169     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
170       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
171       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
172     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
173       :requires_restart => true,
174       :desc => "local user the bot should appear to be", :wizard => true)
175     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
176       :default => [], :wizard => true,
177       :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'")
178     BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
179       :default => [], 
180       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
181
182     BotConfig.register BotConfigIntegerValue.new('core.save_every',
183       :default => 60, :validate => Proc.new{|v| v >= 0},
184       # TODO change timer via on_change proc
185       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
186
187     BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
188       :default => false, :requires_restart => true,
189       :desc => "Should the bot run as a daemon?")
190
191     BotConfig.register BotConfigStringValue.new('log.file',
192       :default => false, :requires_restart => true,
193       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
194     BotConfig.register BotConfigIntegerValue.new('log.level',
195       :default => 1, :requires_restart => false,
196       :validate => Proc.new { |v| (0..5).include?(v) },
197       :on_change => Proc.new { |bot, v|
198         $logger.level = v
199       },
200       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
201     BotConfig.register BotConfigIntegerValue.new('log.keep',
202       :default => 1, :requires_restart => true,
203       :validate => Proc.new { |v| v >= 0 },
204       :desc => "How many old console messages logfiles to keep")
205     BotConfig.register BotConfigIntegerValue.new('log.max_size',
206       :default => 10, :requires_restart => true,
207       :validate => Proc.new { |v| v > 0 },
208       :desc => "Maximum console messages logfile size (in megabytes)")
209
210     @argv = params[:argv]
211
212     unless FileTest.directory? Config::datadir
213       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
214       exit 2
215     end
216
217     unless botclass and not botclass.empty?
218       # We want to find a sensible default.
219       #  * On POSIX systems we prefer ~/.rbot for the effective uid of the process
220       #  * On Windows (at least the NT versions) we want to put our stuff in the
221       #    Application Data folder.
222       # We don't use any particular O/S detection magic, exploiting the fact that
223       # Etc.getpwuid is nil on Windows
224       if Etc.getpwuid(Process::Sys.geteuid)
225         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
226       else
227         if ENV.has_key?('APPDATA')
228           botclass = ENV['APPDATA'].dup
229           botclass.gsub!("\\","/")
230         end
231       end
232       botclass += "/.rbot"
233     end
234     botclass = File.expand_path(botclass)
235     @botclass = botclass.gsub(/\/$/, "")
236
237     unless FileTest.directory? botclass
238       log "no #{botclass} directory found, creating from templates.."
239       if FileTest.exist? botclass
240         error "file #{botclass} exists but isn't a directory"
241         exit 2
242       end
243       FileUtils.cp_r Config::datadir+'/templates', botclass
244     end
245
246     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
247     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
248
249     @ping_timer = nil
250     @pong_timer = nil
251     @last_ping = nil
252     @startup_time = Time.new
253     @config = BotConfig.new(self)
254
255     if @config['core.run_as_daemon']
256       $daemonize = true
257     end
258
259     @logfile = @config['log.file']
260     if @logfile.class!=String || @logfile.empty?
261       @logfile = File.basename(botclass)+".log"
262     end
263
264     # See http://blog.humlab.umu.se/samuel/archives/000107.html
265     # for the backgrounding code 
266     if $daemonize
267       begin
268         exit if fork
269         Process.setsid
270         exit if fork
271       rescue NotImplementedError
272         warning "Could not background, fork not supported"
273       rescue => e
274         warning "Could not background. #{e.inspect}"
275       end
276       Dir.chdir botclass
277       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
278       log "Redirecting standard input/output/error"
279       begin
280         STDIN.reopen "/dev/null"
281       rescue Errno::ENOENT
282         # On Windows, there's not such thing as /dev/null
283         STDIN.reopen "NUL"
284       end
285       def STDOUT.write(str=nil)
286         log str, 2
287         return str.to_s.length
288       end
289       def STDERR.write(str=nil)
290         if str.to_s.match(/:\d+: warning:/)
291           warning str, 2
292         else
293           error str, 2
294         end
295         return str.to_s.length
296       end
297     end
298
299     # Set the new logfile and loglevel. This must be done after the daemonizing
300     $logger.close
301     $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
302     $logger.datetime_format= $dateformat
303     $logger.level = @config['log.level']
304     $logger.level = $cl_loglevel if $cl_loglevel
305     $logger.level = 0 if $debug
306
307     log_session_start
308
309     @timer = Timer::Timer.new(1.0) # only need per-second granularity
310     @registry = BotRegistry.new self
311     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
312     @channels = Hash.new
313     @logs = Hash.new
314     @httputil = Utils::HttpUtil.new(self)
315     @lang = Language::Language.new(@config['core.language'])
316     @keywords = Keywords.new(self)
317     @auth = IrcAuth.new(self)
318
319     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
320     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
321
322     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
323     @nick = @config['irc.nick']
324
325     @client = IrcClient.new
326     @client[:isupport] = proc { |data|
327       if data[:capab]
328         sendq "CAPAB IDENTIFY-MSG"
329       end
330     }
331     @client[:datastr] = proc { |data|
332       debug data.inspect
333       if data[:text] == "IDENTIFY-MSG"
334         @capabilities["identify-msg".to_sym] = true
335       else
336         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
337       end
338     }
339     @client[:privmsg] = proc { |data|
340       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
341       onprivmsg(message)
342     }
343     @client[:notice] = proc { |data|
344       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
345       # pass it off to plugins that want to hear everything
346       @plugins.delegate "listen", message
347     }
348     @client[:motd] = proc { |data|
349       data[:motd].each_line { |line|
350         irclog "MOTD: #{line}", "server"
351       }
352     }
353     @client[:nicktaken] = proc { |data|
354       nickchg "#{data[:nick]}_"
355       @plugins.delegate "nicktaken", data[:nick]
356     }
357     @client[:badnick] = proc {|data|
358       warning "bad nick (#{data[:nick]})"
359     }
360     @client[:ping] = proc {|data|
361       @socket.queue "PONG #{data[:pingid]}"
362     }
363     @client[:pong] = proc {|data|
364       @last_ping = nil
365     }
366     @client[:nick] = proc {|data|
367       sourcenick = data[:sourcenick]
368       nick = data[:nick]
369       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
370       if(sourcenick == @nick)
371         debug "my nick is now #{nick}"
372         @nick = nick
373       end
374       @channels.each {|k,v|
375         if(v.users.has_key?(sourcenick))
376           irclog "@ #{sourcenick} is now known as #{nick}", k
377           v.users[nick] = v.users[sourcenick]
378           v.users.delete(sourcenick)
379         end
380       }
381       @plugins.delegate("listen", m)
382       @plugins.delegate("nick", m)
383     }
384     @client[:quit] = proc {|data|
385       source = data[:source]
386       sourcenick = data[:sourcenick]
387       sourceurl = data[:sourceaddress]
388       message = data[:message]
389       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
390       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
391       else
392         @channels.each {|k,v|
393           if(v.users.has_key?(sourcenick))
394             irclog "@ Quit: #{sourcenick}: #{message}", k
395             v.users.delete(sourcenick)
396           end
397         }
398       end
399       @plugins.delegate("listen", m)
400       @plugins.delegate("quit", m)
401     }
402     @client[:mode] = proc {|data|
403       source = data[:source]
404       sourcenick = data[:sourcenick]
405       sourceurl = data[:sourceaddress]
406       channel = data[:channel]
407       targets = data[:targets]
408       modestring = data[:modestring]
409       irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
410     }
411     @client[:welcome] = proc {|data|
412       irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
413       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
414       if data[:nick] && data[:nick].length > 0
415         @nick = data[:nick]
416       end
417
418       @plugins.delegate("connect")
419
420       @config['irc.join_channels'].each {|c|
421         debug "autojoining channel #{c}"
422         if(c =~ /^(\S+)\s+(\S+)$/i)
423           join $1, $2
424         else
425           join c if(c)
426         end
427       }
428     }
429     @client[:join] = proc {|data|
430       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
431       onjoin(m)
432     }
433     @client[:part] = proc {|data|
434       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
435       onpart(m)
436     }
437     @client[:kick] = proc {|data|
438       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
439       onkick(m)
440     }
441     @client[:invite] = proc {|data|
442       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
443         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
444       end
445     }
446     @client[:changetopic] = proc {|data|
447       channel = data[:channel]
448       sourcenick = data[:sourcenick]
449       topic = data[:topic]
450       timestamp = data[:unixtime] || Time.now.to_i
451       if(sourcenick == @nick)
452         irclog "@ I set topic \"#{topic}\"", channel
453       else
454         irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
455       end
456       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
457
458       ontopic(m)
459       @plugins.delegate("listen", m)
460       @plugins.delegate("topic", m)
461     }
462     @client[:topic] = @client[:topicinfo] = proc {|data|
463       channel = data[:channel]
464       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
465         ontopic(m)
466     }
467     @client[:names] = proc {|data|
468       channel = data[:channel]
469       users = data[:users]
470       unless(@channels[channel])
471         warning "got names for channel '#{channel}' I didn't think I was in\n"
472         # exit 2
473       end
474       @channels[channel].users.clear
475       users.each {|u|
476         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
477       }
478       @plugins.delegate "names", data[:channel], data[:users]
479     }
480     @client[:unknown] = proc {|data|
481       #debug "UNKNOWN: #{data[:serverstring]}"
482       irclog data[:serverstring], ".unknown"
483     }
484   end
485
486   def got_sig(sig)
487     debug "received #{sig}, queueing quit"
488     $interrupted += 1
489     debug "interrupted #{$interrupted} times"
490     if $interrupted >= 5
491       debug "drastic!"
492       log_session_end
493       exit 2
494     elsif $interrupted >= 3
495       debug "quitting"
496       quit
497     end
498   end
499
500   # connect the bot to IRC
501   def connect
502     begin
503       trap("SIGINT") { got_sig("SIGINT") }
504       trap("SIGTERM") { got_sig("SIGTERM") }
505       trap("SIGHUP") { got_sig("SIGHUP") }
506     rescue ArgumentError => e
507       debug "failed to trap signals (#{e.inspect}): running on Windows?"
508     rescue => e
509       debug "failed to trap signals: #{e.inspect}"
510     end
511     begin
512       quit if $interrupted > 0
513       @socket.connect
514     rescue => e
515       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
516     end
517     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
518     @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
519     @capabilities = Hash.new
520     start_server_pings
521   end
522
523   # begin event handling loop
524   def mainloop
525     while true
526       begin
527         quit if $interrupted > 0
528         connect
529         @timer.start
530
531         while @socket.connected?
532           if @socket.select
533             break unless reply = @socket.gets
534             @client.process reply
535           end
536           quit if $interrupted > 0
537         end
538
539       # I despair of this. Some of my users get "connection reset by peer"
540       # exceptions that ARENT SocketError's. How am I supposed to handle
541       # that?
542       rescue SystemExit
543         log_session_end
544         exit 0
545       rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
546         error "network exception: #{e.class}: #{e}"
547         debug e.backtrace.join("\n")
548       rescue BDB::Fatal => e
549         error "fatal bdb error: #{e.class}: #{e}"
550         error e.backtrace.join("\n")
551         DBTree.stats
552         restart("Oops, we seem to have registry problems ...")
553       rescue Exception => e
554         error "non-net exception: #{e.class}: #{e}"
555         error e.backtrace.join("\n")
556       rescue => e
557         error "unexpected exception: #{e.class}: #{e}"
558         error e.backtrace.join("\n")
559         log_session_end
560         exit 2
561       end
562
563       stop_server_pings
564       @channels.clear
565       if @socket.connected?
566         @socket.clearq
567         @socket.shutdown
568       end
569
570       log "disconnected"
571
572       quit if $interrupted > 0
573
574       log "waiting to reconnect"
575       sleep @config['server.reconnect_wait']
576     end
577   end
578
579   # type:: message type
580   # where:: message target
581   # message:: message text
582   # send message +message+ of type +type+ to target +where+
583   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
584   # relevant say() or notice() methods. This one should be used for IRCd
585   # extensions you want to use in modules.
586   def sendmsg(type, where, message, chan=nil, ring=0)
587     # limit it according to the byterate, splitting the message
588     # taking into consideration the actual message length
589     # and all the extra stuff
590     # TODO allow something to do for commands that produce too many messages
591     # TODO example: math 10**10000
592     left = @socket.bytes_per - type.length - where.length - 4
593     begin
594       if(left >= message.length)
595         sendq "#{type} #{where} :#{message}", chan, ring
596         log_sent(type, where, message)
597         return
598       end
599       line = message.slice!(0, left)
600       lastspace = line.rindex(/\s+/)
601       if(lastspace)
602         message = line.slice!(lastspace, line.length) + message
603         message.gsub!(/^\s+/, "")
604       end
605       sendq "#{type} #{where} :#{line}", chan, ring
606       log_sent(type, where, line)
607     end while(message.length > 0)
608   end
609
610   # queue an arbitraty message for the server
611   def sendq(message="", chan=nil, ring=0)
612     # temporary
613     @socket.queue(message, chan, ring)
614   end
615
616   # send a notice message to channel/nick +where+
617   def notice(where, message, mchan=nil, mring=-1)
618     if mchan == ""
619       chan = where
620     else
621       chan = mchan
622     end
623     if mring < 0
624       if where =~ /^#/
625         ring = 2
626       else
627         ring = 1
628       end
629     else
630       ring = mring
631     end
632     message.each_line { |line|
633       line.chomp!
634       next unless(line.length > 0)
635       sendmsg "NOTICE", where, line, chan, ring
636     }
637   end
638
639   # say something (PRIVMSG) to channel/nick +where+
640   def say(where, message, mchan="", mring=-1)
641     if mchan == ""
642       chan = where
643     else
644       chan = mchan
645     end
646     if mring < 0
647       if where =~ /^#/
648         ring = 2
649       else
650         ring = 1
651       end
652     else
653       ring = mring
654     end
655     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
656       line.chomp!
657       next unless(line.length > 0)
658       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
659         sendmsg "PRIVMSG", where, line, chan, ring 
660       end
661     }
662   end
663
664   # perform a CTCP action with message +message+ to channel/nick +where+
665   def action(where, message, mchan="", mring=-1)
666     if mchan == ""
667       chan = where
668     else
669       chan = mchan
670     end
671     if mring < 0
672       if where =~ /^#/
673         ring = 2
674       else
675         ring = 1
676       end
677     else
678       ring = mring
679     end
680     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
681     if(where =~ /^#/)
682       irclog "* #{@nick} #{message}", where
683     elsif (where =~ /^(\S*)!.*$/)
684       irclog "* #{@nick}[#{where}] #{message}", $1
685     else
686       irclog "* #{@nick}[#{where}] #{message}", where
687     end
688   end
689
690   # quick way to say "okay" (or equivalent) to +where+
691   def okay(where)
692     say where, @lang.get("okay")
693   end
694
695   # log IRC-related message +message+ to a file determined by +where+.
696   # +where+ can be a channel name, or a nick for private message logging
697   def irclog(message, where="server")
698     message = message.chomp
699     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
700     where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
701     unless(@logs.has_key?(where))
702       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
703       @logs[where].sync = true
704     end
705     @logs[where].puts "[#{stamp}] #{message}"
706     #debug "[#{stamp}] <#{where}> #{message}"
707   end
708
709   # set topic of channel +where+ to +topic+
710   def topic(where, topic)
711     sendq "TOPIC #{where} :#{topic}", where, 2
712   end
713
714   # disconnect from the server and cleanup all plugins and modules
715   def shutdown(message = nil)
716     debug "Shutting down ..."
717     ## No we don't restore them ... let everything run through
718     # begin
719     #   trap("SIGINT", "DEFAULT")
720     #   trap("SIGTERM", "DEFAULT")
721     #   trap("SIGHUP", "DEFAULT")
722     # rescue => e
723     #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
724     # end
725     message = @lang.get("quit") if (message.nil? || message.empty?)
726     if @socket.connected?
727       debug "Clearing socket"
728       @socket.clearq
729       debug "Sending quit message"
730       @socket.emergency_puts "QUIT :#{message}"
731       debug "Flushing socket"
732       @socket.flush
733       debug "Shutting down socket"
734       @socket.shutdown
735     end
736     debug "Logging quits"
737     @channels.each_value {|v|
738       irclog "@ quit (#{message})", v.name
739     }
740     debug "Saving"
741     save
742     debug "Cleaning up"
743     @plugins.cleanup
744     # debug "Closing registries"
745     # @registry.close
746     debug "Cleaning up the db environment"
747     DBTree.cleanup_env
748     log "rbot quit (#{message})"
749   end
750
751   # message:: optional IRC quit message
752   # quit IRC, shutdown the bot
753   def quit(message=nil)
754     begin
755       shutdown(message)
756     ensure
757       exit 0
758     end
759   end
760
761   # totally shutdown and respawn the bot
762   def restart(message = false)
763     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
764     shutdown(msg)
765     sleep @config['server.reconnect_wait']
766     # now we re-exec
767     # Note, this fails on Windows
768     exec($0, *@argv)
769   end
770
771   # call the save method for bot's config, keywords, auth and all plugins
772   def save
773     @config.save
774     @keywords.save
775     @auth.save
776     @plugins.save
777     DBTree.cleanup_logs
778   end
779
780   # call the rescan method for the bot's lang, keywords and all plugins
781   def rescan
782     @lang.rescan
783     @plugins.rescan
784     @keywords.rescan
785   end
786
787   # channel:: channel to join
788   # key::     optional channel key if channel is +s
789   # join a channel
790   def join(channel, key=nil)
791     if(key)
792       sendq "JOIN #{channel} :#{key}", channel, 2
793     else
794       sendq "JOIN #{channel}", channel, 2
795     end
796   end
797
798   # part a channel
799   def part(channel, message="")
800     sendq "PART #{channel} :#{message}", channel, 2
801   end
802
803   # attempt to change bot's nick to +name+
804   def nickchg(name)
805       sendq "NICK #{name}"
806   end
807
808   # changing mode
809   def mode(channel, mode, target)
810       sendq "MODE #{channel} #{mode} #{target}", channel, 2
811   end
812
813   # m::     message asking for help
814   # topic:: optional topic help is requested for
815   # respond to online help requests
816   def help(topic=nil)
817     topic = nil if topic == ""
818     case topic
819     when nil
820       helpstr = "help topics: core, auth, keywords"
821       helpstr += @plugins.helptopics
822       helpstr += " (help <topic> for more info)"
823     when /^core$/i
824       helpstr = corehelp
825     when /^core\s+(.+)$/i
826       helpstr = corehelp $1
827     when /^auth$/i
828       helpstr = @auth.help
829     when /^auth\s+(.+)$/i
830       helpstr = @auth.help $1
831     when /^keywords$/i
832       helpstr = @keywords.help
833     when /^keywords\s+(.+)$/i
834       helpstr = @keywords.help $1
835     else
836       unless(helpstr = @plugins.help(topic))
837         helpstr = "no help for topic #{topic}"
838       end
839     end
840     return helpstr
841   end
842
843   # returns a string describing the current status of the bot (uptime etc)
844   def status
845     secs_up = Time.new - @startup_time
846     uptime = Utils.secs_to_string secs_up
847     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
848     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
849   end
850
851   # we'll ping the server every 30 seconds or so, and expect a response
852   # before the next one come around..
853   def start_server_pings
854     stop_server_pings
855     return unless @config['server.ping_timeout'] > 0
856     # we want to respond to a hung server within 30 secs or so
857     @ping_timer = @timer.add(30) {
858       @last_ping = Time.now
859       @socket.queue "PING :rbot"
860     }
861     @pong_timer = @timer.add(10) {
862       unless @last_ping.nil?
863         diff = Time.now - @last_ping
864         unless diff < @config['server.ping_timeout']
865           debug "no PONG from server for #{diff} seconds, reconnecting"
866           begin
867             @socket.shutdown
868           rescue
869             debug "couldn't shutdown connection (already shutdown?)"
870           end
871           @last_ping = nil
872           raise TimeoutError, "no PONG from server in #{diff} seconds"
873         end
874       end
875     }
876   end
877
878   def stop_server_pings
879     @last_ping = nil
880     # stop existing timers if running
881     unless @ping_timer.nil?
882       @timer.remove @ping_timer
883       @ping_timer = nil
884     end
885     unless @pong_timer.nil?
886       @timer.remove @pong_timer
887       @pong_timer = nil
888     end
889   end
890
891   private
892
893   # handle help requests for "core" topics
894   def corehelp(topic="")
895     case topic
896       when "quit"
897         return "quit [<message>] => quit IRC with message <message>"
898       when "restart"
899         return "restart => completely stop and restart the bot (including reconnect)"
900       when "join"
901         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"
902       when "part"
903         return "part <channel> => part channel <channel>"
904       when "hide"
905         return "hide => part all channels"
906       when "save"
907         return "save => save current dynamic data and configuration"
908       when "rescan"
909         return "rescan => reload modules and static facts"
910       when "nick"
911         return "nick <nick> => attempt to change nick to <nick>"
912       when "say"
913         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
914       when "action"
915         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
916         #       when "topic"
917         #         return "topic <channel> <message> => set topic of <channel> to <message>"
918       when "quiet"
919         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>"
920       when "talk"
921         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>"
922       when "version"
923         return "version => describes software version"
924       when "botsnack"
925         return "botsnack => reward #{@nick} for being good"
926       when "hello"
927         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
928       else
929         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
930     end
931   end
932
933   # handle incoming IRC PRIVMSG +m+
934   def onprivmsg(m)
935     # log it first
936     if(m.action?)
937       if(m.private?)
938         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
939       else
940         irclog "* #{m.sourcenick} #{m.message}", m.target
941       end
942     else
943       if(m.public?)
944         irclog "<#{m.sourcenick}> #{m.message}", m.target
945       else
946         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
947       end
948     end
949
950     @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
951
952     # pass it off to plugins that want to hear everything
953     @plugins.delegate "listen", m
954
955     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
956       notice m.sourcenick, "\001PING #$1\001"
957       irclog "@ #{m.sourcenick} pinged me"
958       return
959     end
960
961     if(m.address?)
962       delegate_privmsg(m)
963       case m.message
964         when (/^join\s+(\S+)\s+(\S+)$/i)
965           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
966         when (/^join\s+(\S+)$/i)
967           join $1 if(@auth.allow?("join", m.source, m.replyto))
968         when (/^part$/i)
969           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
970         when (/^part\s+(\S+)$/i)
971           part $1 if(@auth.allow?("join", m.source, m.replyto))
972         when (/^quit(?:\s+(.*))?$/i)
973           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
974         when (/^restart(?:\s+(.*))?$/i)
975           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
976         when (/^hide$/i)
977           join 0 if(@auth.allow?("join", m.source, m.replyto))
978         when (/^save$/i)
979           if(@auth.allow?("config", m.source, m.replyto))
980             save
981             m.okay
982           end
983         when (/^nick\s+(\S+)$/i)
984           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
985         when (/^say\s+(\S+)\s+(.*)$/i)
986           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
987         when (/^action\s+(\S+)\s+(.*)$/i)
988           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
989           # when (/^topic\s+(\S+)\s+(.*)$/i)
990           #   topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
991         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
992           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
993         when (/^ping$/i)
994           say m.replyto, "pong"
995         when (/^rescan$/i)
996           if(@auth.allow?("config", m.source, m.replyto))
997             m.reply "Saving ..."
998             save
999             m.reply "Rescanning ..."
1000             rescan
1001             m.okay
1002           end
1003         when (/^quiet$/i)
1004           if(auth.allow?("talk", m.source, m.replyto))
1005             m.okay
1006             @channels.each_value {|c| c.quiet = true }
1007           end
1008         when (/^quiet in (\S+)$/i)
1009           where = $1
1010           if(auth.allow?("talk", m.source, m.replyto))
1011             m.okay
1012             where.gsub!(/^here$/, m.target) if m.public?
1013             @channels[where].quiet = true if(@channels.has_key?(where))
1014           end
1015         when (/^talk$/i)
1016           if(auth.allow?("talk", m.source, m.replyto))
1017             @channels.each_value {|c| c.quiet = false }
1018             m.okay
1019           end
1020         when (/^talk in (\S+)$/i)
1021           where = $1
1022           if(auth.allow?("talk", m.source, m.replyto))
1023             where.gsub!(/^here$/, m.target) if m.public?
1024             @channels[where].quiet = false if(@channels.has_key?(where))
1025             m.okay
1026           end
1027         when (/^status\??$/i)
1028           m.reply status if auth.allow?("status", m.source, m.replyto)
1029         when (/^registry stats$/i)
1030           if auth.allow?("config", m.source, m.replyto)
1031             m.reply @registry.stat.inspect
1032           end
1033         when (/^(help\s+)?config(\s+|$)/)
1034           @config.privmsg(m)
1035         when (/^(version)|(introduce yourself)$/i)
1036           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1037         when (/^help(?:\s+(.*))?$/i)
1038           say m.replyto, help($1)
1039           #TODO move these to a "chatback" plugin
1040         when (/^(botsnack|ciggie)$/i)
1041           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1042           say m.replyto, @lang.get("thanks") if(m.private?)
1043         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1044           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1045           say m.replyto, @lang.get("hello") if(m.private?)
1046       end
1047     else
1048       # stuff to handle when not addressed
1049       case m.message
1050         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1051           say m.replyto, @lang.get("hello_X") % m.sourcenick
1052         when (/^#{Regexp.escape(@nick)}!*$/)
1053           say m.replyto, @lang.get("hello_X") % m.sourcenick
1054         else
1055           @keywords.privmsg(m)
1056       end
1057     end
1058   end
1059
1060   # log a message. Internal use only.
1061   def log_sent(type, where, message)
1062     case type
1063       when "NOTICE"
1064         if(where =~ /^#/)
1065           irclog "-=#{@nick}=- #{message}", where
1066         elsif (where =~ /(\S*)!.*/)
1067              irclog "[-=#{where}=-] #{message}", $1
1068         else
1069              irclog "[-=#{where}=-] #{message}"
1070         end
1071       when "PRIVMSG"
1072         if(where =~ /^#/)
1073           irclog "<#{@nick}> #{message}", where
1074         elsif (where =~ /^(\S*)!.*$/)
1075           irclog "[msg(#{where})] #{message}", $1
1076         else
1077           irclog "[msg(#{where})] #{message}", where
1078         end
1079     end
1080   end
1081
1082   def onjoin(m)
1083     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1084     if(m.address?)
1085       debug "joined channel #{m.channel}"
1086       irclog "@ Joined channel #{m.channel}", m.channel
1087     else
1088       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1089       @channels[m.channel].users[m.sourcenick] = Hash.new
1090       @channels[m.channel].users[m.sourcenick]["mode"] = ""
1091     end
1092
1093     @plugins.delegate("listen", m)
1094     @plugins.delegate("join", m)
1095   end
1096
1097   def onpart(m)
1098     if(m.address?)
1099       debug "left channel #{m.channel}"
1100       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1101       @channels.delete(m.channel)
1102     else
1103       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1104       if @channels.has_key?(m.channel)
1105         @channels[m.channel].users.delete(m.sourcenick)
1106       else
1107         warning "got part for channel '#{channel}' I didn't think I was in\n"
1108         # exit 2
1109       end
1110     end
1111
1112     # delegate to plugins
1113     @plugins.delegate("listen", m)
1114     @plugins.delegate("part", m)
1115   end
1116
1117   # respond to being kicked from a channel
1118   def onkick(m)
1119     if(m.address?)
1120       debug "kicked from channel #{m.channel}"
1121       @channels.delete(m.channel)
1122       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1123     else
1124       @channels[m.channel].users.delete(m.sourcenick)
1125       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1126     end
1127
1128     @plugins.delegate("listen", m)
1129     @plugins.delegate("kick", m)
1130   end
1131
1132   def ontopic(m)
1133     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1134     @channels[m.channel].topic = m.topic if !m.topic.nil?
1135     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1136     @channels[m.channel].topic.by = m.source if !m.source.nil?
1137
1138     debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1139   end
1140
1141   # delegate a privmsg to auth, keyword or plugin handlers
1142   def delegate_privmsg(message)
1143     [@auth, @plugins, @keywords].each {|m|
1144       break if m.privmsg(message)
1145     }
1146   end
1147 end
1148
1149 end