]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
8030fd41a8cc80fad926fdddcdec8e1b5b47b978
[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)
39 end
40
41 def log(message=nil, who_pos=1)
42   rawlog(Logger::Severity::INFO, message)
43 end
44
45 def warning(message=nil, who_pos=1)
46   rawlog(Logger::Severity::WARN, message)
47 end
48
49 def error(message=nil, who_pos=1)
50   rawlog(Logger::Severity::ERROR, message)
51 end
52
53 def fatal(message=nil, who_pos=1)
54   rawlog(Logger::Severity::FATAL, message)
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       STDOUT.reopen @logfile, "a"
286       STDERR.reopen @logfile, "a"
287     end
288
289     # Set the new logfile and loglevel. This must be done after the daemonizing
290     $logger.close
291     $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
292     $logger.datetime_format= $dateformat
293     $logger.level = @config['log.level']
294     $logger.level = $cl_loglevel if $cl_loglevel
295     $logger.level = 0 if $debug
296
297     log_session_start
298
299     @timer = Timer::Timer.new(1.0) # only need per-second granularity
300     @registry = BotRegistry.new self
301     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
302     @channels = Hash.new
303     @logs = Hash.new
304     @httputil = Utils::HttpUtil.new(self)
305     @lang = Language::Language.new(@config['core.language'])
306     @keywords = Keywords.new(self)
307     @auth = IrcAuth.new(self)
308
309     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
310     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
311
312     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
313     @nick = @config['irc.nick']
314
315     @client = IrcClient.new
316     @client[:isupport] = proc { |data|
317       if data[:capab]
318         sendq "CAPAB IDENTIFY-MSG"
319       end
320     }
321     @client[:datastr] = proc { |data|
322       debug data.inspect
323       if data[:text] == "IDENTIFY-MSG"
324         @capabilities["identify-msg".to_sym] = true
325       else
326         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
327       end
328     }
329     @client[:privmsg] = proc { |data|
330       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
331       onprivmsg(message)
332     }
333     @client[:notice] = proc { |data|
334       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
335       # pass it off to plugins that want to hear everything
336       @plugins.delegate "listen", message
337     }
338     @client[:motd] = proc { |data|
339       data[:motd].each_line { |line|
340         irclog "MOTD: #{line}", "server"
341       }
342     }
343     @client[:nicktaken] = proc { |data|
344       nickchg "#{data[:nick]}_"
345       @plugins.delegate "nicktaken", data[:nick]
346     }
347     @client[:badnick] = proc {|data|
348       warning "bad nick (#{data[:nick]})"
349     }
350     @client[:ping] = proc {|data|
351       @socket.queue "PONG #{data[:pingid]}"
352     }
353     @client[:pong] = proc {|data|
354       @last_ping = nil
355     }
356     @client[:nick] = proc {|data|
357       sourcenick = data[:sourcenick]
358       nick = data[:nick]
359       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
360       if(sourcenick == @nick)
361         debug "my nick is now #{nick}"
362         @nick = nick
363       end
364       @channels.each {|k,v|
365         if(v.users.has_key?(sourcenick))
366           irclog "@ #{sourcenick} is now known as #{nick}", k
367           v.users[nick] = v.users[sourcenick]
368           v.users.delete(sourcenick)
369         end
370       }
371       @plugins.delegate("listen", m)
372       @plugins.delegate("nick", m)
373     }
374     @client[:quit] = proc {|data|
375       source = data[:source]
376       sourcenick = data[:sourcenick]
377       sourceurl = data[:sourceaddress]
378       message = data[:message]
379       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
380       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
381       else
382         @channels.each {|k,v|
383           if(v.users.has_key?(sourcenick))
384             irclog "@ Quit: #{sourcenick}: #{message}", k
385             v.users.delete(sourcenick)
386           end
387         }
388       end
389       @plugins.delegate("listen", m)
390       @plugins.delegate("quit", m)
391     }
392     @client[:mode] = proc {|data|
393       source = data[:source]
394       sourcenick = data[:sourcenick]
395       sourceurl = data[:sourceaddress]
396       channel = data[:channel]
397       targets = data[:targets]
398       modestring = data[:modestring]
399       irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
400     }
401     @client[:welcome] = proc {|data|
402       irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
403       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
404       if data[:nick] && data[:nick].length > 0
405         @nick = data[:nick]
406       end
407
408       @plugins.delegate("connect")
409
410       @config['irc.join_channels'].each {|c|
411         debug "autojoining channel #{c}"
412         if(c =~ /^(\S+)\s+(\S+)$/i)
413           join $1, $2
414         else
415           join c if(c)
416         end
417       }
418     }
419     @client[:join] = proc {|data|
420       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
421       onjoin(m)
422     }
423     @client[:part] = proc {|data|
424       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
425       onpart(m)
426     }
427     @client[:kick] = proc {|data|
428       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
429       onkick(m)
430     }
431     @client[:invite] = proc {|data|
432       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
433         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
434       end
435     }
436     @client[:changetopic] = proc {|data|
437       channel = data[:channel]
438       sourcenick = data[:sourcenick]
439       topic = data[:topic]
440       timestamp = data[:unixtime] || Time.now.to_i
441       if(sourcenick == @nick)
442         irclog "@ I set topic \"#{topic}\"", channel
443       else
444         irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
445       end
446       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
447
448       ontopic(m)
449       @plugins.delegate("listen", m)
450       @plugins.delegate("topic", m)
451     }
452     @client[:topic] = @client[:topicinfo] = proc {|data|
453       channel = data[:channel]
454       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
455         ontopic(m)
456     }
457     @client[:names] = proc {|data|
458       channel = data[:channel]
459       users = data[:users]
460       unless(@channels[channel])
461         warning "got names for channel '#{channel}' I didn't think I was in\n"
462         # exit 2
463       end
464       @channels[channel].users.clear
465       users.each {|u|
466         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
467       }
468       @plugins.delegate "names", data[:channel], data[:users]
469     }
470     @client[:unknown] = proc {|data|
471       #debug "UNKNOWN: #{data[:serverstring]}"
472       irclog data[:serverstring], ".unknown"
473     }
474   end
475
476   def got_sig(sig)
477     debug "received #{sig}, queueing quit"
478     $interrupted += 1
479     debug "interrupted #{$interrupted} times"
480     if $interrupted >= 5
481       debug "drastic!"
482       log_session_end
483       exit 2
484     elsif $interrupted >= 3
485       debug "quitting"
486       quit
487     end
488   end
489
490   # connect the bot to IRC
491   def connect
492     begin
493       trap("SIGINT") { got_sig("SIGINT") }
494       trap("SIGTERM") { got_sig("SIGTERM") }
495       trap("SIGHUP") { got_sig("SIGHUP") }
496     rescue ArgumentError => e
497       debug "failed to trap signals (#{e.inspect}): running on Windows?"
498     rescue => e
499       debug "failed to trap signals: #{e.inspect}"
500     end
501     begin
502       quit if $interrupted > 0
503       @socket.connect
504     rescue => e
505       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
506     end
507     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
508     @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
509     @capabilities = Hash.new
510     start_server_pings
511   end
512
513   # begin event handling loop
514   def mainloop
515     while true
516       begin
517         quit if $interrupted > 0
518         connect
519         @timer.start
520
521         while @socket.connected?
522           if @socket.select
523             break unless reply = @socket.gets
524             @client.process reply
525           end
526           quit if $interrupted > 0
527         end
528
529       # I despair of this. Some of my users get "connection reset by peer"
530       # exceptions that ARENT SocketError's. How am I supposed to handle
531       # that?
532       rescue SystemExit
533         log_session_end
534         exit 0
535       rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
536         error "network exception: #{e.class}: #{e}"
537         debug e.backtrace.join("\n")
538       rescue BDB::Fatal => e
539         error "fatal bdb error: #{e.class}: #{e}"
540         error e.backtrace.join("\n")
541         DBTree.stats
542         restart("Oops, we seem to have registry problems ...")
543       rescue Exception => e
544         error "non-net exception: #{e.class}: #{e}"
545         error e.backtrace.join("\n")
546       rescue => e
547         error "unexpected exception: #{e.class}: #{e}"
548         error e.backtrace.join("\n")
549         log_session_end
550         exit 2
551       end
552
553       stop_server_pings
554       @channels.clear
555       if @socket.connected?
556         @socket.clearq
557         @socket.shutdown
558       end
559
560       log "disconnected"
561
562       quit if $interrupted > 0
563
564       log "waiting to reconnect"
565       sleep @config['server.reconnect_wait']
566     end
567   end
568
569   # type:: message type
570   # where:: message target
571   # message:: message text
572   # send message +message+ of type +type+ to target +where+
573   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
574   # relevant say() or notice() methods. This one should be used for IRCd
575   # extensions you want to use in modules.
576   def sendmsg(type, where, message, chan=nil, ring=0)
577     # limit it according to the byterate, splitting the message
578     # taking into consideration the actual message length
579     # and all the extra stuff
580     # TODO allow something to do for commands that produce too many messages
581     # TODO example: math 10**10000
582     left = @socket.bytes_per - type.length - where.length - 4
583     begin
584       if(left >= message.length)
585         sendq "#{type} #{where} :#{message}", chan, ring
586         log_sent(type, where, message)
587         return
588       end
589       line = message.slice!(0, left)
590       lastspace = line.rindex(/\s+/)
591       if(lastspace)
592         message = line.slice!(lastspace, line.length) + message
593         message.gsub!(/^\s+/, "")
594       end
595       sendq "#{type} #{where} :#{line}", chan, ring
596       log_sent(type, where, line)
597     end while(message.length > 0)
598   end
599
600   # queue an arbitraty message for the server
601   def sendq(message="", chan=nil, ring=0)
602     # temporary
603     @socket.queue(message, chan, ring)
604   end
605
606   # send a notice message to channel/nick +where+
607   def notice(where, message, mchan=nil, mring=-1)
608     if mchan == ""
609       chan = where
610     else
611       chan = mchan
612     end
613     if mring < 0
614       if where =~ /^#/
615         ring = 2
616       else
617         ring = 1
618       end
619     else
620       ring = mring
621     end
622     message.each_line { |line|
623       line.chomp!
624       next unless(line.length > 0)
625       sendmsg "NOTICE", where, line, chan, ring
626     }
627   end
628
629   # say something (PRIVMSG) to channel/nick +where+
630   def say(where, message, mchan="", mring=-1)
631     if mchan == ""
632       chan = where
633     else
634       chan = mchan
635     end
636     if mring < 0
637       if where =~ /^#/
638         ring = 2
639       else
640         ring = 1
641       end
642     else
643       ring = mring
644     end
645     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
646       line.chomp!
647       next unless(line.length > 0)
648       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
649         sendmsg "PRIVMSG", where, line, chan, ring 
650       end
651     }
652   end
653
654   # perform a CTCP action with message +message+ to channel/nick +where+
655   def action(where, message, mchan="", mring=-1)
656     if mchan == ""
657       chan = where
658     else
659       chan = mchan
660     end
661     if mring < 0
662       if where =~ /^#/
663         ring = 2
664       else
665         ring = 1
666       end
667     else
668       ring = mring
669     end
670     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
671     if(where =~ /^#/)
672       irclog "* #{@nick} #{message}", where
673     elsif (where =~ /^(\S*)!.*$/)
674       irclog "* #{@nick}[#{where}] #{message}", $1
675     else
676       irclog "* #{@nick}[#{where}] #{message}", where
677     end
678   end
679
680   # quick way to say "okay" (or equivalent) to +where+
681   def okay(where)
682     say where, @lang.get("okay")
683   end
684
685   # log IRC-related message +message+ to a file determined by +where+.
686   # +where+ can be a channel name, or a nick for private message logging
687   def irclog(message, where="server")
688     message = message.chomp
689     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
690     where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
691     unless(@logs.has_key?(where))
692       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
693       @logs[where].sync = true
694     end
695     @logs[where].puts "[#{stamp}] #{message}"
696     #debug "[#{stamp}] <#{where}> #{message}"
697   end
698
699   # set topic of channel +where+ to +topic+
700   def topic(where, topic)
701     sendq "TOPIC #{where} :#{topic}", where, 2
702   end
703
704   # disconnect from the server and cleanup all plugins and modules
705   def shutdown(message = nil)
706     debug "Shutting down ..."
707     ## No we don't restore them ... let everything run through
708     # begin
709     #   trap("SIGINT", "DEFAULT")
710     #   trap("SIGTERM", "DEFAULT")
711     #   trap("SIGHUP", "DEFAULT")
712     # rescue => e
713     #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
714     # end
715     message = @lang.get("quit") if (message.nil? || message.empty?)
716     if @socket.connected?
717       debug "Clearing socket"
718       @socket.clearq
719       debug "Sending quit message"
720       @socket.emergency_puts "QUIT :#{message}"
721       debug "Flushing socket"
722       @socket.flush
723       debug "Shutting down socket"
724       @socket.shutdown
725     end
726     debug "Logging quits"
727     @channels.each_value {|v|
728       irclog "@ quit (#{message})", v.name
729     }
730     debug "Saving"
731     save
732     debug "Cleaning up"
733     @plugins.cleanup
734     # debug "Closing registries"
735     # @registry.close
736     debug "Cleaning up the db environment"
737     DBTree.cleanup_env
738     log "rbot quit (#{message})"
739   end
740
741   # message:: optional IRC quit message
742   # quit IRC, shutdown the bot
743   def quit(message=nil)
744     begin
745       shutdown(message)
746     ensure
747       exit 0
748     end
749   end
750
751   # totally shutdown and respawn the bot
752   def restart(message = false)
753     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
754     shutdown(msg)
755     sleep @config['server.reconnect_wait']
756     # now we re-exec
757     # Note, this fails on Windows
758     exec($0, *@argv)
759   end
760
761   # call the save method for bot's config, keywords, auth and all plugins
762   def save
763     @config.save
764     @keywords.save
765     @auth.save
766     @plugins.save
767     DBTree.cleanup_logs
768   end
769
770   # call the rescan method for the bot's lang, keywords and all plugins
771   def rescan
772     @lang.rescan
773     @plugins.rescan
774     @keywords.rescan
775   end
776
777   # channel:: channel to join
778   # key::     optional channel key if channel is +s
779   # join a channel
780   def join(channel, key=nil)
781     if(key)
782       sendq "JOIN #{channel} :#{key}", channel, 2
783     else
784       sendq "JOIN #{channel}", channel, 2
785     end
786   end
787
788   # part a channel
789   def part(channel, message="")
790     sendq "PART #{channel} :#{message}", channel, 2
791   end
792
793   # attempt to change bot's nick to +name+
794   def nickchg(name)
795       sendq "NICK #{name}"
796   end
797
798   # changing mode
799   def mode(channel, mode, target)
800       sendq "MODE #{channel} #{mode} #{target}", channel, 2
801   end
802
803   # m::     message asking for help
804   # topic:: optional topic help is requested for
805   # respond to online help requests
806   def help(topic=nil)
807     topic = nil if topic == ""
808     case topic
809     when nil
810       helpstr = "help topics: core, auth, keywords"
811       helpstr += @plugins.helptopics
812       helpstr += " (help <topic> for more info)"
813     when /^core$/i
814       helpstr = corehelp
815     when /^core\s+(.+)$/i
816       helpstr = corehelp $1
817     when /^auth$/i
818       helpstr = @auth.help
819     when /^auth\s+(.+)$/i
820       helpstr = @auth.help $1
821     when /^keywords$/i
822       helpstr = @keywords.help
823     when /^keywords\s+(.+)$/i
824       helpstr = @keywords.help $1
825     else
826       unless(helpstr = @plugins.help(topic))
827         helpstr = "no help for topic #{topic}"
828       end
829     end
830     return helpstr
831   end
832
833   # returns a string describing the current status of the bot (uptime etc)
834   def status
835     secs_up = Time.new - @startup_time
836     uptime = Utils.secs_to_string secs_up
837     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
838     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
839   end
840
841   # we'll ping the server every 30 seconds or so, and expect a response
842   # before the next one come around..
843   def start_server_pings
844     stop_server_pings
845     return unless @config['server.ping_timeout'] > 0
846     # we want to respond to a hung server within 30 secs or so
847     @ping_timer = @timer.add(30) {
848       @last_ping = Time.now
849       @socket.queue "PING :rbot"
850     }
851     @pong_timer = @timer.add(10) {
852       unless @last_ping.nil?
853         diff = Time.now - @last_ping
854         unless diff < @config['server.ping_timeout']
855           debug "no PONG from server for #{diff} seconds, reconnecting"
856           begin
857             @socket.shutdown
858           rescue
859             debug "couldn't shutdown connection (already shutdown?)"
860           end
861           @last_ping = nil
862           raise TimeoutError, "no PONG from server in #{diff} seconds"
863         end
864       end
865     }
866   end
867
868   def stop_server_pings
869     @last_ping = nil
870     # stop existing timers if running
871     unless @ping_timer.nil?
872       @timer.remove @ping_timer
873       @ping_timer = nil
874     end
875     unless @pong_timer.nil?
876       @timer.remove @pong_timer
877       @pong_timer = nil
878     end
879   end
880
881   private
882
883   # handle help requests for "core" topics
884   def corehelp(topic="")
885     case topic
886       when "quit"
887         return "quit [<message>] => quit IRC with message <message>"
888       when "restart"
889         return "restart => completely stop and restart the bot (including reconnect)"
890       when "join"
891         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"
892       when "part"
893         return "part <channel> => part channel <channel>"
894       when "hide"
895         return "hide => part all channels"
896       when "save"
897         return "save => save current dynamic data and configuration"
898       when "rescan"
899         return "rescan => reload modules and static facts"
900       when "nick"
901         return "nick <nick> => attempt to change nick to <nick>"
902       when "say"
903         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
904       when "action"
905         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
906         #       when "topic"
907         #         return "topic <channel> <message> => set topic of <channel> to <message>"
908       when "quiet"
909         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>"
910       when "talk"
911         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>"
912       when "version"
913         return "version => describes software version"
914       when "botsnack"
915         return "botsnack => reward #{@nick} for being good"
916       when "hello"
917         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
918       else
919         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
920     end
921   end
922
923   # handle incoming IRC PRIVMSG +m+
924   def onprivmsg(m)
925     # log it first
926     if(m.action?)
927       if(m.private?)
928         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
929       else
930         irclog "* #{m.sourcenick} #{m.message}", m.target
931       end
932     else
933       if(m.public?)
934         irclog "<#{m.sourcenick}> #{m.message}", m.target
935       else
936         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
937       end
938     end
939
940     @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
941
942     # pass it off to plugins that want to hear everything
943     @plugins.delegate "listen", m
944
945     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
946       notice m.sourcenick, "\001PING #$1\001"
947       irclog "@ #{m.sourcenick} pinged me"
948       return
949     end
950
951     if(m.address?)
952       delegate_privmsg(m)
953       case m.message
954         when (/^join\s+(\S+)\s+(\S+)$/i)
955           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
956         when (/^join\s+(\S+)$/i)
957           join $1 if(@auth.allow?("join", m.source, m.replyto))
958         when (/^part$/i)
959           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
960         when (/^part\s+(\S+)$/i)
961           part $1 if(@auth.allow?("join", m.source, m.replyto))
962         when (/^quit(?:\s+(.*))?$/i)
963           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
964         when (/^restart(?:\s+(.*))?$/i)
965           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
966         when (/^hide$/i)
967           join 0 if(@auth.allow?("join", m.source, m.replyto))
968         when (/^save$/i)
969           if(@auth.allow?("config", m.source, m.replyto))
970             save
971             m.okay
972           end
973         when (/^nick\s+(\S+)$/i)
974           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
975         when (/^say\s+(\S+)\s+(.*)$/i)
976           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
977         when (/^action\s+(\S+)\s+(.*)$/i)
978           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
979           # when (/^topic\s+(\S+)\s+(.*)$/i)
980           #   topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
981         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
982           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
983         when (/^ping$/i)
984           say m.replyto, "pong"
985         when (/^rescan$/i)
986           if(@auth.allow?("config", m.source, m.replyto))
987             m.reply "Saving ..."
988             save
989             m.reply "Rescanning ..."
990             rescan
991             m.okay
992           end
993         when (/^quiet$/i)
994           if(auth.allow?("talk", m.source, m.replyto))
995             m.okay
996             @channels.each_value {|c| c.quiet = true }
997           end
998         when (/^quiet in (\S+)$/i)
999           where = $1
1000           if(auth.allow?("talk", m.source, m.replyto))
1001             m.okay
1002             where.gsub!(/^here$/, m.target) if m.public?
1003             @channels[where].quiet = true if(@channels.has_key?(where))
1004           end
1005         when (/^talk$/i)
1006           if(auth.allow?("talk", m.source, m.replyto))
1007             @channels.each_value {|c| c.quiet = false }
1008             m.okay
1009           end
1010         when (/^talk in (\S+)$/i)
1011           where = $1
1012           if(auth.allow?("talk", m.source, m.replyto))
1013             where.gsub!(/^here$/, m.target) if m.public?
1014             @channels[where].quiet = false if(@channels.has_key?(where))
1015             m.okay
1016           end
1017         when (/^status\??$/i)
1018           m.reply status if auth.allow?("status", m.source, m.replyto)
1019         when (/^registry stats$/i)
1020           if auth.allow?("config", m.source, m.replyto)
1021             m.reply @registry.stat.inspect
1022           end
1023         when (/^(help\s+)?config(\s+|$)/)
1024           @config.privmsg(m)
1025         when (/^(version)|(introduce yourself)$/i)
1026           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1027         when (/^help(?:\s+(.*))?$/i)
1028           say m.replyto, help($1)
1029           #TODO move these to a "chatback" plugin
1030         when (/^(botsnack|ciggie)$/i)
1031           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1032           say m.replyto, @lang.get("thanks") if(m.private?)
1033         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1034           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1035           say m.replyto, @lang.get("hello") if(m.private?)
1036       end
1037     else
1038       # stuff to handle when not addressed
1039       case m.message
1040         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1041           say m.replyto, @lang.get("hello_X") % m.sourcenick
1042         when (/^#{Regexp.escape(@nick)}!*$/)
1043           say m.replyto, @lang.get("hello_X") % m.sourcenick
1044         else
1045           @keywords.privmsg(m)
1046       end
1047     end
1048   end
1049
1050   # log a message. Internal use only.
1051   def log_sent(type, where, message)
1052     case type
1053       when "NOTICE"
1054         if(where =~ /^#/)
1055           irclog "-=#{@nick}=- #{message}", where
1056         elsif (where =~ /(\S*)!.*/)
1057              irclog "[-=#{where}=-] #{message}", $1
1058         else
1059              irclog "[-=#{where}=-] #{message}"
1060         end
1061       when "PRIVMSG"
1062         if(where =~ /^#/)
1063           irclog "<#{@nick}> #{message}", where
1064         elsif (where =~ /^(\S*)!.*$/)
1065           irclog "[msg(#{where})] #{message}", $1
1066         else
1067           irclog "[msg(#{where})] #{message}", where
1068         end
1069     end
1070   end
1071
1072   def onjoin(m)
1073     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1074     if(m.address?)
1075       debug "joined channel #{m.channel}"
1076       irclog "@ Joined channel #{m.channel}", m.channel
1077     else
1078       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1079       @channels[m.channel].users[m.sourcenick] = Hash.new
1080       @channels[m.channel].users[m.sourcenick]["mode"] = ""
1081     end
1082
1083     @plugins.delegate("listen", m)
1084     @plugins.delegate("join", m)
1085   end
1086
1087   def onpart(m)
1088     if(m.address?)
1089       debug "left channel #{m.channel}"
1090       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1091       @channels.delete(m.channel)
1092     else
1093       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1094       if @channels.has_key?(m.channel)
1095         @channels[m.channel].users.delete(m.sourcenick)
1096       else
1097         warning "got part for channel '#{channel}' I didn't think I was in\n"
1098         # exit 2
1099       end
1100     end
1101
1102     # delegate to plugins
1103     @plugins.delegate("listen", m)
1104     @plugins.delegate("part", m)
1105   end
1106
1107   # respond to being kicked from a channel
1108   def onkick(m)
1109     if(m.address?)
1110       debug "kicked from channel #{m.channel}"
1111       @channels.delete(m.channel)
1112       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1113     else
1114       @channels[m.channel].users.delete(m.sourcenick)
1115       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1116     end
1117
1118     @plugins.delegate("listen", m)
1119     @plugins.delegate("kick", m)
1120   end
1121
1122   def ontopic(m)
1123     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1124     @channels[m.channel].topic = m.topic if !m.topic.nil?
1125     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1126     @channels[m.channel].topic.by = m.source if !m.source.nil?
1127
1128     debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1129   end
1130
1131   # delegate a privmsg to auth, keyword or plugin handlers
1132   def delegate_privmsg(message)
1133     [@auth, @plugins, @keywords].each {|m|
1134       break if m.privmsg(message)
1135     }
1136   end
1137 end
1138
1139 end