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