import binascii, functools, operator, os, uuid from src import ModuleManager, utils STR_NOVOTE = "Unknown vote '%s'" class Module(ModuleManager.BaseModule): def _get_vote(self, channel, vote_id): return channel.get_setting("vote-%s" % vote_id, None) def _set_vote(self, channel, vote_id, vote): channel.set_setting("vote-%s" % vote_id, vote) def _random_id(self, channel): while True: vote_id = binascii.hexlify(os.urandom(4)).decode("ascii") if self._get_vote(channel, vote_id) == None: return vote_id def _close_vote(self, channel, vote_id): vote = self._get_vote(channel, vote_id) if vote: vote["open"] = False self._set_vote(channel, vote_id, vote) return True return False def _start_vote(self, channel, description): vote_id = self._random_id(channel) vote = {"description": description, "options": {"yes": [], "no": []}, "electorate": [], "open": True, "id": vote_id} self._set_vote(channel, vote_id, vote) return vote def _format_vote(self, vote): options = ["%d %s" % (len(v), k) for k, v in vote["options"].items()] return "%s (%s)" % (vote["description"], ", ".join(options)) def _format_options(self, vote): return ", ".join("'%s'" % o for o in vote["options"]) def _cast_vote(self, channel, vote_id, user, option): vote = self._get_vote(channel, vote_id) option = vote["options"][option] voters = functools.reduce(operator.concat, list(vote["options"].values())) if user.name in voters: return False option.append(user.name) self._set_vote(channel, vote_id, vote) return True def _open_votes(self, channel): open = [] for setting, vote in channel.find_settings_prefix("vote-"): if vote["open"]: open.append(vote) return open @utils.hook("received.command.startvote", channel_only=True, min_args=1) def start_vote(self, event): """ :help: Start a vote :usage: :require_mode: o :permission: vote """ vote = self._start_vote(event["target"], event["args"]) event["stdout"].write( "Vote %s started. use '%svote