]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
factoids plugin: config option to reply to queries only when addressed
[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   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     @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
171       s = str.dup
172       if s =~ /:(\d+)$/
173         idx = $1.to_i
174         s.sub!(/:\d+$/,'')
175       else
176         idx = 1
177       end
178       list << [/^#{s}$/iu, idx]
179     }
180   end
181
182   def parse_for_trigger(f, rx=nil)
183     if !rx
184       regs = trigger_patterns_to_rx
185     else
186       regs = rx
187     end
188     regs.inject([]) { |list, a|
189       r = a.first
190       i = a.last
191       m = r.match(f.to_s)
192       if m
193         list << m[i].downcase
194       else
195         list
196       end
197     }
198   end
199
200   def reset_triggers
201     start_time = Time.now
202     rx = trigger_patterns_to_rx
203     triggers = @factoids.inject(Set.new) { |set, f|
204       found = parse_for_trigger(f, rx)
205       if found.empty?
206         set
207       else
208         set | found
209       end
210     }
211     debug "Triggers done in #{Time.now - start_time}"
212     @triggers.replace(triggers)
213   end
214
215   def help(plugin, topic="")
216     _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
217   end
218
219   def learn(m, params)
220     factoid = Factoid.new(
221       :fact => params[:stuff].to_s,
222       :when => Time.now,
223       :who => m.source.fullform,
224       :where => m.channel.to_s
225     )
226     if idx = @factoids.index(factoid)
227       m.reply _("I already know that %{factoid} [#%{idx}]" % {
228         :factoid => factoid,
229         :idx => idx
230       })
231     else
232       @factoids << factoid
233       @changed = true
234       m.okay
235       fact(m, :index => @factoids.length.to_s)
236       parse_for_trigger(factoid)
237     end
238   end
239
240   def forget(m, params)
241     if params[:index]
242       idx = params[:index].scan(/\d+/).first.to_i
243       total = @factoids.length
244       if idx <= 0 or idx > total
245         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
246         return
247       end
248       if factoid = @factoids.delete_at(idx-1)
249         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
250         @changed = true
251       else
252         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
253       end
254     else
255       factoid = params[:stuff].to_s
256       if @factoids.delete(factoid)
257         @changed = true
258         m.okay
259       else
260         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
261       end
262     end
263   end
264
265   def long_fact(fact,index=nil,total=@factoids.length)
266     idx = index || @factoids.index(fact)+1
267     _("fact #%{idx} of %{total}: %{fact}" % {
268       :idx => idx,
269       :total => total,
270       :fact => fact.to_s(:meta => true)
271     })
272   end
273
274   def facts(m, params)
275     total = @factoids.length
276     if params[:words].empty?
277       m.reply _("I know %{total} facts" % { :total => total })
278     else
279       rx = Regexp.new(params[:words].to_s, true)
280       known = @factoids.grep(rx)
281       reply = []
282       if known.empty?
283         reply << _("I know nothing about %{words}" % params)
284       else
285         # TODO config
286         max_facts = 5
287         len = known.length
288         if len > max_facts
289           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
290             :len => len,
291             :total => total,
292             :words => params[:words].to_s,
293             :max => max_facts
294           })
295           while known.length > max_facts
296             known.delete_one
297           end
298         end
299         known.each { |f|
300           reply << long_fact(f)
301         }
302       end
303       m.reply reply.join(" -- ")
304     end
305   end
306
307   def unreplied(m)
308     return if @bot.config['factoids.address'] and !m.address?
309     return if @factoids.empty?
310     return if @triggers.empty?
311     return unless m.message =~ /^(.*)\?\s*$/
312     query = $1.strip.downcase
313     if @triggers.include?(query)
314       facts(m, :words => query)
315     end
316   end
317
318   def fact(m, params)
319     fact = nil
320     idx = 0
321     total = @factoids.length
322     if params[:index]
323       idx = params[:index].scan(/\d+/).first.to_i
324       if idx <= 0 or idx > total
325         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
326         return
327       end
328       fact = @factoids[idx-1]
329     else
330       known = nil
331       if params[:words].empty?
332         if @factoids.empty?
333           m.reply _("I know nothing")
334           return
335         end
336         known = @factoids
337       else
338         rx = Regexp.new(params[:words].to_s, true)
339         known = @factoids.grep(rx)
340         if known.empty?
341           m.reply _("I know nothing about %{words}" % params)
342           return
343         end
344       end
345       fact = known.pick_one
346       idx = @factoids.index(fact)+1
347     end
348     m.reply long_fact(fact, idx, total)
349   end
350
351   def edit_fact(m, params)
352     fact = nil
353     idx = 0
354     total = @factoids.length
355     idx = params[:index].scan(/\d+/).first.to_i
356     if idx <= 0 or idx > total
357       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
358       return
359     end
360     fact = @factoids[idx-1]
361     begin
362       if params[:who]
363         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
364         fact[:who] = who
365         @changed = true
366       end
367       if params[:when]
368         dstr = params[:when].to_s
369         begin
370           fact[:when] = Time.parse(dstr, "")
371           @changed = true
372         rescue
373           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
374         end
375       end
376       if params[:where]
377         fact[:where] = params[:where].to_s
378         @changed = true
379       end
380     rescue Exception
381       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
382         :fact => fact,
383         :err => $!
384       })
385       return
386     end
387     m.okay
388   end
389
390   def import(m, params)
391     fname = params[:filename].to_s
392     oldlen = @factoids.length
393     begin
394       read_factfile(fname)
395     rescue
396       m.reply _("failed to import facts from %{fname}: %{err}" % {
397         :fname => fname,
398         :err => $!
399       })
400     end
401     m.reply _("%{len} facts loaded from %{fname}" % {
402       :fname => fname,
403       :len => @factoids.length - oldlen
404     })
405     @changed = true
406   end
407
408 end
409
410 plugin = FactoidsPlugin.new
411
412 plugin.default_auth('edit', false)
413 plugin.default_auth('import', false)
414
415 plugin.map 'learn that *stuff'
416 plugin.map 'forget that *stuff', :auth_path => 'edit'
417 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
418 plugin.map 'facts [about *words]'
419 plugin.map 'fact [about *words]'
420 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
421
422 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
423 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
424 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
425
426 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'