def add_activity(activity, event_id):
    data = client.query(q.get(q.ref(q.collection("event"), event_id)))['data']

    data['activityLog'].append(activity)
    data['base'] -= activity['damage']

    if data['base'] <= 0:
        delete_event(event_id)
        return 'd'

    update_event(event_id, data)
    return 'u'
def writeDataToDatabase(responseJson, matchID, process_name, collection_name):
    try:
        client.query(
            q.create(q.ref(q.collection(collection_name), matchID),
                     {"data": responseJson}))
    except Exception as e:
        if str(e) != 'Document already exists':
            data = matchID
            publisher.publish(topic_path, data=data.encode('utf-8'))
    logging.debug(
        log_with_process_name(process_name,
                              f'Added matchID {matchID} to database'))
Exemple #3
0
def end_quiz(update, context):
    chat_id = update.effective_chat.id
    message = update.message.text
    try:
        name = update["message"]["chat"]["first_name"]
    except:
        name = update["message"]["chat"]["username"]

    quizzes = client.query(q.paginate(q.match(q.index("quiz"), chat_id)))
    user = client.query(q.get(q.match(q.index("users"), chat_id)))

    #Gets uncompleted quiz

    quizzz = []
    for i in quizzes["data"]:
        quiz_ = client.query(q.get(q.ref(q.collection("quiz"), i.id())))
        if not quiz_["data"]["completed"]:
            quizzz.append(quiz_)

    quiz = quizzz[-1]

    client.query(
        q.update(q.ref(q.collection("users"), user["ref"].id()),
                 {"data": {
                     "last_command": "end_quiz"
                 }}))

    client.query(
        q.update(q.ref(q.collection("quiz"), quiz["ref"].id()),
                 {"data": {
                     "completed": True
                 }}))
    context.bot.send_message(
        chat_id=chat_id,
        text=f"Quiz completed\nScore: {int(quiz['data']['score'])}/10 ",
        reply_markup=telegram.ReplyKeyboardRemove())

    botler = Botler().get()
    msg = messenger.get(name, botler)
    context.bot.send_message(chat_id=chat_id, text=msg)
Exemple #4
0
def answer_quiz(request,slug):
    question_all=client.query(q.paginate(q.match(q.index("question_get_index"), slug)))["data"]
    question_count=len(question_all)
    page_number = int(request.GET.get('page', 1))
    question = client.query(q.get(q.ref(q.collection("Question"), question_all[page_number-1].id())))["data"]
    if page_number==question_count:
        context={"question":question,"next_page": min(question_count, page_number + 1), "prev_page": max(1, page_number - 1),"finish":"true"}
    else:
        context={"question":question,"next_page": min(question_count, page_number + 1), "prev_page": max(1, page_number - 1)}
    if request.method=="POST":
        answer=request.POST.get("answer")
        question=request.POST.get("question")
        try:
            check_answer=client.query(q.get(q.match(q.index("answer_get_index"), request.session["user"]["username"],question)))["data"]
            messages.add_message(request, messages.INFO, 'You already answered this question')
        except Exception:
            answer_create = client.query(q.create(q.collection("Answers"), {
                "data": {
                    "user": request.session["user"]["username"],
                    "quiz": slug,
                    "question": question,
                    "answer": answer,
                }
            }))
            messages.add_message(request, messages.INFO, 'Answer Saved')
    if request.GET.get("finish")=="true":
        score=0
        check_answer=client.query(q.paginate(q.match(q.index("answer_score_index"), request.session["user"]["username"],slug)))
        all_answer=[]
        for i in check_answer["data"]:
            all_answer.append(q.get(q.ref(q.collection("Answers"),i.id())))
        answers=client.query(all_answer)
        for i in answers:
            try:
                mark_answer=client.query(q.get(q.match(q.index("question_answer"),i["data"]["answer"])))
                score=score+1
            except:
                score=score
        context={"score":score,"question_count":question_count}
    return render(request,"answer_quiz.html",context)
