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