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