Search code examples
pythonpython-3.xredditpraw

Reddit Bot which replies to comments


Using the PRAW library, the reddit bot replies to the post title in a subthread when the given keyword is mentioned. I would like to change so it replies when mentioned within the comments in a sub, not the post.

from urllib.parse import quote_plus

    import praw

    QUESTIONS = ["!hello"]
    REPLY_TEMPLATE = "world"


    def main():
        reddit = praw.Reddit(
            user_agent="xxx",
            client_id="xxx",
            client_secret="xxx",
            username="xxx",
            password="xxx",
        )

        subreddit = reddit.subreddit("sandboxtest")
        for submission in subreddit.stream.submissions():
            process_submission(submission)


    def process_submission(submission):
        # Ignore titles with more than 10 words as they probably are not simple
        # questions.
        if len(submission.title.split()) > 15:
            return

        normalized_title = submission.title.lower()
        for question_phrase in QUESTIONS:
            if question_phrase in normalized_title:
                url_title = quote_plus(submission.title)
                reply_text = REPLY_TEMPLATE.format(url_title)
                print("Replying to: {}".format(submission.title))
                submission.reply(reply_text)
                # A reply has been made so do not attempt to match other phrases.
                break


    if __name__ == "__main__":
        main()

Solution

  • If you just want to process comments change:

    for submission in subreddit.stream.submissions():
      process_submission(submission)
    

    to:

    for comment in subreddit.stream.comments():
      process_comment(comment)
    
    # def process_comment you have to write yourself
    

    If you want to process comments and submissions do:

    while True:
      for submission in subreddit.stream.submissions(pause_after=-1):
        process_submission(submission)
      for commentin subreddit.stream.comments(pause_after=-1):
        process_comment(comment)
    

    an example of process_comment():

    def process_comment(comment):
      for question_phrase in QUESTIONS:
        if question_phrase in comment.body.lower():
          comment.reply("Hello")