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