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