]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
refactor: wordlist shouldn't use bot singleton #35
[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 { |fs| fs[: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::ArrayValue.new('factoids.not_triggers',
95     :default => [
96       "this","that","the","a","right","who","what","why"
97     ],
98     :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_triggers },
99     :desc => "A list of words that won't be set as keywords")
100   Config.register Config::BooleanValue.new('factoids.address',
101     :default => true,
102     :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")
103   Config.register Config::ArrayValue.new('factoids.learn_pattern',
104     :default => [
105       ".*\\s+(is|are|has|have)\\s+.*"
106     ],
107     :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_learn_patterns },
108     :desc => "A list of regular expressions matching factoids that the bot can learn. append ':n' if the factoid is defined by the n-th group instead of the whole match.")
109   Config.register Config::BooleanValue.new('factoids.listen_and_learn',
110     :default => false,
111     :desc => "Should the bot learn factoids from what is being said in chat? if true, phrases matching patterns in factoids.learn_pattern will tell the bot when a phrase can be learned")
112   Config.register Config::BooleanValue.new('factoids.silent_listen_and_learn',
113     :default => true,
114     :desc => "Should the bot be silent about the factoids he learns from the chat? If true, the bot will not declare what he learned every time he learns something from factoids.listen_and_learn being true")
115   Config.register Config::IntegerValue.new('factoids.search_results',
116     :default => 5,
117     :desc => "How many factoids to display at a time")
118
119   def initialize
120     super
121
122     # TODO config
123     @dir = datafile
124     @filename = "factoids.rbot"
125     @factoids = FactoidList.new
126     @triggers = Set.new
127     @learn_patterns = []
128     reset_learn_patterns
129     begin
130       read_factfile
131     rescue
132       debug $!
133     end
134     @changed = false
135   end
136
137   def read_factfile(name=@filename,dir=@dir)
138     fname = File.join(dir,name)
139
140     expf = File.expand_path(fname)
141     expd = File.expand_path(dir)
142     raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
143       :name => name,
144       :fname => expf,
145       :dir => dir
146     }) unless expf.index(expd) == 0
147
148     if File.exist?(fname)
149       raise ArgumentError, _("%{name} is not a file" % {
150         :name => name
151       }) unless File.file?(fname)
152       factoids = File.readlines(fname)
153       return if factoids.empty?
154       firstline = factoids.shift
155       pattern = firstline.chomp.split(" | ")
156       if pattern.length == 1 and pattern.first != "fact"
157         factoids.unshift(firstline)
158         factoids.each { |f|
159           @factoids << Factoid.new( :fact => f.chomp )
160         }
161       else
162         pattern.map! { |p| p.intern }
163         raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
164         factoids.each { |f|
165           ar = f.chomp.split(" | ", pattern.length)
166           @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
167         }
168       end
169     else
170       raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
171         :name => name,
172         :fname => fname
173       })
174     end
175     reset_triggers
176   end
177
178   def save
179     return unless @changed
180     Dir.mkdir(@dir) unless FileTest.directory?(@dir)
181     fname = File.join(@dir,@filename)
182     ar = ["when | who | where | fact"]
183     @factoids.each { |f|
184       ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
185     }
186     Utils.safe_save(fname) do |file|
187       file.puts ar
188     end
189     @changed = false
190   end
191
192   def trigger_patterns_to_rx
193     return [] if @bot.config['factoids.trigger_pattern'].empty?
194     @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
195       s = str.dup
196       if s =~ /:(\d+)$/
197         idx = $1.to_i
198         s.sub!(/:\d+$/,'')
199       else
200         idx = 1
201       end
202       list << [/^#{s}$/iu, idx]
203     }
204   end
205
206   def learn_patterns_to_rx
207     return [] if @bot.config['factoids.learn_pattern'].empty?
208     @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
209       s = str.dup
210       if s =~ /:(\d+)$/
211         idx = $1.to_i
212         s.sub!(/:\d+$/,'')
213       else
214         idx = 0
215       end
216       list << [/^#{s}$/iu, idx]
217     }
218   end
219
220   def parse_for_trigger(f, rx=nil)
221     if !rx
222       regs = trigger_patterns_to_rx
223     else
224       regs = rx
225     end
226     if regs.empty?
227       f.to_s.scan(/\w+/u)
228     else
229       regs.inject([]) { |list, a|
230         r = a.first
231         i = a.last
232         m = r.match(f.to_s)
233         if m
234           list << m[i].downcase
235         else
236           list
237         end
238       }
239     end
240   end
241
242   def reset_triggers
243     return unless @factoids
244     start_time = Time.now
245     rx = trigger_patterns_to_rx
246     triggers = @factoids.inject(Set.new) { |set, f|
247       found = parse_for_trigger(f, rx)
248       if found.empty?
249         set
250       else
251         set | found
252       end
253     }
254     debug "Triggers done in #{Time.now - start_time}"
255     @triggers.replace(triggers - @bot.config['factoids.not_triggers'])
256   end
257
258   def reset_learn_patterns
259     @learn_patterns.replace(learn_patterns_to_rx)
260   end
261
262   def help(plugin, topic="")
263     case plugin
264     when 'learn'
265       _("learn that <factoid> => learn a factoid")
266     when 'forget'
267       _("forget fact <#num> => forget factoid number #num ; forget about <factoid> => forget a factoid")
268     else
269       _("factoids plugin: learn that <factoid>, forget that <factoid>, facts about <words>")
270     end
271   end
272
273   def learn(m, params)
274     factoid = Factoid.new(
275       :fact => params[:stuff].to_s,
276       :when => Time.now,
277       :who => m.source.fullform,
278       :where => m.channel.to_s
279     )
280     if idx = @factoids.index(factoid)
281       m.reply _("I already know that %{factoid} [#%{idx}]" % {
282         :factoid => factoid,
283         :idx => idx
284       }) unless params[:silent]
285     else
286       @factoids << factoid
287       @changed = true
288       m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last}) unless params[:silent]
289       trigs = parse_for_trigger(factoid)
290       @triggers |= trigs unless trigs.empty?
291     end
292   end
293
294   def forget(m, params)
295     if params[:index]
296       idx = params[:index].scan(/\d+/).first.to_i
297       total = @factoids.length
298       if idx <= 0 or idx > total
299         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
300         return
301       end
302       if factoid = @factoids.delete_at(idx-1)
303         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
304         @changed = true
305       else
306         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
307       end
308     else
309       factoid = params[:stuff].to_s
310       if @factoids.delete(factoid)
311         @changed = true
312         m.okay
313       else
314         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
315       end
316     end
317   end
318
319   def short_fact(fact,index=nil,total=@factoids.length)
320     idx = index || @factoids.index(fact)+1
321     _("[%{idx}/%{total}] %{fact}" % {
322       :idx => idx,
323       :total => total,
324       :fact => fact.to_s(:meta => false)
325     })
326   end
327
328   def long_fact(fact,index=nil,total=@factoids.length)
329     idx = index || @factoids.index(fact)+1
330     _("fact #%{idx} of %{total}: %{fact}" % {
331       :idx => idx,
332       :total => total,
333       :fact => fact.to_s(:meta => true)
334     })
335   end
336
337   def words2rx(words)
338     # When looking for words we separate them with
339     # arbitrary whitespace, not whatever they came with
340     pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
341     pre << '\b' if pre.match(/\b$/)
342     pre = '\b' + pre if pre.match(/^\b/)
343     return Regexp.new(pre, true)
344   end
345
346   def facts(m, params)
347     total = @factoids.length
348     if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
349       m.reply _("I know %{total} facts" % { :total => total })
350     else
351       unless params.key? :words and not params[:words].empty?
352         rx = Regexp.new(params[:rx].to_s, true)
353       else
354         rx = words2rx(params[:words])
355       end
356       known = @factoids.grep(rx)
357       reply = []
358       if known.empty?
359         if params.key? :words
360           reply << _("I know nothing about %{words}" % params)
361         else params.key? :rx
362           reply << _("I know nothing matching %{rx}" % params)
363         end
364       else
365         max_facts = @bot.config['factoids.search_results']
366         len = known.length
367         if len > max_facts
368           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
369             :len => len,
370             :total => total,
371             :words => params[:words].to_s,
372             :max => max_facts
373           })
374           while known.length > max_facts
375             known.delete_one
376           end
377         end
378         known.each { |f|
379           reply << short_fact(f)
380         }
381       end
382       m.reply reply.join(". "), :split_at => /\[\d+\/\d+\] /, :purge_split => false
383     end
384   end
385
386   def unreplied(m)
387     if m.message =~ /^(.*)\?\s*$/
388       return if @bot.config['factoids.address'] and !m.address?
389       return if @factoids.empty?
390       return if @triggers.empty?
391       query = $1.strip.downcase
392       if @triggers.include?(query)
393         words = query.split
394         words.instance_variable_set(:@string_value, query)
395         def words.to_s
396           @string_value
397         end
398         facts(m, :words => words)
399       end
400     else
401       return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
402       return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
403       @learn_patterns.each do |pat, i|
404         g = pat.match(m.message)
405         if g and g[i]
406           learn(m, :stuff => g[i], :silent => @bot.config['factoids.silent_listen_and_learn'])
407           break
408         end
409       end
410     end
411   end
412
413   def fact(m, params)
414     fact = nil
415     idx = 0
416     total = @factoids.length
417     if params[:index]
418       idx = params[:index].scan(/\d+/).first.to_i
419       if idx <= 0 or idx > total
420         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
421         return
422       end
423       fact = @factoids[idx-1]
424     else
425       known = nil
426       if params[:words].empty?
427         if @factoids.empty?
428           m.reply _("I know nothing")
429           return
430         end
431         known = @factoids
432       else
433         rx = words2rx(params[:words])
434         known = @factoids.grep(rx)
435         if known.empty?
436           m.reply _("I know nothing about %{words}" % params)
437           return
438         end
439       end
440       fact = known.pick_one
441       idx = @factoids.index(fact)+1
442     end
443     m.reply long_fact(fact, idx, total)
444   end
445
446   def edit_fact(m, params)
447     fact = nil
448     idx = 0
449     total = @factoids.length
450     idx = params[:index].scan(/\d+/).first.to_i
451     if idx <= 0 or idx > total
452       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
453       return
454     end
455     fact = @factoids[idx-1]
456     begin
457       if params[:who]
458         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
459         fact[:who] = who
460         @changed = true
461       end
462       if params[:when]
463         dstr = params[:when].to_s
464         begin
465           fact[:when] = Time.parse(dstr, "")
466           @changed = true
467         rescue
468           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
469         end
470       end
471       if params[:where]
472         fact[:where] = params[:where].to_s
473         @changed = true
474       end
475     rescue Exception
476       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
477         :fact => fact,
478         :err => $!
479       })
480       return
481     end
482     m.okay
483   end
484
485   def import(m, params)
486     fname = params[:filename].to_s
487     oldlen = @factoids.length
488     begin
489       read_factfile(fname)
490     rescue
491       m.reply _("failed to import facts from %{fname}: %{err}" % {
492         :fname => fname,
493         :err => $!
494       })
495     end
496     m.reply _("%{len} facts loaded from %{fname}" % {
497       :fname => fname,
498       :len => @factoids.length - oldlen
499     })
500     @changed = true
501   end
502
503 end
504
505 plugin = FactoidsPlugin.new
506
507 plugin.default_auth('edit', false)
508 plugin.default_auth('import', false)
509
510 plugin.map 'learn that *stuff'
511 plugin.map 'forget that *stuff', :auth_path => 'edit'
512 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
513 plugin.map 'facts [about *words]'
514 plugin.map 'facts search *rx'
515 plugin.map 'fact [about *words]'
516 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
517
518 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
519 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
520 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
521
522 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'