factoids plugin: 'facts about' searches whole words, 'facts search' uses regular...
[rbot] / data / rbot / plugins / factoids.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Factoids pluing
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
8 # License:: GPLv2
9 #
10 # Store (and retrieve) unstructured one-sentence factoids
11
12 class FactoidsPlugin < Plugin
13
14   class Factoid
15     def initialize(hash)
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]
20       end
21     end
22
23     def to_s(opts={})
24       show_meta = opts[:meta]
25       fact = @hash[:fact]
26       if !show_meta
27         return fact
28       end
29       meta = ""
30       metadata = []
31       if @hash[:who]
32         metadata << _("from %{who}" % @hash)
33       end
34       if @hash[:when]
35         metadata << _("on %{when}" % @hash)
36       end
37       if @hash[:where]
38         metadata << _("in %{where}" % @hash)
39       end
40       unless metadata.empty?
41         meta << _(" [%{data}]" % {:data => metadata.join(" ")})
42       end
43       return fact+meta
44     end
45
46     def [](*args)
47       @hash[*args]
48     end
49
50     def []=(*args)
51       @hash.send(:[]=,*args)
52     end
53
54     def to_hsh
55       return @hash
56     end
57     alias :to_hash :to_hsh
58   end
59
60   class FactoidList < ArrayOf
61     def initialize(ar=[])
62       super(Factoid, ar)
63     end
64
65     def index(f)
66       fact = f.to_s
67       return if fact.empty?
68       self.map { |f| f[:fact] }.index(fact)
69     end
70
71     def delete(f)
72       idx = index(f)
73       return unless idx
74       self.delete_at(idx)
75     end
76
77     def grep(x)
78       self.find_all { |f|
79         x === f[:fact]
80       }
81     end
82   end
83
84   # TODO default should be language-specific
85   Config.register Config::ArrayValue.new('factoids.trigger_pattern',
86     :default => [
87       "(this|that|a|the|an|all|both)\\s+(.*)\\s+(is|are)\\s+.*:2",
88       "(this|that|a|the|an|all|both)\\s+(.*?)\\s+(is|are)\\s+.*:2",
89       "(.*)\\s+(is|are)\\s+.*",
90       "(.*?)\\s+(is|are)\\s+.*",
91     ],
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',
95     :default => true,
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',
98     :default => 5,
99     :desc => "How many factoids to display at a time")
100
101   def initialize
102     super
103
104     # TODO config
105     @dir = File.join(@bot.botclass,"factoids")
106     @filename = "factoids.rbot"
107     @factoids = FactoidList.new
108     @triggers = Set.new
109     begin
110       read_factfile
111     rescue
112       debug $!
113     end
114     @changed = false
115   end
116
117   def read_factfile(name=@filename,dir=@dir)
118     fname = File.join(dir,name)
119
120     expf = File.expand_path(fname)
121     expd = File.expand_path(dir)
122     raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
123       :name => name,
124       :fname => expf,
125       :dir => dir
126     }) unless expf.index(expd) == 0
127
128     if File.exist?(fname)
129       raise ArgumentError, _("%{name} is not a file" % {
130         :name => name
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)
138         factoids.each { |f|
139           @factoids << Factoid.new( :fact => f.chomp )
140         }
141       else
142         pattern.map! { |p| p.intern }
143         raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
144         factoids.each { |f|
145           ar = f.chomp.split(" | ", pattern.length)
146           @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
147         }
148       end
149     else
150       raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
151         :name => name,
152         :fname => fname
153       })
154     end
155     reset_triggers
156   end
157
158   def save
159     return unless @changed
160     Dir.mkdir(@dir) unless FileTest.directory?(@dir)
161     fname = File.join(@dir,@filename)
162     ar = ["when | who | where | fact"]
163     @factoids.each { |f|
164       ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
165     }
166     Utils.safe_save(fname) do |file|
167       file.puts ar
168     end
169     @changed = false
170   end
171
172   def trigger_patterns_to_rx
173     return [] if @bot.config['factoids.trigger_pattern'].empty?
174     @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
175       s = str.dup
176       if s =~ /:(\d+)$/
177         idx = $1.to_i
178         s.sub!(/:\d+$/,'')
179       else
180         idx = 1
181       end
182       list << [/^#{s}$/iu, idx]
183     }
184   end
185
186   def parse_for_trigger(f, rx=nil)
187     if !rx
188       regs = trigger_patterns_to_rx
189     else
190       regs = rx
191     end
192     if regs.empty?
193       f.to_s.scan(/\w+/u)
194     else
195       regs.inject([]) { |list, a|
196         r = a.first
197         i = a.last
198         m = r.match(f.to_s)
199         if m
200           list << m[i].downcase
201         else
202           list
203         end
204       }
205     end
206   end
207
208   def reset_triggers
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)
214       if found.empty?
215         set
216       else
217         set | found
218       end
219     }
220     debug "Triggers done in #{Time.now - start_time}"
221     @triggers.replace(triggers)
222   end
223
224   def help(plugin, topic="")
225     _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
226   end
227
228   def learn(m, params)
229     factoid = Factoid.new(
230       :fact => params[:stuff].to_s,
231       :when => Time.now,
232       :who => m.source.fullform,
233       :where => m.channel.to_s
234     )
235     if idx = @factoids.index(factoid)
236       m.reply _("I already know that %{factoid} [#%{idx}]" % {
237         :factoid => factoid,
238         :idx => idx
239       })
240     else
241       @factoids << factoid
242       @changed = true
243       m.okay
244       fact(m, :index => @factoids.length.to_s)
245       parse_for_trigger(factoid)
246     end
247   end
248
249   def forget(m, params)
250     if params[:index]
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 })
255         return
256       end
257       if factoid = @factoids.delete_at(idx-1)
258         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
259         @changed = true
260       else
261         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
262       end
263     else
264       factoid = params[:stuff].to_s
265       if @factoids.delete(factoid)
266         @changed = true
267         m.okay
268       else
269         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
270       end
271     end
272   end
273
274   def long_fact(fact,index=nil,total=@factoids.length)
275     idx = index || @factoids.index(fact)+1
276     _("fact #%{idx} of %{total}: %{fact}" % {
277       :idx => idx,
278       :total => total,
279       :fact => fact.to_s(:meta => true)
280     })
281   end
282
283   def words2rx(words)
284     # When looking for words we separate them with
285     # arbitrary whitespace, not whatever they came with
286     pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
287     return Regexp.new("\\b#{pre}\\b", true)
288   end
289
290   def facts(m, params)
291     total = @factoids.length
292     if params[:words].empty? and params[:rx].empty?
293       m.reply _("I know %{total} facts" % { :total => total })
294     else
295       if params[:words].empty?
296         rx = Regexp.new(params[:rx].to_s, true)
297       else
298         rx = words2rx(params[:words])
299       end
300       known = @factoids.grep(rx)
301       reply = []
302       if known.empty?
303         reply << _("I know nothing about %{words}" % params)
304       else
305         max_facts = @bot.config['factoids.search_results']
306         len = known.length
307         if len > max_facts
308           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
309             :len => len,
310             :total => total,
311             :words => params[:words].to_s,
312             :max => max_facts
313           })
314           while known.length > max_facts
315             known.delete_one
316           end
317         end
318         known.each { |f|
319           reply << long_fact(f)
320         }
321       end
322       m.reply reply.join(" -- ")
323     end
324   end
325
326   def unreplied(m)
327     return if @bot.config['factoids.address'] and !m.address?
328     return if @factoids.empty?
329     return if @triggers.empty?
330     return unless m.message =~ /^(.*)\?\s*$/
331     query = $1.strip.downcase
332     if @triggers.include?(query)
333       facts(m, :words => query.split)
334     end
335   end
336
337   def fact(m, params)
338     fact = nil
339     idx = 0
340     total = @factoids.length
341     if params[:index]
342       idx = params[:index].scan(/\d+/).first.to_i
343       if idx <= 0 or idx > total
344         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
345         return
346       end
347       fact = @factoids[idx-1]
348     else
349       known = nil
350       if params[:words].empty?
351         if @factoids.empty?
352           m.reply _("I know nothing")
353           return
354         end
355         known = @factoids
356       else
357         rx = words2rx(params[:words])
358         known = @factoids.grep(rx)
359         if known.empty?
360           m.reply _("I know nothing about %{words}" % params)
361           return
362         end
363       end
364       fact = known.pick_one
365       idx = @factoids.index(fact)+1
366     end
367     m.reply long_fact(fact, idx, total)
368   end
369
370   def edit_fact(m, params)
371     fact = nil
372     idx = 0
373     total = @factoids.length
374     idx = params[:index].scan(/\d+/).first.to_i
375     if idx <= 0 or idx > total
376       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
377       return
378     end
379     fact = @factoids[idx-1]
380     begin
381       if params[:who]
382         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
383         fact[:who] = who
384         @changed = true
385       end
386       if params[:when]
387         dstr = params[:when].to_s
388         begin
389           fact[:when] = Time.parse(dstr, "")
390           @changed = true
391         rescue
392           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
393         end
394       end
395       if params[:where]
396         fact[:where] = params[:where].to_s
397         @changed = true
398       end
399     rescue Exception
400       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
401         :fact => fact,
402         :err => $!
403       })
404       return
405     end
406     m.okay
407   end
408
409   def import(m, params)
410     fname = params[:filename].to_s
411     oldlen = @factoids.length
412     begin
413       read_factfile(fname)
414     rescue
415       m.reply _("failed to import facts from %{fname}: %{err}" % {
416         :fname => fname,
417         :err => $!
418       })
419     end
420     m.reply _("%{len} facts loaded from %{fname}" % {
421       :fname => fname,
422       :len => @factoids.length - oldlen
423     })
424     @changed = true
425   end
426
427 end
428
429 plugin = FactoidsPlugin.new
430
431 plugin.default_auth('edit', false)
432 plugin.default_auth('import', false)
433
434 plugin.map 'learn that *stuff'
435 plugin.map 'forget that *stuff', :auth_path => 'edit'
436 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
437 plugin.map 'facts [about *words]'
438 plugin.map 'facts search *rx'
439 plugin.map 'fact [about *words]'
440 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
441
442 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
443 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
444 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
445
446 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'