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")
102 @dir = File.join(@bot.botclass,"factoids")
103 @filename = "factoids.rbot"
104 @factoids = FactoidList.new
114 def read_factfile(name=@filename,dir=@dir)
115 fname = File.join(dir,name)
117 expf = File.expand_path(fname)
118 expd = File.expand_path(dir)
119 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
123 }) unless expf.index(expd) == 0
125 if File.exist?(fname)
126 raise ArgumentError, _("%{name} is not a file" % {
128 }) unless File.file?(fname)
129 factoids = File.readlines(fname)
130 return if factoids.empty?
131 firstline = factoids.shift
132 pattern = firstline.chomp.split(" | ")
133 if pattern.length == 1 and pattern.first != "fact"
134 factoids.unshift(firstline)
136 @factoids << Factoid.new( :fact => f.chomp )
139 pattern.map! { |p| p.intern }
140 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
142 ar = f.chomp.split(" | ", pattern.length)
143 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
147 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
156 return unless @changed
157 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
158 fname = File.join(@dir,@filename)
159 ar = ["when | who | where | fact"]
161 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
163 Utils.safe_save(fname) do |file|
169 def trigger_patterns_to_rx
170 return [] if @bot.config['factoids.trigger_pattern'].empty?
171 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
179 list << [/^#{s}$/iu, idx]
183 def parse_for_trigger(f, rx=nil)
185 regs = trigger_patterns_to_rx
192 regs.inject([]) { |list, a|
197 list << m[i].downcase
206 return unless @factoids
207 start_time = Time.now
208 rx = trigger_patterns_to_rx
209 triggers = @factoids.inject(Set.new) { |set, f|
210 found = parse_for_trigger(f, rx)
217 debug "Triggers done in #{Time.now - start_time}"
218 @triggers.replace(triggers)
221 def help(plugin, topic="")
222 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
226 factoid = Factoid.new(
227 :fact => params[:stuff].to_s,
229 :who => m.source.fullform,
230 :where => m.channel.to_s
232 if idx = @factoids.index(factoid)
233 m.reply _("I already know that %{factoid} [#%{idx}]" % {
241 fact(m, :index => @factoids.length.to_s)
242 parse_for_trigger(factoid)
246 def forget(m, params)
248 idx = params[:index].scan(/\d+/).first.to_i
249 total = @factoids.length
250 if idx <= 0 or idx > total
251 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
254 if factoid = @factoids.delete_at(idx-1)
255 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
258 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
261 factoid = params[:stuff].to_s
262 if @factoids.delete(factoid)
266 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
271 def long_fact(fact,index=nil,total=@factoids.length)
272 idx = index || @factoids.index(fact)+1
273 _("fact #%{idx} of %{total}: %{fact}" % {
276 :fact => fact.to_s(:meta => true)
281 total = @factoids.length
282 if params[:words].empty?
283 m.reply _("I know %{total} facts" % { :total => total })
285 rx = Regexp.new(params[:words].to_s, true)
286 known = @factoids.grep(rx)
289 reply << _("I know nothing about %{words}" % params)
295 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
298 :words => params[:words].to_s,
301 while known.length > max_facts
306 reply << long_fact(f)
309 m.reply reply.join(" -- ")
314 return if @bot.config['factoids.address'] and !m.address?
315 return if @factoids.empty?
316 return if @triggers.empty?
317 return unless m.message =~ /^(.*)\?\s*$/
318 query = $1.strip.downcase
319 if @triggers.include?(query)
320 facts(m, :words => query)
327 total = @factoids.length
329 idx = params[:index].scan(/\d+/).first.to_i
330 if idx <= 0 or idx > total
331 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
334 fact = @factoids[idx-1]
337 if params[:words].empty?
339 m.reply _("I know nothing")
344 rx = Regexp.new(params[:words].to_s, true)
345 known = @factoids.grep(rx)
347 m.reply _("I know nothing about %{words}" % params)
351 fact = known.pick_one
352 idx = @factoids.index(fact)+1
354 m.reply long_fact(fact, idx, total)
357 def edit_fact(m, params)
360 total = @factoids.length
361 idx = params[:index].scan(/\d+/).first.to_i
362 if idx <= 0 or idx > total
363 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
366 fact = @factoids[idx-1]
369 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
374 dstr = params[:when].to_s
376 fact[:when] = Time.parse(dstr, "")
379 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
383 fact[:where] = params[:where].to_s
387 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
396 def import(m, params)
397 fname = params[:filename].to_s
398 oldlen = @factoids.length
402 m.reply _("failed to import facts from %{fname}: %{err}" % {
407 m.reply _("%{len} facts loaded from %{fname}" % {
409 :len => @factoids.length - oldlen
416 plugin = FactoidsPlugin.new
418 plugin.default_auth('edit', false)
419 plugin.default_auth('import', false)
421 plugin.map 'learn that *stuff'
422 plugin.map 'forget that *stuff', :auth_path => 'edit'
423 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
424 plugin.map 'facts [about *words]'
425 plugin.map 'fact [about *words]'
426 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
428 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
429 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
430 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
432 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'