コード例 #1
0
def find_mentions() -> None:
    """
    Find bot name mentions and responds with a comment
    """
    logger.info("Starting Mentions")
    to_add = []
    for message in reddit.inbox.mentions():
        # Needs the mentions database because I was unable to mark them as read
        # with praw
        if str(message) not in mentions:
            try:
                logger.debug(
                    "Found mention %s, User: %s, Body: %s",
                    message,
                    message.author,
                    message.body,
                )
                message.reply("Hello, I see you mentioned me. How can I help?")
                logger.debug("Replying to %s", message)
                marked = [
                    message.id,
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                ]
                to_add.append(marked)
            except Exception as err:
                logger.warning(err)
    dh.insert("replied_mentions", to_add)
    logger.info("Finished mentions")
コード例 #2
0
 def replace_subreddit(self) -> None:
     """
     Sets the new subreddit to monitor
     """
     new = input("Enter the new subreddit: ")
     dh.delete("configurations", "id", "'subreddit'")
     dh.insert("configurations", [["subreddit", new]])
     print("Subreddit changed to: {}".format(self.fetch_config("subreddit")))
コード例 #3
0
def message_check(additional: list):
    """
    Checks messages received
    Parameters
    ----------
    additional: list
        List of customer message triggers and responses
    """
    logger.info("Starting Messages")
    marked = []
    for message in reddit.inbox.unread():  # Gets all unread messages
        to_break = False
        received_subject = message.subject.lower()
        name = message.author.name.lower()
        if received_subject in ["stop", "ignore", "ignored"
                                ] and name not in ignored:
            data = [[
                name,
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                message.body,
            ]]
            logger.info("Ignoring user: %s", message.author.name)
            message_send(message.author.name, "Ignored add")
            dh.insert("ignored", data)
            marked.append(message)
        elif received_subject in ["resume", "unignore"] and name in ignored:
            dh.delete("ignored", "user", name)
            logger.info("Unignoring %s", message.author.name)
            message_send(message.author.name, "ignore remove")
            marked.append(message)
        for i, _ in enumerate(additional):  # Looks
            if additional[i][0] == received_subject:
                global ADDITIONAL_CHOICE  # pylint: disable=global-statement
                ADDITIONAL_CHOICE = i
                message_send(message.author.name, "additional")
                to_break = True
                marked.append(message)
        if to_break:
            break
        # Username mentions appear in the inbox so this filters them out
        if received_subject != "username mention":
            logger.warning(
                "Message with subject and body not understood. Subject: %s Body: %s",
                message.subject,
                message.body,
            )
            message_send(message.author.name, "unknown")
            marked.append(message)
    reddit.inbox.mark_read(marked)
    logger.info("Finished Messages")
コード例 #4
0
 def response_add(self) -> None:
     """
     Creates addition response for messages, comments, or posts
     """
     to_add = []
     choice = input(
         "What kind of response do you want to set; Comment, Post, or Message: "
     ).lower()
     if choice.startswith("c"):
         table = "comment_responses"
     elif choice.startswith("p"):
         table = "post_responses"
     elif choice.startswith("m"):
         table = "message_responses"
     else:
         print("Exiting: no valid selection")
         self.run()
     to_add.append(input("Enter what the keyword you want to trigger a response: "))
     if table == "message_responses":
         to_add.append(input("Enter what you want the reply subject to be: "))
     to_add.append(input("Enter the message for the reply: "))
     if table == "message_responses":
         print(
             "For the message response, \n' {0} ' is the trigger word/phrase."
             "' {1} ' is the response subject and ' {2} ' is the response body. \n"
             "Enter Y to conform, R to redo or N to cancel.".format(
                 to_add[0], to_add[1], to_add[2]
             )
         )
     else:
         print(
             "For the comment/post response, \n' "
             "{0} ' is the trigger word/phrase. The response body is ' {1} ' \n"
             "Enter Y to confirm, R to redo or N to cancel.".format(
                 to_add[0], to_add[1]
             )
         )
     if input().lower() == "y":
         dh.insert(table, [to_add])
     elif input().lower() == "r":
         self.response_add()
