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