Beispiel #1
0
def show_categories():
    category_text = ["Here are the list of categories the bot knows about:\n"]

    for category in Category.select():
        category_text.append(" - *%s* (_%s_)" %
                             (category.display_name, category.name))

    constants.slack.chat.post_message(OUTPUT_CHANNEL,
                                      "\n".join(category_text),
                                      as_user=True)
Beispiel #2
0
def handle_summary_parsing(summary_text, user_profile):
    print("Attempting to parse text...")
    results = parse_summary(summary_text, user_profile)

    if results is not None and len(results) > 0:
        glory_walls = save_glory_walls(results, user_profile)
        render_to_wiki(Category.select(), UTOPIA_AGE)
        send_response(glory_walls, user_profile)
    else:
        response = chatbot.get_response(summary_text)
        constants.slack.chat.post_message(OUTPUT_CHANNEL,
                                          response,
                                          as_user=True)
Beispiel #3
0
def select_website():
    """查询当前用户的网址"""
    sites = UserSite.select(lambda x: x.user == request.user and x.status ==
                            UserSiteStatus.normal)[:]
    categories = Category.select(
        lambda c: c.user == request.user and not c.delete).order_by(
            Category.order)[:]
    ss = defaultdict(list)
    for s in sites:
        key = s.cate.id if s.cate else ""
        ss[key].append(s)
    categories = list(categories)
    categories.insert(0, {"id": '', 'name': '', 'order': 0})
    return ss, categories
Beispiel #4
0
def user_category_delete(u_id: int):
    form = request.form
    logging.info('user {} delete data {}'.format(u_id, form))
    cate_id = form.get('id', '')
    if not cate_id or not cate_id.isdigit():
        return jsonify({'status': -1})
    cate_id = int(cate_id)
    cate = Category.select(lambda x: x.id == cate_id and x.user == request.user
                           and not x.delete).first()
    if not cate:
        return jsonify({'status': -1})
    cate.delete = True
    logging.warning('user {} delete category {}'.format(u_id, cate.id))
    commit()
    return jsonify({'status': 1, 'id': cate.id})
Beispiel #5
0
def user_category_put(u_id: int):
    form = request.form
    logging.info('user {} update data {}'.format(u_id, form))
    cate_id = form.get('id', '')
    name = form.get('name', '')
    order = form.get('order', '')
    if not cate_id or not cate_id.isdigit(
    ) or not name or not order or not order.isdigit():
        return jsonify({'status': -1})
    order = int(order)
    if 1 > order or order > 1000:
        return jsonify({'status': -1})
    cate = Category.select(lambda x: x.id == cate_id and x.user == request.user
                           and not x.delete).first()
    cate.name = name
    cate.order = order
    commit()
    logging.info('user {} update category {}'.format(u_id, cate.id))
    return jsonify({'status': 1, 'id': cate.id})
Beispiel #6
0
def user_website_post(u_id: int):
    form = request.form
    logging.info('user {} post data {}'.format(u_id, form))
    cate_id = form.get('cate_id', '')
    name = form.get('name', '')
    url = form.get('url', '')
    order = form.get('order', '')
    type_ = form.get('type', '')

    if not name or not url or not order or not order.isdigit():
        return jsonify({'status': -1})
    order = int(order)
    if order > 1000 or order < 1:
        return jsonify({'status': -1})
    if not cate_id or not cate_id.isdigit():
        cate_id = None
        cate = None
    else:
        cate_id = int(cate_id)
        cate = Category.select(lambda x: x.user == request.user and x.id ==
                               cate_id and not x.delete).first()
        if not cate:
            return jsonify({'status': -1})
    try:
        icon = query_icon(urlparse(url).netloc)
    except Exception:
        icon = ''
    site = UserSite(name=name,
                    url=url,
                    user=request.user,
                    icon=icon,
                    cate=cate,
                    order=order)
    commit()
    logging.info('user {} post site {}'.format(u_id, site.id))
    if not icon:
        logging.warning("icon not found, send to redis")
        download_icon_job(site.id)
    if type_ == 'index':
        return redirect_home()
    return jsonify({'status': 1, 'id': site.id})
