#--depends-on check_mode #--depends-on commands #--depends-on permissions import binascii, enum, os, uuid from src import ModuleManager, utils STR_NOVOTE = "Unknown vote '%s'" class VoteCastResult(enum.Enum): Cast = 1 Changed = 2 Unchanged = 3 @utils.export("channelset", utils.BoolSetting("votes-start-restricted", "Whether starting a vote should be restricted to ops")) 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(3)).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, chosen_option): vote = self._get_vote(channel, vote_id) option_nicks = vote["options"][chosen_option] cast_type = VoteCastResult.Cast for option, nicks in vote["options"].items(): if user.name in nicks: if option == chosen_option: return VoteCastResult.Unchanged else: nicks.remove(user.name) cast_type = VoteCastResult.Changed break option_nicks.append(user.name) self._set_vote(channel, vote_id, vote) return cast_type 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: """ if event["target"].get_setting("votes-start-restricted", True): event["check_assert"](utils.Check("channel-mode", "o")| utils.Check("permission", "vote")| utils.Check("channel-access", "vote")) vote = self._start_vote(event["target"], event["args"]) event["stdout"].write( "Vote %s started. use '%svote