Esempio n. 1
0
def update_comments(reddit, database):
    count_incorrect = database.get_pending_incorrect_comments()

    incorrect_items = database.get_incorrect_comments(
        utils.requests_available(count_incorrect))
    if len(incorrect_items):
        i = 0
        for db_comment, reminder, new_count in incorrect_items:
            i += 1
            log.info(
                f"{i}/{len(incorrect_items)}/{count_incorrect}: Updating comment : "
                f"{db_comment.comment_id} : {db_comment.current_count}/{new_count}"
            )

            bldr = utils.get_footer(
                reminder.render_comment_confirmation(db_comment.thread_id,
                                                     new_count))
            result = reddit.edit_comment(''.join(bldr),
                                         comment_id=db_comment.comment_id)
            if result != ReturnType.SUCCESS:
                log.warning(
                    f"Failed to edit comment {db_comment.comment_id}: {result}"
                )

            db_comment.current_count = new_count

    else:
        log.debug("No incorrect comments")
Esempio n. 2
0
def process_message(message, reddit, database, count_string=""):
    if message.author is None:
        log.info(f"Subreddit message, skipping : {message.id}")
        return
    log.info(f"{count_string}: Message u/{message.author.name} : {message.id}")
    body = message.body.lower()

    bldr = None
    if static.TRIGGER_LOWER in body:
        bldr = process_remind_me(message, database)
    elif "myreminders!" in body:
        bldr = process_get_reminders(message, database)
    elif "remove!" in body:
        bldr = process_remove_reminder(message, database)
    elif "removeall!" in body:
        bldr = process_remove_all_reminders(message, database)
    elif "delete!" in body:
        bldr = process_delete_comment(message, reddit, database)
    elif "cakeday!" in body:
        bldr = process_cakeday_message(message, database)
    elif "timezone!" in body:
        bldr = process_timezone_message(message, database)

    if bldr is None:
        bldr = ["I couldn't find anything in your message."]

    bldr.extend(utils.get_footer())
    result = reddit.reply_message(message, ''.join(bldr))
    if result != ReturnType.SUCCESS:
        if result == ReturnType.INVALID_USER:
            log.info("User banned before reply could be sent")
        else:
            raise ValueError(f"Error sending message: {result.name}")
Esempio n. 3
0
def send_reminders(reddit, database):
    timestamp = utils.datetime_now()
    count_reminders = database.get_count_pending_reminders(timestamp)
    counters.queue.set(count_reminders)

    reminders_sent = 0
    if count_reminders > 0:
        reminders = database.get_pending_reminders(
            utils.requests_available(count_reminders), timestamp)
        for reminder in reminders:
            reminders_sent += 1
            counters.notifications.inc()
            counters.queue.dec()
            log.info(
                f"{reminders_sent}/{len(reminders)}/{count_reminders}: Sending reminder to u/{reminder.user.name} : "
                f"{reminder.id} : {utils.get_datetime_string(reminder.target_date)}"
            )
            bldr = utils.get_footer(reminder.render_notification())
            result = reddit.send_message(reminder.user.name,
                                         "RemindMeBot Here!", ''.join(bldr))
            if result in [
                    ReturnType.INVALID_USER, ReturnType.USER_DOESNT_EXIST
            ]:
                log.info(f"User doesn't exist: u/{reminder.user.name}")
            if result in [ReturnType.NOT_WHITELISTED_BY_USER_MESSAGE]:
                log.info(
                    f"User blocked notification message: u/{reminder.user.name}"
                )

            if reminder.recurrence is not None:
                if reminder.user.recurring_sent > static.RECURRING_LIMIT:
                    log.info(
                        f"User u/{reminder.user.name} hit their recurring limit, deleting reminder {reminder.id}"
                    )
                    database.delete_reminder(reminder)
                else:
                    new_target_date = utils.parse_time(reminder.recurrence,
                                                       reminder.target_date,
                                                       reminder.user.timezone)
                    log.info(
                        f"{reminder.id} recurring from {utils.get_datetime_string(reminder.target_date)} to "
                        f"{utils.get_datetime_string(new_target_date)}")
                    reminder.target_date = new_target_date
                    reminder.user.recurring_sent += 1
            else:
                log.debug(f"{reminder.id} deleted")
                database.delete_reminder(reminder)

        database.commit()

    else:
        log.debug("No reminders to send")

    return reminders_sent
Esempio n. 4
0
def process_message(message, reddit, database, count_string=""):
    log.info(f"{count_string}: Message u/{message.author.name} : {message.id}")
    user = database.get_or_add_user(message.author.name)
    user.recurring_sent = 0
    body = message.body.lower()

    result_messages = None
    created = False
    if static.TRIGGER_RECURRING_LOWER in body:
        result_messages, created = process_remind_me(message, reddit, database,
                                                     True)
        if created:
            counters.replies.labels(source='message', type='repeat').inc()
    elif static.TRIGGER_LOWER in body:
        result_messages, created = process_remind_me(message, reddit, database,
                                                     False)
        if created:
            counters.replies.labels(source='message', type='single').inc()
    elif "myreminders!" in body:
        result_messages = process_get_reminders(message, database)
    elif "remove!" in body:
        result_messages = process_remove_reminder(message, database)
    elif "removeall!" in body:
        result_messages = process_remove_all_reminders(message, database)
    elif "delete!" in body:
        result_messages = process_delete_comment(message, reddit, database)
    elif "cakeday!" in body:
        result_messages, created = process_cakeday_message(
            message, reddit, database)
        if created:
            counters.replies.labels(source='message', type='cake').inc()
    elif "timezone!" in body:
        result_messages = process_timezone_message(message, database)
    elif "clock!" in body:
        result_messages = process_clock_message(message, database)

    if not created:
        counters.replies.labels(source='message', type='other').inc()

    if result_messages is None:
        result_messages = ["I couldn't find anything in your message."]

    result_messages[-1] = result_messages[-1] + ''.join(utils.get_footer())
    for result_message in result_messages:
        result = reddit.reply_message(message, result_message)
        if result != ReturnType.SUCCESS:
            if result == ReturnType.INVALID_USER:
                log.info("User banned before reply could be sent")
                break
            else:
                raise ValueError(f"Error sending message: {result.name}")

    database.commit()
