Пример #1
0
    def create_new_poll(cls):
        owner = input("Please provide your name: ")
        while not owner:
            owner = input("Try again. Please provide your name: ")
        poll_question = input(
            "Please provide a question you want your poll respond for: ")
        while not poll_question:
            poll_question = input(
                "Try again. Please provide a question you want your poll responds for: "
            )
        options = []
        option = input("Please provide the first option: ")
        while option != '':
            options.append(option)
            option = input(
                "Please provide the next option or leave it blank to finish the process, then press Enter : "
            )
        try:
            new_poll = Poll(poll_question, owner)
            poll_id = new_poll.save_to_db()[0]
            for option in options:
                Option(poll_id, option).save_to_db()
        except Exception as e:
            print(e)
            return

        input("Your poll has been created! Press Enter to see it...")
        print("\nPoll id: ", poll_id)
        print(poll_question)
        for option in options:
            print("\t", option)
        input("\nPres Enter to continue...")
        cls.select_from_menu()
Пример #2
0
def getPolls(user = None):
    if user:
        query = Poll.query(Poll.ownerId == user).fetch()
    else:
        query = Poll.query()
        
    poll_result = list()
    for p in query:
        poll_item = {"title": p.title, "description": p.description, "poll_id": str(p.key.id()) }
        poll_result.append(poll_item)

    return poll_result
Пример #3
0
async def test_vote_400_if_votes_not_allowed(init_db):
    db = init_db
    task = Task(**{**MOCK_TASK, "allow_votes": False})

    # Get Token headers
    headers = await create_user_and_get_token(db, client)

    # Create poll
    await crud.poll.create_in_db(db, poll=Poll(name=MOCK_POLL_NAME))

    # Get poll
    poll = await crud.poll.get_poll(db, slug=slugify(MOCK_POLL_NAME))

    # Create task
    poll.current_task = task
    res = await crud.poll.update_poll(db, poll=poll)

    # Get poll
    poll = await crud.poll.get_poll(db, slug=slugify(MOCK_POLL_NAME))

    assert poll.current_task.allow_votes == False

    res = client.post(
        "http://localhost:8000/poll/vote",
        headers=headers,
        json={"vote": "1/2", "slug": slugify(MOCK_POLL_NAME)},
    )

    data = res.json()

    assert res.status_code is status.HTTP_400_BAD_REQUEST
    assert data == {"detail": "Votes not allowed at the moment!"}
Пример #4
0
def makePoll(ownerID, title, desc, type, status, photoURL, contestants=None):
   try:
        nPoll = Poll(title=title, description=desc, ownerID=ownerID,type=type, status=status, photoURL=photoURL)
        key = nPoll.put()
        id = str(key.id())
        contestants_results = []
        if contestants is not None:
            for c in contestants:
               contestant_result = addContestant(c['name'], id, c['photoURL'], c['information'], c['code'])
               contestants_results.append(contestant_result)

        result = {"poll_id": id, "title": title, "description": desc, "ownerID": ownerID, "contestants": contestants_results }
        return result

   except KeyError as e:
        return {"error": "There has been an error These key(s) are missing: %s"%e }
Пример #5
0
def show_poll_votes():
    poll_id = int(input("Какой опрос хотите посмотреть?: "))
    try:
        options = Poll.get(poll_id).options
        votes_per_option = [len(option.votes) for option in options]
        total_votes = sum(votes_per_option)
        try:
            for option, votes in zip(options, votes_per_option):
                percentage = votes / total_votes * 100
                if votes % 10 in [2, 3, 4]:
                    print(
                        f"Пункт {option.text} получил {votes} голоса ({percentage:.1f}% от общего числа)"
                    )
                elif votes % 10 == 1:
                    print(
                        f"Пункт {option.text} получил {votes} голос ({percentage:.1f}% от общего числа)"
                    )
                else:
                    print(
                        f"Пункт {option.text} получил {votes} голосов ({percentage:.1f}% от общего числа)"
                    )

        except ZeroDivisionError:
            print("В нем ещё нет голосов.")

        vote_log = input("Хотите увидеть логи? (да/Нет): ")
        if vote_log == "да":
            _print_vote_for_options(options)
    except TypeError:
        print("Нет опроса под этим номером!")
