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")
99 @dir = File.join(@bot.botclass,"factoids")
100 @filename = "factoids.rbot"
101 @factoids = FactoidList.new
111 def read_factfile(name=@filename,dir=@dir)
112 fname = File.join(dir,name)
114 expf = File.expand_path(fname)
115 expd = File.expand_path(dir)
116 raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
120 }) unless expf.index(expd) == 0
122 if File.exist?(fname)
123 raise ArgumentError, _("%{name} is not a file" % {
125 }) unless File.file?(fname)
126 factoids = File.readlines(fname)
127 return if factoids.empty?
128 firstline = factoids.shift
129 pattern = firstline.chomp.split(" | ")
130 if pattern.length == 1 and pattern.first != "fact"
131 factoids.unshift(firstline)
133 @factoids << Factoid.new( :fact => f.chomp )
136 pattern.map! { |p| p.intern }
137 raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
139 ar = f.chomp.split(" | ", pattern.length)
140 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
144 raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
153 return unless @changed
154 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
155 fname = File.join(@dir,@filename)
156 ar = ["when | who | where | fact"]
158 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
160 Utils.safe_save(fname) do |file|
166 def trigger_patterns_to_rx
167 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
175 list << [/^#{s}$/iu, idx]
179 def parse_for_trigger(f, rx=nil)
181 regs = trigger_patterns_to_rx
185 regs.inject([]) { |list, a|
198 start_time = Time.now
199 rx = trigger_patterns_to_rx
200 triggers = @factoids.inject(Set.new) { |set, f|
201 found = parse_for_trigger(f, rx)
208 debug "Triggers done in #{Time.now - start_time}"
209 @triggers.replace(triggers)
212 def help(plugin, topic="")
213 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
217 factoid = Factoid.new(
218 :fact => params[:stuff].to_s,
220 :who => m.source.fullform,
221 :where => m.channel.to_s
223 if idx = @factoids.index(factoid)
224 m.reply _("I already know that %{factoid} [#%{idx}]" % {
232 fact(m, :index => @factoids.length.to_s)
233 parse_for_trigger(factoid)
237 def forget(m, params)
239 idx = params[:index].scan(/\d+/).first.to_i
240 total = @factoids.length
241 if idx <= 0 or idx > total
242 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
245 if factoid = @factoids.delete_at(idx-1)
246 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
249 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
252 factoid = params[:stuff].to_s
253 if @factoids.delete(factoid)
257 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
262 def long_fact(fact,index=nil,total=@factoids.length)
263 idx = index || @factoids.index(fact)+1
264 _("fact #%{idx} of %{total}: %{fact}" % {
267 :fact => fact.to_s(:meta => true)
272 total = @factoids.length
273 if params[:words].empty?
274 m.reply _("I know %{total} facts" % { :total => total })
276 rx = Regexp.new(params[:words].to_s, true)
277 known = @factoids.grep(rx)
280 reply << _("I know nothing about %{words}" % params)
286 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
289 :words => params[:words].to_s,
292 while known.length > max_facts
297 reply << long_fact(f)
300 m.reply reply.join(" -- ")
307 total = @factoids.length
309 idx = params[:index].scan(/\d+/).first.to_i
310 if idx <= 0 or idx > total
311 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
314 fact = @factoids[idx-1]
317 if params[:words].empty?
319 m.reply _("I know nothing")
324 rx = Regexp.new(params[:words].to_s, true)
325 known = @factoids.grep(rx)
327 m.reply _("I know nothing about %{words}" % params)
331 fact = known.pick_one
332 idx = @factoids.index(fact)+1
334 m.reply long_fact(fact, idx, total)
337 def edit_fact(m, params)
340 total = @factoids.length
341 idx = params[:index].scan(/\d+/).first.to_i
342 if idx <= 0 or idx > total
343 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
346 fact = @factoids[idx-1]
349 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
354 dstr = params[:when].to_s
356 fact[:when] = Time.parse(dstr, "")
359 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
363 fact[:where] = params[:where].to_s
367 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
376 def import(m, params)
377 fname = params[:filename].to_s
378 oldlen = @factoids.length
382 m.reply _("failed to import facts from %{fname}: %{err}" % {
387 m.reply _("%{len} facts loaded from %{fname}" % {
389 :len => @factoids.length - oldlen
396 plugin = FactoidsPlugin.new
398 plugin.default_auth('edit', false)
399 plugin.default_auth('import', false)
401 plugin.map 'learn that *stuff'
402 plugin.map 'forget that *stuff', :auth_path => 'edit'
403 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
404 plugin.map 'facts [about *words]'
405 plugin.map 'fact [about *words]'
406 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
408 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
409 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
410 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
412 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'