]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/keywords.rb
win32 thing for signal handling
[user/henk/code/ruby/rbot.git] / lib / rbot / keywords.rb
1 require 'pp'
2
3 module Irc
4
5   # Keyword class
6   #
7   # Encapsulates a keyword ("foo is bar" is a keyword called foo, with type
8   # is, and has a single value of bar).
9   # Keywords can have multiple values, to_s() will choose one at random
10   class Keyword
11
12     # type of keyword (e.g. "is" or "are")
13     attr_reader :type
14     
15     # type::   type of keyword (e.g "is" or "are")
16     # values:: array of values
17     # 
18     # create a keyword of type +type+ with values +values+
19     def initialize(type, values)
20       @type = type.downcase
21       @values = values
22     end
23
24     # pick a random value for this keyword and return it
25     def to_s
26       if(@values.length > 1)
27         Keyword.unescape(@values[rand(@values.length)])
28       else
29         Keyword.unescape(@values[0])
30       end
31     end
32
33     # describe the keyword (show all values without interpolation)
34     def desc
35       @values.join(" | ")
36     end
37
38     # return the keyword in a stringified form ready for storage
39     def dump
40       @type + "/" + Keyword.unescape(@values.join("<=or=>"))
41     end
42
43     # deserialize the stringified form to an object
44     def Keyword.restore(str)
45       if str =~ /^(\S+?)\/(.*)$/
46         type = $1
47         vals = $2.split("<=or=>")
48         return Keyword.new(type, vals)
49       end
50       return nil
51     end
52
53     # values:: array of values to add
54     # add values to a keyword
55     def <<(values)
56       if(@values.length > 1 || values.length > 1)
57         values.each {|v|
58           @values << v
59         }
60       else
61         @values[0] += " or " + values[0]
62       end
63     end
64
65     # unescape special words/characters in a keyword
66     def Keyword.unescape(str)
67       str.gsub(/\\\|/, "|").gsub(/ \\is /, " is ").gsub(/ \\are /, " are ").gsub(/\\\?(\s*)$/, "?\1")
68     end
69
70     # escape special words/characters in a keyword
71     def Keyword.escape(str)
72       str.gsub(/\|/, "\\|").gsub(/ is /, " \\is ").gsub(/ are /, " \\are ").gsub(/\?(\s*)$/, "\\?\1")
73     end
74   end
75
76   # keywords class. 
77   #
78   # Handles all that stuff like "bot: foo is bar", "bot: foo?"
79   #
80   # Fallback after core and auth have had a look at a message and refused to
81   # handle it, checks for a keyword command or lookup, otherwise the message
82   # is delegated to plugins
83   class Keywords
84     BotConfig.register BotConfigBooleanValue.new('keyword.listen',
85       :default => false,
86       :desc => "Should the bot listen to all chat and attempt to automatically detect keywords? (e.g. by spotting someone say 'foo is bar')")
87     BotConfig.register BotConfigBooleanValue.new('keyword.address',
88       :default => true,
89       :desc => "Should the bot require that keyword lookups are addressed to it? If not, the bot will attempt to lookup foo if someone says 'foo?' in channel")
90     
91     # create a new Keywords instance, associated to bot +bot+
92     def initialize(bot)
93       @bot = bot
94       @statickeywords = Hash.new
95       upgrade_data
96       @keywords = DBTree.new bot, "keyword"
97
98       scan
99       
100       # import old format keywords into DBHash
101       if(File.exist?("#{@bot.botclass}/keywords.rbot"))
102         puts "auto importing old keywords.rbot"
103         IO.foreach("#{@bot.botclass}/keywords.rbot") do |line|
104           if(line =~ /^(.*?)\s*<=(is|are)?=?>\s*(.*)$/)
105             lhs = $1
106             mhs = $2
107             rhs = $3
108             mhs = "is" unless mhs
109             rhs = Keyword.escape rhs
110             values = rhs.split("<=or=>")
111             @keywords[lhs] = Keyword.new(mhs, values).dump
112           end
113         end
114         File.delete("#{@bot.botclass}/keywords.rbot")
115       end
116     end
117     
118     # drop static keywords and reload them from files, picking up any new
119     # keyword files that have been added
120     def rescan
121       @statickeywords = Hash.new
122       scan
123     end
124
125     # load static keywords from files, picking up any new keyword files that
126     # have been added
127     def scan
128       # first scan for old DBHash files, and convert them
129       Dir["#{@bot.botclass}/keywords/*"].each {|f|
130         next unless f =~ /\.db$/
131         puts "upgrading keyword db #{f} (rbot 0.9.5 or prior) database format"
132         newname = f.gsub(/\.db$/, ".kdb")
133         old = BDB::Hash.open f, nil, 
134                              "r+", 0600, "set_pagesize" => 1024,
135                              "set_cachesize" => [0, 32 * 1024, 0]
136         new = BDB::CIBtree.open newname, nil, 
137                                 BDB::CREATE | BDB::EXCL | BDB::TRUNCATE,
138                                 0600, "set_pagesize" => 1024,
139                                 "set_cachesize" => [0, 32 * 1024, 0]
140         old.each {|k,v|
141           new[k] = v
142         }
143         old.close
144         new.close
145         File.delete(f)
146       }
147       
148       # then scan for current DBTree files, and load them
149       Dir["#{@bot.botclass}/keywords/*"].each {|f|
150         next unless f =~ /\.kdb$/
151         hsh = DBTree.new @bot, f, true
152         key = File.basename(f).gsub(/\.kdb$/, "")
153         debug "keywords module: loading DBTree file #{f}, key #{key}"
154         @statickeywords[key] = hsh
155       }
156       
157       # then scan for non DB files, and convert/import them and delete
158       Dir["#{@bot.botclass}/keywords/*"].each {|f|
159         next if f =~ /\.kdb$/
160         next if f =~ /CVS$/
161         puts "auto converting keywords from #{f}"
162         key = File.basename(f)
163         unless @statickeywords.has_key?(key)
164           @statickeywords[key] = DBHash.new @bot, "#{f}.db", true
165         end
166         IO.foreach(f) {|line|
167           if(line =~ /^(.*?)\s*<?=(is|are)?=?>\s*(.*)$/)
168             lhs = $1
169             mhs = $2
170             rhs = $3
171             # support infobot style factfiles, by fixing them up here
172             rhs.gsub!(/\$who/, "<who>")
173             mhs = "is" unless mhs
174             rhs = Keyword.escape rhs
175             values = rhs.split("<=or=>")
176             @statickeywords[key][lhs] = Keyword.new(mhs, values).dump
177           end
178         }
179         File.delete(f)
180         @statickeywords[key].flush
181       }
182     end
183
184     # upgrade data files found in old rbot formats to current
185     def upgrade_data
186       if File.exist?("#{@bot.botclass}/keywords.db")
187         puts "upgrading old keywords (rbot 0.9.5 or prior) database format"
188         old = BDB::Hash.open "#{@bot.botclass}/keywords.db", nil, 
189                              "r+", 0600, "set_pagesize" => 1024,
190                              "set_cachesize" => [0, 32 * 1024, 0]
191         new = BDB::CIBtree.open "#{@bot.botclass}/keyword.db", nil, 
192                                 BDB::CREATE | BDB::EXCL | BDB::TRUNCATE,
193                                 0600, "set_pagesize" => 1024,
194                                 "set_cachesize" => [0, 32 * 1024, 0]
195         old.each {|k,v|
196           new[k] = v
197         }
198         old.close
199         new.close
200         File.delete("#{@bot.botclass}/keywords.db")
201       end
202     end
203
204     # save dynamic keywords to file
205     def save
206       @keywords.flush
207     end
208     def oldsave
209       File.open("#{@bot.botclass}/keywords.rbot", "w") do |file|
210         @keywords.each do |key, value|
211           file.puts "#{key}<=#{value.type}=>#{value.dump}"
212         end
213       end
214     end
215     
216     # lookup keyword +key+, return it or nil
217     def [](key)
218       return nil if key.nil?
219       debug "keywords module: looking up key #{key}"
220       if(@keywords.has_key?(key))
221         return Keyword.restore(@keywords[key])
222       else
223         # key name order for the lookup through these
224         @statickeywords.keys.sort.each {|k|
225           v = @statickeywords[k]
226           if v.has_key?(key)
227             return Keyword.restore(v[key])
228           end
229         }
230       end
231       return nil
232     end
233
234     # does +key+ exist as a keyword?
235     def has_key?(key)
236       if @keywords.has_key?(key) && Keyword.restore(@keywords[key]) != nil
237         return true
238       end
239       @statickeywords.each {|k,v|
240         if v.has_key?(key) && Keyword.restore(v[key]) != nil
241           return true
242         end
243       }
244       return false
245     end
246
247     # m::     PrivMessage containing message info
248     # key::   key being queried
249     # dunno:: optional, if true, reply "dunno" if +key+ not found
250     # 
251     # handle a message asking about a keyword
252     def keyword(m, key, dunno=true)
253       return if key.nil?
254        unless(kw = self[key])
255          m.reply @bot.lang.get("dunno") if (dunno)
256          return
257        end
258        response = kw.to_s
259        response.gsub!(/<who>/, m.sourcenick)
260        if(response =~ /^<reply>\s*(.*)/)
261          m.reply "#$1"
262        elsif(response =~ /^<action>\s*(.*)/)
263          @bot.action m.replyto, "#$1"
264        elsif(m.public? && response =~ /^<topic>\s*(.*)/)
265          topic = $1
266          @bot.topic m.target, topic
267        else
268          m.reply "#{key} #{kw.type} #{response}"
269        end
270     end
271
272     
273     # m::      PrivMessage containing message info
274     # target:: channel/nick to tell about the keyword
275     # key::    key being queried
276     # 
277     # handle a message asking the bot to tell someone about a keyword
278     def keyword_tell(m, target, key)
279       unless(kw = self[key])
280         @bot.say m.sourcenick, @bot.lang.get("dunno_about_X") % key
281         return
282       end
283       response = kw.to_s
284       response.gsub!(/<who>/, m.sourcenick)
285       if(response =~ /^<reply>\s*(.*)/)
286         @bot.say target, "#{m.sourcenick} wanted me to tell you: (#{key}) #$1"
287         m.reply "okay, I told #{target}: (#{key}) #$1"
288       elsif(response =~ /^<action>\s*(.*)/)
289         @bot.action target, "#$1 (#{m.sourcenick} wanted me to tell you)"
290         m.reply "okay, I told #{target}: * #$1"
291       else
292         @bot.say target, "#{m.sourcenick} wanted me to tell you that #{key} #{kw.type} #{response}"
293         m.reply "okay, I told #{target} that #{key} #{kw.type} #{response}"
294       end
295     end
296
297     # handle a message which alters a keyword
298     # like "foo is bar", or "no, foo is baz", or "foo is also qux"
299     def keyword_command(sourcenick, target, lhs, mhs, rhs, quiet=false)
300       debug "got keyword command #{lhs}, #{mhs}, #{rhs}"
301       overwrite = false
302       overwrite = true if(lhs.gsub!(/^no,\s*/, ""))
303       also = true if(rhs.gsub!(/^also\s+/, ""))
304       values = rhs.split(/\s+\|\s+/)
305       lhs = Keyword.unescape lhs
306       if(overwrite || also || !has_key?(lhs))
307         if(also && has_key?(lhs))
308           kw = self[lhs]
309           kw << values
310           @keywords[lhs] = kw.dump
311         else
312           @keywords[lhs] = Keyword.new(mhs, values).dump
313         end
314         @bot.okay target if !quiet
315       elsif(has_key?(lhs))
316         kw = self[lhs]
317         @bot.say target, "but #{lhs} #{kw.type} #{kw.desc}" if kw && !quiet
318       end
319     end
320
321     # return help string for Keywords with option topic +topic+
322     def help(topic="")
323       case topic
324         when "overview"
325           return "set: <keyword> is <definition>, overide: no, <keyword> is <definition>, add to definition: <keyword> is also <definition>, random responses: <keyword> is <definition> | <definition> [| ...], plurals: <keyword> are <definition>, escaping: \\is, \\are, \\|, specials: <reply>, <action>, <who>"
326         when "set"
327           return "set => <keyword> is <definition>"
328         when "plurals"
329           return "plurals => <keywords> are <definition>"
330         when "override"
331           return "overide => no, <keyword> is <definition>"
332         when "also"
333           return "also => <keyword> is also <definition>"
334         when "random"
335           return "random responses => <keyword> is <definition> | <definition> [| ...]"
336         when "get"
337           return "asking for keywords => (with addressing) \"<keyword>?\", (without addressing) \"'<keyword>\""
338         when "tell"
339           return "tell <nick> about <keyword> => if <keyword> is known, tell <nick>, via /msg, its definition"
340         when "forget"
341           return "forget <keyword> => forget fact <keyword>"
342         when "keywords"
343           return "keywords => show current keyword counts"
344         when "<reply>"
345           return "<reply> => normal response is \"<keyword> is <definition>\", but if <definition> begins with <reply>, the response will be \"<definition>\""
346         when "<action>"
347           return "<action> => makes keyword respnse \"/me <definition>\""
348         when "<who>"
349           return "<who> => replaced with questioner in reply"
350         when "<topic>"
351           return "<topic> => respond by setting the topic to the rest of the definition"
352         when "search"
353           return "keywords search [--all] [--full] <regexp> => search keywords for <regexp>. If --all is set, search static keywords too, if --full is set, search definitions too."
354         else
355           return "Keyword module (Fact learning and regurgitation) topics: overview, set, plurals, override, also, random, get, tell, forget, keywords, keywords search, <reply>, <action>, <who>, <topic>"
356       end
357     end
358
359     # privmsg handler
360     def privmsg(m)
361       return if m.replied?
362       if(m.address?)
363         if(!(m.message =~ /\\\?\s*$/) && m.message =~ /^(.*\S)\s*\?\s*$/)
364           keyword m, $1 if(@bot.auth.allow?("keyword", m.source, m.replyto))
365         elsif(m.message =~ /^(.*?)\s+(is|are)\s+(.*)$/)
366           keyword_command(m.sourcenick, m.replyto, $1, $2, $3) if(@bot.auth.allow?("keycmd", m.source, m.replyto))
367         elsif (m.message =~ /^tell\s+(\S+)\s+about\s+(.+)$/)
368           keyword_tell(m, $1, $2) if(@bot.auth.allow?("keyword", m.source, m.replyto))
369         elsif (m.message =~ /^forget\s+(.*)$/)
370           key = $1
371           if((@bot.auth.allow?("keycmd", m.source, m.replyto)) && @keywords.has_key?(key))
372             @keywords.delete(key)
373             @bot.okay m.replyto
374           end
375         elsif (m.message =~ /^keywords$/)
376           if(@bot.auth.allow?("keyword", m.source, m.replyto))
377             length = 0
378             @statickeywords.each {|k,v|
379               length += v.length
380             }
381             m.reply "There are currently #{@keywords.length} keywords, #{length} static facts defined."
382           end
383         elsif (m.message =~ /^keywords search\s+(.*)$/)
384           str = $1
385           all = false
386           all = true if str.gsub!(/--all\s+/, "")
387           full = false
388           full = true if str.gsub!(/--full\s+/, "")
389
390           re = Regexp.new(str, Regexp::IGNORECASE)
391           if(@bot.auth.allow?("keyword", m.source, m.replyto))
392             matches = Array.new
393             @keywords.each {|k,v|
394               kw = Keyword.restore(v)
395               if re.match(k) || (full && re.match(kw.desc))
396                 matches << [k,kw]
397               end
398             }
399             if all
400               @statickeywords.each {|k,v|
401                 v.each {|kk,vv|
402                   kw = Keyword.restore(vv)
403                   if re.match(kk) || (full && re.match(kw.desc))
404                     matches << [kk,kw]
405                   end
406                 }
407               }
408             end
409             if matches.length == 1
410               rkw = matches[0]
411               m.reply "#{rkw[0]} #{rkw[1].type} #{rkw[1].desc}"
412             elsif matches.length > 0
413               i = 0
414               matches.each {|rkw|
415                 m.reply "[#{i+1}/#{matches.length}] #{rkw[0]} #{rkw[1].type} #{rkw[1].desc}"
416                 i += 1
417                 break if i == 3
418               }
419             else
420               m.reply "no keywords match #{str}"
421             end
422           end
423         end
424       else
425         # in channel message, not to me
426         # TODO option to do if(m.message =~ /^(.*)$/, ie try any line as a
427         # keyword lookup.
428         if(m.message =~ /^'(.*)$/ || (!@bot.config["keyword.address"] && m.message =~ /^(.*\S)\s*\?\s*$/))
429           keyword m, $1, false if(@bot.auth.allow?("keyword", m.source))
430         elsif(@bot.config["keyword.listen"] == true && (m.message =~ /^(.*?)\s+(is|are)\s+(.*)$/))
431           # TODO MUCH more selective on what's allowed here
432           keyword_command(m.sourcenick, m.replyto, $1, $2, $3, true) if(@bot.auth.allow?("keycmd", m.source))
433         end
434       end
435     end
436   end
437 end