4 # :title: Factoids pluing
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
10 # Store (and retrieve) unstructured one-sentence factoids
12 class FactoidsPlugin < Plugin
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]
24 show_meta = opts[:meta]
32 metadata << _("from %{who}" % @hash)
35 metadata << _("on %{when}" % @hash)
38 metadata << _("in %{where}" % @hash)
40 unless metadata.empty?
41 meta << _(" [%{data}]" % {:data => metadata.join(" ")})
51 @hash.send(:[]=,*args)
57 alias :to_hash :to_hsh
60 class FactoidList < ArrayOf
68 self.map { |f| f[:fact] }.index(fact)
84 # TODO default should be language-specific
85 Config.register Config::ArrayValue.new('factoids.trigger_pattern',
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+.*",
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',
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::ArrayValue.new('factoids.learn_pattern',
99 ".*\\s+(is|are|has|have)\\s+.*"
101 :on_change => Proc.new { |bot, v| bot.plugins['factoids'].reset_learn_patterns },
102 :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.")
103 Config.register Config::BooleanValue.new('factoids.listen_and_learn',
105 :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")
106 Config.register Config::IntegerValue.new('factoids.search_results',
108 :desc => "How many factoids to display at a time")
114 @dir = File.join(@bot.botclass,"factoids")
115 @filename = "factoids.rbot"
116 @factoids = FactoidList.new
128 def read_factfile(name=@filename,dir=@dir)
129 fname = File.join(dir,name)
131 expf = File.expand_path(fname)
132 expd = File.expand_path(dir)
133 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
137 }) unless expf.index(expd) == 0
139 if File.exist?(fname)
140 raise ArgumentError, _("%{name} is not a file" % {
142 }) unless File.file?(fname)
143 factoids = File.readlines(fname)
144 return if factoids.empty?
145 firstline = factoids.shift
146 pattern = firstline.chomp.split(" | ")
147 if pattern.length == 1 and pattern.first != "fact"
148 factoids.unshift(firstline)
150 @factoids << Factoid.new( :fact => f.chomp )
153 pattern.map! { |p| p.intern }
154 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
156 ar = f.chomp.split(" | ", pattern.length)
157 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
161 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
170 return unless @changed
171 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
172 fname = File.join(@dir,@filename)
173 ar = ["when | who | where | fact"]
175 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
177 Utils.safe_save(fname) do |file|
183 def trigger_patterns_to_rx
184 return [] if @bot.config['factoids.trigger_pattern'].empty?
185 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
193 list << [/^#{s}$/iu, idx]
197 def learn_patterns_to_rx
198 return [] if @bot.config['factoids.learn_pattern'].empty?
199 @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
207 list << [/^#{s}$/iu, idx]
211 def parse_for_trigger(f, rx=nil)
213 regs = trigger_patterns_to_rx
220 regs.inject([]) { |list, a|
225 list << m[i].downcase
234 return unless @factoids
235 start_time = Time.now
236 rx = trigger_patterns_to_rx
237 triggers = @factoids.inject(Set.new) { |set, f|
238 found = parse_for_trigger(f, rx)
245 debug "Triggers done in #{Time.now - start_time}"
246 @triggers.replace(triggers)
249 def reset_learn_patterns
250 @learn_patterns.replace(learn_patterns_to_rx)
253 def help(plugin, topic="")
254 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
258 factoid = Factoid.new(
259 :fact => params[:stuff].to_s,
261 :who => m.source.fullform,
262 :where => m.channel.to_s
264 if idx = @factoids.index(factoid)
265 m.reply _("I already know that %{factoid} [#%{idx}]" % {
268 }) unless params[:silent]
272 m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last})
273 parse_for_trigger(factoid)
277 def forget(m, params)
279 idx = params[:index].scan(/\d+/).first.to_i
280 total = @factoids.length
281 if idx <= 0 or idx > total
282 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
285 if factoid = @factoids.delete_at(idx-1)
286 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
289 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
292 factoid = params[:stuff].to_s
293 if @factoids.delete(factoid)
297 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
302 def short_fact(fact,index=nil,total=@factoids.length)
303 idx = index || @factoids.index(fact)+1
304 _("[%{idx}/%{total}] %{fact}" % {
307 :fact => fact.to_s(:meta => false)
311 def long_fact(fact,index=nil,total=@factoids.length)
312 idx = index || @factoids.index(fact)+1
313 _("fact #%{idx} of %{total}: %{fact}" % {
316 :fact => fact.to_s(:meta => true)
321 # When looking for words we separate them with
322 # arbitrary whitespace, not whatever they came with
323 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
324 return Regexp.new("\\b#{pre}\\b", true)
328 total = @factoids.length
329 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
330 m.reply _("I know %{total} facts" % { :total => total })
332 if params[:words].empty?
333 rx = Regexp.new(params[:rx].to_s, true)
335 rx = words2rx(params[:words])
337 known = @factoids.grep(rx)
340 reply << _("I know nothing about %{words}" % params)
342 max_facts = @bot.config['factoids.search_results']
345 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
348 :words => params[:words].to_s,
351 while known.length > max_facts
356 reply << short_fact(f)
359 m.reply reply.join(". "), :split_at => /\s+--\s+/
364 if m.message =~ /^(.*)\?\s*$/
365 return if @bot.config['factoids.address'] and !m.address?
366 return if @factoids.empty?
367 return if @triggers.empty?
368 query = $1.strip.downcase
369 if @triggers.include?(query)
370 facts(m, :words => query.split)
373 return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
374 return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
375 @learn_patterns.each do |pat, i|
376 g = pat.match(m.message)
378 learn(m, :stuff => g[i], :silent => true)
388 total = @factoids.length
390 idx = params[:index].scan(/\d+/).first.to_i
391 if idx <= 0 or idx > total
392 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
395 fact = @factoids[idx-1]
398 if params[:words].empty?
400 m.reply _("I know nothing")
405 rx = words2rx(params[:words])
406 known = @factoids.grep(rx)
408 m.reply _("I know nothing about %{words}" % params)
412 fact = known.pick_one
413 idx = @factoids.index(fact)+1
415 m.reply long_fact(fact, idx, total)
418 def edit_fact(m, params)
421 total = @factoids.length
422 idx = params[:index].scan(/\d+/).first.to_i
423 if idx <= 0 or idx > total
424 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
427 fact = @factoids[idx-1]
430 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
435 dstr = params[:when].to_s
437 fact[:when] = Time.parse(dstr, "")
440 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
444 fact[:where] = params[:where].to_s
448 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
457 def import(m, params)
458 fname = params[:filename].to_s
459 oldlen = @factoids.length
463 m.reply _("failed to import facts from %{fname}: %{err}" % {
468 m.reply _("%{len} facts loaded from %{fname}" % {
470 :len => @factoids.length - oldlen
477 plugin = FactoidsPlugin.new
479 plugin.default_auth('edit', false)
480 plugin.default_auth('import', false)
482 plugin.map 'learn that *stuff'
483 plugin.map 'forget that *stuff', :auth_path => 'edit'
484 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
485 plugin.map 'facts [about *words]'
486 plugin.map 'facts search *rx'
487 plugin.map 'fact [about *words]'
488 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
490 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
491 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
492 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
494 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'