]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - rbot/keywords.rb
rearrange repo for packaging
[user/henk/code/ruby/rbot.git] / 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     
85     # create a new Keywords instance, associated to bot +bot+
86     def initialize(bot)
87       @bot = bot
88       @statickeywords = Hash.new
89       upgrade_data
90       @keywords = DBTree.new bot, "keyword"
91
92       scan
93       
94       # import old format keywords into DBHash
95       if(File.exist?("#{@bot.botclass}/keywords.rbot"))
96         puts "auto importing old keywords.rbot"
97         IO.foreach("#{@bot.botclass}/keywords.rbot") do |line|
98           if(line =~ /^(.*?)\s*<=(is|are)?=?>\s*(.*)$/)
99             lhs = $1
100             mhs = $2
101             rhs = $3
102             mhs = "is" unless mhs
103             rhs = Keyword.escape rhs
104             values = rhs.split("<=or=>")
105             @keywords[lhs] = Keyword.new(mhs, values).dump
106           end
107         end
108         File.delete("#{@bot.botclass}/keywords.rbot")
109       end
110     end
111     
112     # drop static keywords and reload them from files, picking up any new
113     # keyword files that have been added
114     def rescan
115       @statickeywords = Hash.new
116       scan
117     end
118
119     # load static keywords from files, picking up any new keyword files that
120     # have been added
121     def scan
122       # first scan for old DBHash files, and convert them
123       Dir["#{@bot.botclass}/keywords/*"].each {|f|
124         next unless f =~ /\.db$/
125         puts "upgrading keyword db #{f} (rbot 0.9.5 or prior) database format"
126         newname = f.gsub(/\.db$/, ".kdb")
127         old = BDB::Hash.open f, nil, 
128                              "r+", 0600, "set_pagesize" => 1024,
129                              "set_cachesize" => [0, 32 * 1024, 0]
130         new = BDB::CIBtree.open newname, nil, 
131                                 BDB::CREATE | BDB::EXCL | BDB::TRUNCATE,
132                                 0600, "set_pagesize" => 1024,
133                                 "set_cachesize" => [0, 32 * 1024, 0]
134         old.each {|k,v|
135           new[k] = v
136         }
137         old.close
138         new.close
139         File.delete(f)
140       }
141       
142       # then scan for current DBTree files, and load them
143       Dir["#{@bot.botclass}/keywords/*"].each {|f|
144         next unless f =~ /\.kdb$/
145         hsh = DBTree.new @bot, f, true
146         key = File.basename(f).gsub(/\.kdb$/, "")
147         debug "keywords module: loading DBTree file #{f}, key #{key}"
148         @statickeywords[key] = hsh
149       }
150       
151       # then scan for non DB files, and convert/import them and delete
152       Dir["#{@bot.botclass}/keywords/*"].each {|f|
153         next if f =~ /\.kdb$/
154         next if f =~ /CVS$/
155         puts "auto converting keywords from #{f}"
156         key = File.basename(f)
157         unless @statickeywords.has_key?(key)
158           @statickeywords[key] = DBHash.new @bot, "#{f}.db", true
159         end
160         IO.foreach(f) {|line|
161           if(line =~ /^(.*?)\s*<?=(is|are)?=?>\s*(.*)$/)
162             lhs = $1
163             mhs = $2
164             rhs = $3
165             # support infobot style factfiles, by fixing them up here
166             rhs.gsub!(/\$who/, "<who>")
167             mhs = "is" unless mhs
168             rhs = Keyword.escape rhs
169             values = rhs.split("<=or=>")
170             @statickeywords[key][lhs] = Keyword.new(mhs, values).dump
171           end
172         }
173         File.delete(f)
174         @statickeywords[key].flush
175       }
176     end
177
178     # upgrade data files found in old rbot formats to current
179     def upgrade_data
180       if File.exist?("#{@bot.botclass}/keywords.db")
181         puts "upgrading old keywords (rbot 0.9.5 or prior) database format"
182         old = BDB::Hash.open "#{@bot.botclass}/keywords.db", nil, 
183                              "r+", 0600, "set_pagesize" => 1024,
184                              "set_cachesize" => [0, 32 * 1024, 0]
185         new = BDB::CIBtree.open "#{@bot.botclass}/keyword.db", nil, 
186                                 BDB::CREATE | BDB::EXCL | BDB::TRUNCATE,
187                                 0600, "set_pagesize" => 1024,
188                                 "set_cachesize" => [0, 32 * 1024, 0]
189         old.each {|k,v|
190           new[k] = v
191         }
192         old.close
193         new.close
194         File.delete("#{@bot.botclass}/keywords.db")
195       end
196     end
197
198     # save dynamic keywords to file
199     def save
200       @keywords.flush
201     end
202     def oldsave
203       File.open("#{@bot.botclass}/keywords.rbot", "w") do |file|
204         @keywords.each do |key, value|
205           file.puts "#{key}<=#{value.type}=>#{value.dump}"
206         end
207       end
208     end
209     
210     # lookup keyword +key+, return it or nil
211     def [](key)
212       debug "keywords module: looking up key #{key}"
213       if(@keywords.has_key?(key))
214         return Keyword.restore(@keywords[key])
215       else
216         # key name order for the lookup through these
217         @statickeywords.keys.sort.each {|k|
218           v = @statickeywords[k]
219           if v.has_key?(key)
220             return Keyword.restore(v[key])
221           end
222         }
223       end
224       return nil
225     end
226
227     # does +key+ exist as a keyword?
228     def has_key?(key)
229       if @keywords.has_key?(key) && Keyword.restore(@keywords[key]) != nil
230         return true
231       end
232       @statickeywords.each {|k,v|
233         if v.has_key?(key) && Keyword.restore(v[key]) != nil
234           return true
235         end
236       }
237       return false
238     end
239
240     # m::     PrivMessage containing message info
241     # key::   key being queried
242     # dunno:: optional, if true, reply "dunno" if +key+ not found
243     # 
244     # handle a message asking about a keyword
245     def keyword(m, key, dunno=true)
246        unless(kw = self[key])
247          m.reply @bot.lang.get("dunno") if (dunno)
248          return
249        end
250        response = kw.to_s
251        response.gsub!(/<who>/, m.sourcenick)
252        if(response =~ /^<reply>\s*(.*)/)
253          m.reply "#$1"
254        elsif(response =~ /^<action>\s*(.*)/)
255          @bot.action m.replyto, "#$1"
256        elsif(m.public? && response =~ /^<topic>\s*(.*)/)
257          topic = $1
258          @bot.topic m.target, topic
259        else
260          m.reply "#{key} #{kw.type} #{response}"
261        end
262     end
263
264     
265     # m::      PrivMessage containing message info
266     # target:: channel/nick to tell about the keyword
267     # key::    key being queried
268     # 
269     # handle a message asking the bot to tell someone about a keyword
270     def keyword_tell(m, target, key)
271       unless(kw = self[key])
272         @bot.say m.sourcenick, @bot.lang.get("dunno_about_X") % key
273         return
274       end
275       response = kw.to_s
276       response.gsub!(/<who>/, m.sourcenick)
277       if(response =~ /^<reply>\s*(.*)/)
278         @bot.say target, "#{m.sourcenick} wanted me to tell you: (#{key}) #$1"
279         m.reply "okay, I told #{target}: (#{key}) #$1"
280       elsif(response =~ /^<action>\s*(.*)/)
281         @bot.action target, "#$1 (#{m.sourcenick} wanted me to tell you)"
282         m.reply "okay, I told #{target}: * #$1"
283       else
284         @bot.say target, "#{m.sourcenick} wanted me to tell you that #{key} #{kw.type} #{response}"
285         m.reply "okay, I told #{target} that #{key} #{kw.type} #{response}"
286       end
287     end
288
289     # handle a message which alters a keyword
290     # like "foo is bar", or "no, foo is baz", or "foo is also qux"
291     def keyword_command(sourcenick, target, lhs, mhs, rhs, quiet=false)
292       debug "got keyword command #{lhs}, #{mhs}, #{rhs}"
293       overwrite = false
294       overwrite = true if(lhs.gsub!(/^no,\s*/, ""))
295       also = true if(rhs.gsub!(/^also\s+/, ""))
296       values = rhs.split(/\s+\|\s+/)
297       lhs = Keyword.unescape lhs
298       if(overwrite || also || !has_key?(lhs))
299         if(also && has_key?(lhs))
300           kw = self[lhs]
301           kw << values
302           @keywords[lhs] = kw.dump
303         else
304           @keywords[lhs] = Keyword.new(mhs, values).dump
305         end
306         @bot.okay target if !quiet
307       elsif(has_key?(lhs))
308         kw = self[lhs]
309         @bot.say target, "but #{lhs} #{kw.type} #{kw.desc}" if kw && !quiet
310       end
311     end
312
313     # return help string for Keywords with option topic +topic+
314     def help(topic="")
315       case topic
316         when "overview"
317           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>"
318         when "set"
319           return "set => <keyword> is <definition>"
320         when "plurals"
321           return "plurals => <keywords> are <definition>"
322         when "override"
323           return "overide => no, <keyword> is <definition>"
324         when "also"
325           return "also => <keyword> is also <definition>"
326         when "random"
327           return "random responses => <keyword> is <definition> | <definition> [| ...]"
328         when "get"
329           return "asking for keywords => (with addressing) \"<keyword>?\", (without addressing) \"'<keyword>\""
330         when "tell"
331           return "tell <nick> about <keyword> => if <keyword> is known, tell <nick>, via /msg, its definition"
332         when "forget"
333           return "forget <keyword> => forget fact <keyword>"
334         when "keywords"
335           return "keywords => show current keyword counts"
336         when "<reply>"
337           return "<reply> => normal response is \"<keyword> is <definition>\", but if <definition> begins with <reply>, the response will be \"<definition>\""
338         when "<action>"
339           return "<action> => makes keyword respnse \"/me <definition>\""
340         when "<who>"
341           return "<who> => replaced with questioner in reply"
342         when "<topic>"
343           return "<topic> => respond by setting the topic to the rest of the definition"
344         when "search"
345           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."
346         else
347           return "Keyword module (Fact learning and regurgitation) topics: overview, set, plurals, override, also, random, get, tell, forget, keywords, keywords search, <reply>, <action>, <who>, <topic>"
348       end
349     end
350
351     # privmsg handler
352     def privmsg(m)
353       return if m.replied?
354       if(m.address?)
355         if(!(m.message =~ /\\\?\s*$/) && m.message =~ /^(.*\S)\s*\?\s*$/)
356           keyword m, $1 if(@bot.auth.allow?("keyword", m.source, m.replyto))
357         elsif(m.message =~ /^(.*?)\s+(is|are)\s+(.*)$/)
358           keyword_command(m.sourcenick, m.replyto, $1, $2, $3) if(@bot.auth.allow?("keycmd", m.source, m.replyto))
359         elsif (m.message =~ /^tell\s+(\S+)\s+about\s+(.+)$/)
360           keyword_tell(m, $1, $2) if(@bot.auth.allow?("keyword", m.source, m.replyto))
361         elsif (m.message =~ /^forget\s+(.*)$/)
362           key = $1
363           if((@bot.auth.allow?("keycmd", m.source, m.replyto)) && @keywords.has_key?(key))
364             @keywords.delete(key)
365             @bot.okay m.replyto
366           end
367         elsif (m.message =~ /^keywords$/)
368           if(@bot.auth.allow?("keyword", m.source, m.replyto))
369             length = 0
370             @statickeywords.each {|k,v|
371               length += v.length
372             }
373             m.reply "There are currently #{@keywords.length} keywords, #{length} static facts defined."
374           end
375         elsif (m.message =~ /^keywords search\s+(.*)$/)
376           str = $1
377           all = false
378           all = true if str.gsub!(/--all\s+/, "")
379           full = false
380           full = true if str.gsub!(/--full\s+/, "")
381
382           re = Regexp.new(str, Regexp::IGNORECASE)
383           if(@bot.auth.allow?("keyword", m.source, m.replyto))
384             matches = Array.new
385             @keywords.each {|k,v|
386               kw = Keyword.restore(v)
387               if re.match(k) || (full && re.match(kw.desc))
388                 matches << [k,kw]
389               end
390             }
391             if all
392               @statickeywords.each {|k,v|
393                 v.each {|kk,vv|
394                   kw = Keyword.restore(vv)
395                   if re.match(kk) || (full && re.match(kw.desc))
396                     matches << [kk,kw]
397                   end
398                 }
399               }
400             end
401             if matches.length == 1
402               rkw = matches[0]
403               m.reply "#{rkw[0]} #{rkw[1].type} #{rkw[1].desc}"
404             elsif matches.length > 0
405               i = 0
406               matches.each {|rkw|
407                 m.reply "[#{i+1}/#{matches.length}] #{rkw[0]} #{rkw[1].type} #{rkw[1].desc}"
408                 i += 1
409                 break if i == 3
410               }
411             else
412               m.reply "no keywords match #{str}"
413             end
414           end
415         end
416       else
417         # in channel message, not to me
418         if(m.message =~ /^'(.*)$/ || (!@bot.config["keyword.noaddress"] && m.message =~ /^(.*\S)\s*\?\s*$/))
419           keyword m, $1, false if(@bot.auth.allow?("keyword", m.source))
420         elsif(@bot.config["keyword.listen"] == true && (m.message =~ /^(.*?)\s+(is|are)\s+(.*)$/))
421           # TODO MUCH more selective on what's allowed here
422           keyword_command(m.sourcenick, m.replyto, $1, $2, $3, true) if(@bot.auth.allow?("keycmd", m.source))
423         end
424       end
425     end
426   end
427 end