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
15 @hash = hash.reject { |k, val| val.nil? or val.empty? rescue false }
16 raise ArgumentError, "no fact!" unless @hash[:fact]
17 if String === @hash[:when]
18 @hash[:when] = Time.parse @hash[:when]
23 show_meta = opts[:meta]
31 metadata << _("from %{who}" % @hash)
34 metadata << _("on %{when}" % @hash)
37 metadata << _("in %{where}" % @hash)
39 unless metadata.empty?
40 meta << _(" [%{data}]" % {:data => metadata.join(" ")})
50 @hash.send(:[]=,*args)
56 alias :to_hash :to_hsh
59 class ::FactoidList < ArrayOf
67 self.map { |fs| fs[:fact] }.index(fact)
83 class FactoidsPlugin < Plugin
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::ArrayValue.new('factoids.not_triggers',
96 "this","that","the","a","right","who","what","why"
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',
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',
105 ".*\\s+(is|are|has|have)\\s+.*"
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',
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',
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',
117 :desc => "How many factoids to display at a time")
125 @factoids = @registry[:factoids]
127 @factoids = FactoidList.new
130 @filename = "factoids.rbot"
131 debug "migrate from existing factoids #{@dir}/#{@filename}"
146 def read_factfile(name=@filename,dir=@dir)
147 fname = File.join(dir,name)
149 expf = File.expand_path(fname)
150 expd = File.expand_path(dir)
151 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
155 }) unless expf.index(expd) == 0
157 if File.exist?(fname)
158 raise ArgumentError, _("%{name} is not a file" % {
160 }) unless File.file?(fname)
161 factoids = File.readlines(fname)
162 return if factoids.empty?
163 firstline = factoids.shift
164 pattern = firstline.chomp.split(" | ")
165 if pattern.length == 1 and pattern.first != "fact"
166 factoids.unshift(firstline)
168 @factoids << Factoid.new( :fact => f.chomp )
171 pattern.map! { |p| p.intern }
172 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
174 ar = f.chomp.split(" | ", pattern.length)
175 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
179 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
188 return unless @changed
189 @registry[:factoids] = @factoids
194 def trigger_patterns_to_rx
195 return [] if @bot.config['factoids.trigger_pattern'].empty?
196 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
204 list << [/^#{s}$/iu, idx]
208 def learn_patterns_to_rx
209 return [] if @bot.config['factoids.learn_pattern'].empty?
210 @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
218 list << [/^#{s}$/iu, idx]
222 def parse_for_trigger(f, rx=nil)
224 regs = trigger_patterns_to_rx
231 regs.inject([]) { |list, a|
236 list << m[i].downcase
245 return unless @factoids
246 start_time = Time.now
247 rx = trigger_patterns_to_rx
248 triggers = @factoids.inject(Set.new) { |set, f|
249 found = parse_for_trigger(f, rx)
256 debug "Triggers done in #{Time.now - start_time}"
257 @triggers.replace(triggers - @bot.config['factoids.not_triggers'])
260 def reset_learn_patterns
261 @learn_patterns.replace(learn_patterns_to_rx)
264 def help(plugin, topic="")
267 _("learn that <factoid> => learn a factoid")
269 _("forget fact <#num> => forget factoid number #num ; forget about <factoid> => forget a factoid")
271 _("factoids plugin: learn that <factoid>, forget that <factoid>, facts about <words>")
276 factoid = Factoid.new(
277 :fact => params[:stuff].to_s,
279 :who => m.source.fullform,
280 :where => m.channel.to_s
282 if idx = @factoids.index(factoid)
283 m.reply _("I already know that %{factoid} [#%{idx}]" % {
286 }) unless params[:silent]
290 m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last}) unless params[:silent]
291 trigs = parse_for_trigger(factoid)
292 @triggers |= trigs unless trigs.empty?
296 def forget(m, params)
298 idx = params[:index].scan(/\d+/).first.to_i
299 total = @factoids.length
300 if idx <= 0 or idx > total
301 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
304 if factoid = @factoids.delete_at(idx-1)
305 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
308 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
311 factoid = params[:stuff].to_s
312 if @factoids.delete(factoid)
316 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
321 def short_fact(fact,index=nil,total=@factoids.length)
322 idx = index || @factoids.index(fact)+1
323 _("[%{idx}/%{total}] %{fact}" % {
326 :fact => fact.to_s(:meta => false)
330 def long_fact(fact,index=nil,total=@factoids.length)
331 idx = index || @factoids.index(fact)+1
332 _("fact #%{idx} of %{total}: %{fact}" % {
335 :fact => fact.to_s(:meta => true)
340 # When looking for words we separate them with
341 # arbitrary whitespace, not whatever they came with
342 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
343 pre << '\b' if pre.match(/\b$/)
344 pre = '\b' + pre if pre.match(/^\b/)
345 return Regexp.new(pre, true)
349 total = @factoids.length
350 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
351 m.reply _("I know %{total} facts" % { :total => total })
353 unless params.key? :words and not params[:words].empty?
354 rx = Regexp.new(params[:rx].to_s, true)
356 rx = words2rx(params[:words])
358 known = @factoids.grep(rx)
361 if params.key? :words
362 reply << _("I know nothing about %{words}" % params)
364 reply << _("I know nothing matching %{rx}" % params)
367 max_facts = @bot.config['factoids.search_results']
370 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
373 :words => params[:words].to_s,
376 while known.length > max_facts
381 reply << short_fact(f)
384 m.reply reply.join(". "), :split_at => /\[\d+\/\d+\] /, :purge_split => false
389 if m.message =~ /^(.*)\?\s*$/
390 return if @bot.config['factoids.address'] and !m.address?
391 return if @factoids.empty?
392 return if @triggers.empty?
393 query = $1.strip.downcase
394 if @triggers.include?(query)
396 words.instance_variable_set(:@string_value, query)
400 facts(m, :words => words)
403 return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
404 return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
405 @learn_patterns.each do |pat, i|
406 g = pat.match(m.message)
408 learn(m, :stuff => g[i], :silent => @bot.config['factoids.silent_listen_and_learn'])
418 total = @factoids.length
420 idx = params[:index].scan(/\d+/).first.to_i
421 if idx <= 0 or idx > total
422 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
425 fact = @factoids[idx-1]
428 if params[:words].empty?
430 m.reply _("I know nothing")
435 rx = words2rx(params[:words])
436 known = @factoids.grep(rx)
438 m.reply _("I know nothing about %{words}" % params)
442 fact = known.pick_one
443 idx = @factoids.index(fact)+1
445 m.reply long_fact(fact, idx, total)
448 def edit_fact(m, params)
451 total = @factoids.length
452 idx = params[:index].scan(/\d+/).first.to_i
453 if idx <= 0 or idx > total
454 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
457 fact = @factoids[idx-1]
460 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
465 dstr = params[:when].to_s
467 fact[:when] = Time.parse(dstr, "")
470 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
474 fact[:where] = params[:where].to_s
478 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
487 def import(m, params)
488 fname = params[:filename].to_s
489 oldlen = @factoids.length
493 m.reply _("failed to import facts from %{fname}: %{err}" % {
498 m.reply _("%{len} facts loaded from %{fname}" % {
500 :len => @factoids.length - oldlen
507 plugin = FactoidsPlugin.new
509 plugin.default_auth('edit', false)
510 plugin.default_auth('import', false)
512 plugin.map 'learn that *stuff'
513 plugin.map 'forget that *stuff', :auth_path => 'edit'
514 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
515 plugin.map 'facts [about *words]'
516 plugin.map 'facts search *rx'
517 plugin.map 'fact [about *words]'
518 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
520 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
521 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
522 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
524 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'