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")
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 @bot.config['factoids.trigger_pattern'].inject([]) { |list, str|
178 list << [/^#{s}$/iu, idx]
182 def parse_for_trigger(f, rx=nil)
184 regs = trigger_patterns_to_rx
188 regs.inject([]) { |list, a|
193 list << m[i].downcase
201 start_time = Time.now
202 rx = trigger_patterns_to_rx
203 triggers = @factoids.inject(Set.new) { |set, f|
204 found = parse_for_trigger(f, rx)
211 debug "Triggers done in #{Time.now - start_time}"
212 @triggers.replace(triggers)
215 def help(plugin, topic="")
216 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
220 factoid = Factoid.new(
221 :fact => params[:stuff].to_s,
223 :who => m.source.fullform,
224 :where => m.channel.to_s
226 if idx = @factoids.index(factoid)
227 m.reply _("I already know that %{factoid} [#%{idx}]" % {
235 fact(m, :index => @factoids.length.to_s)
236 parse_for_trigger(factoid)
240 def forget(m, params)
242 idx = params[:index].scan(/\d+/).first.to_i
243 total = @factoids.length
244 if idx <= 0 or idx > total
245 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
248 if factoid = @factoids.delete_at(idx-1)
249 m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
252 m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
255 factoid = params[:stuff].to_s
256 if @factoids.delete(factoid)
260 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
265 def long_fact(fact,index=nil,total=@factoids.length)
266 idx = index || @factoids.index(fact)+1
267 _("fact #%{idx} of %{total}: %{fact}" % {
270 :fact => fact.to_s(:meta => true)
275 total = @factoids.length
276 if params[:words].empty?
277 m.reply _("I know %{total} facts" % { :total => total })
279 rx = Regexp.new(params[:words].to_s, true)
280 known = @factoids.grep(rx)
283 reply << _("I know nothing about %{words}" % params)
289 m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
292 :words => params[:words].to_s,
295 while known.length > max_facts
300 reply << long_fact(f)
303 m.reply reply.join(" -- ")
308 return if @bot.config['factoids.address'] and !m.address?
309 return if @factoids.empty?
310 return if @triggers.empty?
311 return unless m.message =~ /^(.*)\?\s*$/
312 query = $1.strip.downcase
313 if @triggers.include?(query)
314 facts(m, :words => query)
321 total = @factoids.length
323 idx = params[:index].scan(/\d+/).first.to_i
324 if idx <= 0 or idx > total
325 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
328 fact = @factoids[idx-1]
331 if params[:words].empty?
333 m.reply _("I know nothing")
338 rx = Regexp.new(params[:words].to_s, true)
339 known = @factoids.grep(rx)
341 m.reply _("I know nothing about %{words}" % params)
345 fact = known.pick_one
346 idx = @factoids.index(fact)+1
348 m.reply long_fact(fact, idx, total)
351 def edit_fact(m, params)
354 total = @factoids.length
355 idx = params[:index].scan(/\d+/).first.to_i
356 if idx <= 0 or idx > total
357 m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
360 fact = @factoids[idx-1]
363 who = params[:who].to_s.sub(/^me$/, m.source.fullform)
368 dstr = params[:when].to_s
370 fact[:when] = Time.parse(dstr, "")
373 raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
377 fact[:where] = params[:where].to_s
381 m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
390 def import(m, params)
391 fname = params[:filename].to_s
392 oldlen = @factoids.length
396 m.reply _("failed to import facts from %{fname}: %{err}" % {
401 m.reply _("%{len} facts loaded from %{fname}" % {
403 :len => @factoids.length - oldlen
410 plugin = FactoidsPlugin.new
412 plugin.default_auth('edit', false)
413 plugin.default_auth('import', false)
415 plugin.map 'learn that *stuff'
416 plugin.map 'forget that *stuff', :auth_path => 'edit'
417 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
418 plugin.map 'facts [about *words]'
419 plugin.map 'fact [about *words]'
420 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
422 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
423 plugin.map 'fact :index :learn on *when', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
424 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
426 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'