Ejemplo n.º 1
0
def show_contest(contestId, chat_id, admin):
    try:
        contest = backend.get_contest_information(contestId)
        if not 'activity' in contest:
            activity = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
            backend.update_contest(contest['id'], {'activity': activity})
        else:
            activity = contest['activity']
        contestInformation = "<b>" + contest['name'] + ":</b>\n\n"
        for num in range(3):
            contestInformation += 'Div. ' + str((num + 1)) + ':\n'
            for (index, color) in enumerate(const.activity):
                contestInformation += str(color[0]) + ': ' + str(activity[num][index]) + '\n'
            contestInformation += '\n'

        rating = contest['allActivity']
        if admin:
            key = InlineKeyboardMarkup()
            but_1 = InlineKeyboardButton(text="Изменить активность",
                                         callback_data="choose_div " + str(contestId) + ' ' + str(chat_id))
            key.add(but_1)
            bot.send_message(chat_id, contestInformation + 'Активность за контест:\n\n<pre>' + rating + '</pre>', parse_mode="html", reply_markup=key)
        else:
            bot.send_message(chat_id, contestInformation + 'Активность за контест:\n\n<pre>' + rating + '</pre>',
                             parse_mode="html")
    except Exception as err:
        print('Не удалось показать информацию о контесте', err)
        bot.send_message(chat_id, 'Не удалось показать информацию о контесте')
Ejemplo n.º 2
0
def get_hq_contests():
    try:
        for ind in range(3):
            hq_contest = req.get_codeforces_contest_list(const.apiKey[ind], const.apiSecret[ind], True)
            for contest in hq_contest['result']:
                if contest['name'].find("Тренировка H2Q №") != -1 and const.authors.count(contest['preparedBy']) != 0:
                    finished = False
                    if contest['phase'] == 'FINISHED':
                        finished = True
                    backend.update_contest(str(contest['id']),
                                           {
                                               'name': contest['name'],
                                               'apis': [const.apiKey[ind], const.apiSecret[ind]],
                                               'finished': finished
                                           })
                    contest_inf = backend.get_contest_information(contest['id'])
                    if not 'activity' in contest_inf:
                        activity = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
                        backend.update_contest(contest['id'], {'activity': activity})
                    if not 'good_luck' in contest_inf or finished:
                        backend.update_contest(str(contest['id']), {'good_luck': finished})
                    if not 'reminder' in contest_inf or finished:
                        backend.update_contest(str(contest['id']), {'reminder': finished})
                    if contest['relativeTimeSeconds'] >= -600 and contest['phase'] == 'BEFORE' and not (
                            contest_inf['good_luck']):
                        backend.update_contest(str(contest['id']), {'good_luck': True})
                        good_luck()
                    if contest['relativeTimeSeconds'] >= -61200 and contest['phase'] == 'BEFORE' and not (
                            contest_inf['reminder']):
                        backend.update_contest(str(contest['id']), {'reminder': True})
                        reminder()
    except:
        print('CF UPAL')
Ejemplo n.º 3
0
def get_first_three_place(contestId):
    try:
        contestInfomation = backend.get_contest_information(contestId)
        cnt = 0
        firstPlaces = []
        for user in contestInfomation['users']:
            if contestInfomation['users'][user]['rank'] != 0:
                firstPlaces.append([user, contestInfomation['users'][user]['solvedCount']])
                cnt += 1
            if cnt == 3:
                break
        backend.update_contest(contestId, {'contestTop': firstPlaces})
    except:
        print('Не удалось взять топ 3')
Ejemplo n.º 4
0
def change_activity(mes, chat_id, args):
    try:
        activity = [0, 0, 0, 0, 0]
        mes += ' '
        pos = 1
        while mes.find(' ') != -1:
            s = mes[0 : mes.find(' ')]
            activity[pos] = int(s)
            pos += 1
            mes = mes[mes.find(' ') + 1: len(mes)]
        new_activity = backend.get_contest_information(args['contest_id'])['activity']
        new_activity[int(args['div']) - 1] = activity
        backend.update_contest(args['contest_id'], {'activity': new_activity})
        show_contest(args['contest_id'], chat_id, True)
    except Exception as err:
        print('Не удалось поменять активность', err)
        bot.send_message(chat_id, 'Не удалось поменять активность')
