]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
factoids plugin: actually output metadata in long form of Factoid#to_s
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / factoids.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Factoids pluing
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
8 # License:: GPLv2
9 #
10 # Store (and retrieve) unstructured one-sentence factoids
11
12 class FactoidsPlugin < Plugin
13
14   class Factoid
15     def initialize(hash)
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]
20       end
21     end
22
23     def to_s(opts={})
24       show_meta = opts[:meta]
25       fact = @hash[:fact]
26       if !show_meta
27         return fact
28       end
29       meta = ""
30       metadata = []
31       if @hash[:who]
32         metadata << _("from %{who}" % @hash)
33       end
34       if @hash[:when]
35         metadata << _("on %{when}" % @hash)
36       end
37       if @hash[:where]
38         metadata << _("in %{where}" % @hash)
39       end
40       unless metadata.empty?
41         meta << _(" [learnt %{data}]" % {:data => metadata.join(" ")})
42       end
43       return fact+meta
44     end
45
46     def [](*args)
47       @hash[*args]
48     end
49
50     def []=(*args)
51       @hash.send(:[]=,*args)
52     end
53
54     def to_hsh
55       return @hash
56     end
57     alias :to_hash :to_hsh
58   end
59
60   class FactoidList < ArrayOf
61     def initialize(ar=[])
62       super(Factoid, ar)
63     end
64
65     def index(f)
66       fact = f.to_s
67       return if fact.empty?
68       self.map { |f| f[:fact] }.index(fact)
69     end
70
71     def delete(f)
72       idx = index(f)
73       return unless idx
74       self.delete_at(idx)
75     end
76
77     def grep(x)
78       self.find_all { |f|
79         x === f[:fact]
80       }
81     end
82   end
83
84   def initialize
85     super
86
87     # TODO config
88     @dir = File.join(@bot.botclass,"factoids")
89     @filename = "factoids.rbot"
90     @factoids = FactoidList.new
91     begin
92       read_factfile
93     rescue
94       debug $!
95     end
96     @changed = false
97   end
98
99   def read_factfile(name=@filename,dir=@dir)
100     fname = File.join(dir,name)
101
102     expf = File.expand_path(fname)
103     expd = File.expand_path(dir)
104     raise ArgumentError, _("%{name} (%{fname}) must be under %{dir}" % {
105       :name => name,
106       :fname => expf,
107       :dir => dir
108     }) unless expf.index(expd) == 0
109
110     if File.exist?(fname)
111       raise ArgumentError, _("%{name} is not a file" % {
112         :name => name
113       }) unless File.file?(fname)
114       factoids = File.readlines(fname)
115       return if factoids.empty?
116       firstline = factoids.shift
117       pattern = firstline.chomp.split(" | ")
118       if pattern.length == 1 and pattern.first != "fact"
119         factoids.unshift(firstline)
120         factoids.each { |f|
121           @factoids << Factoid.new( :fact => f.chomp )
122         }
123       else
124         pattern.map! { |p| p.intern }
125         raise ArgumentError, _("fact must be the last field") unless pattern.last == :fact
126         factoids.each { |f|
127           ar = f.chomp.split(" | ", pattern.length)
128           @factoids << Factoid.new(Hash[*([pattern, ar].transpose.flatten)])
129         }
130       end
131     else
132       raise ArgumentError, _("%{name} (%{fname}) doesn't exist" % {
133         :name => name,
134         :fname => fname
135       })
136     end
137   end
138
139   def save
140     return unless @changed
141     Dir.mkdir(@dir) unless FileTest.directory?(@dir)
142     fname = File.join(@dir,@filename)
143     ar = ["when | who | where | fact"]
144     @factoids.each { |f|
145       ar << "%s | %s | %s | %s" % [ f[:when], f[:who], f[:where], f[:fact]]
146     }
147     Utils.safe_save(fname) do |file|
148       file.puts ar
149     end
150     @changed = false
151   end
152
153   def help(plugin, topic="")
154     _("factoids plugin: learn that <factoid>, forget that <factoids>, facts about <words>")
155   end
156
157   def learn(m, params)
158     factoid = Factoid.new(
159       :fact => params[:stuff].to_s,
160       :when => Time.now,
161       :who => m.source.fullform,
162       :where => m.channel.to_s
163     )
164     if @factoids.index(factoid)
165       m.reply _("I already know that %{factoid}" % { :factoid => factoid })
166     else
167       @factoids << factoid
168       @changed = true
169       m.okay
170     end
171   end
172
173   def forget(m, params)
174     if params[:index]
175       idx = params[:index].scan(/\d+/).first.to_i
176       total = @factoids.length
177       if idx <= 0 or idx > total
178         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
179         return
180       end
181       if factoid = @factoids.delete_at(idx-1)
182         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
183         @changed = true
184       else
185         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
186       end
187     else
188       factoid = params[:stuff].to_s
189       if @factoids.delete(factoid)
190         @changed = true
191         m.okay
192       else
193         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
194       end
195     end
196   end
197
198   def long_fact(fact,index=nil,total=@factoids.length)
199     idx = index || @factoids.index(fact)+1
200     _("fact #%{idx} of %{total}: %{fact}" % {
201       :idx => idx,
202       :total => total,
203       :fact => fact.to_s(:meta => true)
204     })
205   end
206
207   def facts(m, params)
208     total = @factoids.length
209     if params[:words].empty?
210       m.reply _("I know %{total} facts" % { :total => total })
211     else
212       rx = Regexp.new(params[:words].to_s, true)
213       known = @factoids.grep(rx)
214       reply = []
215       if known.empty?
216         reply << _("I know nothing about %{words}" % params)
217       else
218         # TODO config
219         max_facts = 5
220         len = known.length
221         if len > max_facts
222           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
223             :len => len,
224             :total => total,
225             :words => params[:words].to_s,
226             :max => max_facts
227           })
228           while known.length > max_facts
229             known.delete_one
230           end
231         end
232         known.each { |f|
233           reply << long_fact(f)
234         }
235       end
236       m.reply reply.join(" -- ")
237     end
238   end
239
240   def fact(m, params)
241     fact = nil
242     idx = 0
243     total = @factoids.length
244     if params[:index]
245       idx = params[:index].scan(/\d+/).first.to_i
246       if idx <= 0 or idx > total
247         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
248         return
249       end
250       fact = @factoids[idx-1]
251     else
252       known = nil
253       if params[:words].empty?
254         if @factoids.empty?
255           m.reply _("I know nothing")
256           return
257         end
258         known = @factoids
259       else
260         rx = Regexp.new(params[:words].to_s, true)
261         known = @factoids.grep(rx)
262         if known.empty?
263           m.reply _("I know nothing about %{words}" % params)
264           return
265         end
266       end
267       fact = known.pick_one
268       idx = @factoids.index(fact)+1
269     end
270     m.reply long_fact(fact, idx, total)
271   end
272
273   def edit_fact(m, params)
274     fact = nil
275     idx = 0
276     total = @factoids.length
277     idx = params[:index].scan(/\d+/).first.to_i
278     if idx <= 0 or idx > total
279       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
280       return
281     end
282     fact = @factoids[idx-1]
283     begin
284       if params[:who]
285         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
286         fact[:who] = who
287         @changed = true
288       end
289       if params[:when]
290         dstr = params[:when].to_s
291         begin
292           fact[:when] = Time.parse(dstr, "")
293           @changed = true
294         rescue
295           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
296         end
297       end
298       if params[:where]
299         fact[:where] = params[:where].to_s
300         @changed = true
301       end
302     rescue Exception
303       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
304         :fact => fact,
305         :err => $!
306       })
307       return
308     end
309     m.okay
310   end
311
312   def import(m, params)
313     fname = params[:filename].to_s
314     oldlen = @factoids.length
315     begin
316       read_factfile(fname)
317     rescue
318       m.reply _("failed to import facts from %{fname}: %{err}" % {
319         :fname => fname,
320         :err => $!
321       })
322     end
323     m.reply _("%{len} facts loaded from %{fname}" % {
324       :fname => fname,
325       :len => @factoids.length - oldlen
326     })
327     @changed = true
328   end
329
330 end
331
332 plugin = FactoidsPlugin.new
333
334 plugin.default_auth('edit', false)
335 plugin.default_auth('import', false)
336
337 plugin.map 'learn that *stuff'
338 plugin.map 'forget that *stuff', :auth_path => 'edit'
339 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
340 plugin.map 'facts [about *words]'
341 plugin.map 'fact [about *words]'
342 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
343
344 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
345 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
346 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
347
348 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'