Exemplo n.º 1
0
def change_preference(user_id, key):
    """
    Toggles preference in DB by id and key
    :param user_id: int, id vk [from_id]
    :param key: str, ['subscribe', 'profile', 'report']
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    :raise KeyError - user_id or preference not in DB
    """
    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] == 0:
        raise KeyError('user_id doesn\'t exists')

    key = str(key)
    keys = {
        'subscribe': 'c_is_subscribed',
        'profile': 'c_show_profile',
        'report': 'c_show_report'
    }
    if key not in keys.keys():
        raise KeyError("There is no preference %s" % key)

    state = query("SELECT " + keys[key] + " FROM t_user WHERE c_id_user = %s",
                  user_id)[0][0]
    query("UPDATE t_user SET " + keys[key] + " = %s WHERE c_id_user = %s",
          not bool(state), user_id)
    return
Exemplo n.º 2
0
def change_active(source):
    _validate_source(source)

    state = bool(query("SELECT c_is_active FROM t_squad WHERE c_source = %s", source)[0][0])

    query("UPDATE t_squad SET c_is_active = %s WHERE c_source = %s", not state, source)
    return
Exemplo n.º 3
0
def update_msg(user_id, msg_time):
    """
    Write new time of last message into DB
    :param user_id: int, id vk [from_id]
    :param msg_time: int, unix time vk [date]
    :raise KeyError - user_id doesn't in DB
    :raise ValueError - wrong time value
    :raise TypeError - wrong time type (or can't be cast to type)
    """
    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] == 0:
        raise KeyError('user_id doesn\'t exists')

    try:
        msg_time = int(msg_time)
    except ValueError:
        raise TypeError("time should be int type")

    if msg_time < 0:
        raise ValueError("time can't be negative")

    if msg_time > time.time():
        raise ValueError("time can't be from future")

    query('UPDATE t_user SET c_last_message = %s WHERE c_id_user = %s',
          msg_time, user_id)

    return
Exemplo n.º 4
0
def set_target(source, target, time):
    """
    Set target to send in specified time for squad
    :param source: str(2), squad's source
    :param target: int [0-7]
    :param time: datetime.time, time UTC +3 for remind
    :raise ValueError on wrong target
    :raise TypeError on wrong type of target or time
    """
    _validate_source(source)

    if type(target) != int:
        try:
            target = int(target)
        except ValueError:
            raise TypeError("Target is not int")
    if target > 7 or target < 0:
        # no check for fraction because checking only valid data
        raise ValueError("Target must be in [0..7]")

    # time already sent as datetime.time, and we can't parse nor convert, so we just check it
    if type(time) != t.time:
        raise TypeError("Time is not valid type")

    query("UPDATE t_squad SET c_target = %s, c_target_delay = %s WHERE c_source = %s;", target, time, source)
    return
Exemplo n.º 5
0
def del_remind(source):
    """
    Delete remind for battle timer for squad
    :param source: str(2), squad's source
    """
    _validate_source(source)

    query("UPDATE t_squad SET c_remind_delay = NULL WHERE c_source = %s;", source)
    return
Exemplo n.º 6
0
def del_target(source):
    """
    Removes target and delay by squad's source
    :param source: str(2), squad's source
    """
    _validate_source(source)

    query("UPDATE t_squad SET c_target = NULL, c_target_delay = NULL WHERE c_source = %s;", source)
    return
