]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
factoids plugin: scan factoids for query triggers
[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)\\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")
94
95   def initialize
96     super
97
98     # TODO config
99     @dir = File.join(@bot.botclass,"factoids")
100     @filename = "factoids.rbot"
101     @factoids = FactoidList.new
102     @triggers = Set.new
103     begin
104       read_factfile
105     rescue
106       debug $!
107     end
108     @changed = false
109   end
110
111   def read_factfile(name=@filename,dir=@dir)
112     fname = File.join(dir,name)
113
114     expf = File.expand_path(fname)
115     expd = File.expand_path(dir)
116     raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
117       :name => name,
118       :fname => expf,
119       :dir => dir
120     }) unless expf.index(expd) == 0
121
122     if File.exist?(fname)
123       raise ArgumentError, _("%{name} is not a file" % {
124         :name => name
125       }) unless File.file?(fname)
126       factoids = File.readlines(fname)
127       return if factoids.empty?
128       firstline = factoids.shift
129       pattern = firstline.chomp.split(" | ")
130       if pattern.length == 1 and pattern.first != "fact"
131         factoids.unshift(firstline)
132         factoids.each { |f|
133           @factoids << Factoid.new( :fact => f.chomp )
134         }
135       else
136         pattern.map! { |p| p.intern }
137         raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
138         factoids.each { |f|
139           ar = f.chomp.split(" | ", pattern.length)
140           @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
141         }
142       end
143     else
144       raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
145         :name => name,
146         :fname => fname
147       })
148     end
149     reset_triggers
150   end
151
152   def save
153     return unless @changed
154     Dir.mkdir(@dir) unless FileTest.directory?(@dir)
155     fname = File.join(@dir,@filename)
156     ar = ["when | who | where | fact"]
157     @factoids.each { |f|
158       ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
159     }
160     Utils.safe_save(fname) do |file|
161       file.puts ar
162     end
163     @changed = false
164   end
165
166   def trigger_patterns_to_rx
167     @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
168       s = str.dup
169       if s =~ /:(\d+)$/
170         idx = $1.to_i
171         s.sub!(/:\d+$/,'')
172       else
173         idx = 1
174       end
175       list << [/^#{s}$/iu, idx]
176     }
177   end
178
179   def parse_for_trigger(f, rx=nil)
180     if !rx
181       regs = trigger_patterns_to_rx
182     else
183       regs = rx
184     end
185     regs.inject([]) { |list, a|
186       r = a.first
187       i = a.last
188       m = r.match(f.to_s)
189       if m
190         list << m[i]
191       else
192         list
193       end
194     }
195   end
196
197   def reset_triggers
198     start_time = Time.now
199     rx = trigger_patterns_to_rx
200     triggers = @factoids.inject(Set.new) { |set, f|
201       found = parse_for_trigger(f, rx)
202       if found.empty?
203         set
204       else
205         set | found
206       end
207     }
208     debug "Triggers done in #{Time.now - start_time}"
209     @triggers.replace(triggers)
210   end
211
212   def help(plugin, topic="")
213     _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
214   end
215
216   def learn(m, params)
217     factoid = Factoid.new(
218       :fact => params[:stuff].to_s,
219       :when => Time.now,
220       :who => m.source.fullform,
221       :where => m.channel.to_s
222     )
223     if idx = @factoids.index(factoid)
224       m.reply _("I already know that %{factoid} [#%{idx}]" % {
225         :factoid => factoid,
226         :idx => idx
227       })
228     else
229       @factoids << factoid
230       @changed = true
231       m.okay
232       fact(m, :index => @factoids.length.to_s)
233       parse_for_trigger(factoid)
234     end
235   end
236
237   def forget(m, params)
238     if params[:index]
239       idx = params[:index].scan(/\d+/).first.to_i
240       total = @factoids.length
241       if idx <= 0 or idx > total
242         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
243         return
244       end
245       if factoid = @factoids.delete_at(idx-1)
246         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
247         @changed = true
248       else
249         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
250       end
251     else
252       factoid = params[:stuff].to_s
253       if @factoids.delete(factoid)
254         @changed = true
255         m.okay
256       else
257         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
258       end
259     end
260   end
261
262   def long_fact(fact,index=nil,total=@factoids.length)
263     idx = index || @factoids.index(fact)+1
264     _("fact #%{idx} of %{total}: %{fact}" % {
265       :idx => idx,
266       :total => total,
267       :fact => fact.to_s(:meta => true)
268     })
269   end
270
271   def facts(m, params)
272     total = @factoids.length
273     if params[:words].empty?
274       m.reply _("I know %{total} facts" % { :total => total })
275     else
276       rx = Regexp.new(params[:words].to_s, true)
277       known = @factoids.grep(rx)
278       reply = []
279       if known.empty?
280         reply << _("I know nothing about %{words}" % params)
281       else
282         # TODO config
283         max_facts = 5
284         len = known.length
285         if len > max_facts
286           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
287             :len => len,
288             :total => total,
289             :words => params[:words].to_s,
290             :max => max_facts
291           })
292           while known.length > max_facts
293             known.delete_one
294           end
295         end
296         known.each { |f|
297           reply << long_fact(f)
298         }
299       end
300       m.reply reply.join(" -- ")
301     end
302   end
303
304   def fact(m, params)
305     fact = nil
306     idx = 0
307     total = @factoids.length
308     if params[:index]
309       idx = params[:index].scan(/\d+/).first.to_i
310       if idx <= 0 or idx > total
311         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
312         return
313       end
314       fact = @factoids[idx-1]
315     else
316       known = nil
317       if params[:words].empty?
318         if @factoids.empty?
319           m.reply _("I know nothing")
320           return
321         end
322         known = @factoids
323       else
324         rx = Regexp.new(params[:words].to_s, true)
325         known = @factoids.grep(rx)
326         if known.empty?
327           m.reply _("I know nothing about %{words}" % params)
328           return
329         end
330       end
331       fact = known.pick_one
332       idx = @factoids.index(fact)+1
333     end
334     m.reply long_fact(fact, idx, total)
335   end
336
337   def edit_fact(m, params)
338     fact = nil
339     idx = 0
340     total = @factoids.length
341     idx = params[:index].scan(/\d+/).first.to_i
342     if idx <= 0 or idx > total
343       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
344       return
345     end
346     fact = @factoids[idx-1]
347     begin
348       if params[:who]
349         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
350         fact[:who] = who
351         @changed = true
352       end
353       if params[:when]
354         dstr = params[:when].to_s
355         begin
356           fact[:when] = Time.parse(dstr, "")
357           @changed = true
358         rescue
359           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
360         end
361       end
362       if params[:where]
363         fact[:where] = params[:where].to_s
364         @changed = true
365       end
366     rescue Exception
367       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
368         :fact => fact,
369         :err => $!
370       })
371       return
372     end
373     m.okay
374   end
375
376   def import(m, params)
377     fname = params[:filename].to_s
378     oldlen = @factoids.length
379     begin
380       read_factfile(fname)
381     rescue
382       m.reply _("failed to import facts from %{fname}: %{err}" % {
383         :fname => fname,
384         :err => $!
385       })
386     end
387     m.reply _("%{len} facts loaded from %{fname}" % {
388       :fname => fname,
389       :len => @factoids.length - oldlen
390     })
391     @changed = true
392   end
393
394 end
395
396 plugin = FactoidsPlugin.new
397
398 plugin.default_auth('edit', false)
399 plugin.default_auth('import', false)
400
401 plugin.map 'learn that *stuff'
402 plugin.map 'forget that *stuff', :auth_path => 'edit'
403 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
404 plugin.map 'facts [about *words]'
405 plugin.map 'fact [about *words]'
406 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
407
408 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
409 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
410 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
411
412 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'