Ejemplo n.º 5
0
def print_contest_information(chatId, contestId):
    try:
        contest = backend.get_contest_information(contestId)
        contestTop = contest['contestTop']
        rating = contest['allRating']
        top = ""
        if len(contestTop) >= 1:
            top += "Топ:\n" + "🥇 " + backend.get_user(contestTop[0][0])['name'] + " - " + str(contestTop[0][1]) \
                   + " " + struct.declension(contestTop[0][1], "задача", "задачи", "задач") + "\n"
        if len(contestTop) >= 2:
            top += "🥈 " + backend.get_user(contestTop[1][0])['name'] + " - " + str(contestTop[1][1]) \
                   + " " + struct.declension(contestTop[1][1], "задача", "задачи", "задач") + "\n"
        if len(contestTop) >= 3:
            top += "🥉 " + backend.get_user(contestTop[2][0])['name'] + " - " + str(contestTop[2][1]) \
                   + " " + struct.declension(contestTop[2][1], "задача", "задачи", "задач") + "\n"
        if len(contestTop) >= 1:
            top += "\n"

        first_submit = ""
        if 'firstSubmission' in contest:
            first_submit = "Первая успешная посылка:\n" + backend.get_user(contest['firstSubmission']['name'])['name'] + "\n"\
                           + "Время посылки: " + str(contest['firstSubmission']['time']) + " " + \
                           struct.declension(contest['firstSubmission']['time'], "минута", "минуты", "минут") + "\n\n"
        key = InlineKeyboardMarkup()
        but_1 = InlineKeyboardButton(text="Посмотреть активность",
                                     callback_data="not_admin_contest_id" +
                                     str(contestId))
        key.add(but_1)
        bot.send_message(chatId,
                         "<b>" + contest['name'] + ":</b>\n\n" + first_submit +
                         top + "Рейтинг за тренировку:\n\n<pre>" + rating +
                         "</pre>",
                         parse_mode="html",
                         reply_markup=key)
    except Exception as err:
        bot.send_message(chatId,
                         "Произошла ошибка при выводе таблицы контеста", err)
