]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/fortune.rb
467d452dffce28521da225d3b40425f813f6c033
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / fortune.rb
1 class FortunePlugin < Plugin
2   BotConfig.register BotConfigStringValue.new('fortune.path',
3     :default => '',
4     :desc => "Full path to the fortune executable")
5
6   def help(plugin, topic="")
7     "fortune [<category>] => get a (short) fortune, optionally specifying fortune category || fortune categories => show categories"
8   end
9
10
11   ## Pick a fortune
12   def fortune(m, params)
13     db = params[:db]
14     fortune = @bot.config['fortune.path']
15     if fortune.empty?
16       ["/usr/bin/fortune",
17        "/usr/share/bin/fortune",
18        "/usr/games/fortune",
19        "/usr/local/games/fortune",
20        "/usr/local/bin/fortune"].each do |f|
21           if FileTest.executable? f
22             fortune = f
23
24             # Try setting the config entry
25             config_par = {:key => 'fortune.path', :value => [f], :silent => true }
26             debug "Setting fortune.path to #{f}"
27             set_path = @bot.plugins['config'].handle_set(m, config_par)
28             if set_path
29               debug "fortune.path set to #{@bot.config['fortune.path']}"
30             else
31               debug "couldn't set fortune.path"
32             end
33
34             break
35           end
36         end
37     end
38     m.reply "fortune executable not found (try setting the 'fortune.path' variable)" unless fortune
39
40     begin
41       ret = Utils.safe_exec(fortune, "-n", "350", "-s", db)
42
43       ## cleanup ret
44       ret = ret.split(/\n+/).map do |l|
45         # check if this is a "  -- Some Dood" line
46         if l =~ /^\s+-{1,3}\s+\w/
47           # turn "-" into "--"
48           l.gsub!(/^\s+-\s/, '-- ')
49           # extra space
50           " " + l.strip
51         else
52           # just remove leading and trailing whitespace
53           l.strip
54         end
55       end.join(" ")
56
57     rescue
58       ret = "failed to execute fortune"
59       # TODO reset fortune.path when execution fails
60     end
61
62     m.reply ret
63   end
64
65
66   # Print the fortune categories
67   def categories(m, params)
68     ## list all fortune files in /usr/share/games/fortune
69     categories = Dir["/usr/share/games/fortune/*"].select{|f|File.split(f).last.match /^\w+$/}.select{|f|File.file? f}.map{|p|File.split(p).last}.sort
70     ## say 'em!
71     m.reply "Fortune categories: #{categories.join ', '}"
72   end
73  
74 end
75 plugin = FortunePlugin.new
76 plugin.map 'fortune categories', :action => "categories"
77 plugin.map 'fortune list', :action => "categories"
78 plugin.map 'fortune :db', :defaults => {:db => ''},
79                           :requirements => {:db => /^[^-][\w-]+$/}