poll: oopsie in the gettext string for poll status
[rbot] / data / rbot / plugins / poll.rb
1 #-- vim:ts=2:et:sw=2
2 #++
3 #
4 # :title: Voting plugin for rbot
5 # Author:: David Gadling <dave@toasterwaffles.com>
6 # Copyright:: (C) 2010 David Gadling
7 # License:: BSD
8 #
9 # Submit a poll question to a channel, wait for glorious outcome.
10 #
11 # TODO better display for start/end times
12 # TODO 'until ...' time spec
13 # TODO early poll termination
14 # TODO option to inform people about running polls on join (if they haven't voted yet)
15
16 class ::Poll
17   attr_accessor :id, :author, :channel, :running, :ends_at, :started
18   attr_accessor :question, :answers, :duration, :voters, :outcome
19
20   def initialize(originating_message, question, answers, duration)
21     @author = originating_message.sourcenick
22     @channel = originating_message.channel
23     @question = question
24     @running = false
25     @duration = duration
26
27     @answers = Hash.new
28     @voters  = Hash.new
29
30     answer_index = "A"
31     answers.each do |ans|
32       @answers[answer_index] = {
33         :value => ans,
34         :count => 0
35       }
36       answer_index.next!
37     end
38   end
39
40   def start!
41     return if @running
42
43     @started = Time.now
44     @ends_at = @started + @duration
45     @running = true
46   end
47
48   def stop!
49     return if @running == false
50     @running = false
51   end
52
53   def record_vote(voter, choice)
54     if @running == false
55       return _("poll's closed!")
56     end
57
58     if @voters.has_key? voter
59       return _("you already voted for %{vote}!") % {
60         :vote => @voters[voter]
61       }
62     end
63
64     choice.upcase!
65     if @answers.has_key? choice
66       @answers[choice][:count] += 1
67       @voters[voter] = choice
68
69       return _("recorded your vote for %{choice}: %{value}") % {
70         :choice => choice,
71         :value => @answers[choice][:value]
72       }
73     else
74       return _("don't have an option %{choice}") % {
75         :choice => choice
76       }
77     end
78   end
79
80   def printing_values
81     return Hash[:question => @question,
82             :answers => @answers.keys.collect { |a| [a, @answers[a][:value]] }
83     ]
84   end
85
86   def to_s
87     return @question
88   end
89
90   def options
91     options = _("options are: ").dup
92     @answers.each { |letter, info|
93       options << "#{Bold}#{letter}#{NormalText}) #{info[:value]} "
94     }
95     return options
96   end
97 end
98
99 class PollPlugin < Plugin
100   Config.register Config::IntegerValue.new('poll.max_concurrent_polls',
101     :default => 2,
102     :desc => _("How many polls a user can have running at once"))
103   Config.register Config::StringValue.new('poll.default_duration',
104     :default => "2 minutes",
105     :desc => _("How long a poll will accept answers, by default."))
106   Config.register Config::BooleanValue.new('poll.save_results',
107     :default => true,
108     :desc => _("Should we save results until we see the nick of the pollster?"))
109
110   def init_reg_entry(sym, default)
111     unless @registry.has_key?(sym)
112       @registry[sym] = default
113     end
114   end
115
116   def initialize()
117     super
118     init_reg_entry :running, Hash.new
119     init_reg_entry :archives, Hash.new
120     init_reg_entry :last_poll_id, 0
121   end
122
123   def authors_running_count(victim)
124     return @registry[:running].values.collect { |p|
125       if p.author == victim
126         1
127       else
128         0
129       end
130     }.inject(0) { |acc, v| acc + v }
131   end
132
133   def start(m, params)
134     author = m.sourcenick
135     chan = m.channel
136
137     max_concurrent = @bot.config['poll.max_concurrent_polls']
138     if authors_running_count(author) == max_concurrent
139       m.reply _("Sorry, you're already at the limit (%{limit}) polls") % {
140         :limit => max_concurrent
141       }
142       return
143     end
144
145     input_blob = params[:blob].to_s.strip
146     quote_character = input_blob[0,1]
147     chunks = input_blob.split(/#{quote_character}\s+#{quote_character}/)
148     if chunks.length <= 2
149       m.reply _("This isn't a dictatorship!")
150       return
151     end
152
153     # grab the question, removing the leading quote character
154     question = chunks[0][1..-1].strip
155     question << "?" unless question[-1,1] == "?"
156     answers = chunks[1..-1].map { |a| a.strip }
157
158     # if the last answer terminates with a quote character,
159     # there is no time specification, so strip the quote character
160     # and assume default duration
161     if answers.last[-1,1] == quote_character
162       answers.last.chomp!(quote_character)
163       time_word = :for
164       target_duration = @bot.config['poll.default_duration']
165     else
166       last_quote = answers.last.rindex(quote_character)
167       time_spec = answers.last[(last_quote+1)..-1].strip
168       answers.last[last_quote..-1] = String.new
169       answers.last.strip!
170       # now answers.last is really the (cleaned-up) last answer,
171       # while time_spec holds the (cleaned-up) time spec, which
172       # should start with 'for' or 'until'
173       time_word, target_duration = time_spec.split(/\s+/, 2)
174       time_word = time_word.strip.intern rescue nil
175     end
176
177     case time_word
178     when :for
179       duration = Utils.parse_time_offset(target_duration) rescue nil
180     else
181       # TODO "until <some moment in time>"
182       duration = nil
183     end
184
185     unless duration
186       m.reply _("I don't understand the time spec %{timespec}") % {
187         :timespec => "'#{time_word} #{target_duration}'"
188       }
189       return
190     end
191
192     poll = Poll.new(m, question, answers, duration)
193
194     m.reply _("new poll from %{author}: %{question}") % {
195       :author => author,
196       :question => "#{Bold}#{question}#{Bold}"
197     }
198     m.reply poll.options
199
200     poll.id = @registry[:last_poll_id] + 1
201     poll.start!
202     command = _("poll vote %{id} <SINGLE-LETTER>") % {
203       :id => poll.id
204     }
205     instructions = _("you have %{duration}, vote with ").dup
206     instructions << _("%{priv} or %{public}")
207     m.reply instructions % {
208       :duration => "#{Bold}#{target_duration}#{Bold}",
209       :priv => "#{Bold}/msg #{@bot.nick} #{command}#{Bold}",
210       :public => "#{Bold}#{@bot.config['core.address_prefix'].first}#{command}#{Bold}"
211     }
212
213     running = @registry[:running]
214     running[poll.id] = poll
215     @registry[:running] = running
216     @bot.timer.add_once(duration) { count_votes(poll.id) }
217     @registry[:last_poll_id] = poll.id
218   end
219
220   def count_votes(poll_id)
221     poll = @registry[:running][poll_id]
222
223     # Hrm, it vanished!
224     return if poll == nil
225     poll.stop!
226
227     @bot.say(poll.channel, _("let's find the answer to: %{q}") % {
228       :q => "#{Bold}#{poll.question}#{Bold}"
229     })
230
231     sorted = poll.answers.sort { |a,b| b[1][:count]<=>a[1][:count] }
232
233     winner_info = sorted.first
234     winner_info << sorted.inject(0) { |accum, choice| accum + choice[1][:count] }
235
236     if winner_info[2] == 0
237       poll.outcome = _("nobody voted")
238     else
239       if sorted[0][1][:count] == sorted[1][1][:count]
240         poll.outcome = _("no clear winner: ") +
241           sorted.select { |a|
242             a[1][:count] > 0
243           }.collect { |a|
244             _("'#{a[1][:value]}' got #{a[1][:count]} vote#{a[1][:count] > 1 ? 's' : ''}")
245           }.join(", ")
246       else
247         winning_pct = "%3.0f%%" % [ 100 * (winner_info[1][:count] / winner_info[2]) ]
248         poll.outcome = n_("the winner was choice %{choice}: %{value} with %{count} vote (%{pct})",
249                           "the winner was choice %{choice}: %{value} with %{count} votes (%{pct})",
250                           winner_info[1][:count]) % {
251           :choice => winner_info[0],
252           :value => winner_info[1][:value],
253           :count => winner_info[1][:count],
254           :pct => winning_pct
255         }
256       end
257     end
258
259     @bot.say poll.channel, poll.outcome
260
261     # Now that we're done, move it to the archives
262     archives = @registry[:archives]
263     archives[poll_id] = poll
264     @registry[:archives] = archives
265
266     # ... and take it out of the running list
267     running = @registry[:running]
268     running.delete(poll_id)
269     @registry[:running] = running
270   end
271
272   def list(m, params)
273     if @registry[:running].keys.length == 0
274       m.reply _("no polls running right now")
275       return
276     end
277
278     @registry[:running].each { |id, p|
279       m.reply _("%{author}'s poll \"%{question}\" (id #%{id}) runs until %{end}") % {
280         :author => p.author, :question => p.question, :id => p.id, :end => p.ends_at
281       }
282     }
283   end
284
285   def record_vote(m, params)
286     poll_id = params[:id].to_i
287     if @registry[:running].has_key?(poll_id) == false
288       m.reply _("I don't have poll ##{poll_id} running :(")
289       return
290     end
291
292     running = @registry[:running]
293
294     poll = running[poll_id]
295     result = poll.record_vote(m.sourcenick, params[:choice])
296
297     running[poll_id] = poll
298     @registry[:running] = running
299     m.reply result
300   end
301
302   def info(m, params)
303     params[:id] = params[:id].to_i
304     if @registry[:running].has_key? params[:id]
305       poll = @registry[:running][params[:id]]
306     elsif @registry[:archives].has_key? params[:id]
307       poll = @registry[:archives][params[:id]]
308     else
309       m.reply _("sorry, couldn't find poll %{b}#%{id}%{b}") % {
310         :bold => Bold,
311         :id => params[:id]
312       }
313       return
314     end
315
316     to_reply = _("poll #%{id} was asked by %{bold}%{author}%{bold} in %{bold}%{channel}%{bold} %{started}.")
317     options = ''
318     outcome = ''
319     if poll.running
320       to_reply << _(" It's still running!")
321       if poll.voters.has_key? m.sourcenick
322         to_reply << _(" Be patient, it'll end %{end}")
323       else
324         to_reply << _(" You have until %{end} to vote if you haven't!")
325         options << " #{poll.options}"
326       end
327     else
328       outcome << " #{poll.outcome}"
329     end
330
331     m.reply((to_reply % {
332       :bold => Bold,
333       :id => poll.id, :author => poll.author, :channel => poll.channel,
334       :started => poll.started,
335       :end => poll.ends_at
336     }) + options + outcome)
337   end
338
339   def help(plugin,topic="")
340     case topic
341     when "start"
342       _("poll [start] 'my question' 'answer1' 'answer2' ['answer3' ...] " +
343         "[for 5 minutes] : Start a poll for the given duration. " +
344         "If you don't specify a duration the default will be used.")
345     when "list"
346       _("poll list : Give some info about currently active polls")
347     when "info"
348       _("poll info #{Bold}id#{Bold} : Get info about /results from a given poll")
349     when "vote"
350       _("poll vote #{Bold}id choice#{Bold} : Vote on the given poll with your choice")
351     else
352       _("Hold informative polls: poll start|list|info|vote")
353     end
354   end
355 end
356
357 plugin = PollPlugin.new
358 plugin.map 'poll list', :action => 'list'
359 plugin.map 'poll info :id', :action => 'info'
360 plugin.map 'poll vote :id :choice', :action => 'record_vote', :threaded => true
361 plugin.map 'poll [start] *blob', :action => 'start'