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 trigs = parse_for_trigger(factoid)
274 @triggers |= trigs unless trigs.empty?
278 def forget(m, params)
280 idx = params[:index].scan(/\d+/).first.to_i
281 total = @factoids.length
282 if idx <= 0 or idx > total
283 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
286 if factoid = @factoids.delete_at(idx-1)
287 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
290 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
293 factoid = params[:stuff].to_s
294 if @factoids.delete(factoid)
298 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
303 def short_fact(fact,index=nil,total=@factoids.length)
304 idx = index || @factoids.index(fact)+1
305 _("[%{idx}/%{total}] %{fact}" % {
308 :fact => fact.to_s(:meta => false)
312 def long_fact(fact,index=nil,total=@factoids.length)
313 idx = index || @factoids.index(fact)+1
314 _("fact #%{idx} of %{total}: %{fact}" % {
317 :fact => fact.to_s(:meta => true)
322 # When looking for words we separate them with
323 # arbitrary whitespace, not whatever they came with
324 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
325 return Regexp.new("\\b#{pre}\\b", true)
329 total = @factoids.length
330 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
331 m.reply _("I know %{total} facts" % { :total => total })
333 if params[:words].empty?
334 rx = Regexp.new(params[:rx].to_s, true)
336 rx = words2rx(params[:words])
338 known = @factoids.grep(rx)
341 reply << _("I know nothing about %{words}" % params)
343 max_facts = @bot.config['factoids.search_results']
346 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
349 :words => params[:words].to_s,
352 while known.length > max_facts
357 reply << short_fact(f)
360 m.reply reply.join(". "), :split_at => /\s+--\s+/
365 if m.message =~ /^(.*)\?\s*$/
366 return if @bot.config['factoids.address'] and !m.address?
367 return if @factoids.empty?
368 return if @triggers.empty?
369 query = $1.strip.downcase
370 if @triggers.include?(query)
371 facts(m, :words => query.split)
374 return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
375 return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
376 @learn_patterns.each do |pat, i|
377 g = pat.match(m.message)
379 learn(m, :stuff => g[i], :silent => true)
389 total = @factoids.length
391 idx = params[:index].scan(/\d+/).first.to_i
392 if idx <= 0 or idx > total
393 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
396 fact = @factoids[idx-1]
399 if params[:words].empty?
401 m.reply _("I know nothing")
406 rx = words2rx(params[:words])
407 known = @factoids.grep(rx)
409 m.reply _("I know nothing about %{words}" % params)
413 fact = known.pick_one
414 idx = @factoids.index(fact)+1
416 m.reply long_fact(fact, idx, total)
419 def edit_fact(m, params)
422 total = @factoids.length
423 idx = params[:index].scan(/\d+/).first.to_i
424 if idx <= 0 or idx > total
425 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
428 fact = @factoids[idx-1]
431 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
436 dstr = params[:when].to_s
438 fact[:when] = Time.parse(dstr, "")
441 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
445 fact[:where] = params[:where].to_s
449 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
458 def import(m, params)
459 fname = params[:filename].to_s
460 oldlen = @factoids.length
464 m.reply _("failed to import facts from %{fname}: %{err}" % {
469 m.reply _("%{len} facts loaded from %{fname}" % {
471 :len => @factoids.length - oldlen
478 plugin = FactoidsPlugin.new
480 plugin.default_auth('edit', false)
481 plugin.default_auth('import', false)
483 plugin.map 'learn that *stuff'
484 plugin.map 'forget that *stuff', :auth_path => 'edit'
485 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
486 plugin.map 'facts [about *words]'
487 plugin.map 'facts search *rx'
488 plugin.map 'fact [about *words]'
489 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
491 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
492 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
493 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
495 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'