]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
Initial factorization of botconfig into kernel functionality and a coremodule
[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
272     begin
273       @config = BotConfig.configmanager
274       @config.bot_associate(self)
275     rescue => e
276       fatal e.inspect
277       fatal e.backtrace.join("\n")
278       log_session_end
279       exit 2
280     end
281
282     if @config['core.run_as_daemon']
283       $daemonize = true
284     end
285
286     @logfile = @config['log.file']
287     if @logfile.class!=String || @logfile.empty?
288       @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
289     end
290
291     # See http://blog.humlab.umu.se/samuel/archives/000107.html
292     # for the backgrounding code 
293     if $daemonize
294       begin
295         exit if fork
296         Process.setsid
297         exit if fork
298       rescue NotImplementedError
299         warning "Could not background, fork not supported"
300       rescue => e
301         warning "Could not background. #{e.inspect}"
302       end
303       Dir.chdir botclass
304       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
305       log "Redirecting standard input/output/error"
306       begin
307         STDIN.reopen "/dev/null"
308       rescue Errno::ENOENT
309         # On Windows, there's not such thing as /dev/null
310         STDIN.reopen "NUL"
311       end
312       def STDOUT.write(str=nil)
313         log str, 2
314         return str.to_s.length
315       end
316       def STDERR.write(str=nil)
317         if str.to_s.match(/:\d+: warning:/)
318           warning str, 2
319         else
320           error str, 2
321         end
322         return str.to_s.length
323       end
324     end
325
326     # Set the new logfile and loglevel. This must be done after the daemonizing
327     $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
328     $logger.datetime_format= $dateformat
329     $logger.level = @config['log.level']
330     $logger.level = $cl_loglevel if $cl_loglevel
331     $logger.level = 0 if $debug
332
333     log_session_start
334
335     @registry = BotRegistry.new self
336
337     @timer = Timer::Timer.new(1.0) # only need per-second granularity
338     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
339
340     @logs = Hash.new
341
342     @httputil = Utils::HttpUtil.new(self)
343
344     @lang = Language::Language.new(@config['core.language'])
345
346     # @keywords = Keywords.new(self)
347
348     begin
349       @auth = Auth::authmanager
350       @auth.bot_associate(self)
351       # @auth.load("#{botclass}/botusers.yaml")
352     rescue => e
353       fatal e.inspect
354       fatal e.backtrace.join("\n")
355       log_session_end
356       exit 2
357     end
358     @auth.everyone.set_default_permission("*", true)
359
360     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
361     @plugins = Plugins::pluginmanager
362     @plugins.bot_associate(self)
363     @plugins.add_botmodule_dir(Config::coredir)
364     @plugins.add_botmodule_dir("#{botclass}/plugins")
365     @plugins.add_botmodule_dir(Config::datadir + "/plugins")
366     @plugins.scan
367
368     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
369     @client = IrcClient.new
370     @server = @client.server
371     @myself = @client.client
372     @myself.nick = @config['irc.nick']
373
374     # Channels where we are quiet
375     # It's nil when we are not quiet, an empty list when we are quiet
376     # in all channels, a list of channels otherwise
377     @quiet = nil
378
379     @client[:welcome] = proc {|data|
380       irclog "joined server #{@client.server} as #{myself}", "server"
381
382       @plugins.delegate("connect")
383
384       @config['irc.join_channels'].each { |c|
385         debug "autojoining channel #{c}"
386         if(c =~ /^(\S+)\s+(\S+)$/i)
387           join $1, $2
388         else
389           join c if(c)
390         end
391       }
392     }
393     @client[:isupport] = proc { |data|
394       # TODO this needs to go into rfc2812.rb
395       # Since capabs are two-steps processes, server.supports[:capab]
396       # should be a three-state: nil, [], [....]
397       sendq "CAPAB IDENTIFY-MSG" if @server.supports[:capab]
398     }
399     @client[:datastr] = proc { |data|
400       # TODO this needs to go into rfc2812.rb
401       if data[:text] == "IDENTIFY-MSG"
402         @server.capabilities["identify-msg".to_sym] = true
403       else
404         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
405       end
406     }
407     @client[:privmsg] = proc { |data|
408       m = PrivMessage.new(self, @server, data[:source], data[:target], data[:message])
409
410       # TODO use the new Netmask class
411       # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
412
413       irclogprivmsg(m)
414
415       @plugins.delegate "listen", m
416       @plugins.privmsg(m)
417     }
418     @client[:notice] = proc { |data|
419       message = NoticeMessage.new(self, @server, data[:source], data[:target], data[:message])
420       # pass it off to plugins that want to hear everything
421       @plugins.delegate "listen", message
422     }
423     @client[:motd] = proc { |data|
424       data[:motd].each_line { |line|
425         irclog "MOTD: #{line}", "server"
426       }
427     }
428     @client[:nicktaken] = proc { |data|
429       nickchg "#{data[:nick]}_"
430       @plugins.delegate "nicktaken", data[:nick]
431     }
432     @client[:badnick] = proc {|data|
433       warning "bad nick (#{data[:nick]})"
434     }
435     @client[:ping] = proc {|data|
436       sendq "PONG #{data[:pingid]}"
437     }
438     @client[:pong] = proc {|data|
439       @last_ping = nil
440     }
441     @client[:nick] = proc {|data|
442       source = data[:source]
443       old = data[:oldnick]
444       new = data[:newnick]
445       m = NickMessage.new(self, @server, source, old, new)
446       if source == myself
447         debug "my nick is now #{new}"
448       end
449       data[:is_on].each { |ch|
450           irclog "@ #{old} is now known as #{new}", ch
451       }
452       @plugins.delegate("listen", m)
453       @plugins.delegate("nick", m)
454     }
455     @client[:quit] = proc {|data|
456       source = data[:source]
457       message = data[:message]
458       m = QuitMessage.new(self, @server, source, source, message)
459       data[:was_on].each { |ch|
460         irclog "@ Quit: #{source}: #{message}", ch
461       }
462       @plugins.delegate("listen", m)
463       @plugins.delegate("quit", m)
464     }
465     @client[:mode] = proc {|data|
466       irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
467     }
468     @client[:join] = proc {|data|
469       m = JoinMessage.new(self, @server, data[:source], data[:channel], data[:message])
470       irclogjoin(m)
471
472       @plugins.delegate("listen", m)
473       @plugins.delegate("join", m)
474     }
475     @client[:part] = proc {|data|
476       m = PartMessage.new(self, @server, data[:source], data[:channel], data[:message])
477       irclogpart(m)
478
479       @plugins.delegate("listen", m)
480       @plugins.delegate("part", m)
481     }
482     @client[:kick] = proc {|data|
483       m = KickMessage.new(self, @server, data[:source], data[:target], data[:channel],data[:message])
484       irclogkick(m)
485
486       @plugins.delegate("listen", m)
487       @plugins.delegate("kick", m)
488     }
489     @client[:invite] = proc {|data|
490       if data[:target] == myself
491         join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
492       end
493     }
494     @client[:changetopic] = proc {|data|
495       m = TopicMessage.new(self, @server, data[:source], data[:channel], data[:topic])
496       irclogtopic(m)
497
498       @plugins.delegate("listen", m)
499       @plugins.delegate("topic", m)
500     }
501     @client[:topic] = proc { |data|
502       irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
503     }
504     @client[:topicinfo] = proc { |data|
505       channel = data[:channel]
506       topic = channel.topic
507       irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
508       m = TopicMessage.new(self, @server, data[:source], channel, topic)
509
510       @plugins.delegate("listen", m)
511       @plugins.delegate("topic", m)
512     }
513     @client[:names] = proc { |data|
514       @plugins.delegate "names", data[:channel], data[:users]
515     }
516     @client[:unknown] = proc { |data|
517       #debug "UNKNOWN: #{data[:serverstring]}"
518       irclog data[:serverstring], ".unknown"
519     }
520   end
521
522   # checks if we should be quiet on a channel
523   def quiet_on?(channel)
524     return false unless @quiet
525     return true if @quiet.empty?
526     return @quiet.include?(channel.to_s)
527   end
528
529   def set_quiet(channel=nil)
530     if channel
531       @quiet << channel.to_s unless @quiet.include?(channel.to_s)
532     else
533       @quiet = []
534     end
535   end
536
537   def reset_quiet(channel=nil)
538     if channel
539       @quiet.delete_if { |x| x == channel.to_s }
540     else
541       @quiet = nil
542     end
543   end
544
545   # things to do when we receive a signal
546   def got_sig(sig)
547     debug "received #{sig}, queueing quit"
548     $interrupted += 1
549     debug "interrupted #{$interrupted} times"
550     if $interrupted >= 5
551       debug "drastic!"
552       log_session_end
553       exit 2
554     elsif $interrupted >= 3
555       debug "quitting"
556       quit
557     end
558   end
559
560   # connect the bot to IRC
561   def connect
562     begin
563       trap("SIGINT") { got_sig("SIGINT") }
564       trap("SIGTERM") { got_sig("SIGTERM") }
565       trap("SIGHUP") { got_sig("SIGHUP") }
566     rescue ArgumentError => e
567       debug "failed to trap signals (#{e.inspect}): running on Windows?"
568     rescue => e
569       debug "failed to trap signals: #{e.inspect}"
570     end
571     begin
572       quit if $interrupted > 0
573       @socket.connect
574     rescue => e
575       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
576     end
577     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
578     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
579     start_server_pings
580   end
581
582   # begin event handling loop
583   def mainloop
584     while true
585       begin
586         quit if $interrupted > 0
587         connect
588         @timer.start
589
590         while @socket.connected?
591           if @socket.select
592             break unless reply = @socket.gets
593             @client.process reply
594           end
595           quit if $interrupted > 0
596         end
597
598       # I despair of this. Some of my users get "connection reset by peer"
599       # exceptions that ARENT SocketError's. How am I supposed to handle
600       # that?
601       rescue SystemExit
602         log_session_end
603         exit 0
604       rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
605         error "network exception: #{e.class}: #{e}"
606         debug e.backtrace.join("\n")
607       rescue BDB::Fatal => e
608         fatal "fatal bdb error: #{e.class}: #{e}"
609         fatal e.backtrace.join("\n")
610         DBTree.stats
611         # Why restart? DB problems are serious stuff ...
612         # restart("Oops, we seem to have registry problems ...")
613         log_session_end
614         exit 2
615       rescue Exception => e
616         error "non-net exception: #{e.class}: #{e}"
617         error e.backtrace.join("\n")
618       rescue => e
619         fatal "unexpected exception: #{e.class}: #{e}"
620         fatal e.backtrace.join("\n")
621         log_session_end
622         exit 2
623       end
624
625       stop_server_pings
626       @server.clear
627       if @socket.connected?
628         @socket.clearq
629         @socket.shutdown
630       end
631
632       log "disconnected"
633
634       quit if $interrupted > 0
635
636       log "waiting to reconnect"
637       sleep @config['server.reconnect_wait']
638     end
639   end
640
641   # type:: message type
642   # where:: message target
643   # message:: message text
644   # send message +message+ of type +type+ to target +where+
645   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
646   # relevant say() or notice() methods. This one should be used for IRCd
647   # extensions you want to use in modules.
648   def sendmsg(type, where, message, chan=nil, ring=0)
649     # limit it according to the byterate, splitting the message
650     # taking into consideration the actual message length
651     # and all the extra stuff
652     # TODO allow something to do for commands that produce too many messages
653     # TODO example: math 10**10000
654     left = @socket.bytes_per - type.length - where.to_s.length - 4
655     begin
656       if(left >= message.length)
657         sendq "#{type} #{where} :#{message}", chan, ring
658         log_sent(type, where, message)
659         return
660       end
661       line = message.slice!(0, left)
662       lastspace = line.rindex(/\s+/)
663       if(lastspace)
664         message = line.slice!(lastspace, line.length) + message
665         message.gsub!(/^\s+/, "")
666       end
667       sendq "#{type} #{where} :#{line}", chan, ring
668       log_sent(type, where, line)
669     end while(message.length > 0)
670   end
671
672   # queue an arbitraty message for the server
673   def sendq(message="", chan=nil, ring=0)
674     # temporary
675     @socket.queue(message, chan, ring)
676   end
677
678   # send a notice message to channel/nick +where+
679   def notice(where, message, mchan="", mring=-1)
680     if mchan == ""
681       chan = where
682     else
683       chan = mchan
684     end
685     if mring < 0
686       case where
687       when User
688         ring = 1
689       else
690         ring = 2
691       end
692     else
693       ring = mring
694     end
695     message.each_line { |line|
696       line.chomp!
697       next unless(line.length > 0)
698       sendmsg "NOTICE", where, line, chan, ring
699     }
700   end
701
702   # say something (PRIVMSG) to channel/nick +where+
703   def say(where, message, mchan="", mring=-1)
704     if mchan == ""
705       chan = where
706     else
707       chan = mchan
708     end
709     if mring < 0
710       case where
711       when User
712         ring = 1
713       else
714         ring = 2
715       end
716     else
717       ring = mring
718     end
719     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
720       line.chomp!
721       next unless(line.length > 0)
722       unless quiet_on?(where)
723         sendmsg "PRIVMSG", where, line, chan, ring 
724       end
725     }
726   end
727
728   # perform a CTCP action with message +message+ to channel/nick +where+
729   def action(where, message, mchan="", mring=-1)
730     if mchan == ""
731       chan = where
732     else
733       chan = mchan
734     end
735     if mring < 0
736       case where
737       when Channel
738         ring = 2
739       else
740         ring = 1
741       end
742     else
743       ring = mring
744     end
745     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
746     case where
747     when Channel
748       irclog "* #{myself} #{message}", where
749     else
750       irclog "* #{myself}[#{where}] #{message}", where
751     end
752   end
753
754   # quick way to say "okay" (or equivalent) to +where+
755   def okay(where)
756     say where, @lang.get("okay")
757   end
758
759   # log IRC-related message +message+ to a file determined by +where+.
760   # +where+ can be a channel name, or a nick for private message logging
761   def irclog(message, where="server")
762     message = message.chomp
763     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
764     where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
765     unless(@logs.has_key?(where))
766       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
767       @logs[where].sync = true
768     end
769     @logs[where].puts "[#{stamp}] #{message}"
770     #debug "[#{stamp}] <#{where}> #{message}"
771   end
772
773   # set topic of channel +where+ to +topic+
774   def topic(where, topic)
775     sendq "TOPIC #{where} :#{topic}", where, 2
776   end
777
778   # disconnect from the server and cleanup all plugins and modules
779   def shutdown(message = nil)
780     debug "Shutting down ..."
781     ## No we don't restore them ... let everything run through
782     # begin
783     #   trap("SIGINT", "DEFAULT")
784     #   trap("SIGTERM", "DEFAULT")
785     #   trap("SIGHUP", "DEFAULT")
786     # rescue => e
787     #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
788     # end
789     message = @lang.get("quit") if (message.nil? || message.empty?)
790     if @socket.connected?
791       debug "Clearing socket"
792       @socket.clearq
793       debug "Sending quit message"
794       @socket.emergency_puts "QUIT :#{message}"
795       debug "Flushing socket"
796       @socket.flush
797       debug "Shutting down socket"
798       @socket.shutdown
799     end
800     debug "Logging quits"
801     @server.channels.each { |ch|
802       irclog "@ quit (#{message})", ch
803     }
804     debug "Saving"
805     save
806     debug "Cleaning up"
807     @plugins.cleanup
808     # debug "Closing registries"
809     # @registry.close
810     debug "Cleaning up the db environment"
811     DBTree.cleanup_env
812     log "rbot quit (#{message})"
813   end
814
815   # message:: optional IRC quit message
816   # quit IRC, shutdown the bot
817   def quit(message=nil)
818     begin
819       shutdown(message)
820     ensure
821       exit 0
822     end
823   end
824
825   # totally shutdown and respawn the bot
826   def restart(message = false)
827     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
828     shutdown(msg)
829     sleep @config['server.reconnect_wait']
830     # now we re-exec
831     # Note, this fails on Windows
832     exec($0, *@argv)
833   end
834
835   # call the save method for bot's config, keywords, auth and all plugins
836   def save
837     @config.save
838     # @keywords.save
839     @auth.save
840     @plugins.save
841     DBTree.cleanup_logs
842   end
843
844   # call the rescan method for the bot's lang, keywords and all plugins
845   def rescan
846     @lang.rescan
847     @plugins.rescan
848     # @keywords.rescan
849   end
850
851   # channel:: channel to join
852   # key::     optional channel key if channel is +s
853   # join a channel
854   def join(channel, key=nil)
855     if(key)
856       sendq "JOIN #{channel} :#{key}", channel, 2
857     else
858       sendq "JOIN #{channel}", channel, 2
859     end
860   end
861
862   # part a channel
863   def part(channel, message="")
864     sendq "PART #{channel} :#{message}", channel, 2
865   end
866
867   # attempt to change bot's nick to +name+
868   def nickchg(name)
869       sendq "NICK #{name}"
870   end
871
872   # changing mode
873   def mode(channel, mode, target)
874       sendq "MODE #{channel} #{mode} #{target}", channel, 2
875   end
876
877   # m::     message asking for help
878   # topic:: optional topic help is requested for
879   # respond to online help requests
880   def help(topic=nil)
881     topic = nil if topic == ""
882     case topic
883     when nil
884       helpstr = "help topics: "
885       helpstr += @plugins.helptopics
886       helpstr += " (help <topic> for more info)"
887     else
888       unless(helpstr = @plugins.help(topic))
889         helpstr = "no help for topic #{topic}"
890       end
891     end
892     return helpstr
893   end
894
895   # returns a string describing the current status of the bot (uptime etc)
896   def status
897     secs_up = Time.new - @startup_time
898     uptime = Utils.secs_to_string secs_up
899     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
900     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
901   end
902
903   # we'll ping the server every 30 seconds or so, and expect a response
904   # before the next one come around..
905   def start_server_pings
906     stop_server_pings
907     return unless @config['server.ping_timeout'] > 0
908     # we want to respond to a hung server within 30 secs or so
909     @ping_timer = @timer.add(30) {
910       @last_ping = Time.now
911       @socket.queue "PING :rbot"
912     }
913     @pong_timer = @timer.add(10) {
914       unless @last_ping.nil?
915         diff = Time.now - @last_ping
916         unless diff < @config['server.ping_timeout']
917           debug "no PONG from server for #{diff} seconds, reconnecting"
918           begin
919             @socket.shutdown
920           rescue
921             debug "couldn't shutdown connection (already shutdown?)"
922           end
923           @last_ping = nil
924           raise TimeoutError, "no PONG from server in #{diff} seconds"
925         end
926       end
927     }
928   end
929
930   def stop_server_pings
931     @last_ping = nil
932     # stop existing timers if running
933     unless @ping_timer.nil?
934       @timer.remove @ping_timer
935       @ping_timer = nil
936     end
937     unless @pong_timer.nil?
938       @timer.remove @pong_timer
939       @pong_timer = nil
940     end
941   end
942
943   private
944
945   def irclogprivmsg(m)
946     if(m.action?)
947       if(m.private?)
948         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
949       else
950         irclog "* #{m.sourcenick} #{m.message}", m.target
951       end
952     else
953       if(m.public?)
954         irclog "<#{m.sourcenick}> #{m.message}", m.target
955       else
956         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
957       end
958     end
959   end
960
961   # log a message. Internal use only.
962   def log_sent(type, where, message)
963     case type
964       when "NOTICE"
965         case where
966         when Channel
967           irclog "-=#{myself}=- #{message}", where
968         when User
969              irclog "[-=#{where}=-] #{message}", $1
970         else
971              irclog "[-=#{where}=-] #{message}", where
972         end
973       when "PRIVMSG"
974         case where
975         when Channel
976           irclog "<#{myself}> #{message}", where
977         when User
978           irclog "[msg(#{where})] #{message}", $1
979         else
980           irclog "[msg(#{where})] #{message}", where
981         end
982     end
983   end
984
985   def irclogjoin(m)
986     if m.address?
987       debug "joined channel #{m.channel}"
988       irclog "@ Joined channel #{m.channel}", m.channel
989     else
990       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
991     end
992   end
993
994   def irclogpart(m)
995     if(m.address?)
996       debug "left channel #{m.channel}"
997       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
998     else
999       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1000     end
1001   end
1002
1003   def irclogkick(m)
1004     if(m.address?)
1005       debug "kicked from channel #{m.channel}"
1006       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1007     else
1008       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1009     end
1010   end
1011
1012   def irclogtopic(m)
1013     if m.source == myself
1014       irclog "@ I set topic \"#{m.topic}\"", m.channel
1015     else
1016       irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel
1017     end
1018   end
1019
1020 end
1021
1022 end