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