示例#1
0
def make_reply(body, id, reply_func, markers=None, additions=()):
    """Makes a reply for the given comment."""
    try:
        reply = list(formulate_reply(body, markers, additions))
    except StoryLimitExceeded:
        if not DRY_RUN:
            reply_func("You requested too many fics.\n"
                       "\nWe allow a maximum of 30 stories")
        bot_tools.print_exception(level=logging.DEBUG)
        print("Too many fics...")
        return

    raw_reply = "".join(reply)
    if len(raw_reply) > 10:
        print(
            "Writing reply to", id, "(", len(raw_reply), "characters in",
            len(reply), "messages)")
        # Do not send the comment.
        if not DRY_RUN:
            for part in reply:
                reply_func(part + FOOTER)

        bot_tools.pause(1, 20)
        print('Continuing to parse submissions...')
    else:
        logging.info("No reply conditions met.")
def main():
    """Basic main function."""
    # moved call for agruments to avoid double calling
    bot_parameters = get_bot_parameters()
    login_to_reddit(bot_parameters)
    load_checked_comments()
    load_subreddits(bot_parameters)

    while True:
        for SUBREDDIT in SUBREDDIT_LIST:
            parse_submissions(r.get_subreddit(SUBREDDIT))
            bot_tools.pause(1, 0)
示例#3
0
def _run_forever():
    """Run-Forever"""
    while True:
        try:
            main()
        # Exit on sys.exit and keyboard interrupts.
        except KeyboardInterrupt:
            raise
        except SystemExit as e:
            return e.code
        except:
            bot_tools.print_exception()
            bot_tools.pause(0, 10)
def _run_forever():
    """Run-Forever"""
    while True:
        try:
            main()
        except SystemExit as e:
            return e.code
        except KeyboardInterrupt:
            return 0
        except:
            logging.error("MAIN: AN EXCEPTION HAS OCCURED!")
            bot_tools.print_exception()
            bot_tools.pause(1, 0)
示例#5
0
def single_pass():
    try:
        # We actually use a multireddit to acieve our goal
        # of watching multiple reddits.
        subreddit = r.get_subreddit("+".join(SUBREDDIT_LIST))

        logging.info("Parsing new submissions.")
        for submission in subreddit.get_new(limit=50):
            handle_submission(submission)

        logging.info("Parsing new comments.")
        for comment in subreddit.get_comments(limit=100):
            handle_comment(comment)
    except Exception:
        bot_tools.print_exception()
    bot_tools.pause(1, 0)
示例#6
0
def _run_forever():
    """Run-Forever"""
    while True:
        try:
            main()
        # Exit on sys.exit and keyboard interrupts.
        except KeyboardInterrupt:
            raise
        except SystemExit as e:
            return e.code
        except:
            logging.error("MAIN: AN EXCEPTION HAS OCCURED!")
            bot_tools.print_exception()
            bot_tools.pause(1, 0)
        finally:
            if CHECKED_COMMENTS is not None:
                CHECKED_COMMENTS.save()
def _run_forever(argv):
    """Run-Forever"""
    while True:
        try:
            return main(argv)
        # Exit on sys.exit and keyboard interrupts.
        except KeyboardInterrupt as e:
            # Exit the program unclean.
            bot_tools.print_exception(e, level=logging.debug)
            save_things()
            os._exit(0)
        except SystemExit as e:
            return e.code
        except:
            logging.error("MAIN: AN EXCEPTION HAS OCCURED!")
            bot_tools.print_exception()
            bot_tools.pause(1, 0)
        finally:
            save_things()
示例#8
0
def _run_forever(argv):
    """Run-Forever"""
    while True:
        try:
            return main(argv)
        # Exit on sys.exit and keyboard interrupts.
        except KeyboardInterrupt as e:
            # Exit the program unclean.
            bot_tools.print_exception(e, level=logging.debug)
            save_things()
            os._exit(0)
        except SystemExit as e:
            return e.code
        except:
            logging.error("MAIN: AN EXCEPTION HAS OCCURED!")
            bot_tools.print_exception()
            bot_tools.pause(1, 0)
        finally:
            save_things()