Exemplo n.º 7
0
def set_profile(user_id, nick, lvl, squad, prac, teo, hit, mud):
    """
    Updates user's profile data in DB by id
    :param user_id: int, id vk [from_id]
    :param nick: str
    :param lvl: int
    :param squad: str(2)
    :param prac: int
    :param teo: int
    :param hit: int
    :param mud: int
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    :raise KeyError - user or squad not in DB
    """
    def _validate_stats(stat):
        """
        Check stats before input
        :param stat: int, stat param to check
        :return: int, stat parameter
        :raise TypeErrorwrong type (or can't be cast to type)
        :raise ValueError - wrong value
        """
        try:
            stat = int(stat)
        except ValueError:
            raise TypeError("Some stt is not int type")
        if stat < 0:
            raise ValueError("Stat can't be negative")
        return stat

    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] == 0:
        raise KeyError('user_id doesn\'t exists')

    # nick and squad can't raise ValueError, so just str them
    nick = str(nick)
    if len(nick) < 3 or len(nick) > 25:
        raise ValueError('nickname should be in length 3-25')

    _validate_stats(lvl)

    _validate_source(squad)

    prac, teo, hit, mud = _validate_stats(prac), _validate_stats(
        teo), _validate_stats(hit), _validate_stats(mud)

    args = (nick, lvl, squad, prac, teo, hit, mud, user_id)
    query(
        'UPDATE t_user '
        'SET c_nickname = %s, c_level = %s, c_squad = %s, c_practice = %s, c_theory = %s, c_guile = %s, c_wisdom = %s'
        ' WHERE c_id_user = %s;', args)

    return
Exemplo n.º 8
0
def del_user(user_id):
    """
    Delete user from DB by id
    :param user_id: int, id vk [from_id]
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    """
    _validate_user(user_id)

    query('DELETE FROM t_user WHERE c_id_user = %s;', user_id)
    return
Exemplo n.º 9
0
def set_chat(source, chat_id):
    _validate_source(source)

    try:
        chat_id = int(chat_id)
    except ValueError:
        raise TypeError("chat_id is not int")
    if chat_id < 2000000000:
        raise ValueError("chat_id should be greater than 2000000000")

    query("UPDATE t_squad SET c_id_chat = %s WHERE c_source = %s", chat_id, source)
    return
Exemplo n.º 10
0
def get_user(user_id):
    """
    Get user data from DB by vk_id [from_id]
    :param user_id: int, id from vk
    :return: dict, {user_id: int,
                    role_id: int,
                    subscribe: bool,
                    show_profile: bool,
                    show_report: bool,
                    nickname: str,
                    lvl: int,
                    squad: str,
                    practice: int,
                    theory: int,
                    guile: int,
                    wisdom: int,
                    date_report: datetime,
                    income: int,
                    pure_income: int,
                    target: int,
                    last_message: int}
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    :raise KeyError - user not in DB
    """
    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] == 0:
        raise KeyError('user_id doesn\'t exists')

    user_data = query('SELECT * FROM t_user WHERE c_id_user = %s', user_id)[0]
    user = {
        'user_id': int(user_data[0]),
        'role_id': int(user_data[1]),
        'subscribe': bool(user_data[2]),
        'show_profile': bool(user_data[3]),
        'show_report': bool(user_data[4]),
        'nickname': str(user_data[5]),
        'lvl': int(user_data[6]),
        'squad': str(user_data[7]),
        'practice': int(user_data[8]),
        'theory': int(user_data[9]),
        'guile': int(user_data[10]),
        'wisdom': int(user_data[11]),
        'date_report': user_data[12],
        'income': int(user_data[13]),
        'pure_income': int(user_data[14]),
        'target': int(user_data[15]),
        'last_message': int(user_data[16])
    }
    return user
Exemplo n.º 11
0
def set_remind(source, time):
    """
    Updates squad's remind for battle
    :param source: str(2), squad's source
    :param time: datetime.time, time UTC +3 for remind
    :raise TypeError if not datetime.time
    """
    _validate_source(source)

    # time already sent as datetime.time, and we can't parse nor convert, so we just check it
    if type(time) != t.time:
        raise TypeError("Time is not valid type")

    query("UPDATE t_squad SET c_remind_delay = %s WHERE c_source = %s;", time, source)
    return
Exemplo n.º 12
0
def reg_user(user_id):
    """
    Adds new user into DB
    :param user_id: id vk [from_id]
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    """
    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] != 0:
        raise KeyError('user_id already exists')

    values = (user_id, fraction, dt.min)
    query(
        'INSERT INTO t_user VALUE (%s, 8, 0, 0, 0, "Аноним", 0, %s, 0, 0, 0, 0, %s, 0, 0, 0, 0);',
        values)
    return