def dashboard():

    elections = client.query(
        q.paginate(
            q.match(q.index("election_index"), session["user"]["username"])))

    elections_ref = []
    for i in elections["data"]:
        elections_ref.append(q.get(q.ref(q.collection("Elections"), i.id())))

    return render_template("dashboard.html",
                           elections=client.query(elections_ref),
                           length=lambda x: len(x))
def election(election_id):
    try:
        election = client.query(
            q.get(q.ref(q.collection("Elections"), election_id)))

        if election["data"]["creator"] != session["user"]["username"]:
            return redirect(url_for('vote', election_id=election_id))
        else:
            return redirect(
                url_for('view_single_election', election_id=election_id))

    except:
        return render_template('404.html')
    def test_set(self):
        index = Ref("frogs_by_size", Native.INDEXES)
        json_index = '{"@ref":{"collection":{"@ref":{"id":"indexes"}},"id":"frogs_by_size"}}'
        match = SetRef(query.match(index, self.ref))
        json_match = '{"@set":{"match":%s,"terms":%s}}' % (json_index,
                                                           self.json_ref)
        self.assertJson(match, json_match)

        self.assertNotEqual(
            match,
            SetRef(
                query.match(index, query.ref(query.collection("frogs"),
                                             "456"))))
Exemple #8
0
def loans():
    loans = client.query(
        q.paginate(
            q.match(q.index("loans_by_pending"), True),
            size=100_000
        )
    )
    loans_data = [
        q.get(
            q.ref(q.collection("loans"), loan.id())
        ) for loan in loans["data"]
    ]
    return render_template("loans.html", loans_data=client.query(loans_data))
Exemple #9
0
def reply_question(question_id):
    try:
        question = client.query(
            q.get(q.ref(q.collection("questions"), question_id)))
        if question["data"]["user_asked"] != session["user"]["username"]:
            raise Exception()
    except:
        abort(404)

    if request.method == "POST":
        client.query(
            q.update(
                q.ref(q.collection("questions"), question_id), {
                    "data": {
                        "answer": request.form.get("reply").strip(),
                        "resolved": True
                    }
                }))
        flash("You have successfully responded to this question!", "success")
        return redirect(url_for("reply_question", question_id=question_id))

    return render_template("reply-question.html", question=question)
def update(collection, id, data):
    """
    Update Record
    """
    try:
        serverClient = FaunaClient(
            secret=os.environ.get("FAUNA_SERVER_SECRET"))
        res = serverClient.query(
            q.update(q.ref(q.collection(collection), id), {"data": data}))
        res["data"]["ref_id"] = res["ref"].id()
        return res["data"]
    except Exception as ex:
        raise ex
Exemple #11
0
def today_appointment(request):
    if "user" in request.session:
        appointments = client.query(
            q.paginate(
                q.match(q.index("events_today_paginate"),
                        request.session["user"]["username"],
                        str(datetime.date.today()))))["data"]
        appointments_count = len(appointments)
        page_number = int(request.GET.get('page', 1))
        appointment = client.query(
            q.get(
                q.ref(q.collection("Events"),
                      appointments[page_number - 1].id())))["data"]
        if request.GET.get("complete"):
            client.query(
                q.update(
                    q.ref(q.collection("Events"),
                          appointments[page_number - 1].id()),
                    {"data": {
                        "status": "True"
                    }}))["data"]
            return redirect("App:today-appointment")
        if request.GET.get("delete"):
            client.query(
                q.delete(
                    q.ref(q.collection("Events"),
                          appointments[page_number - 1].id())))
            return redirect("App:today-appointment")
        context = {
            "count": appointments_count,
            "appointment": appointment,
            "page_num": page_number,
            "next_page": min(appointments_count, page_number + 1),
            "prev_page": max(1, page_number - 1)
        }
        return render(request, "today-appointment.html", context)
    else:
        return HttpResponseNotFound("Page not found")