Beispiel #7
0
def save_glory_walls(results, user_profile):
    """Take the parsed results and compare them to existing glory walls. Create or update glory walls as necessary."""
    top_score = []  # when the user's score has beaten the top score
    own_score = []  # when the user's score has beaten their own score
    new_score = [
    ]  # when the user does not have an entry for the given category

    for result in results:
        category = Category.select().where(
            Category.name == result['category_name']).get()
        # Get the existing glory wall entry for the current user and category
        user_glory_wall = GloryWall.get_or_none(
            GloryWall.category == category.id,
            GloryWall.user == user_profile.id, GloryWall.age == UTOPIA_AGE)

        new_entry = False
        # Create a glory wall entry if the user does not yet have one
        if user_glory_wall is None:
            new_entry = True
            user_glory_wall = GloryWall.create(
                category=category.id,
                user=user_profile.id,
                full_summary_text=result['summary_text'],
                value=result['value'],
                timestamp=datetime.datetime.now(),
                age=UTOPIA_AGE)

        try:
            if category.compare_greater:
                # Grab the top score
                high_score = GloryWall.select().where(GloryWall.category == category.id,
                                                      GloryWall.age == UTOPIA_AGE) \
                                               .order_by(GloryWall.value.desc()) \
                                               .limit(1).get()
            else:
                high_score = GloryWall.select() \
                                      .where(GloryWall.category == category.id,
                                             GloryWall.age == UTOPIA_AGE) \
                                      .order_by(GloryWall.value.asc()) \
                                      .limit(1).get()
        except GloryWall.DoesNotExist:
            high_score = None

        # A player only qualifies for top score if they beat the existing top score that was not their own,
        # or there was no existing top score in that category.
        if high_score and high_score.user != user_profile and \
           ((category.compare_greater and result['value'] > high_score.value) or
               (not category.compare_greater and result['value'] < high_score.value)):
            print("Existing high score exceeded")
            update_glory_wall(user_glory_wall, result)
            top_score.append({
                'old_score': high_score,
                'current_high_score': user_glory_wall
            })
        elif high_score.user == user_profile and new_entry:
            print("New entry achieved top score")
            old_top_score = GloryWall.select() \
                                     .where(GloryWall.category == category.id,
                                            GloryWall.age == UTOPIA_AGE,
                                            GloryWall.user != user_profile) \
                                     .order_by(GloryWall.value.asc()) \
                                     .limit(1)
            old_top_score = old_top_score.get() if len(
                old_top_score) == 1 else None
            top_score.append({
                'old_score': old_top_score,
                'current_high_score': user_glory_wall
            })
        elif high_score is None:
            print("High score did not exist.")
            # If there was no high score for this entry, it means nobody had ever entered anything.
            # In which case, this user gets the top score by default.
            update_glory_wall(user_glory_wall, result)
            top_score.append({
                'old_score': None,
                'current_high_score': user_glory_wall
            })
        elif (category.compare_greater and result['value']) > user_glory_wall.value or \
             (not category.compare_greater and result['value'] < user_glory_wall.value):
            print("User's own score exceeded")
            # Check if the user's new score exceeds their old score
            # Logic note: Whether the category is meant to be compared greater than or less than,
            # the result is still the same.
            update_glory_wall(user_glory_wall, result)
            own_score.append(user_glory_wall)
        elif new_entry:
            print("New entry")
            # If they did not beat the top score, but they did not have an entry for this category yet...
            new_score.append(user_glory_wall)

    return {
        'top_score': top_score,
        'own_score': own_score,
        'new_score': new_score
    }
Beispiel #8
0
def show_scores(message):
    message_parts = message.split()
    message_parts.reverse()

    if len(message_parts) == 0:
        constants.slack.chat.post_message(
            OUTPUT_CHANNEL,
            "I need to know what category of scores to look up. See `@glorywall help` for more details.\n Example: `@glorywall [category] [limit]`.",
            as_user=True)
        return

    category_name = message_parts.pop()

    limit = None
    if len(message_parts) > 0:
        limit = message_parts.pop()
        try:
            limit = int(limit)
        except ValueError:
            constants.slack.chat.post_message(
                OUTPUT_CHANNEL,
                "I don't know what limit _%s_ means" % limit,
                as_user=True)
            return

        if limit is not None and limit <= 0:
            constants.slack.chat.post_message(
                OUTPUT_CHANNEL,
                "Tell me honestly, does asking for a limit of zero or less make any sense to you?",
                as_user=True)
            return

    try:
        category = Category.select().where(
            Category.name == category_name).get()
    except Category.DoesNotExist:
        constants.slack.chat.post_message(
            OUTPUT_CHANNEL,
            "Sorry, I don't have any categories called '%s'" % category_name,
            as_user=True)
        return

    scores_query = GloryWall.select() \
                            .where(GloryWall.category == category, GloryWall.age == UTOPIA_AGE)
    if category.compare_greater:
        scores_query.order_by(GloryWall.value.desc())
    else:
        scores_query.order_by(GloryWall.value.asc())

    if limit:
        scores_query = scores_query.limit(limit)

    if scores_query.count() == 0:
        constants.slack.chat.post_message(
            OUTPUT_CHANNEL,
            "Sorry, I could not find any scores for category %s" %
            category_name,
            as_user=True)
        return

    output = ["*Here are the list of scores for _%s_*" % category_name]
    for score in scores_query:
        output.append('%s: %s' % (score.user.name, score.value))
    constants.slack.chat.post_message(OUTPUT_CHANNEL,
                                      "\n".join(output),
                                      as_user=True)
Beispiel #9
0
def user_category(u_id: int):
    categories = Category.select(
        lambda x: x.user == request.user and not x.delete)[:]
    return render_template('user.html', page='category', categories=categories)