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]
36 class FactoidList < ArrayOf
44 self.map { |f| f[:fact] }.index(fact)
64 @dir = File.join(@bot.botclass,"factoids")
65 @filename = "factoids.rbot"
66 @factoids = FactoidList.new
71 def read_factfile(name=@filename,dir=@dir)
72 fname = File.join(dir,name)
74 factoids = File.readlines(fname)
75 return if factoids.empty?
76 firstline = factoids.shift
77 pattern = firstline.chomp.split(" | ")
78 if pattern.length == 1 and pattern.first != "fact"
79 factoids.unshift(firstline)
81 @factoids << Factoid.new( :fact => f.chomp )
84 pattern.map! { |p| p.intern }
85 raise ArgumentError, "fact must be the last field" unless pattern.last == :fact
87 ar = f.chomp.split(" | ", pattern.length)
88 @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
95 return unless @changed
96 Dir.mkdir(@dir) unless FileTest.directory?(@dir)
97 fname = File.join(@dir,@filename)
98 ar = ["when | who | where | fact"]
100 ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
102 Utils.safe_save(fname) do |file|
108 def help(plugin, topic="")
109 _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
113 factoid = Factoid.new(
114 :fact => params[:stuff].to_s,
116 :who => m.source.fullform,
117 :where => m.channel.to_s
119 if @factoids.index(factoid)
120 m.reply _("I already know that %{factoid}" % { :factoid => factoid })
128 def forget(m, params)
129 factoid = params[:stuff].to_s
130 if @factoids.delete(factoid)
134 m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
139 if params[:words].empty?
140 m.reply _("I know %{count} facts" % { :count => @factoids.length })
142 rx = Regexp.new(params[:words].to_s, true)
143 known = @factoids.grep(rx)
145 m.reply _("I know nothing about %{words}" % params)
147 m.reply known.join(" | "), :split_at => /\s+\|\s+/
154 if params[:words].empty?
156 m.reply _("I know nothing")
161 rx = Regexp.new(params[:words].to_s, true)
162 known = @factoids.grep(rx)
164 m.reply _("I know nothing about %{words}" % params)
168 fact = known.pick_one
169 idx = @factoids.index(fact)+1
170 m.reply _("fact %{idx}/%{total}: %{fact}" % {
172 :total => @factoids.length,
179 plugin = FactoidsPlugin.new
180 plugin.map 'learn that *stuff'
181 plugin.map 'forget that *stuff'
182 plugin.map 'facts [about *words]'
183 plugin.map 'fact [about *words]'