Exemple #12
0
def find_order(secret, order_ref):
    client = FaunaClient(secret=secret)
    return client.query(
        q.let(
            {
                "order": q.get(q.ref(q.collection("orders"), order_ref)),
                "status_history": q.call("get_order_status_history", q.select(["ref"], q.var("order")))
            }, 
            {
                "ref": q.select(["ref"], q.var("order")),
                "data": q.merge(q.select(["data"], q.var("order")), {"status_history": q.var("status_history")})
            }
        )
    )
def add_appointment(update, context):
    chat_id = update.effective_chat.id

    user = client.query(q.get(q.match(q.index("users_index"), chat_id)))
    client.query(
        q.update(q.ref(q.collection("Users"), user["ref"].id()),
                 {"data": {
                     "last_command": "add_appointment"
                 }}))
    context.bot.send_message(
        chat_id=chat_id,
        text=
        "Enter the appointment event you want to add along with its due in this format(mm/dd/yyyy) date seperated by a comma 😁"
    )
Exemple #14
0
def update_product(secret, ref, data):
    client = FaunaClient(secret=secret)
    if(data.get("categories") == None):
        return client.query(q.update(
            q.ref(q.collection('products'), ref),
            { "data": data }
        ))
    
    return client.query(
        q.if_(
            q.call('check_if_categories_exists', data.get("categories")),
            q.update(
                q.ref(q.collection('products'), ref),
                { "data": {
                    **data,
                    "categories": list(map(
                        lambda category: q.ref(q.collection("categories"), category),
                        data.get("categories")
                    ))
                } }
            ),
            q.abort('Categories not found'),
        )
    ) 
Exemple #15
0
def send_broadcast(args):
    print(args)
    try:
        updater.bot.send_message(chat_id=args[0], text=args[1])
    except Unauthorized:
        # user blocked bot so delete user from list
        user = client.query(q.get(q.ref(q.collection(users), args[0])))
        client.query(q.delete(user['ref'], ))
        logger.info("a user has been deleted from user list")
        return ''
    except Exception as err:
        log_error(err)
        return ''
    else:
        return 'success'
def donate(update, context):
    try:
        for message in config['message']['donate']:
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text=message)
        client.query(
            q.let(
                {'user': q.ref(q.collection(users), update.effective_chat.id)},
                q.if_(
                    q.exists(q.var('user')),
                    q.update(q.var('user'), {'data': {
                        'last_command': '',
                    }}), 'Success!')))
    except Exception as err:
        log_error(err)
def updatePairInformationForTeam(hero_ids, team_win):
    key_list=[]
    for k in range(0, len(hero_ids)):
        for j in range(k + 1, len(hero_ids)):
            if hero_ids[k] < hero_ids[j]:
                key = format(hero_ids[k], '03d') + format(hero_ids[j], '03d')
            else:
                key = format(hero_ids[j], '03d') + format(hero_ids[k], '03d')
            key_list.append(key)

    try: 
        hero_data_list=client.query(
            q.map_(
                q.lambda_(
                    'hero_pair',
                    q.get(q.ref(q.collection('hero_pairs'), q.var('hero_pair')))
                ),
                key_list
            )
        )
    except Exception as e:
        logging.info(e)
        logging.info(key_list)

    hero_team_list=[]
    for hero_data in hero_data_list :
        hero_team_dictionary = {}
        hero_pair_ref=hero_data['ref']
        hero_pair_data = hero_data['data']
        hero_pair_data['games']+=1
        if team_win:
            hero_pair_data['wins'] += 1
        hero_team_dictionary['ref']=hero_pair_ref
        hero_team_dictionary['data']=hero_pair_data
        hero_team_list.append(hero_team_dictionary)

    client.query(
        q.map_(
            q.lambda_(
                'hero_pair',
                q.update(
                    q.select(['ref'],q.var('hero_pair')),
                    {'data': q.select(['data'], q.var('hero_pair'))}
                )
            ),
            hero_team_list
        )
    )
    def get_all_tweets(self):
        """ Fetch all tweets in the tweets collection """
        try:
            # Using the "all_tweets" index
            tweets = client.query(q.paginate(q.match(q.index('all_tweets'))))
        except (Exception, NotFound) as e:
            return None

        if tweets.get('errors'):
            return None
        else:
            return list(
                map(
                    lambda tweet: client.query(
                        q.get(q.ref(q.collection(self.collection), tweet.id()))
                    )['data'], tweets['data']))
