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}") % {
70 :value => @answers[choice][:value]
73 return _("don't have an option %{choice}") % {
80 return Hash[:question => @question,
81 :answers => @answers.keys.collect { |a| [a, @answers[a][:value]] }
90 options = _("options are: ").dup
91 @answers.each { |letter, info|
92 options << "#{Bold}#{letter}#{NormalText}) #{info[:value]} "
98 class PollPlugin < Plugin
99 Config.register Config::IntegerValue.new('poll.max_concurrent_polls',
101 :desc => _("How many polls a user can have running at once"))
102 Config.register Config::StringValue.new('poll.default_duration',
103 :default => "2 minutes",
104 :desc => _("How long a poll will accept answers, by default."))
105 Config.register Config::BooleanValue.new('poll.save_results',
107 :desc => _("Should we save results until we see the nick of the pollster?"))
109 def init_reg_entry(sym, default)
110 unless @registry.has_key?(sym)
111 @registry[sym] = default
117 init_reg_entry :running, Hash.new
118 init_reg_entry :archives, Hash.new
119 init_reg_entry :last_poll_id, 0
122 def authors_running_count(victim)
123 return @registry[:running].values.collect { |p|
124 if p.author == victim
129 }.inject(0) { |acc, v| acc + v }
133 author = m.sourcenick
136 max_concurrent = @bot.config['poll.max_concurrent_polls']
137 if authors_running_count(author) == max_concurrent
138 m.reply _("Sorry, you're already at the limit (%{limit}) polls") % {
139 :limit => max_concurrent
144 input_blob = params[:blob].to_s.strip
145 quote_character = input_blob[0,1]
146 chunks = input_blob.split(/#{quote_character}\s+#{quote_character}/)
147 if chunks.length <= 2
148 m.reply _("This isn't a dictatorship!")
152 # grab the question, removing the leading quote character
153 question = chunks[0][1..-1].strip
154 question << "?" unless question[-1,1] == "?"
155 answers = chunks[1..-1].map { |a| a.strip }
157 # if the last answer terminates with a quote character,
158 # there is no time specification, so strip the quote character
159 # and assume default duration
160 if answers.last[-1,1] == quote_character
161 answers.last.chomp!(quote_character)
163 target_duration = @bot.config['poll.default_duration']
165 last_quote = answers.last.rindex(quote_character)
166 time_spec = answers.last[(last_quote+1)..-1].strip
167 answers.last[last_quote..-1] = String.new
169 # now answers.last is really the (cleaned-up) last answer,
170 # while time_spec holds the (cleaned-up) time spec, which
171 # should start with 'for' or 'until'
172 time_word, target_duration = time_spec.split(/\s+/, 2)
173 time_word = time_word.strip.intern rescue nil
178 duration = Utils.parse_time_offset(target_duration) rescue nil
180 # TODO "until <some moment in time>"
185 m.reply _("I don't understand the time spec %{timespec}") % {
186 :timespec => "'#{time_word} #{target_duration}'"
191 poll = Poll.new(m, question, answers, duration)
193 m.reply _("new poll from %{author}: %{question}") % {
195 :question => "#{Bold}#{question}#{Bold}"
199 poll.id = @registry[:last_poll_id] + 1
201 command = _("poll vote %{id} <SINGLE-LETTER>") % {
204 instructions = _("you have %{duration}, vote with ").dup
205 instructions << _("%{priv} or %{public}")
206 m.reply instructions % {
207 :duration => "#{Bold}#{target_duration}#{Bold}",
208 :priv => "#{Bold}/msg #{@bot.nick} #{command}#{Bold}",
209 :public => "#{Bold}#{@bot.config['core.address_prefix'].first}#{command}#{Bold}"
212 running = @registry[:running]
213 running[poll.id] = poll
214 @registry[:running] = running
215 @bot.timer.add_once(duration) { count_votes(poll.id) }
216 @registry[:last_poll_id] = poll.id
219 def count_votes(poll_id)
220 poll = @registry[:running][poll_id]
223 return if poll == nil
226 @bot.say(poll.channel, _("let's find the answer to: %{q}") % {
227 :q => "#{Bold}#{poll.question}#{Bold}"
230 sorted = poll.answers.sort { |a,b| b[1][:count]<=>a[1][:count] }
232 winner_info = sorted.first
233 winner_info << sorted.inject(0) { |accum, choice| accum + choice[1][:count] }
235 if winner_info[2] == 0
236 poll.outcome = _("nobody voted")
238 if sorted[0][1][:count] == sorted[1][1][:count]
239 poll.outcome = _("no clear winner: ") +
243 _("'#{a[1][:value]}' got #{a[1][:count]} vote#{a[1][:count] > 1 ? 's' : ''}")
246 winning_pct = "%3.0f%%" % [ 100 * (winner_info[1][:count] / winner_info[2]) ]
247 poll.outcome = n_("the winner was choice %{choice}: %{value} with %{count} vote (%{pct})",
248 "the winner was choice %{choice}: %{value} with %{count} votes (%{pct})",
249 winner_info[1][:count]) % {
250 :choice => winner_info[0],
251 :value => winner_info[1][:value],
252 :count => winner_info[1][:count],
258 @bot.say poll.channel, poll.outcome
260 # Now that we're done, move it to the archives
261 archives = @registry[:archives]
262 archives[poll_id] = poll
263 @registry[:archives] = archives
265 # ... and take it out of the running list
266 running = @registry[:running]
267 running.delete(poll_id)
268 @registry[:running] = running
272 if @registry[:running].keys.length == 0
273 m.reply _("no polls running right now")
277 @registry[:running].each { |id, p|
278 m.reply _("%{author}'s poll \"%{question}\" (id #%{id}) runs until %{end}") % {
279 :author => p.author, :question => p.question, :id => p.id, :end => p.ends_at
284 def record_vote(m, params)
285 poll_id = params[:id].to_i
286 if @registry[:running].has_key?(poll_id) == false
287 m.reply _("I don't have poll ##{poll_id} running :(")
291 running = @registry[:running]
293 poll = running[poll_id]
294 result = poll.record_vote(m.sourcenick, params[:choice])
296 running[poll_id] = poll
297 @registry[:running] = running
302 params[:id] = params[:id].to_i
303 if @registry[:running].has_key? params[:id]
304 poll = @registry[:running][params[:id]]
305 elsif @registry[:archives].has_key? params[:id]
306 poll = @registry[:archives][params[:id]]
308 m.reply _("sorry, couldn't find poll %{b}#%{id}%{b}") % {
315 to_reply = _("poll #%{id} was asked by %{bold}%{author}%{bold} in %{bold}%{channel}%{bold} %{started}.")
319 to_reply << _(" It's still running!")
320 if poll.voters.has_key? m.sourcenick
321 to_reply << _(" Be patient, it'll end %{end}")
323 to_reply << _(" You have until %{poll.ends_at} to vote if you haven't!")
324 options << " #{poll.options}"
327 outcome << " #{poll.outcome}"
330 m.reply((to_reply % {
332 :id => poll.id, :author => poll.author, :channel => poll.channel,
333 :started => poll.started,
335 }) + options + outcome)
338 def help(plugin,topic="")
341 _("poll [start] 'my question' 'answer1' 'answer2' ['answer3' ...] " +
342 "[for 5 minutes] : Start a poll for the given duration. " +
343 "If you don't specify a duration the default will be used.")
345 _("poll list : Give some info about currently active polls")
347 _("poll info #{Bold}id#{Bold} : Get info about /results from a given poll")
349 _("poll vote #{Bold}id choice#{Bold} : Vote on the given poll with your choice")
351 _("Hold informative polls: poll start|list|info|vote")
356 plugin = PollPlugin.new
357 plugin.map 'poll list', :action => 'list'
358 plugin.map 'poll info :id', :action => 'info'
359 plugin.map 'poll vote :id :choice', :action => 'record_vote', :threaded => true
360 plugin.map 'poll [start] *blob', :action => 'start'