]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/factoids.rb
factoids plugin: echo the newly learned fact
[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 << _(" [%{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 idx = @factoids.index(factoid)
165       m.reply _("I already know that %{factoid} [#%{idx}]" % {
166         :factoid => factoid,
167         :idx => idx
168       })
169     else
170       @factoids << factoid
171       @changed = true
172       m.okay
173       fact(m, :index => @factoids.length.to_s)
174     end
175   end
176
177   def forget(m, params)
178     if params[:index]
179       idx = params[:index].scan(/\d+/).first.to_i
180       total = @factoids.length
181       if idx <= 0 or idx > total
182         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
183         return
184       end
185       if factoid = @factoids.delete_at(idx-1)
186         m.reply _("I forgot that %{factoid}" % { :factoid => factoid })
187         @changed = true
188       else
189         m.reply _("I couldn't delete factoid %{idx}" % { :idx => idx })
190       end
191     else
192       factoid = params[:stuff].to_s
193       if @factoids.delete(factoid)
194         @changed = true
195         m.okay
196       else
197         m.reply _("I didn't know that %{factoid}" % { :factoid => factoid })
198       end
199     end
200   end
201
202   def long_fact(fact,index=nil,total=@factoids.length)
203     idx = index || @factoids.index(fact)+1
204     _("fact #%{idx} of %{total}: %{fact}" % {
205       :idx => idx,
206       :total => total,
207       :fact => fact.to_s(:meta => true)
208     })
209   end
210
211   def facts(m, params)
212     total = @factoids.length
213     if params[:words].empty?
214       m.reply _("I know %{total} facts" % { :total => total })
215     else
216       rx = Regexp.new(params[:words].to_s, true)
217       known = @factoids.grep(rx)
218       reply = []
219       if known.empty?
220         reply << _("I know nothing about %{words}" % params)
221       else
222         # TODO config
223         max_facts = 5
224         len = known.length
225         if len > max_facts
226           m.reply _("%{len} out of %{total} facts refer to %{words}, I'll only show %{max}" % {
227             :len => len,
228             :total => total,
229             :words => params[:words].to_s,
230             :max => max_facts
231           })
232           while known.length > max_facts
233             known.delete_one
234           end
235         end
236         known.each { |f|
237           reply << long_fact(f)
238         }
239       end
240       m.reply reply.join(" -- ")
241     end
242   end
243
244   def fact(m, params)
245     fact = nil
246     idx = 0
247     total = @factoids.length
248     if params[:index]
249       idx = params[:index].scan(/\d+/).first.to_i
250       if idx <= 0 or idx > total
251         m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
252         return
253       end
254       fact = @factoids[idx-1]
255     else
256       known = nil
257       if params[:words].empty?
258         if @factoids.empty?
259           m.reply _("I know nothing")
260           return
261         end
262         known = @factoids
263       else
264         rx = Regexp.new(params[:words].to_s, true)
265         known = @factoids.grep(rx)
266         if known.empty?
267           m.reply _("I know nothing about %{words}" % params)
268           return
269         end
270       end
271       fact = known.pick_one
272       idx = @factoids.index(fact)+1
273     end
274     m.reply long_fact(fact, idx, total)
275   end
276
277   def edit_fact(m, params)
278     fact = nil
279     idx = 0
280     total = @factoids.length
281     idx = params[:index].scan(/\d+/).first.to_i
282     if idx <= 0 or idx > total
283       m.reply _("please select a fact number between 1 and %{total}" % { :total => total })
284       return
285     end
286     fact = @factoids[idx-1]
287     begin
288       if params[:who]
289         who = params[:who].to_s.sub(/^me$/, m.source.fullform)
290         fact[:who] = who
291         @changed = true
292       end
293       if params[:when]
294         dstr = params[:when].to_s
295         begin
296           fact[:when] = Time.parse(dstr, "")
297           @changed = true
298         rescue
299           raise ArgumentError, _("not a date '%{dstr}'" % { :dstr => dstr })
300         end
301       end
302       if params[:where]
303         fact[:where] = params[:where].to_s
304         @changed = true
305       end
306     rescue Exception
307       m.reply _("couldn't change learn data for fact %{fact}: %{err}" % {
308         :fact => fact,
309         :err => $!
310       })
311       return
312     end
313     m.okay
314   end
315
316   def import(m, params)
317     fname = params[:filename].to_s
318     oldlen = @factoids.length
319     begin
320       read_factfile(fname)
321     rescue
322       m.reply _("failed to import facts from %{fname}: %{err}" % {
323         :fname => fname,
324         :err => $!
325       })
326     end
327     m.reply _("%{len} facts loaded from %{fname}" % {
328       :fname => fname,
329       :len => @factoids.length - oldlen
330     })
331     @changed = true
332   end
333
334 end
335
336 plugin = FactoidsPlugin.new
337
338 plugin.default_auth('edit', false)
339 plugin.default_auth('import', false)
340
341 plugin.map 'learn that *stuff'
342 plugin.map 'forget that *stuff', :auth_path => 'edit'
343 plugin.map 'forget fact :index', :requirements => { :index => /^#?\d+$/ }, :auth_path => 'edit'
344 plugin.map 'facts [about *words]'
345 plugin.map 'fact [about *words]'
346 plugin.map 'fact :index', :requirements => { :index => /^#?\d+$/ }
347
348 plugin.map 'fact :index :learn from *who', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
349 plugin.map 'fact :index :learn on *when',  :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
350 plugin.map 'fact :index :learn in *where', :action => :edit_fact, :requirements => { :learn => /^((?:is|was)\s+)?learn(ed|t)$/, :index => /^#?\d+$/ }, :auth_path => 'edit'
351
352 plugin.map 'facts import [from] *filename', :action => :import, :auth_path => 'import'