示例#1
0
def send_everyone(contestId):
    connection = data.create_connection(dbname)

    ids = data.execute_read_query(connection, ids_handler.select_all_ids())
    contestants, name = cf.get_contestants(contestId)
    if contestants is None:
        connection.close()
        return

    for x in ids:
        id = x[0]
        handles = data.execute_read_query(connection,
                                          ids_handler.select_cf_handles(id))

        maxLenNickname = 0
        for y in handles:
            handle = y[0]
            if contestants.get(handle) is None:
                continue
            maxLenNickname = max(maxLenNickname, len(handle))

        if maxLenNickname == 0:
            continue

        results = list()

        for y in handles:
            handle = y[0]
            if contestants.get(handle) is None:
                continue
            oldRating = contestants[handle][0]
            newRating = contestants[handle][1]
            delta = newRating - oldRating
            if delta < 0:
                delta = str(delta)
            else:
                delta = '+' + str(delta)

            results.append((handle, oldRating, newRating, delta))

        results.sort(reverse=True, key=lambda x: int(x[3]))

        header = '[{0}](https://codeforces.com/contest/{1}) был обновлен!\n\n'.format(
            name, contestId)
        message = ''

        for handle, oldRating, newRating, delta in results:
            message += handle
            message += ': '
            message += ' ' * (maxLenNickname - len(handle))
            message += '{0} -> {1} ({2})\n'.format(oldRating, newRating, delta)

        send_message(id,
                     message,
                     header=header,
                     mode='markdown',
                     web_page_preview=False,
                     all_monospace=True)

    connection.close()
示例#2
0
def sync(message):
    id = message.chat.id
    if (message.chat.type == 'group'):
        send_message(
            id,
            'Эта команда не может быть выполнена в групповых чатах в целях безопасности ваших данных'
        )
    else:
        connection = data.create_connection(dbname)

        elems = data.execute_read_query(connection,
                                        keys_handler.select_keys(id))
        if elems == []:
            send_message(id, 'Вы не добавили api ключи. Посмотрите /help')
        else:
            open, secret = elems[0]
            handles, status = cf.get_friends(open, secret)

            if handles is None:
                if 'Incorrect API key' in status:
                    send_message(id, 'Вы указали неправильные ключи')
                else:
                    send_message(
                        id,
                        'Что-то пошло не так. Скорее всего, codeforces сейчас недоступен.'
                    )
                    logger.critical(status)
            else:
                send_message(
                    id,
                    util.__add_handles(id,
                                       list(map(lambda x: x.lower(), handles)),
                                       handles, connection))

        connection.close()
示例#3
0
def _clear(id, connection):
    size = data.execute_read_query(connection,
                                   ids_handler.count_handles(id))[0][0]
    data.execute_query(connection, ids_handler.remove_id(id))

    if size > maximumExtraHandles:
        data.execute_query(connection, data.delete_extra_handles())

    data.execute_query(connection, keys_handler.remove_keys(id))
    data.execute_query(connection, queue_handler.remove_id(id))
    return 'Все данные успешно удалены'
示例#4
0
def __add_handles(id, handles, handles_cf, connection):
    added = data.execute_read_query(connection, ids_handler.select_handles(id))
    size = len(set(list(map(lambda x: x[0], added)) + handles))

    if size > limit:
        return 'Общее количество хэндлов не может превышать {0}'.format(limit)

    for i in range(len(handles)):
        handle = handles[i]
        cf_handle = handles_cf[i]

        data.execute_query(connection, ids_handler.insert_handle(id, handle))
        data.execute_query(connection,
                           handles_handler.insert_handles(handle, cf_handle))

    return 'Все хэндлы успешно добавлены'
示例#5
0
def check_changes():
    try:
        resp = requests.get(
            'https://codeforces.com/api/contest.list?gym=false').json()
    except Exception as e:
        logger.critical(str(e))
        return list()

    if resp['status'] == 'FAILED':
        logger.critical(resp['comment'])
        return list()

    res = list()
    connection = data.create_connection(dbname)

    i = 0
    while resp['result'][i]['relativeTimeSeconds'] < maxTime:
        id = resp['result'][i]['id']

        if resp['result'][i]['phase'] != 'FINISHED' or \
                data.execute_read_query(connection, contests_handler.select_id(id)) != []:
            i += 1
            continue

        try:
            resp2 = requests.get(
                'https://codeforces.com/api/contest.ratingChanges?contestId={0}'
                .format(id)).json()
        except Exception as e:
            logger.critical(str(e))
            i += 1
            continue

        logger.debug('i = {0}; id = {1};'.format(i, id))

        if resp2['status'] == 'OK' and resp2['result'] != []:
            res.append(id)
            data.execute_query(connection, contests_handler.insert_id(id))
        i += 1

    connection.close()
    logger.debug('found {0}'.format(res))

    return res
示例#6
0
def _list(id, connection):
    handles = data.execute_read_query(connection,
                                      ids_handler.select_cf_handles(id))
    if handles == []:
        return 'Хэндлов нет'
    else:
        resp = 'Хэндлы:\n'
        handles.sort(key=lambda x: x[0].lower())

        cnt = 1
        cntLen = len(str(len(handles)))
        for handle in handles:
            resp += str(cnt)
            resp += '. ' + ' ' * (cntLen - len(str(cnt)))
            resp += handle[0]
            resp += '\n'
            cnt += 1

        return resp
示例#7
0
def text_handler(message):
    id = message.chat.id
    connection = data.create_connection(dbname)

    resp = data.execute_read_query(connection, queue_handler.select_type(id))
    if resp == []:
        connection.close()
        return

    data.execute_query(connection, queue_handler.remove_id(id))
    args = message.text.split()
    if resp[0][0] == 0:
        message = util._add_handles(id, args, connection)
    elif resp[0][0] == 1:
        message = util._remove_handles(id, args, connection)
    else:
        if len(args) == 2:
            message = util._add_keys(id, args, connection)
        else:
            message = 'Неверные аргументы. Посмотрите /help'
    send_message(id, message)

    connection.close()
示例#8
0
def _get_ratings(id, connection):
    handles = data.execute_read_query(connection,
                                      ids_handler.select_cf_handles(id))
    if handles == []:
        return 'Хэндлов нет'
    else:
        query = list()
        ratings = dict()

        for i in range(len(handles)):
            query.append(handles[i])
            if i % groupSize == groupSize - 1 or i == len(handles) - 1:
                _ratings = get_ratings(query)
                if _ratings is None:
                    return 'Произошла ошибка codeforces. Скорее всего было отправлено слишком много запросов или codeforces сейчас недоступен. Повторите позже'

                for key, val in _ratings.items():
                    ratings[key] = val

                query = list()

        ratings = {
            key: val
            for key, val in sorted(
                ratings.items(), key=lambda item: item[1], reverse=True)
        }
        res = ''

        maxLenNickname = max(map(len, map(lambda x: x[0], ratings.keys())))

        for item in ratings.items():
            res += item[0][0]
            res += ': '
            res += ' ' * (maxLenNickname - len(item[0][0]))
            res += str(item[1])
            res += '\n'
        return res