Beispiel #1
0
def test_change_karma(giver, receiver, channel, amount):

    with database.session_manager() as session:
        pre_change_karma = session.query(KarmaUser).get(receiver).karma_points

    karma = Karma(giver, receiver, channel)
    karma.change_karma(amount)

    with database.session_manager() as session:
        post_change = session.query(KarmaUser).get(receiver).karma_points

    assert post_change == (pre_change_karma + amount)
Beispiel #2
0
def _note_exists(msg: str, user: KarmaUser) -> bool:
    with database.session_manager() as session:
        selected_note = session.query(KarmaNote).filter_by(
            note=msg, user_id=user.user_id)
        note_exists = session.query(
            selected_note.exists()).scalar()  # returns True or False
    return note_exists
Beispiel #3
0
def get_user_name(**kwargs):
    """Shows the current Username"""
    user_id = kwargs.get("user_id")
    if user_id:
        user_id = user_id.strip("<>@")

    with database.session_manager() as session:
        karma_user: KarmaUser = session.query(KarmaUser).get(user_id)

    if not karma_user:
        return "Sorry, you are not yet known to karmabot. Try to give some Karma! :)"
    username = karma_user.username

    return f"Your current username for karmabot is '{username}'"
Beispiel #4
0
def update_username(**kwargs):
    """Changes the Username"""
    user_id = kwargs.get("user_id")
    if user_id:
        user_id = user_id.strip("<>@")

    with database.session_manager() as session:
        karma_user: KarmaUser = session.query(KarmaUser).get(user_id)

    if not karma_user:
        return "User not found"

    old_username = karma_user.username

    response = bot.app.client.users_profile_get(user=user_id)
    status = response.status_code

    if status != 200:
        logging.error("Cannot get user info for %s - API error: %s", user_id,
                      status)
        return "Sorry, I could not retrieve your user information from the slack API :("

    user_profile = response.data["profile"]
    new_username = karmabot.slack.get_available_username(user_profile)

    if old_username == new_username:
        return (
            f"Sorry, you have not updated your username: {old_username}. \n"
            "Please update your real-name or display-name in your Slack "
            "profile and retry.")

    with database.session_manager() as session:
        karma_user.username = new_username
        session.commit()

    return (f"Sucessfully updated your KarmaUser name "
            f"from '{old_username}' to '{new_username}'!")
Beispiel #5
0
def get_karma(**kwargs):
    """Get your current karma score"""
    user_id = kwargs.get("user_id")
    slack_id = karmabot.slack.get_slack_id(user_id)

    with database.session_manager() as session:
        kama_user = session.query(KarmaUser).get(user_id)

    if not kama_user:
        return "User not found"

    if kama_user.karma_points == 0:
        return "Sorry, you don't have any karma yet"

    return f"Hey {slack_id}, your current karma is {kama_user.karma_points}"
Beispiel #6
0
def top_karma(**kwargs):
    """Get the PyBites members with most karma"""
    output = ["PyBites members with most karma:"]

    with database.session_manager() as session:
        top_users = (session.query(KarmaUser).order_by(
            KarmaUser.karma_points.desc()).limit(TOP_NUMBER))

    if top_users:
        for top_user in top_users:
            output.append(
                f"{top_user.username:<20} -> {top_user.karma_points}")
        ret = "\n".join(output)
        return "```{}```".format(ret)

    return "Sorry, no users found"
Beispiel #7
0
def _add_note(text: str, user: KarmaUser) -> str:
    """Adds a new note to the database for the given user."""
    _, note_msg = _parse_note_cmd(text)
    if not note_msg:
        return f"Sorry {user.username}, could not find a note in your message."

    if _note_exists(note_msg, user):
        return f"Sorry {user.username}, you already have an identical note."

    note = KarmaNote(user_id=user.user_id,
                     timestamp=datetime.datetime.now(),
                     note=note_msg)

    with database.session_manager() as session:
        session.add(note)
        session.commit()

    return f"Hey {user.username}, you've just stored a note."
Beispiel #8
0
def _del_note(text: str, user: KarmaUser) -> str:
    """Deletes the note with the given note id."""
    _, note_id = _parse_note_cmd(text)

    if not note_id:
        return f"Sorry {user.username}, it seems you did not provide a valid id."

    with database.session_manager() as session:
        query = session.query(KarmaNote).filter_by(id=note_id,
                                                   user_id=user.user_id)

        row_count = query.delete()
        session.commit()  # otherwise, the deletion is not performed

    if row_count:
        return f"Hey {user.username}, your note was successfully deleted."

    return (
        f"Sorry {user.username}, something went wrong, no record was deleted. "
        f"Please ask an admin...")
Beispiel #9
0
def note(user_id: str, channel: str, text: str) -> Union[None, str]:
    """Allows the user to store and retrieve simple notes.

    - Syntax for adding a note: @karmabot note add <">my note<"> (note message can be in quotes)
    - Syntax for listing notes: @karmabot note list
    - Syntax for removing a note: @karmabote note del 1

    Each note is stored for the current user only. A user can only list and delete her own notes.
    """
    user_id = user_id.strip("<>@")

    # retrieve current user
    with database.session_manager() as session:
        user = session.query(KarmaUser).get(user_id)

    cmd, _ = _parse_note_cmd(text)

    note_cmd_fnc = NOTE_COMMANDS.get(cmd, _command_not_found)

    return note_cmd_fnc(text, user)
Beispiel #10
0
def _get_notes_for_user(user: KarmaUser) -> list:
    with database.session_manager() as session:
        notes = session.query(KarmaNote).filter_by(user_id=user.user_id).all()
    return notes