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