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