factoids: fix 'facts search'
[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|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+.*",
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::ArrayValue.new('factoids.not_triggers',
95     :default => [
96       "this","that","the","a","right","who","what","why"
97     ],
98     :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_triggers },
99     :desc => "A list of words that won't be set as keywords")
100   Config.register Config::BooleanValue.new('factoids.address',
101     :default => true,
102     :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")
103   Config.register Config::ArrayValue.new('factoids.learn_pattern',
104     :default => [
105       ".*\\s+(is|are|has|have)\\s+.*"
106     ],
107     :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_learn_patterns },
108     :desc => "A list of regular expressions matching factoids that the bot can learn. append ':n' if the factoid is defined by the n-th group instead of the whole match.")
109   Config.register Config::BooleanValue.new('factoids.listen_and_learn',
110     :default => false,
111     :desc => "Should the bot learn factoids from what is being said in chat? if true, phrases matching patterns in factoids.learn_pattern will tell the bot when a phrase can be learned")
112   Config.register Config::BooleanValue.new('factoids.silent_listen_and_learn',
113     :default => true,
114     :desc => "Should the bot be silent about the factoids he learns from the chat? If true, the bot will not declare what he learned every time he learns something from factoids.listen_and_learn being true")
115   Config.register Config::IntegerValue.new('factoids.search_results',
116     :default => 5,
117     :desc => "How many factoids to display at a time")
118
119   def initialize
120     super
121
122     # TODO config
123     @dir = datafile
124     @filename = "factoids.rbot"
125     @factoids = FactoidList.new
126     @triggers = Set.new
127     @learn_patterns = []
128     reset_learn_patterns
129     begin
130       read_factfile
131     rescue
132       debug $!
133     end
134     @changed = false
135   end
136
137   def read_factfile(name=@filename,dir=@dir)
138     fname = File.join(dir,name)
139
140     expf = File.expand_path(fname)
141     expd = File.expand_path(dir)
142     raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
143       :name => name,
144       :fname => expf,
145       :dir => dir
146     }) unless expf.index(expd) == 0
147
148     if File.exist?(fname)
149       raise ArgumentError, _("%{name} is not a file" % {
150         :name => name
151       }) unless File.file?(fname)
152       factoids = File.readlines(fname)
153       return if factoids.empty?
154       firstline = factoids.shift
155       pattern = firstline.chomp.split(" | ")
156       if pattern.length == 1 and pattern.first != "fact"
157         factoids.unshift(firstline)
158         factoids.each { |f|
159           @factoids << Factoid.new( :fact => f.chomp )
160         }
161       else
162         pattern.map! { |p| p.intern }
163         raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
164         factoids.each { |f|
165           ar = f.chomp.split(" | ", pattern.length)
166           @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
167         }
168       end
169     else
170       raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
171         :name => name,
172         :fname => fname
173       })
174     end
175     reset_triggers
176   end
177
178   def save
179     return unless @changed
180     Dir.mkdir(@dir) unless FileTest.directory?(@dir)
181     fname = File.join(@dir,@filename)
182     ar = ["when | who | where | fact"]
183     @factoids.each { |f|
184       ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
185     }
186     Utils.safe_save(fname) do |file|
187       file.puts ar
188     end
189     @changed = false
190   end
191
192   def trigger_patterns_to_rx
193     return [] if @bot.config['factoids.trigger_pattern'].empty?
194     @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
195       s = str.dup
196       if s =~ /:(\d+)$/
197         idx = $1.to_i
198         s.sub!(/:\d+$/,'')
199       else
200         idx = 1
201       end
202       list << [/^#{s}$/iu, idx]
203     }
204   end
205
206   def learn_patterns_to_rx
207     return [] if @bot.config['factoids.learn_pattern'].empty?
208     @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
209       s = str.dup
210       if s =~ /:(\d+)$/
211         idx = $1.to_i
212         s.sub!(/:\d+$/,'')
213       else
214         idx = 0
215       end
216       list << [/^#{s}$/iu, idx]
217     }
218   end
219
220   def parse_for_trigger(f, rx=nil)
221     if !rx
222       regs = trigger_patterns_to_rx
223     else
224       regs = rx
225     end
226     if regs.empty?
227       f.to_s.scan(/\w+/u)
228     else
229       regs.inject([]) { |list, a|
230         r = a.first
231         i = a.last
232         m = r.match(f.to_s)
233         if m
234           list << m[i].downcase
235         else
236           list
237         end
238       }
239     end
240   end
241
242   def reset_triggers
243     return unless @factoids
244     start_time = Time.now
245     rx = trigger_patterns_to_rx
246     triggers = @factoids.inject(Set.new) { |set, f|
247       found = parse_for_trigger(f, rx)
248       if found.empty?
249         set
250       else
251         set | found
252       end
253     }
254     debug "Triggers done in #{Time.now - start_time}"
255     @triggers.replace(triggers - @bot.config['factoids.not_triggers'])
256   end
257
258   def reset_learn_patterns
259     @learn_patterns.replace(learn_patterns_to_rx)
260   end
261
262   def help(plugin, topic="")
263     _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
264   end
265
266   def learn(m, params)
267     factoid = Factoid.new(
268       :fact => params[:stuff].to_s,
269       :when => Time.now,
270       :who => m.source.fullform,
271       :where => m.channel.to_s
272     )
273     if idx = @factoids.index(factoid)
274       m.reply _("I already know that %{factoid} [#%{idx}]" % {
275         :factoid => factoid,
276         :idx => idx
277       }) unless params[:silent]
278     else
279       @factoids << factoid
280       @changed = true
281       m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last}) unless params[:silent]
282       trigs = parse_for_trigger(factoid)
283       @triggers |= trigs unless trigs.empty?
284     end
285   end
286
287   def forget(m, params)
288     if params[:index]
289       idx = params[:index].scan(/\d+/).first.to_i
290       total = @factoids.length
291       if idx <= 0 or idx > total
292         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
293         return
294       end
295       if factoid = @factoids.delete_at(idx-1)
296         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
297         @changed = true
298       else
299         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
300       end
301     else
302       factoid = params[:stuff].to_s
303       if @factoids.delete(factoid)
304         @changed = true
305         m.okay
306       else
307         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
308       end
309     end
310   end
311
312   def short_fact(fact,index=nil,total=@factoids.length)
313     idx = index || @factoids.index(fact)+1
314     _("[%{idx}/%{total}] %{fact}" % {
315       :idx => idx,
316       :total => total,
317       :fact => fact.to_s(:meta => false)
318     })
319   end
320
321   def long_fact(fact,index=nil,total=@factoids.length)
322     idx = index || @factoids.index(fact)+1
323     _("fact #%{idx} of %{total}: %{fact}" % {
324       :idx => idx,
325       :total => total,
326       :fact => fact.to_s(:meta => true)
327     })
328   end
329
330   def words2rx(words)
331     # When looking for words we separate them with
332     # arbitrary whitespace, not whatever they came with
333     pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
334     pre << '\b' if pre.match(/\b$/)
335     pre = '\b' + pre if pre.match(/^\b/)
336     return Regexp.new(pre, true)
337   end
338
339   def facts(m, params)
340     total = @factoids.length
341     if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
342       m.reply _("I know %{total} facts" % { :total => total })
343     else
344       unless params.key? :words and not params[:words].empty?
345         rx = Regexp.new(params[:rx].to_s, true)
346       else
347         rx = words2rx(params[:words])
348       end
349       known = @factoids.grep(rx)
350       reply = []
351       if known.empty?
352         reply << _("I know nothing about %{words}" % params)
353       else
354         max_facts = @bot.config['factoids.search_results']
355         len = known.length
356         if len > max_facts
357           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
358             :len => len,
359             :total => total,
360             :words => params[:words].to_s,
361             :max => max_facts
362           })
363           while known.length > max_facts
364             known.delete_one
365           end
366         end
367         known.each { |f|
368           reply << short_fact(f)
369         }
370       end
371       m.reply reply.join(". "), :split_at => /\[\d+\/\d+\] /, :purge_split => false
372     end
373   end
374
375   def unreplied(m)
376     if m.message =~ /^(.*)\?\s*$/
377       return if @bot.config['factoids.address'] and !m.address?
378       return if @factoids.empty?
379       return if @triggers.empty?
380       query = $1.strip.downcase
381       if @triggers.include?(query)
382         words = query.split
383         words.instance_variable_set(:@string_value, query)
384         def words.to_s
385           @string_value
386         end
387         facts(m, :words => words)
388       end
389     else
390       return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
391       return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
392       @learn_patterns.each do |pat, i|
393         g = pat.match(m.message)
394         if g and g[i]
395           learn(m, :stuff => g[i], :silent => @bot.config['factoids.silent_listen_and_learn'])
396           break
397         end
398       end
399     end
400   end
401
402   def fact(m, params)
403     fact = nil
404     idx = 0
405     total = @factoids.length
406     if params[:index]
407       idx = params[:index].scan(/\d+/).first.to_i
408       if idx <= 0 or idx > total
409         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
410         return
411       end
412       fact = @factoids[idx-1]
413     else
414       known = nil
415       if params[:words].empty?
416         if @factoids.empty?
417           m.reply _("I know nothing")
418           return
419         end
420         known = @factoids
421       else
422         rx = words2rx(params[:words])
423         known = @factoids.grep(rx)
424         if known.empty?
425           m.reply _("I know nothing about %{words}" % params)
426           return
427         end
428       end
429       fact = known.pick_one
430       idx = @factoids.index(fact)+1
431     end
432     m.reply long_fact(fact, idx, total)
433   end
434
435   def edit_fact(m, params)
436     fact = nil
437     idx = 0
438     total = @factoids.length
439     idx = params[:index].scan(/\d+/).first.to_i
440     if idx <= 0 or idx > total
441       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
442       return
443     end
444     fact = @factoids[idx-1]
445     begin
446       if params[:who]
447         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
448         fact[:who] = who
449         @changed = true
450       end
451       if params[:when]
452         dstr = params[:when].to_s
453         begin
454           fact[:when] = Time.parse(dstr, "")
455           @changed = true
456         rescue
457           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
458         end
459       end
460       if params[:where]
461         fact[:where] = params[:where].to_s
462         @changed = true
463       end
464     rescue Exception
465       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
466         :fact => fact,
467         :err => $!
468       })
469       return
470     end
471     m.okay
472   end
473
474   def import(m, params)
475     fname = params[:filename].to_s
476     oldlen = @factoids.length
477     begin
478       read_factfile(fname)
479     rescue
480       m.reply _("failed to import facts from %{fname}: %{err}" % {
481         :fname => fname,
482         :err => $!
483       })
484     end
485     m.reply _("%{len} facts loaded from %{fname}" % {
486       :fname => fname,
487       :len => @factoids.length - oldlen
488     })
489     @changed = true
490   end
491
492 end
493
494 plugin = FactoidsPlugin.new
495
496 plugin.default_auth('edit', false)
497 plugin.default_auth('import', false)
498
499 plugin.map 'learn that *stuff'
500 plugin.map 'forget that *stuff', :auth_path => 'edit'
501 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
502 plugin.map 'facts [about *words]'
503 plugin.map 'facts search *rx'
504 plugin.map 'fact [about *words]'
505 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
506
507 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
508 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
509 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
510
511 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'