Exemple #19
0
def list_todo(update, context):
    chat_id = update.effective_chat.id

    task_message = ""
    tasks = client.query(q.paginate(q.match(q.index("todo"), chat_id)))
    for i in tasks["data"]:
        task = client.query(q.get(q.ref(q.collection("todo"), i.id())))
        if task["data"]["completed"]:
            task_status = "Completed"
        else:
            task_status = "Not Completed"
        task_message += "{}\nStatus: {}\nUpdate Link: /update_{}\nDelete Link: /delete_{}\n\n".format(
            task["data"]["todo"], task_status, i.id(), i.id())
    if task_message == "":
        task_message = "You have not added any task, do that with /add_todo 😇"
    context.bot.send_message(chat_id=chat_id, text=task_message)
Exemple #20
0
def view_profile(username):
    try:
        user = client.query(q.get(q.match(q.index("users_index"), username)))
    except:
        abort(404)

    question_indexes = client.query(
        q.paginate(q.match(q.index("questions_index"), True, username),
                   size=100_000))
    questions = [
        q.get(q.ref(q.collection("questions"), i.id()))
        for i in question_indexes["data"]
    ]
    return render_template("view-profile.html",
                           username=username,
                           questions=client.query(questions)[::-1])
def help_user(update, context):
    user = User(update.effective_chat.id)
    if str(user.chat_id) == str(os.getenv('ADMIN_CHAT_ID')):
        message = config['message']['help_admin']
    else:
        message = config['message']['help']
    context.bot.send_message(chat_id=user.chat_id, text=message)
    try:
        client.query(
            q.let({'user': q.ref(q.collection(users), user.chat_id)},
                  q.if_(
                      q.exists(q.var('user')),
                      q.update(q.var('user'), {'data': {
                          'last_command': '',
                      }}), 'Success!')))
    except Exception as err:
        log_error(err)
    def get_all_users(self):
        """ Get all the users in the users collection """
        try:
            # Using the "all_users" index defined in FaunaDB indexes for the database
            users = client.query(q.paginate(q.match(q.index('all_users'))))
        except NotFound as e:
            return None

        if users.get('errors'):
            return None
        else:
            # Get the data for each user Fauna ID returned.
            return list(
                map(
                    lambda user: client.query(
                        q.get(q.ref(q.collection('users'), user.id())))[
                            'data'], users['data']))
    def get_user_following(self, user_id: str):
        """ Get all users being followed by a specific user """
        try:
            user_following = client.query(
                q.paginate(q.match(q.index('get_user_following'), user_id)))
        except (Exception, NotFound) as e:
            return str(e) or None

        following_ids = list(
            map(
                lambda relationship: client.query(
                    q.get(
                        q.ref(q.collection(self.collection), relationship.id())
                    ))['data']['following_id'], user_following['data']))
        user_following = list(
            map(lambda user_id: User().get_user(user_id)['data'],
                following_ids))
        return user_following
def event_id_from_project_id(project_id):
    return int(
        client.query(
            q.get(
                q.match(
                    q.index("event_by_region_name"),
                    client.query(
                        q.get(
                            q.ref(
                            q.collection("projects"),
                            project_id
                            )
                        )
                    )['data']['region']
                )
            )
        )['ref'].id()
    )
Exemple #25
0
def create_product(secret, name, price, quantity, categories):
    client = FaunaClient(secret=secret)
    return client.query(
        q.if_(
            q.call('check_if_categories_exists', categories),
            q.create(q.collection('products'), {"data": { 
                "name": name,
                "price": price,
                "quantity":quantity,
                "createdAt": q.now(),
                "categories": list(map(
                    lambda category: q.ref(q.collection("categories"), category),
                    categories
                ))
             }}),
            q.abort('Categories not found'),
        )
    )
