def parse(self): with open(self.json_location, 'r') as file: content = file.read() data = json.loads(content) for i in list(set(data['users'].keys())): self.users[i] = user.User(i) self.users[i].lastActive = data['users'][i]["dateActivity"] for i in data['polls']: for j in data['polls'][i]: timestamp = np.random.uniform(low=(time.time()-24*3600), high=time.time()) # data['polls'][i][j]['creationDate'] # title = data['polls'][i][j]['question'] this = data['polls'][i][j]['this'] that = data['polls'][i][j]['that'] if j != "-LVcLeir9mEFVXOqDd30": p = poll.Poll(self.users[i].userid,j, timestamp, title, this, that) self.polls.append(p) self.users[i].add_interaction(j,8, self.polls.index(p)) else: self.hidden_interactions.append([i,8]) for i in data['votes'].keys(): #I = pollid if next((x for x in self.polls if x.pollid == i), None) == None: continue pollidx = self.polls.index(next((x for x in self.polls if x.pollid == i), None)) for j in data['votes'][i].keys(): # J is userid if j not in self.users.keys(): self.users[j] = user.User(j) if j in self.users.keys() and u'skip' in data['votes'][i][j].keys(): if i != "-LVcLeir9mEFVXOqDd30": self.users[j].add_interaction(i,16,pollidx) else: self.hidden_interactions.append([j,16]) if j in self.users.keys() and u'this0that1removed2' in data['votes'][i][j].keys() and data['votes'][i][j][u'this0that1removed2'] in [0,1]: if i != "-LVcLeir9mEFVXOqDd30": self.users[j].add_interaction(i,1, pollidx) else: self.hidden_interactions.append([j,1]) # self.users[j].polls[i] += 1 for i in data['commentsPath'].keys(): #i = userID for j in data['commentsPath'][i].keys(): # j is pollId if next((x for x in self.polls if x.pollid == j), None) == None: continue pollidx = self.polls.index(next((x for x in self.polls if x.pollid == j), None)) if j != "-LVcLeir9mEFVXOqDd30": self.users[i].add_interaction(j,2, pollidx) else: self.hidden_interactions.append([i,2]) # self.users[i].polls[j] += 2 for i in data['tracking'].keys(): #i = userID for j in data['tracking'][i].keys(): # j is unknown for k in data['tracking'][i][j].keys(): if next((x for x in self.polls if x.pollid == k), None) == None: continue pollidx = self.polls.index(next((x for x in self.polls if x.pollid == k), None)) if i not in self.users.keys(): self.users[i] = user.User(i) if k != "-LVcLeir9mEFVXOqDd30": self.users[i].add_interaction(k,4,pollidx) else: self.hidden_interactions.append([i,4])
async def create(ctx, *, choices): g.obj_poll = _poll.Poll() poll = g.obj_poll await g.client.say(poll.create(ctx.message.author.id, choices)) await asyncio.sleep(60) if poll.is_active == True: await g.client.say(poll.close(ctx.message.author.id))
def poll_create(self, message, name, question, *options): if name in self.polls: yield from self.client.send_message( message.channel, "Poll " + name + " already exists") return self.polls[name] = poll.Poll(name, question, options) yield from self.client.send_message(message.channel, "Created poll " + name)
def get_parent_poll_details(member_id): sql = 'SELECT P.* FROM Polls P, PollMembers M WHERE P.id=M.poll_id \ AND M.id=:member_id' poll_data = db.session.execute(sql, {'member_id': member_id}).fetchone() if poll_data is None: return None phase = poll.poll_details_to_phase(poll_data[6], poll_data[7]) return poll.Poll(*poll_data, phase)
def __init__(self, prefix, client, status='{}help'): self.prefix = prefix self.status = status.format(self.prefix) self.client = client if " " in self.prefix: self.self_destruct() self.Token = customToken.Token("db/token.txt") self.UI = ui.UI(discord.Embed, "db/ui.cfg") self.Poll = poll.Poll(self.UI, "db/polls.json") self.Commands = commands.Commands(self.client, self.Poll, self.UI)
def cmd_poll(self, mess, args): '"/poll" Init a poll. Syntax: /poll question' who = self.get_sender_username(mess) msg = mess.getBody() if len(msg.split(' ')) == 1: return 'It works like ,poll question' active_poll = poll.PollFactory.get_active_poll() if active_poll is not None: user = self.users[active_poll.author] return "There is a running poll:\nAuthor: %s\nQuestion: %s\nAuthor must close it using ,endpoll before starting another" % ( user, active_poll.question) currentpoll = poll.Poll() try: polltxt = ' '.join(msg.split(' ')[1:]) currentpoll.new(polltxt, who) except poll.PollException, e: reply = e.message self.log.exception(reply) return reply
def __create_description(self, update, context): # TYPING_DESCRIPTION --> DEFAULT """Completes the /create chain. Get description. Args: update (telegram.Update): The update that triggered this action. context (telegram.ext.CallbackContext): Context for this update. """ self.__log_update(update, context) context.user_data['create_description'] = update.message.text new_poll = poll.Poll(context.user_data['create_name'], context.user_data['create_description'], \ update.message.from_user.id, context.user_data['create_length']) while new_poll.get_id( ) in self.__poll_data: # UUID(4) collisions? Really? new_poll.new_id() self.__poll_data[new_poll.get_id()] = new_poll self.__persistence.update_poll_data(new_poll.get_id(), new_poll) context.user_data['polls'].append(new_poll.get_id()) new_poll.print(context.bot, update.effective_chat) update.message.reply_text(f"Created poll named {context.user_data['create_name']} with {context.user_data['create_length']} columns.\nYou can now /add this poll to whichever chat(s) you want to use it in.", reply_markup=ReplyKeyboardRemove(selective=True)) #pylint: disable=line-too-long context.user_data['conversation_state'] = States.DEFAULT
async def nick_change(self, clean_message, message): """ change ...'s nickname to ... put up for vote Args: clean_message: message command without 359! message: message object from discord.py Returns: None """ # ["votenick", "Benutzer", "neuer nick"] split_message = clean_message.split(" ") wanted_member = self.get_user(split_message[1], message.author.guild) if not wanted_member: await message.channel.send("Keinen solchen Benutzer gefunden.") return # start new poll nick_poll = poll.Poll(wanted_member, message.channel, 10) # change user nick if poll successful nick_poll.successful = lambda m: m.edit(nick=split_message[2]) # start poll await nick_poll.start_poll(f"Starte nickvote für {wanted_member}") # delete user message await message.delete()
async def votekick(self, clean_message, message): """ votekick certain user Args: clean_message: message command without 359! message: actual message object Returns: None """ kick_user = clean_message[len("votekick") + 1:] # go through all members on server kick_member = self.get_user(kick_user, message.author.guild) # no member with given name if not kick_member: await message.channel.send(f"Keinen solchen Benutzer gefunden.") return # member found, start vote votekick_poll = poll.Poll(kick_member, message.channel, 10) # kick user from voice channel if successful votekick_poll.successful = lambda m: m.edit(voice_channel=None) # start poll await votekick_poll.start_poll(f"Starte votekick für {kick_user}") # delete user message await message.delete()
def add_poll(self, text): self._polls.append(poll.Poll(text))
def start_poll(cade, message): obj = poll.Poll(cade, message)
async def processMessage(self, message: discord.Message): author: int = message.author authorId: int = message.author.id # Remove command prefix msg = re.sub("^.*"+self.commandWords.get("vote"), "", message.content, 1).strip() # get current command option cmd = msg.split(" ", 1) + [""] cmdoption = cmd[0].lower() cmdargs = cmd[1] # Create a new poll if cmdoption.startswith("new") or cmdoption.startswith("create"): multivote: bool = False editable: bool = True showAuthors: bool = False showVotes: bool = False canVoteNow: bool = True question: str = "" options: [] = [] poll = polllib.Poll(authorId, question, multivote, editable, showVotes, showAuthors, canVoteNow, options) id = self.table.insert(poll.getDataObject()) return await message.channel.send('Poll created: ||%{0}|| {1.question}'.format(id, poll)) # Show all polls if cmdoption.startswith("history"): output = "Historical Polls:" output += "\n-----------------" polls = self.table.all() for poll in polls: output += "\n\|\| ||%{0.doc_id}|| \|\| {0[question]}".format(poll) output += "\n-----------------" return await message.channel.send(output) # Show current polls if cmdoption.startswith("current") or cmdoption.startswith("active"): output = "Current Polls:" output += "\n-----------------" qry = tinydb.Query() polls = self.table.search(qry._finished == False) for poll in polls: output += "\n\|\| ||%{0.doc_id}|| \|\| {0[question]}".format(poll) output += "\n-----------------" return await message.channel.send(output) # Perform an operation for an existing poll # Allow % prefix or no prefix if cmdoption.startswith("%"): cmdoption = cmdoption.replace("%", "") if cmdoption.isnumeric(): pollobj = self.table.get(doc_id=int(cmdoption)) # Verify a poll was found if not pollobj: return await message.channel.send('Unknown Poll ID!') poll = self.pollFrom(pollobj) # get subcommand option and args cmd = cmdargs.split(" ", 1) + [""] cmdoption = cmd[0].lower() cmdargs = cmd[1] # add an option to the poll if cmdoption.startswith("add"): if poll.addOption(authorId, cmdargs): self.table.update(poll.getDataObject(),None,[pollobj.doc_id]) return await message.channel.send('Added option {1} to ||%{0.doc_id}|| {0[question]}'.format(pollobj, cmdargs)) else: return await message.channel.send("Couldn't add option {1} to ||%{0.id}|| {0.question}. The poll may not allow editing.".format(poll, cmdargs)) # TODO: remove option # TODO: edit option # Vote for an option if cmdoption.isnumeric(): poll.vote(authorId, int(cmdoption)) self.table.update(poll.getDataObject(),None,[pollobj.doc_id]) return await message.channel.send("TODO") # TODO: response # Display the status of the poll if cmdoption.startswith("status"): return await message.channel.send(poll.status()) # list the options of the poll if cmdoption.startswith("list"): return await message.channel.send("Poll ||%{0.doc_id}|| {0[question]}:\n".format(pollobj) + poll.listOptions()) # Display the current results of the poll if cmdoption.startswith("results") or cmdoption.startswith("tally"): return await message.channel.send("Poll ||%{0.doc_id}|| {0[question]}:\n{1}".format(pollobj, poll.listOptions(True))) # Create a new instance of an existing poll if cmdoption.startswith("redo"): poll = poll.redo(authorId) id = self.table.insert(poll.getDataObject()) return await message.channel.send('Recreated: {0}\n{1}'.format(poll.status(), poll.listOptions())) # Admin & poll owner commands if self.auth.isBotAdmin(authorId) or author.permissions_in(message.channel).administrator or authorId is poll.owner: # Delete the poll if cmdoption.startswith("delete"): self.table.remove(doc_ids=pollobj.doc_id) return await message.channel.send('Poll deleted: ||%{0.id}|| {0.question}'.format(poll)) # TODO: edit the poll question # TODO: reset a running poll if cmdoption.startswith("start") or cmdoption.startswith("restart"): poll.start() # TODO: update msg self.table.update(poll.getDataObject(),None,[pollobj.doc_id]) return await message.channel.send('Poll: ||%{0.id}|| {0.question}\n{1}\n----\nPlease vote now: msg me "~vote ||%{0.id}|| your_options_number"'.format(poll, poll.listOptions())) # Restart a finished poll if cmdoption.startswith("start") or cmdoption.startswith("restart"): poll.reset() # TODO: update msg self.table.update(poll.getDataObject(),None,[pollobj.doc_id]) return await message.channel.send('Poll: ||%{0.id}|| {0.question}\n{1}\n----\nPlease vote now: msg me "~vote ||%{0.id}|| your_options_number"'.format(poll, poll.listOptions())) # End a running poll if cmdoption.startswith("finish") or cmdoption.startswith("end"): # TODO: update msg out = poll.finish() self.table.update(poll.getDataObject(),None,[pollobj.doc_id]) return await message.channel.send(out) # No matching commands options found. return await message.channel.send('Looks like your vote command was incomplete or invalid! "{0}"'.format(message.content))
def pollFrom(self, dicti: dict): poll = polllib.Poll(-1, "Null") poll.setDataObject(dicti) return poll
def test_vote(self, title, options): tested_poll = p.Poll(5, 'attempt', ['A', 'C', 'B']) result = tested_poll.vote('voleyball', ['C', 'A']) self.assertEqual(result.pollnumber, 3)
def new_poll(self, userid, pollid, timestamp, title, this, that): new_poll = poll.Poll(userid, pollid, timestamp, title, this, that) self.polls.append(new_poll) self.update_graph() self.add_interaction(userid, pollid, self.interaction_dict['owns'], self.polls.index(new_poll))
teachers_file = "teachersOM3.json" students_file = "studentsOM3.txt" randomSeed = "abHkk1o3Ac-BKVup" teachersJson = "" with open(teachers_file, "r") as f: for s in f.readlines(): teachersJson += s wantedRaw = dict() with open(students_file, "r") as f: for s in f.readlines(): surname, wantedTeachers = s.split(maxsplit=1) wantedRaw[surname] = wantedTeachers p = poll.Poll(0, "", [], randomSeed) p.importFromJson(teachersJson) print(p.showClass()) i = 1 for surname, wantedTeachers in wantedRaw.items(): r = poll.Response() r.name = surname r.id = i i += 1 r.prior, r.prefer = poll.parseResponse(wantedTeachers, p) print(surname, p.checkResponse(r.prior, r.prefer), p.addResponse(r), sep='\t')