4 # :title: Factoids pluing
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
10 # Store (and retrieve) unstructured one-sentence factoids
12 class FactoidsPlugin < Plugin
16 @hash = hash.reject { |k, val| val.nil? or val.empty? rescue false }
17 raise ArgumentError, "no fact!" unless @hash[:fact]
18 if String === @hash[:when]
19 @hash[:when] = Time.parse @hash[:when]
24 show_meta = opts[:meta]
32 metadata << _("from %{who}" % @hash)
35 metadata << _("on %{when}" % @hash)
38 metadata << _("in %{where}" % @hash)
40 unless metadata.empty?
41 meta << _(" [%{data}]" % {:data => metadata.join(" ")})
51 @hash.send(:[]=,*args)
57 alias :to_hash :to_hsh
60 class FactoidList < ArrayOf
68 self.map { |f| f[:fact] }.index(fact)
84 # TODO default should be language-specific
85 Config.register Config::ArrayValue.new('factoids.trigger_pattern',
87 "(this|that|a|the|an|all|both)\\s+(.*)\\s+(is|are|has|have|does|do)\\s+.*:2",
88 "(this|that|a|the|an|all|both)\\s+(.*?)\\s+(is|are|has|have|does|do)\\s+.*:2",
89 "(.*)\\s+(is|are|has|have|does|do)\\s+.*",
90 "(.*?)\\s+(is|are|has|have|does|do)\\s+.*",
92 :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_triggers },
93 :desc => "A list of regular expressions matching factoids where keywords can be identified. append ':n' if the keyword is defined by the n-th group instead of the first. if the list is empty, any word will be considered a keyword")
94 Config.register Config::BooleanValue.new('factoids.address',
96 :desc => "Should the bot reply with relevant factoids only when addressed with a direct question? If not, the bot will attempt to lookup foo if someone says 'foo?' in channel")
97 Config.register Config::IntegerValue.new('factoids.search_results',
99 :desc => "How many factoids to display at a time")
105 @dir = File.join(@bot.botclass,"factoids")
106 @filename = "factoids.rbot"
107 @factoids = FactoidList.new
117 def read_factfile(name=@filename,dir=@dir)
118 fname = File.join(dir,name)
120 expf = File.expand_path(fname)
121 expd = File.expand_path(dir)
122 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
126 }) unless expf.index(expd) == 0
128 if File.exist?(fname)
129 raise ArgumentError, _("%{name} is not a file" % {
131 }) unless File.file?(fname)
132 factoids = File.readlines(fname)
133 return if factoids.empty?
134 firstline = factoids.shift
135 pattern = firstline.chomp.split(" | ")
136 if pattern.length == 1 and pattern.first != "fact"
137 factoids.unshift(firstline)
139 @factoids << Factoid.new( :fact => f.chomp )
142 pattern.map! { |p| p.intern }
143 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
145 ar = f.chomp.split(" | ", pattern.length)
146 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
150 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
159 return unless @changed
160 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
161 fname = File.join(@dir,@filename)
162 ar = ["when | who | where | fact"]
164 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
166 Utils.safe_save(fname) do |file|
172 def trigger_patterns_to_rx
173 return [] if @bot.config['factoids.trigger_pattern'].empty?
174 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
182 list << [/^#{s}$/iu, idx]
186 def parse_for_trigger(f, rx=nil)
188 regs = trigger_patterns_to_rx
195 regs.inject([]) { |list, a|
200 list << m[i].downcase
209 return unless @factoids
210 start_time = Time.now
211 rx = trigger_patterns_to_rx
212 triggers = @factoids.inject(Set.new) { |set, f|
213 found = parse_for_trigger(f, rx)
220 debug "Triggers done in #{Time.now - start_time}"
221 @triggers.replace(triggers)
224 def help(plugin, topic="")
225 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
229 factoid = Factoid.new(
230 :fact => params[:stuff].to_s,
232 :who => m.source.fullform,
233 :where => m.channel.to_s
235 if idx = @factoids.index(factoid)
236 m.reply _("I already know that %{factoid} [#%{idx}]" % {
244 fact(m, :index => @factoids.length.to_s)
245 parse_for_trigger(factoid)
249 def forget(m, params)
251 idx = params[:index].scan(/\d+/).first.to_i
252 total = @factoids.length
253 if idx <= 0 or idx > total
254 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
257 if factoid = @factoids.delete_at(idx-1)
258 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
261 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
264 factoid = params[:stuff].to_s
265 if @factoids.delete(factoid)
269 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
274 def short_fact(fact,index=nil,total=@factoids.length)
275 idx = index || @factoids.index(fact)+1
276 _("[%{idx}/%{total}] %{fact}" % {
279 :fact => fact.to_s(:meta => false)
283 def long_fact(fact,index=nil,total=@factoids.length)
284 idx = index || @factoids.index(fact)+1
285 _("fact #%{idx} of %{total}: %{fact}" % {
288 :fact => fact.to_s(:meta => true)
293 # When looking for words we separate them with
294 # arbitrary whitespace, not whatever they came with
295 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
296 return Regexp.new("\\b#{pre}\\b", true)
300 total = @factoids.length
301 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
302 m.reply _("I know %{total} facts" % { :total => total })
304 if params[:words].empty?
305 rx = Regexp.new(params[:rx].to_s, true)
307 rx = words2rx(params[:words])
309 known = @factoids.grep(rx)
312 reply << _("I know nothing about %{words}" % params)
314 max_facts = @bot.config['factoids.search_results']
317 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
320 :words => params[:words].to_s,
323 while known.length > max_facts
328 reply << short_fact(f)
331 m.reply reply.join(". "), :split_at => /\s+--\s+/
336 return if @bot.config['factoids.address'] and !m.address?
337 return if @factoids.empty?
338 return if @triggers.empty?
339 return unless m.message =~ /^(.*)\?\s*$/
340 query = $1.strip.downcase
341 if @triggers.include?(query)
342 facts(m, :words => query.split)
349 total = @factoids.length
351 idx = params[:index].scan(/\d+/).first.to_i
352 if idx <= 0 or idx > total
353 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
356 fact = @factoids[idx-1]
359 if params[:words].empty?
361 m.reply _("I know nothing")
366 rx = words2rx(params[:words])
367 known = @factoids.grep(rx)
369 m.reply _("I know nothing about %{words}" % params)
373 fact = known.pick_one
374 idx = @factoids.index(fact)+1
376 m.reply long_fact(fact, idx, total)
379 def edit_fact(m, params)
382 total = @factoids.length
383 idx = params[:index].scan(/\d+/).first.to_i
384 if idx <= 0 or idx > total
385 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
388 fact = @factoids[idx-1]
391 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
396 dstr = params[:when].to_s
398 fact[:when] = Time.parse(dstr, "")
401 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
405 fact[:where] = params[:where].to_s
409 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
418 def import(m, params)
419 fname = params[:filename].to_s
420 oldlen = @factoids.length
424 m.reply _("failed to import facts from %{fname}: %{err}" % {
429 m.reply _("%{len} facts loaded from %{fname}" % {
431 :len => @factoids.length - oldlen
438 plugin = FactoidsPlugin.new
440 plugin.default_auth('edit', false)
441 plugin.default_auth('import', false)
443 plugin.map 'learn that *stuff'
444 plugin.map 'forget that *stuff', :auth_path => 'edit'
445 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
446 plugin.map 'facts [about *words]'
447 plugin.map 'facts search *rx'
448 plugin.map 'fact [about *words]'
449 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
451 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
452 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
453 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
455 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'