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)\\s+.*:2",
88 "(this|that|a|the|an|all|both)\\s+(.*?)\\s+(is|are)\\s+.*:2",
89 "(.*)\\s+(is|are)\\s+.*",
90 "(.*?)\\s+(is|are)\\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::IntegerValue.new('factoids.search_results',
99 :desc => "How many factoids to display at a time")
105 @dir = File.join(@bot.botclass,"factoids")
106 @filename = "factoids.rbot"
107 @factoids = FactoidList.new
117 def read_factfile(name=@filename,dir=@dir)
118 fname = File.join(dir,name)
120 expf = File.expand_path(fname)
121 expd = File.expand_path(dir)
122 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
126 }) unless expf.index(expd) == 0
128 if File.exist?(fname)
129 raise ArgumentError, _("%{name} is not a file" % {
131 }) unless File.file?(fname)
132 factoids = File.readlines(fname)
133 return if factoids.empty?
134 firstline = factoids.shift
135 pattern = firstline.chomp.split(" | ")
136 if pattern.length == 1 and pattern.first != "fact"
137 factoids.unshift(firstline)
139 @factoids << Factoid.new( :fact => f.chomp )
142 pattern.map! { |p| p.intern }
143 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
145 ar = f.chomp.split(" | ", pattern.length)
146 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
150 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
159 return unless @changed
160 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
161 fname = File.join(@dir,@filename)
162 ar = ["when | who | where | fact"]
164 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
166 Utils.safe_save(fname) do |file|
172 def trigger_patterns_to_rx
173 return [] if @bot.config['factoids.trigger_pattern'].empty?
174 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
182 list << [/^#{s}$/iu, idx]
186 def parse_for_trigger(f, rx=nil)
188 regs = trigger_patterns_to_rx
195 regs.inject([]) { |list, a|
200 list << m[i].downcase
209 return unless @factoids
210 start_time = Time.now
211 rx = trigger_patterns_to_rx
212 triggers = @factoids.inject(Set.new) { |set, f|
213 found = parse_for_trigger(f, rx)
220 debug "Triggers done in #{Time.now - start_time}"
221 @triggers.replace(triggers)
224 def help(plugin, topic="")
225 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
229 factoid = Factoid.new(
230 :fact => params[:stuff].to_s,
232 :who => m.source.fullform,
233 :where => m.channel.to_s
235 if idx = @factoids.index(factoid)
236 m.reply _("I already know that %{factoid} [#%{idx}]" % {
244 fact(m, :index => @factoids.length.to_s)
245 parse_for_trigger(factoid)
249 def forget(m, params)
251 idx = params[:index].scan(/\d+/).first.to_i
252 total = @factoids.length
253 if idx <= 0 or idx > total
254 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
257 if factoid = @factoids.delete_at(idx-1)
258 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
261 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
264 factoid = params[:stuff].to_s
265 if @factoids.delete(factoid)
269 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
274 def long_fact(fact,index=nil,total=@factoids.length)
275 idx = index || @factoids.index(fact)+1
276 _("fact #%{idx} of %{total}: %{fact}" % {
279 :fact => fact.to_s(:meta => true)
284 total = @factoids.length
285 if params[:words].empty?
286 m.reply _("I know %{total} facts" % { :total => total })
288 rx = Regexp.new(params[:words].to_s, true)
289 known = @factoids.grep(rx)
292 reply << _("I know nothing about %{words}" % params)
294 max_facts = @bot.config['factoids.search_results']
297 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
300 :words => params[:words].to_s,
303 while known.length > max_facts
308 reply << long_fact(f)
311 m.reply reply.join(" -- ")
316 return if @bot.config['factoids.address'] and !m.address?
317 return if @factoids.empty?
318 return if @triggers.empty?
319 return unless m.message =~ /^(.*)\?\s*$/
320 query = $1.strip.downcase
321 if @triggers.include?(query)
322 facts(m, :words => query)
329 total = @factoids.length
331 idx = params[:index].scan(/\d+/).first.to_i
332 if idx <= 0 or idx > total
333 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
336 fact = @factoids[idx-1]
339 if params[:words].empty?
341 m.reply _("I know nothing")
346 rx = Regexp.new(params[:words].to_s, true)
347 known = @factoids.grep(rx)
349 m.reply _("I know nothing about %{words}" % params)
353 fact = known.pick_one
354 idx = @factoids.index(fact)+1
356 m.reply long_fact(fact, idx, total)
359 def edit_fact(m, params)
362 total = @factoids.length
363 idx = params[:index].scan(/\d+/).first.to_i
364 if idx <= 0 or idx > total
365 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
368 fact = @factoids[idx-1]
371 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
376 dstr = params[:when].to_s
378 fact[:when] = Time.parse(dstr, "")
381 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
385 fact[:where] = params[:where].to_s
389 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
398 def import(m, params)
399 fname = params[:filename].to_s
400 oldlen = @factoids.length
404 m.reply _("failed to import facts from %{fname}: %{err}" % {
409 m.reply _("%{len} facts loaded from %{fname}" % {
411 :len => @factoids.length - oldlen
418 plugin = FactoidsPlugin.new
420 plugin.default_auth('edit', false)
421 plugin.default_auth('import', false)
423 plugin.map 'learn that *stuff'
424 plugin.map 'forget that *stuff', :auth_path => 'edit'
425 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
426 plugin.map 'facts [about *words]'
427 plugin.map 'fact [about *words]'
428 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
430 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
431 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
432 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
434 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'