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