Exemplo n.º 13
0
def reg_squad(source, token):
    """

    :param source:
    :param token:
    :return:
    """
    source = str(source)
    if len(source) > 2 or len(source) == 0:
        raise ValueError("source length more than 2 or empty")

    token = str(token)
    if len(token) != 128:
        raise ValueError("token length is not 128")

    if query('SELECT COUNT(*) FROM t_squad WHERE c_source = %s', source)[0][0] == 0:
        query("INSERT INTO t_squad (c_source, c_token) VALUE %s, %s", source, token)
    else:
        query("UPDATE t_squad SET c_token = %s WHERE c_source = %s", token, source)
    return
Exemplo n.º 14
0
def _validate_source(source):
    """
    Inner method to check source for valid input
    :param source: str, squad's source
    :raise ValueError - incorrect source
    :raise: KeyError - squad doesn't exists in DB
    """
    source = str(source)
    if len(source) > 2 or len(source) == 0:
        raise ValueError("Source length more than 2 or empty")
    if query("SELECT COUNT(*) FROM t_squad WHERE c_source = %s", source)[0] == 0:
        raise KeyError("Unknown squad")
    return
Exemplo n.º 15
0
def db_query(**kwargs):
    """
    Execute query directly into DB and send result into chat
    !!! [DANGER] !!! Use it only if you 101% sure what are you doing
    """
    roles = [0]

    if kwargs['role_id'] not in roles:
        vk_api.send(kwargs['chat'], "Access Denied")
        return

    q = kwargs['msg']['text'].replace('/query ', '')
    res = query(q)
    vk_api.send(kwargs['msg']['from_id'], res)
    vk_api.send(kwargs['chat'], "Result is in your chat")

    return
Exemplo n.º 16
0
def get_token(source):
    _validate_source(source)
    token = query("SELECT c_token FROM t_squad WHERE c_source = %s", source)[0][0]
    return token
Exemplo n.º 17
0
def set_report(user_id, dat, inc, pure, target):
    """
    Updates Battle report of user in DB
    :param user_id: inv, id vk [from_id]
    :param dat: date
    :param inc: int, income from battle
    :param pure: int, pure income
    :param target: int, fraction (0-7)
    :raise ValueError - wrong value
    :raise TypeError - wrong type (or can't be cast to type)
    :raise KeyError - user_id not in DB
    """
    _validate_user(user_id)

    if query('SELECT COUNT(*) FROM t_user WHERE c_id_user = %s',
             user_id)[0][0] == 0:
        raise KeyError('user_id doesn\'t exists')

    if type(dat) != dt:
        try:
            dat = dat.date()
        except AttributeError:
            raise TypeError("date is not datetime.date")
    now = datetime.datetime.utcnow()
    yest = dt.today() - datetime.timedelta(days=1)
    battle = datetime.time(15)
    if dat > now.date():
        raise ValueError("date can't be from future")
    if now.time() < battle:
        if dat < yest:
            raise ValueError("date is too old")
    else:
        if dat < now.date():
            raise ValueError("date is too old")

    try:
        inc = int(inc)
    except ValueError:
        raise TypeError("income is not int")

    try:
        pure = int(pure)
    except ValueError:
        raise TypeError("pure income is not int")

    if inc > 0:
        if pure > inc:
            raise ValueError(
                "pure income can\'t be greater than overall income")
    else:
        if pure != 0:
            raise ValueError(
                "pure income can\'t be non-zero if overall income negative")

    try:
        target = int(target)
    except ValueError:
        raise TypeError("target is not int")
    if target < 0 or target > 7:
        raise ValueError("target must be in range 0-7")
    if target == fraction:
        raise ValueError("target can\'t be own fraction")

    # insert data
    args = (dat, inc, pure, target, user_id)
    query(
        'UPDATE t_user '
        'SET c_date_report = %s, c_income = %s, c_pure_income = %s, c_target = %s '
        'WHERE c_id_user = %s', args)
    return
Exemplo n.º 18
0
def get_squads():
    res = query("SELECT c_source FROM t_squad;")
    squad_list = list()
    for squad in res:
        squad_list.append(squad[0])
    return squad_list