Пример #6
0
def respond_to_poll():
    payload = json.loads(request.form['payload'])
    original_message = payload["original_message"]
    action_value = payload["actions"][0]["value"]
    question = original_message["text"]
    attachments = original_message["attachments"]
    user = payload["user"]["name"]
    poll = Poll()
    response = poll.form_response(user=user,
                                  action_value=action_value,
                                  question=question,
                                  attachments=attachments)
    response = app.response_class(response,
                                  status=200,
                                  mimetype='application/json')
    return response
Пример #7
0
def getPollDetails(poll_id):
    try:
        user = users.get_current_user()
        user_id = user.user_id()
        poll = Poll.get_by_id(poll_id)
        if poll is not None:
            result = {
                "poll_id": poll_id,
                "title": poll.title,
                "description": poll.description,
                "ownerID": poll.ownerID,
                "status":poll.status,
                "type": poll.type,
                "date_added": poll.date_added.strftime('%m/%d/%Y'),
                "user_vote": getUserVoteInPoll(user_id, poll_id),
                "photoURL": poll.photoURL
            }

        else:
            result = {"error": "No poll found with that Id"}

    except LookupError as e:
        result = {"error": "There has been an error %s"%e }

    except AttributeError as e:
        result = {"error": "There is no logged in user. Kindly ensure the user is logged in before retrying"}


    return result
Пример #8
0
    async def close_polls(self):
        """This function runs every 60 seconds to schedule prepared polls and close expired polls"""
        while True:
            try:
                if not hasattr(self.bot, 'db'):
                    await asyncio.sleep(30)
                    continue

                query = self.bot.db.polls.find({'active': False, 'activation': {"$not": re.compile("0")}})
                if query:
                    for pd in [poll async for poll in query]:
                        p = Poll(self.bot, load=True)
                        await p.from_dict(pd)
                        if not p.server:
                            continue
                        if p.active:
                            try:
                                await p.channel.send('This poll has been scheduled and is active now!')
                                await p.post_embed(p.channel)
                            except:
                                continue

                query = self.bot.db.polls.find({'open': True, 'duration': {"$not": re.compile("0")}})
                if query:
                    for pd in [poll async for poll in query]:
                        p = Poll(self.bot, load=True)
                        await p.from_dict(pd)
                        if not p.server:
                            continue
                        if not p.open:
                            try:
                                await p.channel.send('This poll has reached the deadline and is closed!')
                                await p.post_embed(p.channel)
                            except:
                                continue
            except AttributeError as ae:
                # Database not loaded yet
                logger.warning("Attribute Error in close_polls loop")
                logger.exception(ae)
                pass
            except Exception as ex:
                # Never break this loop due to an error
                logger.error("Other Error in close_polls loop")
                logger.exception(ex)
                pass

            await asyncio.sleep(60)
Пример #9
0
def prompt_vote_poll():
    poll_id = int(input("Enter poll you would like to vote on: "))

    _print_poll_options(Poll.get(poll_id).options)

    option_id = int(input("Enter option you'd like to vote for: "))
    username = input("Enter the username you'd like to vote as: ")
    Option.get(option_id).vote(username)
Пример #10
0
def randomize_poll_winner():
    poll_id = int(input("Enter poll you'd like to pick a winner for: "))
    _print_poll_options(Poll.get(poll_id).options)

    option_id = int(input("Enter which is the winning option, we'll pick a random winner from voters: "))
    votes = Option.get(option_id).votes
    winner = random.choice(votes)
    print(f"The randomly selected winner is {winner[0]}.")
Пример #11
0
def poll():
    # username = request.form.getlist('user_name')[0]
    text = unidecode(request.form.getlist('text')[0])
    poll_list = list()
    for line in reader(text):
        if re.search('[a-zA-Z]', str(line)):
            poll_list.append(line)
    if len(poll_list) < 2:
        response = return_error()
    elif len(poll_list) > 6:
        response = too_long()
    else:
        poll = Poll()
        response = poll.create_poll(poll_list)
        response = app.response_class(response,
                                      status=200,
                                      mimetype='application/json')
    return response