def make_reply(body, cid, id, reply_func, markers=None, additions=()):
    """Makes a reply for the given comment."""
    reply = formulate_reply(body, markers, additions)

    if not reply:
        print("Empty reply!")
    elif len(reply) > 10:
        print(Fore.GREEN)
        print('--------------------------------------------------')
        print('Outgoing reply to ' + id + ':\n' + reply + FOOTER)
        print('--------------------------------------------------')
        print(Style.RESET_ALL)
        reply_func(reply + FOOTER)
        bot_tools.pause(1, 20)
        print('Continuing to parse submissions...')
    else:
        logging.info("No reply conditions met.")

    if cid is not None:
        check_comment(cid)
def make_reply(body, id, reply_func, markers=None, additions=()):
    """Makes a reply for the given comment."""
    logging.debug("Attempting a reply to: ")
    logging.debug(body)

    try:
        _reply = list(formulate_reply(body, ENVIRONMENT, markers, additions))
    except StoryLimitExceeded:
        # The user requested to many stories. (Which has never ever
        # happened).
        send_reply(
            None,
            (
                "*You requested too many fics.*\n\n"
                "We allow a maximum of 30 stories to prevet abuse.\n\n"
                "Please remove some requests and use **ffnbot\\!refresh** "
                "to retry parsing."
            ),
            reply_func
        )
        logging.info("User requested too many fics...")
        bot_tools.pause(2, 0)
        return
    except GroupLimitExceeded:
        send_reply(
            None,
            (
                "*You requested too many groupings.*\n\n"
                "We allow up to five groups to ensure the bot doesn't "
                "disrupt the current conversation.\n\n"
                "Please remove some requests and use **ffnbot\\!refresh** "
                "to retry parsing."
            ),
            reply_func
        )
        logging.info("User requests too many groups...")
        bot_tools.pause(4, 0)
        return

    raw_reply = "".join(_reply)
    if len(raw_reply) > 10:
        print(
            "Writing reply to", id, "(", len(raw_reply), "characters in",
            len(_reply), "messages)")
        # Do not send the comment on dry-run.
        for part in _reply:
            reply(None, part, reply_func)
        bot_tools.pause(0, 30)
        print('Continuing to parse submissions...')
    else:
        logging.info("No reply conditions met for " + id)
示例#11
0
def make_reply(body, id, reply_func, markers=None, additions=()):
    """Makes a reply for the given comment."""
    logging.debug("Attempting a reply to: ")
    logging.debug(body)

    try:
        _reply = list(formulate_reply(body, ENVIRONMENT, markers, additions))
    except StoryLimitExceeded:
        # The user requested to many stories. (Which has never ever
        # happened).
        send_reply(None,
                   ("*You requested too many fics.*\n\n"
                    "We allow a maximum of 30 stories to prevet abuse.\n\n"
                    "Please remove some requests and use **ffnbot\\!refresh** "
                    "to retry parsing."), reply_func)
        logging.info("User requested too many fics...")
        bot_tools.pause(2, 0)
        return
    except GroupLimitExceeded:
        send_reply(None,
                   ("*You requested too many groupings.*\n\n"
                    "We allow up to five groups to ensure the bot doesn't "
                    "disrupt the current conversation.\n\n"
                    "Please remove some requests and use **ffnbot\\!refresh** "
                    "to retry parsing."), reply_func)
        logging.info("User requests too many groups...")
        bot_tools.pause(4, 0)
        return

    raw_reply = "".join(_reply)
    if len(raw_reply) > 10:
        print("Writing reply to", id, "(", len(raw_reply), "characters in",
              len(_reply), "messages)")
        # Do not send the comment on dry-run.
        for part in _reply:
            reply(None, part, reply_func)
        bot_tools.pause(0, 30)
        print('Continuing to parse submissions...')
    else:
        logging.info("No reply conditions met for " + id)
示例#12
0
 def send_reply(message):
     obj.reply(message)
     bot_tools.pause(0, 10)
