]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/poll.rb
086a929734d7052431471239652e1153a0b7ecd2
[user/henk/code/ruby/rbot.git] / 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         :value => @answers[choice][:value]
71       }
72     else
73       return _("don't have an option %{choice}") % {
74         :choice => choice
75       }
76     end
77   end
78
79   def printing_values
80     return Hash[:question => @question,
81             :answers => @answers.keys.collect { |a| [a, @answers[a][:value]] }
82     ]
83   end
84
85   def to_s
86     return @question
87   end
88
89   def options
90     options = _("options are: ").dup
91     @answers.each { |letter, info|
92       options << "#{Bold}#{letter}#{NormalText}) #{info[:value]} "
93     }
94     return options
95   end
96 end
97
98 class PollPlugin < Plugin
99   Config.register Config::IntegerValue.new('poll.max_concurrent_polls',
100     :default => 2,
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',
106     :default => true,
107     :desc => _("Should we save results until we see the nick of the pollster?"))
108
109   def init_reg_entry(sym, default)
110     unless @registry.has_key?(sym)
111       @registry[sym] = default
112     end
113   end
114
115   def initialize()
116     super
117     init_reg_entry :running, Hash.new
118     init_reg_entry :archives, Hash.new
119     init_reg_entry :last_poll_id, 0
120   end
121
122   def authors_running_count(victim)
123     return @registry[:running].values.collect { |p|
124       if p.author == victim
125         1
126       else
127         0
128       end
129     }.inject(0) { |acc, v| acc + v }
130   end
131
132   def start(m, params)
133     author = m.sourcenick
134     chan = m.channel
135
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
140       }
141       return
142     end
143
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!")
149       return
150     end
151
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 }
156
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)
162       time_word = :for
163       target_duration = @bot.config['poll.default_duration']
164     else
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
168       answers.last.strip!
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
174     end
175
176     case time_word
177     when :for
178       duration = Utils.parse_time_offset(target_duration) rescue nil
179     else
180       # TODO "until <some moment in time>"
181       duration = nil
182     end
183
184     unless duration
185       m.reply _("I don't understand the time spec %{timespec}") % {
186         :timespec => "'#{time_word} #{target_duration}'"
187       }
188       return
189     end
190
191     poll = Poll.new(m, question, answers, duration)
192
193     m.reply _("new poll from %{author}: %{question}") % {
194       :author => author,
195       :question => "#{Bold}#{question}#{Bold}"
196     }
197     m.reply poll.options
198
199     poll.id = @registry[:last_poll_id] + 1
200     poll.start!
201     command = _("poll vote %{id} <SINGLE-LETTER>") % {
202       :id => poll.id
203     }
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}"
210     }
211
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
217   end
218
219   def count_votes(poll_id)
220     poll = @registry[:running][poll_id]
221
222     # Hrm, it vanished!
223     return if poll == nil
224     poll.stop!
225
226     @bot.say(poll.channel, _("let's find the answer to: %{q}") % {
227       :q => "#{Bold}#{poll.question}#{Bold}"
228     })
229
230     sorted = poll.answers.sort { |a,b| b[1][:count]<=>a[1][:count] }
231
232     winner_info = sorted.first
233     winner_info << sorted.inject(0) { |accum, choice| accum + choice[1][:count] }
234
235     if winner_info[2] == 0
236       poll.outcome = _("nobody voted")
237     else
238       if sorted[0][1][:count] == sorted[1][1][:count]
239         poll.outcome = _("no clear winner: ") +
240           sorted.select { |a|
241             a[1][:count] > 0
242           }.collect { |a|
243             _("'#{a[1][:value]}' got #{a[1][:count]} vote#{a[1][:count] > 1 ? 's' : ''}")
244           }.join(", ")
245       else
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],
253           :pct => winning_pct
254         }
255       end
256     end
257
258     @bot.say poll.channel, poll.outcome
259
260     # Now that we're done, move it to the archives
261     archives = @registry[:archives]
262     archives[poll_id] = poll
263     @registry[:archives] = archives
264
265     # ... and take it out of the running list
266     running = @registry[:running]
267     running.delete(poll_id)
268     @registry[:running] = running
269   end
270
271   def list(m, params)
272     if @registry[:running].keys.length == 0
273       m.reply _("no polls running right now")
274       return
275     end
276
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
280       }
281     }
282   end
283
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 :(")
288       return
289     end
290
291     running = @registry[:running]
292
293     poll = running[poll_id]
294     result = poll.record_vote(m.sourcenick, params[:choice])
295
296     running[poll_id] = poll
297     @registry[:running] = running
298     m.reply result
299   end
300
301   def info(m, params)
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]]
307     else
308       m.reply _("sorry, couldn't find poll %{b}#%{id}%{b}") % {
309         :bold => Bold,
310         :id => params[:id]
311       }
312       return
313     end
314
315     to_reply = _("poll #%{id} was asked by %{bold}%{author}%{bold} in %{bold}%{channel}%{bold} %{started}.")
316     options = ''
317     outcome = ''
318     if poll.running
319       to_reply << _(" It's still running!")
320       if poll.voters.has_key? m.sourcenick
321         to_reply << _(" Be patient, it'll end %{end}")
322       else
323         to_reply << _(" You have until %{poll.ends_at} to vote if you haven't!")
324         options << " #{poll.options}"
325       end
326     else
327       outcome << " #{poll.outcome}"
328     end
329
330     m.reply((to_reply % {
331       :bold => Bold,
332       :id => poll.id, :author => poll.author, :channel => poll.channel,
333       :started => poll.started,
334       :end => poll.ends_at
335     }) + options + outcome)
336   end
337
338   def help(plugin,topic="")
339     case topic
340     when "start"
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.")
344     when "list"
345       _("poll list : Give some info about currently active polls")
346     when "info"
347       _("poll info #{Bold}id#{Bold} : Get info about /results from a given poll")
348     when "vote"
349       _("poll vote #{Bold}id choice#{Bold} : Vote on the given poll with your choice")
350     else
351       _("Hold informative polls: poll start|list|info|vote")
352     end
353   end
354 end
355
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'