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