Пример #12
0
def prompt_vote_poll():
    poll_id = int(input("Enter poll would you like to vote: "))
    poll = Poll.get(poll_id)
    poll_options = poll.options
    print_poll_options(poll_options)
    users_choice = int(input("Now choice the option: "))
    option = Option.get(users_choice)
    users_name = input("Enter your name: ")
    option.vote(users_name)
Пример #13
0
def show_poll_votes():
    poll_id = int(input("Enter poll you would like to see votes for: "))
    poll = Poll.get(poll_id)
    options = Poll.get(poll_id).options
    votes_per_option = [len(option.votes) for option in options]
    total_votes = sum(votes_per_option)

    try:
        for option, votes in zip(options, votes_per_option):
            percentage = votes / total_votes * 100
            print(f"{option.text} got {votes} votes ({percentage:.2f}% of total)")
    except ZeroDivisionError:
        print("No votes cast for this poll yet.")

    vote_log = input("Would you like to see the vote log? (y/N) ")

    if vote_log == "y":
        _print_votes_for_options(options)
Пример #14
0
def randomize_poll_winner():
    poll_id = int(input("Enter poll you'd like to see a winner for: "))
    poll = Poll.get(poll_id)
    print_poll_options(poll.options)
    option_id = int(input("Input id of option: "))
    option = Option.get(option_id)
    votes = option.votes
    winner = random.choice(votes)
    print(f"winner is {winner[0]}!")
Пример #15
0
    async def wizard(self, ctx, route, server):
        channel = await ask_for_channel(ctx, self.bot, server, ctx.message)
        if not channel:
            return

        pre = await get_server_pre(self.bot, server)

        # Permission Check
        # member = server.get_member(ctx.message.author.id)
        member = ctx.author
        if not member.guild_permissions.manage_guild:
            result = await self.bot.db.config.find_one({'_id': str(server.id)})
            if result and result.get('admin_role') not in [
                    r.name for r in member.roles
            ] and result.get('user_role') not in [
                    r.name for r in member.roles
            ]:
                await ctx.message.author.send(
                    'You don\'t have sufficient rights to start new polls on this server. '
                    'A server administrator has to assign the user or admin role to you. '
                    f'To view and set the permissions, an admin can use `{pre}userrole` and '
                    f'`{pre}adminrole`')
                return

        # Create object
        poll = Poll(self.bot, ctx, server, channel)

        # Route to define object, passed as argument for different constructors
        if ctx.message and ctx.message.content and not ctx.message.content.startswith(
                f'{pre}cmd '):
            poll.wizard_messages.append(ctx.message)
        try:
            await route(poll)
            poll.finalize()
            await poll.clean_up(ctx.channel)
        except StopWizard:
            await poll.clean_up(ctx.channel)
            return

        # Finalize
        await poll.save_to_db()
        return poll
Пример #16
0
def prompt_vote_poll():
    poll_id = int(input("Введите номер опроса, где хотели бы проголосовать: "))
    try:
        _print_poll_options(Poll.get(poll_id).options)

        option_id = int(input("Выберете интересующий Вас пункт: "))
        username = input("Введите свой ник: ")

        Option.get(option_id).vote(username)
    except TypeError:
        print("Нет опроса под этим номером!")
Пример #17
0
    def select_random_winner(cls):
        poll_ids = Poll.show_poll_ids()
        poll_id = input(
            "Enter an id of a poll voters of which you want to select a random winner from: "
        )
        while poll_id not in [str(id[0]) for id in poll_ids]:
            poll_id = input(
                "This is not a valid poll id. Enter a valid poll id: ")
        start_date = input(
            "Select a time period of which you want to pick up a random winner. \nEnter a start date and start hour (dd-mm-yyyy HH:MM): "
        )
        end_date = input(
            "Enter the end date and the end hour (dd-mm-yyyy HH:MM): ")
        try:
            start_date_naive = datetime.datetime.strptime(
                start_date.strip(), "%d-%m-%Y %H:%M")
            end_date_naive = datetime.datetime.strptime(
                end_date.strip(), "%d-%m-%Y %H:%M")
        except ValueError:
            input(
                "At least one of the dates you've entered is not in a valid date format. Try again. Press Enter..."
            )
            cls.select_random_winner()
            return
        if start_date_naive > end_date_naive:
            input(
                "End date cannot be older than the start date. Try again. Press Enter..."
            )
            cls.select_random_winner()
            return
        timezone_ = input("Enter your timezone: ")
        while timezone_ not in pytz.all_timezones:
            input(
                "You've entered an invalid timezone. Please try again. Press Enter..."
            )
            timezone_ = input("Enter your timezone: ")

        try:
            poll_id, poll_question, username, option_text, selectors_time_of_vote = Vote.select_random_winner(
                poll_id, start_date_naive, end_date_naive, timezone_)

            print(
                f'''\nA winner of a poll number {poll_id} answering a question "{poll_question}" is: {username}.
The winner responded "{option_text}". 
Time of vote: {selectors_time_of_vote.strftime("%d-%m-%Y %H:%M")}.    
            ''')

            input("\nPress Enter to continue...")

        except Exception:
            input("An error occurred. Press Enter...")

        finally:
            cls.select_from_menu()
