quiz plugin: don't crash when the answer is entirely made of sepators
[rbot] / 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 [<module>] => get a (short) fortune, optionally specifying fortune db"
8   end
9   def fortune(m, params)
10     db = params[:db]
11     fortune = @bot.config['fortune.path']
12     if fortune.empty?
13       ["/usr/share/games/fortune",
14        "/usr/share/bin/fortune",
15        "/usr/games/fortune",
16        "/usr/bin/fortune",
17        "/usr/local/games/fortune",
18        "/usr/local/bin/fortune"].each {|f|
19           if FileTest.executable? f
20             fortune = f
21
22             # Try setting the config entry
23             config_par = {:key => 'fortune.path', :value => [f], :silent => true }
24             debug "Setting fortune.path to #{f}"
25             set_path = @bot.plugins['config'].handle_set(m, config_par)
26             if set_path
27               debug "fortune.path set to #{@bot.config['fortune.path']}"
28             else
29               debug "couldn't set fortune.path"
30             end
31
32             break
33           end
34         }
35     end
36     m.reply "fortune binary not found" unless fortune
37     begin
38       ret = Utils.safe_exec(fortune, "-n", "255", "-s", db)
39     rescue
40       ret = "failed to execute fortune"
41       # TODO reset fortune.path when execution fails
42     end
43     m.reply ret.gsub(/\t/, "  ").split(/\n/).join(" ")
44     return
45   end
46 end
47 plugin = FortunePlugin.new
48 plugin.map 'fortune :db', :defaults => {:db => 'fortunes'},
49                           :requirements => {:db => /^[^-][\w-]+$/}