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::BooleanValue.new('factoids.silent_listen_and_learn',
108 :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")
109 Config.register Config::IntegerValue.new('factoids.search_results',
111 :desc => "How many factoids to display at a time")
117 @dir = File.join(@bot.botclass,"factoids")
118 @filename = "factoids.rbot"
119 @factoids = FactoidList.new
131 def read_factfile(name=@filename,dir=@dir)
132 fname = File.join(dir,name)
134 expf = File.expand_path(fname)
135 expd = File.expand_path(dir)
136 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
140 }) unless expf.index(expd) == 0
142 if File.exist?(fname)
143 raise ArgumentError, _("%{name} is not a file" % {
145 }) unless File.file?(fname)
146 factoids = File.readlines(fname)
147 return if factoids.empty?
148 firstline = factoids.shift
149 pattern = firstline.chomp.split(" | ")
150 if pattern.length == 1 and pattern.first != "fact"
151 factoids.unshift(firstline)
153 @factoids << Factoid.new( :fact => f.chomp )
156 pattern.map! { |p| p.intern }
157 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
159 ar = f.chomp.split(" | ", pattern.length)
160 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
164 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
173 return unless @changed
174 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
175 fname = File.join(@dir,@filename)
176 ar = ["when | who | where | fact"]
178 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
180 Utils.safe_save(fname) do |file|
186 def trigger_patterns_to_rx
187 return [] if @bot.config['factoids.trigger_pattern'].empty?
188 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
196 list << [/^#{s}$/iu, idx]
200 def learn_patterns_to_rx
201 return [] if @bot.config['factoids.learn_pattern'].empty?
202 @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
210 list << [/^#{s}$/iu, idx]
214 def parse_for_trigger(f, rx=nil)
216 regs = trigger_patterns_to_rx
223 regs.inject([]) { |list, a|
228 list << m[i].downcase
237 return unless @factoids
238 start_time = Time.now
239 rx = trigger_patterns_to_rx
240 triggers = @factoids.inject(Set.new) { |set, f|
241 found = parse_for_trigger(f, rx)
248 debug "Triggers done in #{Time.now - start_time}"
249 @triggers.replace(triggers)
252 def reset_learn_patterns
253 @learn_patterns.replace(learn_patterns_to_rx)
256 def help(plugin, topic="")
257 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
261 factoid = Factoid.new(
262 :fact => params[:stuff].to_s,
264 :who => m.source.fullform,
265 :where => m.channel.to_s
267 if idx = @factoids.index(factoid)
268 m.reply _("I already know that %{factoid} [#%{idx}]" % {
271 }) unless params[:silent]
275 m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last}) unless params[:silent]
276 trigs = parse_for_trigger(factoid)
277 @triggers |= trigs unless trigs.empty?
281 def forget(m, params)
283 idx = params[:index].scan(/\d+/).first.to_i
284 total = @factoids.length
285 if idx <= 0 or idx > total
286 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
289 if factoid = @factoids.delete_at(idx-1)
290 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
293 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
296 factoid = params[:stuff].to_s
297 if @factoids.delete(factoid)
301 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
306 def short_fact(fact,index=nil,total=@factoids.length)
307 idx = index || @factoids.index(fact)+1
308 _("[%{idx}/%{total}] %{fact}" % {
311 :fact => fact.to_s(:meta => false)
315 def long_fact(fact,index=nil,total=@factoids.length)
316 idx = index || @factoids.index(fact)+1
317 _("fact #%{idx} of %{total}: %{fact}" % {
320 :fact => fact.to_s(:meta => true)
325 # When looking for words we separate them with
326 # arbitrary whitespace, not whatever they came with
327 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
328 return Regexp.new("\\b#{pre}\\b", true)
332 total = @factoids.length
333 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
334 m.reply _("I know %{total} facts" % { :total => total })
336 if params[:words].empty?
337 rx = Regexp.new(params[:rx].to_s, true)
339 rx = words2rx(params[:words])
341 known = @factoids.grep(rx)
344 reply << _("I know nothing about %{words}" % params)
346 max_facts = @bot.config['factoids.search_results']
349 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
352 :words => params[:words].to_s,
355 while known.length > max_facts
360 reply << short_fact(f)
363 m.reply reply.join(". "), :split_at => /\s+--\s+/
368 if m.message =~ /^(.*)\?\s*$/
369 return if @bot.config['factoids.address'] and !m.address?
370 return if @factoids.empty?
371 return if @triggers.empty?
372 query = $1.strip.downcase
373 if @triggers.include?(query)
374 facts(m, :words => query.split)
377 return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
378 return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
379 @learn_patterns.each do |pat, i|
380 g = pat.match(m.message)
382 learn(m, :stuff => g[i], :silent => @bot.config['factoids.silent_listen_and_learn'])
392 total = @factoids.length
394 idx = params[:index].scan(/\d+/).first.to_i
395 if idx <= 0 or idx > total
396 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
399 fact = @factoids[idx-1]
402 if params[:words].empty?
404 m.reply _("I know nothing")
409 rx = words2rx(params[:words])
410 known = @factoids.grep(rx)
412 m.reply _("I know nothing about %{words}" % params)
416 fact = known.pick_one
417 idx = @factoids.index(fact)+1
419 m.reply long_fact(fact, idx, total)
422 def edit_fact(m, params)
425 total = @factoids.length
426 idx = params[:index].scan(/\d+/).first.to_i
427 if idx <= 0 or idx > total
428 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
431 fact = @factoids[idx-1]
434 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
439 dstr = params[:when].to_s
441 fact[:when] = Time.parse(dstr, "")
444 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
448 fact[:where] = params[:where].to_s
452 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
461 def import(m, params)
462 fname = params[:filename].to_s
463 oldlen = @factoids.length
467 m.reply _("failed to import facts from %{fname}: %{err}" % {
472 m.reply _("%{len} facts loaded from %{fname}" % {
474 :len => @factoids.length - oldlen
481 plugin = FactoidsPlugin.new
483 plugin.default_auth('edit', false)
484 plugin.default_auth('import', false)
486 plugin.map 'learn that *stuff'
487 plugin.map 'forget that *stuff', :auth_path => 'edit'
488 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
489 plugin.map 'facts [about *words]'
490 plugin.map 'facts search *rx'
491 plugin.map 'fact [about *words]'
492 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
494 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
495 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
496 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
498 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'