4 # :title: Voting plugin for rbot
5 # Author:: David Gadling <dave@toasterwaffles.com>
6 # Copyright:: (C) 2010 David Gadling
9 # Submit a poll question to a channel, wait for glorious outcome.
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)
17 attr_accessor :id, :author, :channel, :running, :ends_at, :started
18 attr_accessor :question, :answers, :duration, :voters, :outcome
20 def initialize(originating_message, question, answers, duration)
21 @author = originating_message.sourcenick
22 @channel = originating_message.channel
32 @answers[answer_index] = {
44 @ends_at = @started + @duration
49 return if @running == false
53 def record_vote(voter, choice)
55 return _("poll's closed!")
58 if @voters.has_key? voter
59 return _("you already voted for %{vote}!") % {
60 :vote => @voters[voter]
65 if @answers.has_key? choice
66 @answers[choice][:count] += 1
67 @voters[voter] = choice
69 return _("recorded your vote for %{choice}: %{value}") % {
71 :value => @answers[choice][:value]
74 return _("don't have an option %{choice}") % {
81 return Hash[:question => @question,
82 :answers => @answers.keys.collect { |a| [a, @answers[a][:value]] }
91 options = _("options are: ").dup
92 @answers.each { |letter, info|
93 options << "#{Bold}#{letter}#{NormalText}) #{info[:value]} "
99 class PollPlugin < Plugin
100 Config.register Config::IntegerValue.new('poll.max_concurrent_polls',
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',
108 :desc => _("Should we save results until we see the nick of the pollster?"))
110 def init_reg_entry(sym, default)
111 unless @registry.has_key?(sym)
112 @registry[sym] = default
118 init_reg_entry :running, Hash.new
119 init_reg_entry :archives, Hash.new
120 init_reg_entry :last_poll_id, 0
123 def authors_running_count(victim)
124 return @registry[:running].values.collect { |p|
125 if p.author == victim
130 }.inject(0) { |acc, v| acc + v }
134 author = m.sourcenick
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
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!")
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 }
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)
164 target_duration = @bot.config['poll.default_duration']
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
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
179 duration = Utils.parse_time_offset(target_duration) rescue nil
181 # TODO "until <some moment in time>"
186 m.reply _("I don't understand the time spec %{timespec}") % {
187 :timespec => "'#{time_word} #{target_duration}'"
192 poll = Poll.new(m, question, answers, duration)
194 m.reply _("new poll from %{author}: %{question}") % {
196 :question => "#{Bold}#{question}#{Bold}"
200 poll.id = @registry[:last_poll_id] + 1
202 command = _("poll vote %{id} <SINGLE-LETTER>") % {
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}"
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
220 def count_votes(poll_id)
221 poll = @registry[:running][poll_id]
224 return if poll == nil
227 @bot.say(poll.channel, _("let's find the answer to: %{q}") % {
228 :q => "#{Bold}#{poll.question}#{Bold}"
231 sorted = poll.answers.sort { |a,b| b[1][:count]<=>a[1][:count] }
233 winner_info = sorted.first
234 winner_info << sorted.inject(0) { |accum, choice| accum + choice[1][:count] }
236 if winner_info[2] == 0
237 poll.outcome = _("nobody voted")
239 if sorted[0][1][:count] == sorted[1][1][:count]
240 poll.outcome = _("no clear winner: ") +
244 _("'#{a[1][:value]}' got #{a[1][:count]} vote#{a[1][:count] > 1 ? 's' : ''}")
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],
259 @bot.say poll.channel, poll.outcome
261 # Now that we're done, move it to the archives
262 archives = @registry[:archives]
263 archives[poll_id] = poll
264 @registry[:archives] = archives
266 # ... and take it out of the running list
267 running = @registry[:running]
268 running.delete(poll_id)
269 @registry[:running] = running
273 if @registry[:running].keys.length == 0
274 m.reply _("no polls running right now")
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
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 :(")
292 running = @registry[:running]
294 poll = running[poll_id]
295 result = poll.record_vote(m.sourcenick, params[:choice])
297 running[poll_id] = poll
298 @registry[:running] = running
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]]
309 m.reply _("sorry, couldn't find poll %{b}#%{id}%{b}") % {
316 to_reply = _("poll #%{id} was asked by %{bold}%{author}%{bold} in %{bold}%{channel}%{bold} %{started}.")
320 to_reply << _(" It's still running!")
321 if poll.voters.has_key? m.sourcenick
322 to_reply << _(" Be patient, it'll end %{end}")
324 to_reply << _(" You have until %{end} to vote if you haven't!")
325 options << " #{poll.options}"
328 outcome << " #{poll.outcome}"
331 m.reply((to_reply % {
333 :id => poll.id, :author => poll.author, :channel => poll.channel,
334 :started => poll.started,
336 }) + options + outcome)
339 def help(plugin,topic="")
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.")
346 _("poll list : Give some info about currently active polls")
348 _("poll info #{Bold}id#{Bold} : Get info about /results from a given poll")
350 _("poll vote #{Bold}id choice#{Bold} : Vote on the given poll with your choice")
352 _("Hold informative polls: poll start|list|info|vote")
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'