5 # Encapsulates a keyword ("foo is bar" is a keyword called foo, with type
6 # is, and has a single value of bar).
7 # Keywords can have multiple values, to_s() will choose one at random
10 # type of keyword (e.g. "is" or "are")
13 # type:: type of keyword (e.g "is" or "are")
14 # values:: array of values
16 # create a keyword of type +type+ with values +values+
17 def initialize(type, values)
22 # pick a random value for this keyword and return it
24 if(@values.length > 1)
25 Keyword.unescape(@values[rand(@values.length)])
27 Keyword.unescape(@values[0])
31 # return an array of all the possible values
35 debug "key #{key}, value #{val}"
36 vals = val.split(" or ")
38 ar << "%s %s %s" % [key, @type, v]
44 # describe the keyword (show all values without interpolation)
49 # return the keyword in a stringified form ready for storage
51 @type + "/" + Keyword.unescape(@values.join("<=or=>"))
54 # deserialize the stringified form to an object
55 def Keyword.restore(str)
56 if str =~ /^(\S+?)\/(.*)$/
58 vals = $2.split("<=or=>")
59 return Keyword.new(type, vals)
64 # values:: array of values to add
65 # add values to a keyword
67 if(@values.length > 1 || values.length > 1)
72 @values[0] += " or " + values[0]
76 # unescape special words/characters in a keyword
77 def Keyword.unescape(str)
78 str.gsub(/\\\|/, "|").gsub(/ \\is /, " is ").gsub(/ \\are /, " are ").gsub(/\\\?(\s*)$/, "?\1")
81 # escape special words/characters in a keyword
82 def Keyword.escape(str)
83 str.gsub(/\|/, "\\|").gsub(/ is /, " \\is ").gsub(/ are /, " \\are ").gsub(/\?(\s*)$/, "\\?\1")
89 # Handles all that stuff like "bot: foo is bar", "bot: foo?"
91 # Fallback after core and auth have had a look at a message and refused to
92 # handle it, checks for a keyword command or lookup, otherwise the message
93 # is delegated to plugins
94 class Keywords < Plugin
95 Config.register Config::BooleanValue.new('keyword.listen',
97 :desc => "Should the bot listen to all chat and attempt to automatically detect keywords? (e.g. by spotting someone say 'foo is bar')")
98 Config.register Config::BooleanValue.new('keyword.address',
100 :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")
101 Config.register Config::IntegerValue.new('keyword.search_results',
103 :desc => "How many search results to display at a time")
104 Config.register Config::ArrayValue.new('keyword.ignore_words',
105 :default => ["how", "that", "these", "they", "this", "what", "when", "where", "who", "why", "you"],
106 :desc => "A list of words that the bot should passively ignore.")
108 # create a new KeywordPlugin instance, associated to bot +bot+
112 @statickeywords = Hash.new
113 @keywords = @registry.sub_registry('keywords') # DBTree.new bot, "keyword"
118 # import old format keywords into DBHash
119 if(File.exist?("#{@bot.botclass}/keywords.rbot"))
120 log "auto importing old keywords.rbot"
121 IO.foreach("#{@bot.botclass}/keywords.rbot") do |line|
122 if(line =~ /^(.*?)\s*<=(is|are)?=?>\s*(.*)$/)
126 mhs = "is" unless mhs
127 rhs = Keyword.escape rhs
128 values = rhs.split("<=or=>")
129 @keywords[lhs] = Keyword.new(mhs, values).dump
132 File.rename("#{@bot.botclass}/keywords.rbot", "#{@bot.botclass}/keywords.rbot.old")
136 # load static keywords from files, picking up any new keyword files that
139 # first scan for old DBHash files, and convert them
140 Dir["#{@bot.botclass}/keywords/*"].each {|f|
141 next unless f =~ /\.db$/
142 log "upgrading keyword db #{f} (rbot 0.9.5 or prior) database format"
143 newname = f.gsub(/\.db$/, ".kdb")
144 old = BDB::Hash.open f, nil,
146 new = BDB::CIBtree.open(newname, nil,
147 BDB::CREATE | BDB::EXCL,
157 # then scan for current DBTree files, and load them
158 Dir["#{@bot.botclass}/keywords/*"].each {|f|
159 next unless f =~ /\.kdb$/
160 hsh = DBTree.new @bot, f, true
161 key = File.basename(f).gsub(/\.kdb$/, "")
162 debug "keywords module: loading DBTree file #{f}, key #{key}"
163 @statickeywords[key] = hsh
166 # then scan for non DB files, and convert/import them and delete
167 Dir["#{@bot.botclass}/keywords/*"].each {|f|
168 next if f =~ /\.kdb$/
170 log "auto converting keywords from #{f}"
171 key = File.basename(f)
172 unless @statickeywords.has_key?(key)
173 @statickeywords[key] = DBHash.new @bot, "#{f}.db", true
175 IO.foreach(f) {|line|
176 if(line =~ /^(.*?)\s*<?=(is|are)?=?>\s*(.*)$/)
180 # support infobot style factfiles, by fixing them up here
181 rhs.gsub!(/\$who/, "<who>")
182 mhs = "is" unless mhs
183 rhs = Keyword.escape rhs
184 values = rhs.split("<=or=>")
185 @statickeywords[key][lhs] = Keyword.new(mhs, values).dump
189 @statickeywords[key].flush
193 # upgrade data files found in old rbot formats to current
195 if File.exist?("#{@bot.botclass}/keywords.db")
196 log "upgrading old keywords (rbot 0.9.5 or prior) database format"
197 old = BDB::Hash.open "#{@bot.botclass}/keywords.db", nil,
204 File.rename("#{@bot.botclass}/keywords.db", "#{@bot.botclass}/keywords.db.old")
207 if File.exist?("#{@bot.botclass}/keyword.db")
208 log "upgrading old keywords (rbot 0.9.9 or prior) database format"
209 old = BDB::CIBtree.open "#{@bot.botclass}/keyword.db", nil,
216 File.rename("#{@bot.botclass}/keyword.db", "#{@bot.botclass}/keyword.db.old")
220 # save dynamic keywords to file
226 File.open("#{@bot.botclass}/keywords.rbot", "w") do |file|
227 @keywords.each do |key, value|
228 file.puts "#{key}<=#{value.type}=>#{value.dump}"
233 # lookup keyword +key+, return it or nil
235 return nil if key.nil?
236 debug "keywords module: looking up key #{key}"
237 if(@keywords.has_key?(key))
238 return Keyword.restore(@keywords[key])
240 # key name order for the lookup through these
241 @statickeywords.keys.sort.each {|k|
242 v = @statickeywords[k]
244 return Keyword.restore(v[key])
251 # does +key+ exist as a keyword?
253 if @keywords.has_key?(key) && Keyword.restore(@keywords[key]) != nil
256 @statickeywords.each {|k,v|
257 if v.has_key?(key) && Keyword.restore(v[key]) != nil
264 # m:: PrivMessage containing message info
265 # key:: key being queried
266 # quiet:: optional, if false, complain if +key+ is not found
268 # handle a message asking about a keyword
269 def keyword_lookup(m, key, quiet = false)
271 unless(kw = self[key])
272 m.reply "sorry, I don't know about \"#{key}\"" unless quiet
277 response.gsub!(/<who>/, m.sourcenick)
279 if(response =~ /^<reply>\s*(.*)/)
281 elsif(response =~ /^<action>\s*(.*)/)
283 elsif(m.public? && response =~ /^<topic>\s*(.*)/)
284 @bot.topic m.target, $1
286 m.reply "#{key} #{kw.type} #{response}"
291 # handle a message which alters a keyword
292 # like "foo is bar" or "foo is also qux"
293 def keyword_command(m, lhs, mhs, rhs, quiet = false)
294 debug "got keyword command #{lhs}, #{mhs}, #{rhs}"
295 return if lhs.strip.empty?
298 overwrite = true if(lhs.gsub!(/^no,\s*/, ""))
300 also = true if(rhs.gsub!(/^also\s+/, ""))
302 values = rhs.split(/\s+\|\s+/)
303 lhs = Keyword.unescape lhs
305 if(overwrite || also || !has_key?(lhs))
306 if(also && has_key?(lhs))
309 @keywords[lhs] = kw.dump
311 @keywords[lhs] = Keyword.new(mhs, values).dump
316 m.reply "but #{lhs} #{kw.type} #{kw.desc}" if kw && !quiet
320 # return help string for Keywords with option topic +topic+
321 def help(plugin, topic = '')
326 'keyword [lookup] <keyword> => look up the definition for a keyword; writing "lookup" is optional'
328 'keyword set <keyword> is/are <definition> => define a keyword, definition can contain "|" to separate multiple randomly chosen replies'
330 'keyword forget <keyword> => forget a keyword'
332 'keyword tell <nick> about <keyword> => tell somebody about a keyword'
334 'keyword search [--all] [--full] <pattern> => search keywords for <pattern>, which can be a regular expression. If --all is set, search static keywords too, if --full is set, search definitions too.'
336 'when the config option "keyword.listen" is set to false, rbot will try to extract keyword definitions from regular channel messages'
338 'when the config option "keyword.address" is set to true, rbot will try to answer channel questions of the form "<keyword>?"'
340 '<reply> => normal response is "<keyword> is <definition>", but if <definition> begins with <reply>, the response will be "<definition>"'
342 '<action> => makes keyword respond with "/me <definition>"'
344 '<who> => replaced with questioner in reply'
346 '<topic> => respond by setting the topic to the rest of the definition'
348 'keyword module (fact learning and regurgitation) topics: lookup, set, forget, tell, search, listen, address, <reply>, <action>, <who>, <topic>'
351 'forget <keyword> => forget a keyword'
353 'tell <nick> about <keyword> => tell somebody about a keyword'
355 'learn that <keyword> is/are <definition> => define a keyword, definition can contain "|" to separate multiple randomly chosen replies'
357 'keyword module (fact learning and regurgitation) topics: lookup, set, forget, tell, search, listen, address, <reply>, <action>, <who>, <topic>'
361 # handle a message asking the bot to tell someone about a keyword
362 def keyword_tell(m, target, key)
363 unless(kw = self[key])
364 m.reply @bot.lang.get("dunno_about_X") % key
367 if target == @bot.nick
368 m.reply "very funny, trying to make me tell something to myself"
373 response.gsub!(/<who>/, m.sourcenick)
374 if(response =~ /^<reply>\s*(.*)/)
375 @bot.say target, "#{m.sourcenick} wanted me to tell you: (#{key}) #$1"
376 m.reply "okay, I told #{target}: (#{key}) #$1"
377 elsif(response =~ /^<action>\s*(.*)/)
378 @bot.action target, "#$1 (#{m.sourcenick} wanted me to tell you)"
379 m.reply "okay, I told #{target}: * #$1"
381 @bot.say target, "#{m.sourcenick} wanted me to tell you that #{key} #{kw.type} #{response}"
382 m.reply "okay, I told #{target} that #{key} #{kw.type} #{response}"
386 # return the number of known keywords
389 @statickeywords.each {|k,v|
392 m.reply "There are currently #{@keywords.length} keywords, #{length} static facts defined."
395 # search for keywords, optionally also the definition and the static keywords
396 def keyword_search(m, key, full = false, all = false, from = 1)
398 if key =~ /^\/(.+)\/$/
399 re = Regexp.new($1, Regexp::IGNORECASE)
401 re = Regexp.new(Regexp.escape(key), Regexp::IGNORECASE)
405 @keywords.each {|k,v|
406 kw = Keyword.restore(v)
407 if re.match(k) || (full && re.match(kw.desc))
412 @statickeywords.each {|k,v|
414 kw = Keyword.restore(vv)
415 if re.match(kk) || (full && re.match(kw.desc))
422 if matches.length == 1
424 m.reply "#{rkw[0]} #{rkw[1].type} #{rkw[1].desc}"
425 elsif matches.length > 0
426 if from > matches.length
427 m.reply "#{matches.length} found, can't tell you about #{from}"
432 m.reply "[#{i}/#{matches.length}] #{rkw[0]} #{rkw[1].type} #{rkw[1].desc}" if i >= from
434 break if i == from+@bot.config['keyword.search_results']
437 m.reply "no keywords match #{key}"
439 rescue RegexpError => e
440 m.reply "no keywords match #{key}: #{e}"
443 m.reply "no keywords match #{key}: an error occurred"
447 # forget one of the dynamic keywords
448 def keyword_forget(m, key)
449 if @keywords.delete(key)
452 m.reply _("couldn't find keyword %{key}" % { :key => key })
456 # low-level keyword wipe command for when forget doesn't work
457 def keyword_wipe(m, key)
458 reg = @keywords.registry
459 reg.env.begin(reg) { |t, b|
461 (k == key) && (m.reply "wiping keyword #{key} with stored value #{Marshal.restore(v)}")
468 # export keywords to factoids file
469 def keyword_factoids_export
474 @keywords.each { |k, val|
476 kw = Keyword.restore(val)
477 ar |= kw.to_factoids(k)
480 # TODO check factoids config
481 # also TODO: runtime export
482 dir = File.join(@bot.botclass,"factoids")
483 fname = File.join(dir,"keyword_factoids.rbot")
485 Dir.mkdir(dir) unless FileTest.directory?(dir)
486 Utils.safe_save(fname) do |file|
498 keyword_factoids_export
501 m.reply _("failed to export keywords as factoids (%{err})" % {:err => $!})
503 when /^set\s+(.+?)\s+(is|are)\s+(.+)$/
504 keyword_command(m, $1, $2, $3) if @bot.auth.allow?('keycmd', m.source, m.replyto)
505 when /^forget\s+(.+)$/
506 keyword_forget(m, $1) if @bot.auth.allow?('keycmd', m.source, m.replyto)
507 when /^wipe\s(.+)$/ # note that only one space is stripped, allowing removal of space-prefixed keywords
508 keyword_wipe(m, $1) if @bot.auth.allow?('keycmd', m.source, m.replyto)
509 when /^lookup\s+(.+)$/
510 keyword_lookup(m, $1) if @bot.auth.allow?('keyword', m.source, m.replyto)
512 keyword_stats(m) if @bot.auth.allow?('keyword', m.source, m.replyto)
513 when /^search\s+(.+)$/
515 full = key.sub!('--full ', '')
516 all = key.sub!('--all ', '')
517 if key.sub!(/--from (\d+) /, '')
522 from = 1 unless from > 0
523 keyword_search(m, key, full, all, from) if @bot.auth.allow?('keyword', m.source, m.replyto)
524 when /^tell\s+(\S+)\s+about\s+(.+)$/
525 keyword_tell(m, $1, $2) if @bot.auth.allow?('keyword', m.source, m.replyto)
527 keyword_lookup(m, m.params) if @bot.auth.allow?('keyword', m.source, m.replyto)
530 keyword_forget(m, m.params) if @bot.auth.allow?('keycmd', m.source, m.replyto)
532 if m.params =~ /(\S+)\s+about\s+(.+)$/
533 keyword_tell(m, $1, $2) if @bot.auth.allow?('keyword', m.source, m.replyto)
535 m.reply "wrong 'tell' syntax"
538 if m.params =~ /^that\s+(.+?)\s+(is|are)\s+(.+)$/
539 keyword_command(m, $1, $2, $3) if @bot.auth.allow?('keycmd', m.source, m.replyto)
541 m.reply "wrong 'learn' syntax"
547 # TODO option to do if(m.message =~ /^(.*)$/, ie try any line as a
549 if m.message =~ /^(.*\S)\s*\?\s*$/ and (m.address? or not @bot.config["keyword.address"])
550 keyword_lookup m, $1, true if !ignored_word?($1) && @bot.auth.allow?("keyword", m.source)
551 elsif @bot.config["keyword.listen"] && (m.message =~ /^(.*?)\s+(is|are)\s+(.*)$/)
552 # TODO MUCH more selective on what's allowed here
553 keyword_command m, $1, $2, $3, true if !ignored_word?($1) && @bot.auth.allow?("keycmd", m.source)
558 plugin = Keywords.new
559 plugin.register 'keyword'
560 plugin.register 'forget' rescue nil
561 plugin.register 'tell' rescue nil
562 plugin.register 'learn' rescue nil