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::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")
124 @filename = "factoids.rbot"
125 @factoids = FactoidList.new
137 def read_factfile(name=@filename,dir=@dir)
138 fname = File.join(dir,name)
140 expf = File.expand_path(fname)
141 expd = File.expand_path(dir)
142 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
146 }) unless expf.index(expd) == 0
148 if File.exist?(fname)
149 raise ArgumentError, _("%{name} is not a file" % {
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)
159 @factoids << Factoid.new( :fact => f.chomp )
162 pattern.map! { |p| p.intern }
163 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
165 ar = f.chomp.split(" | ", pattern.length)
166 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
170 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
179 return unless @changed
180 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
181 fname = File.join(@dir,@filename)
182 ar = ["when | who | where | fact"]
184 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
186 Utils.safe_save(fname) do |file|
192 def trigger_patterns_to_rx
193 return [] if @bot.config['factoids.trigger_pattern'].empty?
194 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
202 list << [/^#{s}$/iu, idx]
206 def learn_patterns_to_rx
207 return [] if @bot.config['factoids.learn_pattern'].empty?
208 @bot.config['factoids.learn_pattern'].inject([]) { |list, str|
216 list << [/^#{s}$/iu, idx]
220 def parse_for_trigger(f, rx=nil)
222 regs = trigger_patterns_to_rx
229 regs.inject([]) { |list, a|
234 list << m[i].downcase
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)
254 debug "Triggers done in #{Time.now - start_time}"
255 @triggers.replace(triggers - @bot.config['factoids.not_triggers'])
258 def reset_learn_patterns
259 @learn_patterns.replace(learn_patterns_to_rx)
262 def help(plugin, topic="")
263 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
267 factoid = Factoid.new(
268 :fact => params[:stuff].to_s,
270 :who => m.source.fullform,
271 :where => m.channel.to_s
273 if idx = @factoids.index(factoid)
274 m.reply _("I already know that %{factoid} [#%{idx}]" % {
277 }) unless params[:silent]
281 m.reply _("okay, learned fact #%{num}: %{fact}" % { :num => @factoids.length, :fact => @factoids.last}) unless params[:silent]
282 trigs = parse_for_trigger(factoid)
283 @triggers |= trigs unless trigs.empty?
287 def forget(m, params)
289 idx = params[:index].scan(/\d+/).first.to_i
290 total = @factoids.length
291 if idx <= 0 or idx > total
292 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
295 if factoid = @factoids.delete_at(idx-1)
296 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
299 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
302 factoid = params[:stuff].to_s
303 if @factoids.delete(factoid)
307 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
312 def short_fact(fact,index=nil,total=@factoids.length)
313 idx = index || @factoids.index(fact)+1
314 _("[%{idx}/%{total}] %{fact}" % {
317 :fact => fact.to_s(:meta => false)
321 def long_fact(fact,index=nil,total=@factoids.length)
322 idx = index || @factoids.index(fact)+1
323 _("fact #%{idx} of %{total}: %{fact}" % {
326 :fact => fact.to_s(:meta => true)
331 # When looking for words we separate them with
332 # arbitrary whitespace, not whatever they came with
333 pre = words.map { |w| Regexp.escape(w)}.join("\\s+")
334 pre << '\b' if pre.match(/\b$/)
335 pre = '\b' + pre if pre.match(/^\b/)
336 return Regexp.new(pre, true)
340 total = @factoids.length
341 if params[:words].nil_or_empty? and params[:rx].nil_or_empty?
342 m.reply _("I know %{total} facts" % { :total => total })
344 unless params.key? :words and not params[:words].empty?
345 rx = Regexp.new(params[:rx].to_s, true)
347 rx = words2rx(params[:words])
349 known = @factoids.grep(rx)
352 if params.key? :words
353 reply << _("I know nothing about %{words}" % params)
355 reply << _("I know nothing matching %{rx}" % params)
358 max_facts = @bot.config['factoids.search_results']
361 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
364 :words => params[:words].to_s,
367 while known.length > max_facts
372 reply << short_fact(f)
375 m.reply reply.join(". "), :split_at => /\[\d+\/\d+\] /, :purge_split => false
380 if m.message =~ /^(.*)\?\s*$/
381 return if @bot.config['factoids.address'] and !m.address?
382 return if @factoids.empty?
383 return if @triggers.empty?
384 query = $1.strip.downcase
385 if @triggers.include?(query)
387 words.instance_variable_set(:@string_value, query)
391 facts(m, :words => words)
394 return if m.address? # we don't learn stuff directed at us which is not an explicit learn command
395 return if !@bot.config['factoids.listen_and_learn'] or @learn_patterns.empty?
396 @learn_patterns.each do |pat, i|
397 g = pat.match(m.message)
399 learn(m, :stuff => g[i], :silent => @bot.config['factoids.silent_listen_and_learn'])
409 total = @factoids.length
411 idx = params[:index].scan(/\d+/).first.to_i
412 if idx <= 0 or idx > total
413 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
416 fact = @factoids[idx-1]
419 if params[:words].empty?
421 m.reply _("I know nothing")
426 rx = words2rx(params[:words])
427 known = @factoids.grep(rx)
429 m.reply _("I know nothing about %{words}" % params)
433 fact = known.pick_one
434 idx = @factoids.index(fact)+1
436 m.reply long_fact(fact, idx, total)
439 def edit_fact(m, params)
442 total = @factoids.length
443 idx = params[:index].scan(/\d+/).first.to_i
444 if idx <= 0 or idx > total
445 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
448 fact = @factoids[idx-1]
451 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
456 dstr = params[:when].to_s
458 fact[:when] = Time.parse(dstr, "")
461 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
465 fact[:where] = params[:where].to_s
469 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
478 def import(m, params)
479 fname = params[:filename].to_s
480 oldlen = @factoids.length
484 m.reply _("failed to import facts from %{fname}: %{err}" % {
489 m.reply _("%{len} facts loaded from %{fname}" % {
491 :len => @factoids.length - oldlen
498 plugin = FactoidsPlugin.new
500 plugin.default_auth('edit', false)
501 plugin.default_auth('import', false)
503 plugin.map 'learn that *stuff'
504 plugin.map 'forget that *stuff', :auth_path => 'edit'
505 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
506 plugin.map 'facts [about *words]'
507 plugin.map 'facts search *rx'
508 plugin.map 'fact [about *words]'
509 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
511 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
512 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
513 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
515 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'