コード例 #5
0
def comment_reply(
    sreddit: praw.Reddit().subreddit,
) -> None:  # Looks through all comments in a post
    """
    Loops through all comments in a post
    Parameters
    ----------
    sreddit: praw.Reddit.subreddit()
        The subreddit to look through
    """
    logger.info("Starting Comments")
    to_add = []
    for post in sreddit.hot(
            limit=10):  # Gets the top 10 posts in the subreddit
        submission = reddit.submission(post)
        submission.comments.replace_more(
            limit=50)  # Gets 50 comments from each post
        for comment in submission.comments.list():
            text = comment.body
            author = comment.author.name
            for response in comment_responses:
                if ((response[0] in text.lower())
                        and (comment.id not in comments_replied_to)
                        and (author.lower() not in ignored)):
                    try:
                        add = [
                            comment.id,
                            datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S"),
                            response[1],
                            botinfo.subreddit,
                        ]
                        comment.reply(reply_format(response[1], author))
                        logger.debug("Bot replying to %s", text)
                        to_add.append(add)
                    except Exception as err:
                        logger.warning(err)

    dh.insert("Comments", to_add)  # Gets all the comments that were replied to
    logger.info("Finished Comments")
コード例 #6
0
    def cred_import(self) -> None:  # Imports credentials from the botinfo
        """
        Imports the credentials from botinfo.py to the database.
        """
        try:
            for cred in [
                "client_id",
                "client_secret",
                "username",
                "password",
                "user_agent",
            ]:
                try:
                    value = getattr(botinfo, cred)
                    dh.insert("configurations", [[cred, value]])
                except ValueError:
                    self.fetch_config(cred)
            dh.insert("configurations", [["remember", "true"]])
            print("Successfully imported credentials")

        except Exception as err:
            self.logger.error("Error importing: %s", err)
コード例 #7
0
def post_reply(sreddit: praw.Reddit().subreddit) -> None:
    """
    Replies to posts in sreddit that meet the criteria
    Parameters
    ----------
    sreddit: str
        Name of the subreddit
    """
    logger.debug("Starting Posts")
    to_add = []
    for submission in sreddit.hot(
            limit=10
    ):  # Gets submissions from the subreddit. Here it has a limit of 10
        if submission.id not in posts_replied_to:
            for response in post_responses:
                if (re.search(
                        response[0], submission.title, re.IGNORECASE
                )) and (
                        submission.author.name not in ignored
                ):  # If you wanted to have it search the body change submission.title to sub,
                    try:
                        submission.reply(
                            reply_format(response[1], submission.author))
                        logger.debug("Bot replying to : %s", submission.title)
                        add = [
                            submission.id,
                            datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S"),
                            botinfo.subreddit,
                            response[1],
                        ]
                        to_add.append(add)
                        break
                    except Exception as err:
                        logger.warning(err)

    dh.insert("Posts", to_add)  # Adds all the posts that were replied to
    logger.info("Finished Posts")
コード例 #8
0
 def fetch_config(self, find) -> str:  # Fetches the values needed to run the bot
     """
     Fetches the value `find` and returns the string for the needed value
     Parameters
     ----------
     find: str
         configuration value needed
     Returns
     -------
         The value that is mapped to find
     """
     try:
         values = dh.fetch("configurations", "value")
         ids = dh.fetch("configurations", "id")
         return values[ids.index(find)]
     # The exception is called if there are no values in configurations table
     except ValueError:
         value = input("Enter " + find + ": ")
         dh.insert("configurations", [[find, value]])
         return value
     except Exception as err:
         self.logger.error("There was an error retrieving credentials: %s ", err)
         main.stop_bot()