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