Пример #18
0
def show_poll_votes():
    poll_id = int(input("Input id of poll you would like to see: "))
    poll = Poll.get(poll_id)
    options = poll.options
    votes_for_option = [len(option.votes) for option in options]
    sum_of_votes = sum(votes_for_option)
    try:
        for option, votes in zip(options, votes_for_option):
            vote_percentage = votes / sum_of_votes * 100
            print(f"{option.text} got {votes} ({vote_percentage}% of total)")
    except ZeroDivisionError:
        print("Poll didnt'd get any votes")
Пример #19
0
async def create_in_db(db: AsyncIOMotorDatabase, *, poll: Poll) -> InsertOneResult:

    existing_poll = await get_poll(db, slug=slugify(poll.name))

    if existing_poll:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="This poll already exists!"
        )

    poll_in_db = Poll(name=poll.name, slug=slugify(poll.name)).dict()
    db_response = await db[POLL_COLLECTION_NAME].insert_one(poll_in_db)
    return db_response
Пример #20
0
def randomize_poll_winner():
    poll_id = int(
        input("Введите номер опроса, где хотите выбрать победителя: "))
    _print_poll_options(Poll.get(poll_id).options)

    option_id = int(
        input(
            "Введите номер выигрышного ответа, победитель будет выбран из проголосавших за него: "
        ))
    votes = Option.get(option_id).votes
    winner = random.choice(votes)
    print(f"Произвольно выбранный победитель: {winner[0]}.")
Пример #21
0
def prompt_create_poll():
    title = input("Enter poll title: ")
    owner = input("Enter poll owner: ")
    poll = Poll(title, owner)
    poll.save()
    while (new_option := input(NEW_OPTION_PROMPT)):
        poll.add_option(new_option)
Пример #22
0
def prompt_create_poll():
    poll_title = input("Input poll title: ")
    poll_owner = input("input poll owner: ")
    poll = Poll(poll_title, poll_owner)
    poll.save()
    while new_option := input(NEW_OPTION_PROMPT):
        poll.add_option(new_option)
def show_poll_votes():
    poll_id = int(input("Enter poll you would like to see votes for: "))
    poll = Poll.get(poll_id)
    options = poll.options
    votes_per_option = [len(option.votes) for option in options]
    total_votes = sum(votes_per_option)

    try:
        for option, votes in zip(options, votes_per_option):
            percentage = votes / total_votes * 100
            print(f"{option.text} for {votes} ({percentage:.2f}% of total)")
    except ZeroDivisionError:
        print("No votes yet cast for this poll.")
Пример #24
0
def prompt_create_poll():
    poll_title = input("Введите название опроса: ")
    poll_owner = input("Введите имя создателя  опроса: ")
    poll = Poll(poll_title, poll_owner)
    poll.save()

    while new_option := input(NEW_OPTION_PROMPT):
        poll.add_option(new_option)
Пример #25
0
def prompt_create_poll():
    poll_title = input("Enter poll title: ")
    poll_owner = input("Enter poll owner: ")
    poll = Poll(poll_title, poll_owner)
    poll.save()

    while new_option := input(
            NEW_OPTION_PROMPT):  # Empty string ends this loop
        poll.add_option(new_option)