示例#13
0
def handle_comment(comment, extra_markers=frozenset()):
    logging.debug("Handling comment: " + comment.id)
    if (str(comment.id) not in CHECKED_COMMENTS
            ) or ("force" in extra_markers):

        markers = parse_context_markers(comment.body)
        markers |= extra_markers
        if "ignore" in markers:
            # logging.info("Comment forcefully ignored: " + comment.id)
            return
        else:
            logging.info("Found new comment: " + comment.id)

        if "parent" in markers:
            if comment.is_root:
                item = comment.submission
            else:
                item = r.get_info(thing_id=comment.parent_id)
            handle(item, {"directlinks", "submissionlink", "force"})

        if "delete" in markers and (comment.id not in CHECKED_COMMENTS):
            CHECKED_COMMENTS.add(str(comment.id))
            logging.info("Delete requested by " + comment.id)
            if not (comment.is_root):
                parent_comment = r.get_info(thing_id=comment.parent_id)
                if parent_comment.author is not None:
                    if (parent_comment.author.name == "FanfictionBot"):
                        logging.info("Deleting comment " + parent_comment.id)
                        parent_comment.delete()
                    else:
                        logging.error("Delete requested on non-bot comment!")
                else:
                    logging.error("Delete requested on null comment.")
            else:
                logging.error("Delete requested by invalid comment!")

        if "refresh" in markers and (str(comment.id) not in CHECKED_COMMENTS):
            CHECKED_COMMENTS.add(str(comment.id))
            logging.info("(Refresh) Refresh requested by " + comment.id)

            # Get the full comment or submission
            comment_with_requests = get_full(comment.parent_id)
            logging.info("(Refresh) Refreshing on " + type(
                comment_with_requests).__name__ + " with id " + comment_with_requests.id)

            # TODO: Make it so FanfictionBot does not have to be hardcoded
            # If ffnbot!refresh is called on an actual bot reply, then go up
            # one level to find the requesting comment
            if comment_with_requests.author.name == "FanfictionBot":
                logging.info(
                    "(Refresh) Refresh requested on a bot comment (" + comment_with_requests.id + ").")
                # Retrieve the requesting parent submission or comment
                comment_with_requests = get_full(
                    comment_with_requests.parent_id)

                # If the requesting comment has been deleted, abort
                if not valid_comment(comment_with_requests):
                    logging.error(
                        "(Refresh) Parent of bot comment is invalid.")
                    return

                logging.info(
                    "          Refresh request being pushed to parent " + comment_with_requests.id)

            if isinstance(comment_with_requests, praw.objects.Comment):
                logging.info(
                    "(Refresh) Running refresh on COMMENT " + str(comment_with_requests.id))
                logging.info("(Refresh) Appending replies to deletion check list: " +
                             ", ".join(str(c.id) for c in comment_with_requests.replies))
                delete_list = comment_with_requests.replies

            elif isinstance(comment_with_requests, praw.objects.Submission):
                logging.info(
                    "(Refresh) Running refresh on SUBMISSION " + str(comment_with_requests.id))

                unfiltered_delete_list = comment_with_requests.comments
                delete_list = []
                for comment in unfiltered_delete_list:
                    if comment.author is not None:
                        if (comment.author.name == "FanfictionBot"):
                            delete_list.append(comment)
                            print("(Refresh) Found root-level bot comment " + comment.id)
            else:
                logging.error("(Refresh) Can't refresh " + comment_with_requests.type(
                ).__name__ + " with ID " + comment_with_requests.id)
                bot_tools.pause(5, 0)
                return

            if delete_list is not None:
                logging.info("(Refresh) Finding replies to delete.")
                for reply in delete_list:
                    if valid_comment(reply):
                        if (reply.author.name == "FanfictionBot"):
                            logging.error(
                                "(Refresh) Deleting bot comment " + reply.id)
                            reply.delete()
            else:
                logging.info(
                    "(Refresh) No bot replies have been made. Continuing...")
            CHECKED_COMMENTS.add(str(comment.id))

            if isinstance(comment_with_requests, praw.objects.Comment):
                logging.info(
                    "(Refresh) Re-handling comment " + comment_with_requests.id)
                handle_comment(comment_with_requests, frozenset(["force"]))
            elif isinstance(comment_with_requests, praw.objects.Submission):
                logging.info(
                    "(Refresh) Re-handling submission " + comment_with_requests.id)
                handle_submission(comment_with_requests, frozenset(["force"]))
            return

        try:
            make_reply(comment.body, comment.id, comment.reply, markers)
        finally:
            CHECKED_COMMENTS.add(str(comment.id))