def list_appointments(update, context):
    chat_id = update.effective_chat.id

    event_message = ""
    events = client.query(
        q.paginate(q.match(q.index("appointment_index"), chat_id)))
    for i in events["data"]:
        event = client.query(q.get(q.ref(q.collection("Appointments"),
                                         i.id())))
        if event["data"]["completed"]:
            event_status = "Completed"
        else:
            event_status = "Not Completed"
        event_message += "{}\nStatus:{} \nDate Due: {}\nUpdate Link: /update_{}\nDelete Link: /delete_{}\n\n".format(
            event["data"]["event"], event_status, event["data"]["date_due"],
            i.id(), i.id())
    if event_message == "":
        event_message = "You dont hava any appointments saved, type /add_appointment to schedule one now 😇"
    context.bot.send_message(chat_id=chat_id, text=event_message)
    def get_user_followers(self, user_id: str):
        """ Fetch all users following a specific user """
        try:
            user_followers = client.query(
                q.paginate(q.match(q.index('get_user_followers'), user_id)))
            print(user_followers['data'])
        except (Exception, NotFound) as e:
            return str(e) or None

        followers_id = list(
            map(
                lambda relationship: client.query(
                    q.get(
                        q.ref(q.collection(self.collection), relationship.id())
                    ))['data']['follower_id'], user_followers['data']))
        user_followers = list(
            map(lambda user_id: User().get_user(user_id)['data'],
                followers_id))
        return user_followers
    def get_all_user_tweets(self, user_id: str):
        """ Fetch all tweets for a specific user """
        try:
            # Using the "tweets_by_user" index
            user_tweets = client.query(
                q.paginate(q.match(q.index('tweets_by_user'), user_id)))
            print(user_tweets)
        except (Exception, NotFound) as e:
            return None

        if user_tweets.get('errors'):
            return None
        else:
            # Returns tweet documents for the user
            return list(
                map(
                    lambda tweet: client.query(
                        q.get(q.ref(q.collection(self.collection), tweet.id()))
                    )['data'], user_tweets['data']))
Exemple #29
0
    def delete(self, post_id):
        try:
            post_id = post_id.encode('ascii', 'ignore')
            result = client.query(q.delete(q.ref(q.class_("posts"), post_id)))
        except fauna_error.NotFound as e:
            app.logger.debug(e)
            return Response(
                jsonify('Failed to delete a post - post not found.'),
                status=404,
                mimetype='application/json')
        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to delete a post.'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=204,
                        mimetype='application/json')
def getTopHeroPairs(hero_id, n):
    logging.info(f'Query: Fetching top {n} partners for hero: {hero_id}')
    key_list = []
    id_list = []
    for k in range(1, hero_id):
        key = format(k, '03d') + format(hero_id, '03d')
        key_list.append(key)
        id_list.append(k)
    for k in range(hero_id + 1, 130):
        key = format(hero_id, '03d') + format(k, '03d')
        key_list.append(key)
        id_list.append(k)
    try:
        hero_data_list = client.query(
            q.map_(
                q.lambda_(
                    'hero_pair',
                    q.get(q.ref(q.collection('hero_pairs'),
                                q.var('hero_pair')))), key_list))
        logging.debug(
            'Finished querying the hero_pair collection successfully')

        hero_team_list = []
        for i in range(0, len(hero_data_list)):
            hero_team_dictionary = {'partner_id': id_list[i]}
            if hero_data_list[i]['data']['games'] > 0:
                hero_team_dictionary['win_rate'] = format(
                    hero_data_list[i]['data']['wins'] /
                    hero_data_list[i]['data']['games'], '.4f')
            else:
                hero_team_dictionary['win_rate'] = '0.0000'
            hero_team_list.append(hero_team_dictionary)

        hero_team_list = sorted(hero_team_list,
                                key=lambda i: i['win_rate'],
                                reverse=True)

        logging.info('Returning from the function getTopHeroPairs')
        return hero_team_list[0:n]

    except Exception as e:
        logging.error(e)
        logging.error('Could not fetch from hero_pairs collection')