Ejemplo n.º 6
0
def get_contest_information(contestId):
    try:
        contestId = str(contestId)
        contest = backend.get_contest_information(contestId)
        standings = req.get_codeforces_contest_stadings(contestId, contest['apis'][0], contest['apis'][1], True)
        contestInformation = {}
        contestInformation['name'] = req.get_contestName(contestId, contest['apis'][0], contest['apis'][1])

        users = {}
        maxSolved = 1
        problemCount = len(standings['result']['problems'])
        contestInformation['problemCount'] = problemCount

        for user in standings['result']['rows']:
            userName = user['party']['members'][0]['handle']
            userName = get_username(userName)
            if not is_participant(userName):
                continue
            user_id = backend.get_users({'handle': userName})[0]['user_id']
            user_inf = backend.get_user(user_id)
            if not (user_inf['is_participant']):
                continue
            if not (user_id in users):
                users[user_id] = {}
                users[user_id]['rank'] = user['rank']
                users[user_id]['solved'] = [False for i in range(problemCount)]
                users[user_id]['upsolved'] = [False for i in range(problemCount)]

        for user in standings['result']['rows']:
            userName = user['party']['members'][0]['handle']
            if userName.find('=') == -1:
                continue
            userName = get_username(userName)
            if not is_participant(userName):
                continue
            user_id = backend.get_users({'handle': userName})[0]['user_id']
            user_inf = backend.get_user(user_id)
            if not (user_inf['is_participant']):
                continue

            if user['rank'] != 0:
                users[user_id]['rank'] = user['rank']

            for index, problem in enumerate(user['problemResults']):
                if user['rank'] != 0:
                    if problem['points'] == 1:
                        users[user_id]['solved'][index] = True
                else:
                    if problem['points'] == 1:
                        users[user_id]['upsolved'][index] = True

        official = 0
        used = [0] * 200
        for user in users:
            user_inf = users[user]
            if user_inf['rank'] != 0:
                official += 1
                used[int(user_inf['rank'])] = user
            users[user]['solvedCount'], users[user]['upsolvedCount'] = get_solved_count(users[user]['solved'],
                                                                                        users[user]['upsolved'])
            maxSolved = max(maxSolved, users[user]['solvedCount'])

        top = 1
        for i in range(0, len(users)):
            if used[i] != 0:
                users[used[i]]['rank'] = top
                top += 1

        for user in backend.get_users({'is_participant': True}):
            user_id = user['user_id']
            if not (user_id in users):
                users[user_id] = {}
                users[user_id]['rank'] = 0
                users[user_id]['solvedCount'] = 0
                users[user_id]['upsolvedCount'] = 0
                users[user_id]['solved'] = [False for i in range(problemCount)]
                users[user_id]['upsolved'] = [False for i in range(problemCount)]

        for user in users:
            contest_activity = contest['activity']
            user_inf = backend.get_user(int(user))
            user_div = int(user_inf['division'])
            user_activity = -1
            for kol in contest_activity[user_div - 1]:
                if kol <= users[user]['solvedCount'] + users[user]['upsolvedCount']:
                    user_activity += 1
                users[user]['user_activity'] = user_activity

        contestInformation['users'] = users

        status = req.get_codeforces_contest_status(contestId, contest['apis'][0], contest['apis'][1])
        try:
            for submission in range(len(status['result']) - 1, -1, -1):
                name = get_username(status['result'][submission]['author']['members'][0]['handle'])
                if not is_participant(name):
                    continue
                user_id = backend.get_users({'handle': name})[0]['user_id']
                user_inf = backend.get_user(user_id)
                if not (user_inf['is_participant']):
                    continue
                if status['result'][submission]['verdict'] == 'OK':
                    contestInformation['firstSubmission'] = {}
                    contestInformation['firstSubmission']['name'] = backend.get_users({'handle': name})[0]['user_id']
                    contestInformation['firstSubmission']['time'] = status['result'][submission][
                                                                        'relativeTimeSeconds'] // 60
                    break
        except Exception as err:
            print("Trouble with status", err)
        backend.update_contest(contestId, contestInformation)
    except Exception as err:
        print("Failed Contest Information", err)
Ejemplo n.º 7
0
def get_sortedRating(contestId):
    try:
        contest_information = backend.get_contest_information(contestId)
        sortedRating = []
        for user in contest_information['users']:
            sortedRating.append(
                [contest_information['users'][user]['solvedCount'], contest_information['users'][user]['upsolvedCount'],
                 user]
            )

        def compare(x, y):
            if x[0] + x[1] > y[0] + y[1] or x[0] + x[1] == y[0] + y[1] and x[0] > y[0]:
                return -1
            elif x[0] + x[1] < y[0] + y[1] or x[0] + x[1] == y[0] + y[1] and x[0] < y[0]:
                return 1
            else:
                return 0

        sortedRating = sorted(sortedRating, key=cmp_to_key(compare))
        backend.update_contest(contestId, {'sortedRating': sortedRating})
        rating = table.Texttable()
        rating.set_deco(table.Texttable.HEADER)
        rating.set_cols_align(["l", "c", "r"])
        rating.set_cols_valign(["t", "t", "t"])
        rating.set_cols_dtype(['t', 't', 't'])
        rating.add_row(["Фамилия\n", "🏆\n", "Задачи"])
        space = '  '
        for index, item in enumerate(sortedRating):
            userName = backend.get_user(item[2])['name']
            name = userName[userName.find(' ') + 1:]
            if index == 9:
                space = ' '
            rating.add_row([str(index + 1) + space +
                            str(name),
                            str(contest_information['users'][item[2]]['solvedCount'] +
                                contest_information['users'][item[2]]['upsolvedCount']),
                            str(contest_information['users'][item[2]]['solvedCount']) + "/" + str(
                                contest_information['users'][item[2]]['upsolvedCount'])
                            ])
        backend.update_contest(contestId, {'allRating': rating.draw()})
        activity = table.Texttable()
        activity.set_deco(table.Texttable.HEADER)
        activity.set_cols_align(["l", "c", "c"])
        activity.set_cols_valign(["t", "t", "t"])
        activity.set_cols_dtype(['t', 't', 't'])
        activity.add_row(["Фамилия\n", "Div.\n", "Активность\n"])
        space = '  '
        for index, user in enumerate(sortedRating):
            user_inf = backend.get_user(user[2])
            user_div = int(user_inf['division'])
            userName = user_inf['name']
            name = userName[userName.find(' ') + 1:]
            user_activity = -1
            for kol in contest_information['activity'][user_div - 1]:
                if kol <= contest_information['users'][user[2]]['solvedCount'] + \
                        contest_information['users'][user[2]]['upsolvedCount']:
                    user_activity += 1
            backend.update_contest(contestId, {'users.' + user[2] + '.user_activity': user_activity})
            if index == 9:
                space = ' '
            activity.add_row([str(index + 1) + space + str(name),
                              str(user_div),
                              const.activity[user_activity][0]])
        backend.update_contest(contestId, {'allActivity': activity.draw()})
    except Exception as err:
        print('Ошибка при получении отсортированного рейтинга за контест', err)
