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