Esempio n. 5
0
def update_comments(reddit, database):
    count_incorrect = database.get_pending_incorrect_comments()

    incorrect_items = database.get_incorrect_comments(
        utils.requests_available(count_incorrect))
    if len(incorrect_items):
        i = 0
        for db_comment, reminder in incorrect_items:
            i += 1
            log.info(
                f"{i}/{len(incorrect_items)}/{count_incorrect}: Updating comment : "
                f"{db_comment.comment_id} : {db_comment.current_count}/{reminder.count_duplicates}"
            )

            bldr = utils.get_footer(reminder.render_comment_confirmation())
            reddit.edit_comment(''.join(bldr),
                                comment_id=db_comment.comment_id)
            db_comment.current_count = reminder.count_duplicates
            database.save_comment(db_comment)

    else:
        log.debug("No incorrect comments")
Esempio n. 6
0
def process_comment(comment, reddit, database, count_string=""):
    reminder, result_message = parse_comment(comment, database, count_string,
                                             reddit)

    if reminder is None:
        counters.replies.labels(source='comment', type='other').inc()
        log.debug("Not replying")
        return

    commented = False
    thread_id = utils.id_from_fullname(comment['link_id'])
    comment_result = None
    if database.get_comment_by_thread(thread_id) is not None:
        comment_result = ReturnType.THREAD_REPLIED
    if comment_result is None and database.get_subreddit_banned(
            comment['subreddit']):
        comment_result = ReturnType.FORBIDDEN
    if comment_result is None:
        reminder.thread_id = thread_id
        reddit_comment = reddit.get_comment(comment['id'])
        bldr = utils.get_footer(
            reminder.render_comment_confirmation(
                thread_id,
                pushshift_minutes=reddit.get_effective_pushshift_lag()))

        result_id, comment_result = reddit.reply_comment(
            reddit_comment, ''.join(bldr))

        if comment_result in (ReturnType.INVALID_USER,
                              ReturnType.USER_DOESNT_EXIST,
                              ReturnType.THREAD_LOCKED,
                              ReturnType.DELETED_COMMENT,
                              ReturnType.RATELIMIT):
            log.info(f"Unable to reply as comment: {comment_result.name}")

        elif comment_result == ReturnType.FORBIDDEN:
            log.info(f"Banned in subreddit, saving: {comment['subreddit']}")
            database.ban_subreddit(comment['subreddit'])

        else:
            if comment_result == ReturnType.NOTHING_RETURNED:
                result_id = "QUARANTINED"
                log.warning(
                    f"Opting in to quarantined subreddit: {comment['subreddit']}"
                )
                reddit.quarantine_opt_in(comment['subreddit'])

            if result_id is None:
                log.warning(
                    f"Got comment ID of None when replying to {comment['id']}")
                comment_result = ReturnType.FORBIDDEN

            else:
                log.info(
                    f"Reminder created: {reminder.id} : {utils.get_datetime_string(reminder.target_date)}, "
                    f"replied as comment: {result_id}")

                if comment_result != ReturnType.QUARANTINED and comment[
                        'subreddit'] != "RemindMeBot":
                    db_comment = DbComment(thread_id=thread_id,
                                           comment_id=result_id,
                                           reminder_id=reminder.id,
                                           user=reminder.user.name,
                                           source=reminder.source)
                    database.save_comment(db_comment)
                commented = True

    if not commented:
        log.info(
            f"Reminder created: {reminder.id} : {utils.get_datetime_string(reminder.target_date)}, "
            f"replying as message: {comment_result.name}")
        bldr = utils.get_footer(
            reminder.render_message_confirmation(
                result_message,
                comment_result,
                pushshift_minutes=reddit.get_effective_pushshift_lag()))
        result = reddit.send_message(comment['author'],
                                     "RemindMeBot Confirmation", ''.join(bldr))
        if result != ReturnType.SUCCESS:
            log.info(f"Unable to send message: {result.name}")
Esempio n. 7
0
    for ev_id in sorted(
            event_dict.iteritems(),
            key=lambda
        (k, v): (int(v[tag_start_year]), int(v[tag_start_month]),
                 int(v[tag_start_day]), int(v[tag_prio]), v[tag_name])):
        #ev_id is the tuple (ev_id, actual event dict)
        ordered_list.append(ev_id[1])
    return ordered_list


if __name__ == "__main__":
    logging.basicConfig(filename=utils.get_logfile(), level=utils.log_level)
    utils.log_intro(__file__)

    doc_head = utils.get_header()
    doc_foot = utils.get_footer()
    promo_banner = utils.get_promo_banner()
    event_loc = "jsondump/"
    index_loc = "index.html"
    event_dict = create_event_dict(event_loc)
    events_ordered = get_ordered_event_list(event_dict)
    event_blocks = []
    for event in events_ordered:
        event_blocks.append(create_event_block(event))

    locations = set()
    venues = set()
    #get all cities, states, venues for filtering purposes
    for event in event_dict:
        loc = "{}, {}".format(event_dict[event][tag_city],
                              event_dict[event][tag_state])