Ejemplo n.º 8
0
def get_user_infomation():
    try:
        user_information = {}
        contest = {}
        for contest_inf in backend.get_contests():
            contestId = contest_inf['contest_id']
            contest[contestId] = {}
            contest[contestId] = backend.get_contest_information(contestId)

        for user in backend.get_users({'is_participant': True}):
            user_id = user['user_id']
            user_information[user_id] = {}
            user_information[user_id]['name'] = backend.get_user(user_id)['name']
            user_information[user_id]['achievements'] = ''
            user_information[user_id]['activity'] = 0
            user_information[user_id]['last_activities'] = []
            unsolvedCount = 0
            solvedCount = 0
            solvedCountLast = 0
            allCount = 0
            for (index, contest_inf) in enumerate(backend.get_contests()):
                contestId = contest_inf['contest_id']
                if user_id in contest[contestId]['users']:
                    unsolvedCount += contest[contestId]['problemCount'] - \
                                     (contest[contestId]['users'][user_id]['solvedCount'] +
                                      contest[contestId]['users'][user_id]['upsolvedCount'])
                    solvedCount += contest[contestId]['users'][user_id]['solvedCount'] + \
                                   contest[contestId]['users'][user_id][
                                       'upsolvedCount']
                    rank = contest[contestId]['users'][user_id]['rank']
                    if rank == 1:
                        user_information[user_id]['achievements'] += "🥇"
                    elif rank == 2:
                        user_information[user_id]['achievements'] += "🥈"
                    elif rank == 3:
                        user_information[user_id]['achievements'] += "🥉"
                    if len(contest) - index <= 5:
                        solvedCountLast += contest[contestId]['users'][user_id]['solvedCount'] + \
                                           contest[contestId]['users'][user_id]['upsolvedCount']
                        allCount += contest[contestId]['problemCount']
                        user_information[user_id]['last_activities'].append(
                            contest[contestId]['users'][user_id]['user_activity'])
                        user_information[user_id]['activity'] += contest[contestId]['users'][user_id]['user_activity']

            user_information[user_id]['activity'] = round(
                user_information[user_id]['activity'] / min(5, max(1, len(contest))))
            user_inf = backend.get_user(user_id)
            if user_information[user_id]['achievements'] == '' and (
                    'custom_achievements' in user_inf and len(user_inf['custom_achievements']) == 0 or not (
                    'custom_achievements' in user_inf)):
                user_information[user_id]['achievements'] = 'Пока тут ничего нет :('
            user_information[user_id]['solved'] = solvedCount
            user_information[user_id]['unsolved'] = unsolvedCount
            user_information[user_id]['solvedLast'] = solvedCountLast
            user_information[user_id]['allLast'] = allCount
            user_information[user_id]['active_name'] = user_information[user_id]['name'] + ' ' + \
                                                       const.activity[user_information[user_id]['activity']][0]
            updates = user_information[user_id]
            backend.update_user(user_id, updates)
    except Exception as err:
        print('Не удалось взять личную информацию пользователей', err)