]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
just some tiny tweaks. giuseppe! you have been busy! :)
[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     who.gsub!(/./," ")
21   else
22     who = "(unknown)"
23   end
24   message.to_s.each_line { |l|
25     $logger.add(level, l.chomp, who)
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 = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
301     $logger.datetime_format= $dateformat
302     $logger.level = @config['log.level']
303     $logger.level = $cl_loglevel if $cl_loglevel
304     $logger.level = 0 if $debug
305
306     log_session_start
307
308     @timer = Timer::Timer.new(1.0) # only need per-second granularity
309     @registry = BotRegistry.new self
310     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
311     @channels = Hash.new
312     @logs = Hash.new
313     @httputil = Utils::HttpUtil.new(self)
314     @lang = Language::Language.new(@config['core.language'])
315     @keywords = Keywords.new(self)
316     begin
317       @auth = IrcAuth.new(self)
318     rescue => e
319       fatal e.inspect
320       fatal e.backtrace.join("\n")
321       log_session_end
322       exit 2
323     end
324
325     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
326     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
327
328     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
329     @nick = @config['irc.nick']
330
331     @client = IrcClient.new
332     @client[:isupport] = proc { |data|
333       if data[:capab]
334         sendq "CAPAB IDENTIFY-MSG"
335       end
336     }
337     @client[:datastr] = proc { |data|
338       debug data.inspect
339       if data[:text] == "IDENTIFY-MSG"
340         @capabilities["identify-msg".to_sym] = true
341       else
342         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
343       end
344     }
345     @client[:privmsg] = proc { |data|
346       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
347       onprivmsg(message)
348     }
349     @client[:notice] = proc { |data|
350       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
351       # pass it off to plugins that want to hear everything
352       @plugins.delegate "listen", message
353     }
354     @client[:motd] = proc { |data|
355       data[:motd].each_line { |line|
356         irclog "MOTD: #{line}", "server"
357       }
358     }
359     @client[:nicktaken] = proc { |data|
360       nickchg "#{data[:nick]}_"
361       @plugins.delegate "nicktaken", data[:nick]
362     }
363     @client[:badnick] = proc {|data|
364       warning "bad nick (#{data[:nick]})"
365     }
366     @client[:ping] = proc {|data|
367       @socket.queue "PONG #{data[:pingid]}"
368     }
369     @client[:pong] = proc {|data|
370       @last_ping = nil
371     }
372     @client[:nick] = proc {|data|
373       sourcenick = data[:sourcenick]
374       nick = data[:nick]
375       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
376       if(sourcenick == @nick)
377         debug "my nick is now #{nick}"
378         @nick = nick
379       end
380       @channels.each {|k,v|
381         if(v.users.has_key?(sourcenick))
382           irclog "@ #{sourcenick} is now known as #{nick}", k
383           v.users[nick] = v.users[sourcenick]
384           v.users.delete(sourcenick)
385         end
386       }
387       @plugins.delegate("listen", m)
388       @plugins.delegate("nick", m)
389     }
390     @client[:quit] = proc {|data|
391       source = data[:source]
392       sourcenick = data[:sourcenick]
393       sourceurl = data[:sourceaddress]
394       message = data[:message]
395       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
396       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
397       else
398         @channels.each {|k,v|
399           if(v.users.has_key?(sourcenick))
400             irclog "@ Quit: #{sourcenick}: #{message}", k
401             v.users.delete(sourcenick)
402           end
403         }
404       end
405       @plugins.delegate("listen", m)
406       @plugins.delegate("quit", m)
407     }
408     @client[:mode] = proc {|data|
409       source = data[:source]
410       sourcenick = data[:sourcenick]
411       sourceurl = data[:sourceaddress]
412       channel = data[:channel]
413       targets = data[:targets]
414       modestring = data[:modestring]
415       irclog "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
416     }
417     @client[:welcome] = proc {|data|
418       irclog "joined server #{data[:source]} as #{data[:nick]}", "server"
419       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
420       if data[:nick] && data[:nick].length > 0
421         @nick = data[:nick]
422       end
423
424       @plugins.delegate("connect")
425
426       @config['irc.join_channels'].each {|c|
427         debug "autojoining channel #{c}"
428         if(c =~ /^(\S+)\s+(\S+)$/i)
429           join $1, $2
430         else
431           join c if(c)
432         end
433       }
434     }
435     @client[:join] = proc {|data|
436       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
437       onjoin(m)
438     }
439     @client[:part] = proc {|data|
440       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
441       onpart(m)
442     }
443     @client[:kick] = proc {|data|
444       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
445       onkick(m)
446     }
447     @client[:invite] = proc {|data|
448       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
449         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
450       end
451     }
452     @client[:changetopic] = proc {|data|
453       channel = data[:channel]
454       sourcenick = data[:sourcenick]
455       topic = data[:topic]
456       timestamp = data[:unixtime] || Time.now.to_i
457       if(sourcenick == @nick)
458         irclog "@ I set topic \"#{topic}\"", channel
459       else
460         irclog "@ #{sourcenick} set topic \"#{topic}\"", channel
461       end
462       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
463
464       ontopic(m)
465       @plugins.delegate("listen", m)
466       @plugins.delegate("topic", m)
467     }
468     @client[:topic] = @client[:topicinfo] = proc {|data|
469       channel = data[:channel]
470       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
471         ontopic(m)
472     }
473     @client[:names] = proc {|data|
474       channel = data[:channel]
475       users = data[:users]
476       unless(@channels[channel])
477         warning "got names for channel '#{channel}' I didn't think I was in\n"
478         # exit 2
479       end
480       @channels[channel].users.clear
481       users.each {|u|
482         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
483       }
484       @plugins.delegate "names", data[:channel], data[:users]
485     }
486     @client[:unknown] = proc {|data|
487       #debug "UNKNOWN: #{data[:serverstring]}"
488       irclog data[:serverstring], ".unknown"
489     }
490   end
491
492   def got_sig(sig)
493     debug "received #{sig}, queueing quit"
494     $interrupted += 1
495     debug "interrupted #{$interrupted} times"
496     if $interrupted >= 5
497       debug "drastic!"
498       log_session_end
499       exit 2
500     elsif $interrupted >= 3
501       debug "quitting"
502       quit
503     end
504   end
505
506   # connect the bot to IRC
507   def connect
508     begin
509       trap("SIGINT") { got_sig("SIGINT") }
510       trap("SIGTERM") { got_sig("SIGTERM") }
511       trap("SIGHUP") { got_sig("SIGHUP") }
512     rescue ArgumentError => e
513       debug "failed to trap signals (#{e.inspect}): running on Windows?"
514     rescue => e
515       debug "failed to trap signals: #{e.inspect}"
516     end
517     begin
518       quit if $interrupted > 0
519       @socket.connect
520     rescue => e
521       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
522     end
523     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
524     @socket.emergency_puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
525     @capabilities = Hash.new
526     start_server_pings
527   end
528
529   # begin event handling loop
530   def mainloop
531     while true
532       begin
533         quit if $interrupted > 0
534         connect
535         @timer.start
536
537         while @socket.connected?
538           if @socket.select
539             break unless reply = @socket.gets
540             @client.process reply
541           end
542           quit if $interrupted > 0
543         end
544
545       # I despair of this. Some of my users get "connection reset by peer"
546       # exceptions that ARENT SocketError's. How am I supposed to handle
547       # that?
548       rescue SystemExit
549         log_session_end
550         exit 0
551       rescue Errno::ETIMEDOUT, TimeoutError, SocketError => e
552         error "network exception: #{e.class}: #{e}"
553         debug e.backtrace.join("\n")
554       rescue BDB::Fatal => e
555         fatal "fatal bdb error: #{e.class}: #{e}"
556         fatal e.backtrace.join("\n")
557         DBTree.stats
558         # Why restart? DB problems are serious stuff ...
559         # restart("Oops, we seem to have registry problems ...")
560         log_session_end
561         exit 2
562       rescue Exception => e
563         error "non-net exception: #{e.class}: #{e}"
564         error e.backtrace.join("\n")
565       rescue => e
566         fatal "unexpected exception: #{e.class}: #{e}"
567         fatal e.backtrace.join("\n")
568         log_session_end
569         exit 2
570       end
571
572       stop_server_pings
573       @channels.clear
574       if @socket.connected?
575         @socket.clearq
576         @socket.shutdown
577       end
578
579       log "disconnected"
580
581       quit if $interrupted > 0
582
583       log "waiting to reconnect"
584       sleep @config['server.reconnect_wait']
585     end
586   end
587
588   # type:: message type
589   # where:: message target
590   # message:: message text
591   # send message +message+ of type +type+ to target +where+
592   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
593   # relevant say() or notice() methods. This one should be used for IRCd
594   # extensions you want to use in modules.
595   def sendmsg(type, where, message, chan=nil, ring=0)
596     # limit it according to the byterate, splitting the message
597     # taking into consideration the actual message length
598     # and all the extra stuff
599     # TODO allow something to do for commands that produce too many messages
600     # TODO example: math 10**10000
601     left = @socket.bytes_per - type.length - where.length - 4
602     begin
603       if(left >= message.length)
604         sendq "#{type} #{where} :#{message}", chan, ring
605         log_sent(type, where, message)
606         return
607       end
608       line = message.slice!(0, left)
609       lastspace = line.rindex(/\s+/)
610       if(lastspace)
611         message = line.slice!(lastspace, line.length) + message
612         message.gsub!(/^\s+/, "")
613       end
614       sendq "#{type} #{where} :#{line}", chan, ring
615       log_sent(type, where, line)
616     end while(message.length > 0)
617   end
618
619   # queue an arbitraty message for the server
620   def sendq(message="", chan=nil, ring=0)
621     # temporary
622     @socket.queue(message, chan, ring)
623   end
624
625   # send a notice message to channel/nick +where+
626   def notice(where, message, mchan=nil, mring=-1)
627     if mchan == ""
628       chan = where
629     else
630       chan = mchan
631     end
632     if mring < 0
633       if where =~ /^#/
634         ring = 2
635       else
636         ring = 1
637       end
638     else
639       ring = mring
640     end
641     message.each_line { |line|
642       line.chomp!
643       next unless(line.length > 0)
644       sendmsg "NOTICE", where, line, chan, ring
645     }
646   end
647
648   # say something (PRIVMSG) to channel/nick +where+
649   def say(where, message, mchan="", mring=-1)
650     if mchan == ""
651       chan = where
652     else
653       chan = mchan
654     end
655     if mring < 0
656       if where =~ /^#/
657         ring = 2
658       else
659         ring = 1
660       end
661     else
662       ring = mring
663     end
664     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
665       line.chomp!
666       next unless(line.length > 0)
667       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
668         sendmsg "PRIVMSG", where, line, chan, ring 
669       end
670     }
671   end
672
673   # perform a CTCP action with message +message+ to channel/nick +where+
674   def action(where, message, mchan="", mring=-1)
675     if mchan == ""
676       chan = where
677     else
678       chan = mchan
679     end
680     if mring < 0
681       if where =~ /^#/
682         ring = 2
683       else
684         ring = 1
685       end
686     else
687       ring = mring
688     end
689     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
690     if(where =~ /^#/)
691       irclog "* #{@nick} #{message}", where
692     elsif (where =~ /^(\S*)!.*$/)
693       irclog "* #{@nick}[#{where}] #{message}", $1
694     else
695       irclog "* #{@nick}[#{where}] #{message}", where
696     end
697   end
698
699   # quick way to say "okay" (or equivalent) to +where+
700   def okay(where)
701     say where, @lang.get("okay")
702   end
703
704   # log IRC-related message +message+ to a file determined by +where+.
705   # +where+ can be a channel name, or a nick for private message logging
706   def irclog(message, where="server")
707     message = message.chomp
708     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
709     where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
710     unless(@logs.has_key?(where))
711       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
712       @logs[where].sync = true
713     end
714     @logs[where].puts "[#{stamp}] #{message}"
715     #debug "[#{stamp}] <#{where}> #{message}"
716   end
717
718   # set topic of channel +where+ to +topic+
719   def topic(where, topic)
720     sendq "TOPIC #{where} :#{topic}", where, 2
721   end
722
723   # disconnect from the server and cleanup all plugins and modules
724   def shutdown(message = nil)
725     debug "Shutting down ..."
726     ## No we don't restore them ... let everything run through
727     # begin
728     #   trap("SIGINT", "DEFAULT")
729     #   trap("SIGTERM", "DEFAULT")
730     #   trap("SIGHUP", "DEFAULT")
731     # rescue => e
732     #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
733     # end
734     message = @lang.get("quit") if (message.nil? || message.empty?)
735     if @socket.connected?
736       debug "Clearing socket"
737       @socket.clearq
738       debug "Sending quit message"
739       @socket.emergency_puts "QUIT :#{message}"
740       debug "Flushing socket"
741       @socket.flush
742       debug "Shutting down socket"
743       @socket.shutdown
744     end
745     debug "Logging quits"
746     @channels.each_value {|v|
747       irclog "@ quit (#{message})", v.name
748     }
749     debug "Saving"
750     save
751     debug "Cleaning up"
752     @plugins.cleanup
753     # debug "Closing registries"
754     # @registry.close
755     debug "Cleaning up the db environment"
756     DBTree.cleanup_env
757     log "rbot quit (#{message})"
758   end
759
760   # message:: optional IRC quit message
761   # quit IRC, shutdown the bot
762   def quit(message=nil)
763     begin
764       shutdown(message)
765     ensure
766       exit 0
767     end
768   end
769
770   # totally shutdown and respawn the bot
771   def restart(message = false)
772     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
773     shutdown(msg)
774     sleep @config['server.reconnect_wait']
775     # now we re-exec
776     # Note, this fails on Windows
777     exec($0, *@argv)
778   end
779
780   # call the save method for bot's config, keywords, auth and all plugins
781   def save
782     @config.save
783     @keywords.save
784     @auth.save
785     @plugins.save
786     DBTree.cleanup_logs
787   end
788
789   # call the rescan method for the bot's lang, keywords and all plugins
790   def rescan
791     @lang.rescan
792     @plugins.rescan
793     @keywords.rescan
794   end
795
796   # channel:: channel to join
797   # key::     optional channel key if channel is +s
798   # join a channel
799   def join(channel, key=nil)
800     if(key)
801       sendq "JOIN #{channel} :#{key}", channel, 2
802     else
803       sendq "JOIN #{channel}", channel, 2
804     end
805   end
806
807   # part a channel
808   def part(channel, message="")
809     sendq "PART #{channel} :#{message}", channel, 2
810   end
811
812   # attempt to change bot's nick to +name+
813   def nickchg(name)
814       sendq "NICK #{name}"
815   end
816
817   # changing mode
818   def mode(channel, mode, target)
819       sendq "MODE #{channel} #{mode} #{target}", channel, 2
820   end
821
822   # m::     message asking for help
823   # topic:: optional topic help is requested for
824   # respond to online help requests
825   def help(topic=nil)
826     topic = nil if topic == ""
827     case topic
828     when nil
829       helpstr = "help topics: core, auth, keywords"
830       helpstr += @plugins.helptopics
831       helpstr += " (help <topic> for more info)"
832     when /^core$/i
833       helpstr = corehelp
834     when /^core\s+(.+)$/i
835       helpstr = corehelp $1
836     when /^auth$/i
837       helpstr = @auth.help
838     when /^auth\s+(.+)$/i
839       helpstr = @auth.help $1
840     when /^keywords$/i
841       helpstr = @keywords.help
842     when /^keywords\s+(.+)$/i
843       helpstr = @keywords.help $1
844     else
845       unless(helpstr = @plugins.help(topic))
846         helpstr = "no help for topic #{topic}"
847       end
848     end
849     return helpstr
850   end
851
852   # returns a string describing the current status of the bot (uptime etc)
853   def status
854     secs_up = Time.new - @startup_time
855     uptime = Utils.secs_to_string secs_up
856     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
857     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
858   end
859
860   # we'll ping the server every 30 seconds or so, and expect a response
861   # before the next one come around..
862   def start_server_pings
863     stop_server_pings
864     return unless @config['server.ping_timeout'] > 0
865     # we want to respond to a hung server within 30 secs or so
866     @ping_timer = @timer.add(30) {
867       @last_ping = Time.now
868       @socket.queue "PING :rbot"
869     }
870     @pong_timer = @timer.add(10) {
871       unless @last_ping.nil?
872         diff = Time.now - @last_ping
873         unless diff < @config['server.ping_timeout']
874           debug "no PONG from server for #{diff} seconds, reconnecting"
875           begin
876             @socket.shutdown
877           rescue
878             debug "couldn't shutdown connection (already shutdown?)"
879           end
880           @last_ping = nil
881           raise TimeoutError, "no PONG from server in #{diff} seconds"
882         end
883       end
884     }
885   end
886
887   def stop_server_pings
888     @last_ping = nil
889     # stop existing timers if running
890     unless @ping_timer.nil?
891       @timer.remove @ping_timer
892       @ping_timer = nil
893     end
894     unless @pong_timer.nil?
895       @timer.remove @pong_timer
896       @pong_timer = nil
897     end
898   end
899
900   private
901
902   # handle help requests for "core" topics
903   def corehelp(topic="")
904     case topic
905       when "quit"
906         return "quit [<message>] => quit IRC with message <message>"
907       when "restart"
908         return "restart => completely stop and restart the bot (including reconnect)"
909       when "join"
910         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"
911       when "part"
912         return "part <channel> => part channel <channel>"
913       when "hide"
914         return "hide => part all channels"
915       when "save"
916         return "save => save current dynamic data and configuration"
917       when "rescan"
918         return "rescan => reload modules and static facts"
919       when "nick"
920         return "nick <nick> => attempt to change nick to <nick>"
921       when "say"
922         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
923       when "action"
924         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
925         #       when "topic"
926         #         return "topic <channel> <message> => set topic of <channel> to <message>"
927       when "quiet"
928         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>"
929       when "talk"
930         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>"
931       when "version"
932         return "version => describes software version"
933       when "botsnack"
934         return "botsnack => reward #{@nick} for being good"
935       when "hello"
936         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
937       else
938         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
939     end
940   end
941
942   # handle incoming IRC PRIVMSG +m+
943   def onprivmsg(m)
944     # log it first
945     if(m.action?)
946       if(m.private?)
947         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
948       else
949         irclog "* #{m.sourcenick} #{m.message}", m.target
950       end
951     else
952       if(m.public?)
953         irclog "<#{m.sourcenick}> #{m.message}", m.target
954       else
955         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
956       end
957     end
958
959     @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
960
961     # pass it off to plugins that want to hear everything
962     @plugins.delegate "listen", m
963
964     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
965       notice m.sourcenick, "\001PING #$1\001"
966       irclog "@ #{m.sourcenick} pinged me"
967       return
968     end
969
970     if(m.address?)
971       delegate_privmsg(m)
972       case m.message
973         when (/^join\s+(\S+)\s+(\S+)$/i)
974           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
975         when (/^join\s+(\S+)$/i)
976           join $1 if(@auth.allow?("join", m.source, m.replyto))
977         when (/^part$/i)
978           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
979         when (/^part\s+(\S+)$/i)
980           part $1 if(@auth.allow?("join", m.source, m.replyto))
981         when (/^quit(?:\s+(.*))?$/i)
982           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
983         when (/^restart(?:\s+(.*))?$/i)
984           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
985         when (/^hide$/i)
986           join 0 if(@auth.allow?("join", m.source, m.replyto))
987         when (/^save$/i)
988           if(@auth.allow?("config", m.source, m.replyto))
989             save
990             m.okay
991           end
992         when (/^nick\s+(\S+)$/i)
993           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
994         when (/^say\s+(\S+)\s+(.*)$/i)
995           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
996         when (/^action\s+(\S+)\s+(.*)$/i)
997           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
998           # when (/^topic\s+(\S+)\s+(.*)$/i)
999           #   topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
1000         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
1001           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
1002         when (/^ping$/i)
1003           say m.replyto, "pong"
1004         when (/^rescan$/i)
1005           if(@auth.allow?("config", m.source, m.replyto))
1006             m.reply "saving ..."
1007             save
1008             m.reply "rescanning ..."
1009             rescan
1010             m.reply "done. #{@plugins.status(true)}"
1011           end
1012         when (/^quiet$/i)
1013           if(auth.allow?("talk", m.source, m.replyto))
1014             m.okay
1015             @channels.each_value {|c| c.quiet = true }
1016           end
1017         when (/^quiet in (\S+)$/i)
1018           where = $1
1019           if(auth.allow?("talk", m.source, m.replyto))
1020             m.okay
1021             where.gsub!(/^here$/, m.target) if m.public?
1022             @channels[where].quiet = true if(@channels.has_key?(where))
1023           end
1024         when (/^talk$/i)
1025           if(auth.allow?("talk", m.source, m.replyto))
1026             @channels.each_value {|c| c.quiet = false }
1027             m.okay
1028           end
1029         when (/^talk in (\S+)$/i)
1030           where = $1
1031           if(auth.allow?("talk", m.source, m.replyto))
1032             where.gsub!(/^here$/, m.target) if m.public?
1033             @channels[where].quiet = false if(@channels.has_key?(where))
1034             m.okay
1035           end
1036         when (/^status\??$/i)
1037           m.reply status if auth.allow?("status", m.source, m.replyto)
1038         when (/^registry stats$/i)
1039           if auth.allow?("config", m.source, m.replyto)
1040             m.reply @registry.stat.inspect
1041           end
1042         when (/^(help\s+)?config(\s+|$)/)
1043           @config.privmsg(m)
1044         when (/^(version)|(introduce yourself)$/i)
1045           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
1046         when (/^help(?:\s+(.*))?$/i)
1047           say m.replyto, help($1)
1048           #TODO move these to a "chatback" plugin
1049         when (/^(botsnack|ciggie)$/i)
1050           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
1051           say m.replyto, @lang.get("thanks") if(m.private?)
1052         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
1053           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
1054           say m.replyto, @lang.get("hello") if(m.private?)
1055       end
1056     else
1057       # stuff to handle when not addressed
1058       case m.message
1059         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
1060           say m.replyto, @lang.get("hello_X") % m.sourcenick
1061         when (/^#{Regexp.escape(@nick)}!*$/)
1062           say m.replyto, @lang.get("hello_X") % m.sourcenick
1063         else
1064           @keywords.privmsg(m)
1065       end
1066     end
1067   end
1068
1069   # log a message. Internal use only.
1070   def log_sent(type, where, message)
1071     case type
1072       when "NOTICE"
1073         if(where =~ /^#/)
1074           irclog "-=#{@nick}=- #{message}", where
1075         elsif (where =~ /(\S*)!.*/)
1076              irclog "[-=#{where}=-] #{message}", $1
1077         else
1078              irclog "[-=#{where}=-] #{message}"
1079         end
1080       when "PRIVMSG"
1081         if(where =~ /^#/)
1082           irclog "<#{@nick}> #{message}", where
1083         elsif (where =~ /^(\S*)!.*$/)
1084           irclog "[msg(#{where})] #{message}", $1
1085         else
1086           irclog "[msg(#{where})] #{message}", where
1087         end
1088     end
1089   end
1090
1091   def onjoin(m)
1092     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1093     if(m.address?)
1094       debug "joined channel #{m.channel}"
1095       irclog "@ Joined channel #{m.channel}", m.channel
1096     else
1097       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1098       @channels[m.channel].users[m.sourcenick] = Hash.new
1099       @channels[m.channel].users[m.sourcenick]["mode"] = ""
1100     end
1101
1102     @plugins.delegate("listen", m)
1103     @plugins.delegate("join", m)
1104   end
1105
1106   def onpart(m)
1107     if(m.address?)
1108       debug "left channel #{m.channel}"
1109       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1110       @channels.delete(m.channel)
1111     else
1112       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1113       if @channels.has_key?(m.channel)
1114         @channels[m.channel].users.delete(m.sourcenick)
1115       else
1116         warning "got part for channel '#{channel}' I didn't think I was in\n"
1117         # exit 2
1118       end
1119     end
1120
1121     # delegate to plugins
1122     @plugins.delegate("listen", m)
1123     @plugins.delegate("part", m)
1124   end
1125
1126   # respond to being kicked from a channel
1127   def onkick(m)
1128     if(m.address?)
1129       debug "kicked from channel #{m.channel}"
1130       @channels.delete(m.channel)
1131       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1132     else
1133       @channels[m.channel].users.delete(m.sourcenick)
1134       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1135     end
1136
1137     @plugins.delegate("listen", m)
1138     @plugins.delegate("kick", m)
1139   end
1140
1141   def ontopic(m)
1142     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
1143     @channels[m.channel].topic = m.topic if !m.topic.nil?
1144     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
1145     @channels[m.channel].topic.by = m.source if !m.source.nil?
1146
1147     debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
1148   end
1149
1150   # delegate a privmsg to auth, keyword or plugin handlers
1151   def delegate_privmsg(message)
1152     [@auth, @plugins, @keywords].each {|m|
1153       break if m.privmsg(message)
1154     }
1155   end
1156 end
1157
1158 end