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