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