]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
a66c0f523834ef19d4a37205314394d25febac04
[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].downcase
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 unreplied(m)
305     return if @factoids.empty?
306     return if @triggers.empty?
307     return unless m.message =~ /^(.*)\?\s*$/
308     query = $1.strip.downcase
309     if @triggers.include?(query)
310       facts(m, :words => query)
311     end
312   end
313
314   def fact(m, params)
315     fact = nil
316     idx = 0
317     total = @factoids.length
318     if params[:index]
319       idx = params[:index].scan(/\d+/).first.to_i
320       if idx <= 0 or idx > total
321         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
322         return
323       end
324       fact = @factoids[idx-1]
325     else
326       known = nil
327       if params[:words].empty?
328         if @factoids.empty?
329           m.reply _("I know nothing")
330           return
331         end
332         known = @factoids
333       else
334         rx = Regexp.new(params[:words].to_s, true)
335         known = @factoids.grep(rx)
336         if known.empty?
337           m.reply _("I know nothing about %{words}" % params)
338           return
339         end
340       end
341       fact = known.pick_one
342       idx = @factoids.index(fact)+1
343     end
344     m.reply long_fact(fact, idx, total)
345   end
346
347   def edit_fact(m, params)
348     fact = nil
349     idx = 0
350     total = @factoids.length
351     idx = params[:index].scan(/\d+/).first.to_i
352     if idx <= 0 or idx > total
353       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
354       return
355     end
356     fact = @factoids[idx-1]
357     begin
358       if params[:who]
359         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
360         fact[:who] = who
361         @changed = true
362       end
363       if params[:when]
364         dstr = params[:when].to_s
365         begin
366           fact[:when] = Time.parse(dstr, "")
367           @changed = true
368         rescue
369           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
370         end
371       end
372       if params[:where]
373         fact[:where] = params[:where].to_s
374         @changed = true
375       end
376     rescue Exception
377       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
378         :fact => fact,
379         :err => $!
380       })
381       return
382     end
383     m.okay
384   end
385
386   def import(m, params)
387     fname = params[:filename].to_s
388     oldlen = @factoids.length
389     begin
390       read_factfile(fname)
391     rescue
392       m.reply _("failed to import facts from %{fname}: %{err}" % {
393         :fname => fname,
394         :err => $!
395       })
396     end
397     m.reply _("%{len} facts loaded from %{fname}" % {
398       :fname => fname,
399       :len => @factoids.length - oldlen
400     })
401     @changed = true
402   end
403
404 end
405
406 plugin = FactoidsPlugin.new
407
408 plugin.default_auth('edit', false)
409 plugin.default_auth('import', false)
410
411 plugin.map 'learn that *stuff'
412 plugin.map 'forget that *stuff', :auth_path => 'edit'
413 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
414 plugin.map 'facts [about *words]'
415 plugin.map 'fact [about *words]'
416 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
417
418 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
419 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
420 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
421
422 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'