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