Пример #26
0
def getPollsByUser(user_id):
    try:
        polls = Poll.query(Poll.ownerID == user_id).fetch()
        user_polls = list()
        if polls:
            for poll in polls:
                user_polls.append({"poll_id": poll.key.id(), "title": poll.title, "description": poll.description})

            return {"user_id": user_id, "user_polls": user_polls}

        else:
            return {"error": "No Polls have been created by user yet"}

    except LookupError as e:
        return {"error": "There has been an error: %s"%e}
Пример #27
0
def prompt_create_poll():
    poll_title = input("Enter poll title: ")
    poll_owner = input("Enter poll owner: ")
    poll = Poll(poll_title, poll_owner)
    poll.save()

    new_option = input(NEW_OPTION_PROMPT)
    while new_option != "":
        poll.add_option(new_option)
        new_option = input(NEW_OPTION_PROMPT)
Пример #28
0
def group_start(update: Update, context: CallbackContext) -> State:
    if update.effective_chat.type == 'group':
        # create poll based on received event ID
        words = update.effective_message.text.split(' ')

        if len(words) <= 1:
            update.message.reply_text('Please specify the event ID')
        else:
            event_uuid = words[1]
            event = Event.get(uuid=event_uuid)

            if event == None:
                update.message.reply_text(
                    f"Event with ID {event_uuid} does not exist\nPlease try again"
                )
                return None

            context.chat_data['event_id'] = event.id

            poll = Poll.get(event=event.id)
            event_dates = poll.options

            if len(event_dates) == 1:
                update.message.reply_text(
                    f'Hi everybody ! You have been invited to the event {event.name} which will take place on the {event.date}.\n The location is : {event.location}. \n\n Have a nice event !!!'
                )
            else:
                message: Message = context.bot.send_poll(
                    update.effective_chat.id,
                    f"Hi everybody ! You have been invited to the event {event.name} which will take place at : {event.location}.\n\nPlease answer the following poll with your availability so that the date can be chosen.",
                    event_dates,
                    is_anonymous=False,
                    allows_multiple_answers=True,
                )

                update.effective_user.send_message(
                    "Here is the poll for your event")
                message.forward(update.effective_user.id)

                options = [event_dates]
                update.effective_user.send_message(
                    "Have you made your choice for the date ?",
                    reply_markup=ReplyKeyboardMarkup(options,
                                                     one_time_keyboard=True))

            return State.VOTING
    else:
        update.message.reply_text('This command can only be issued in a group')
Пример #29
0
    async def close_activate_polls(self):
        remove_list = []
        for pid, t in self.bot.refresh_blocked.items():
            if t - time.time() < 0:
                remove_list.append(pid)
                if self.bot.refresh_queue.get(pid, False):
                    query = await self.bot.db.polls.find_one(
                        {'_id': ObjectId(pid)})
                    if query:
                        p = Poll(self.bot, load=True)
                        await p.from_dict(query)
                        await p.refresh(self.bot.refresh_queue.get(pid))
                        del self.bot.refresh_queue[pid]

        # don't change dict while iterating
        for pid in remove_list:
            del self.bot.refresh_blocked[pid]
Пример #30
0
async def test_get_poll(init_db):
    db = init_db

    # Get Token headers
    headers = await create_user_and_get_token(db, client)

    # Create poll
    await crud.poll.create_in_db(db, poll=Poll(name=MOCK_POLL_NAME))

    # Get poll
    res = client.get(
        f"http://localhost:8000/poll/{slugify(MOCK_POLL_NAME)}", headers=headers
    )

    assert res.status_code is 200
    assert res.json()["name"] == MOCK_POLL_NAME
    assert res.json()["slug"] == slugify(MOCK_POLL_NAME)
Пример #31
0
def getPollsUserVoted(user_id):
     try:
        votes = Vote.query(Vote.voter == user_id).fetch()
        user_polls = list()
        if votes:
            for vote in votes:
                poll_vote = Poll.get_by_id(int(vote.poll))
                user_polls.append({"poll_id": poll_vote.key.id(), "title": poll_vote.title, "description": poll_vote.description, "user_vote": getUserVoteInPoll(user_id, poll_vote.key.id()) })

            return {"user_id": user_id, "voted_polls": user_polls}

        else:
            return {"error": "No Polls have been created by user yet"}

     except LookupError as e:
        return {"error": "There has been an error: %s"%e}

     except AttributeError as e:
          return {"error": "There has been an error: %s"%e}