Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reddit bot thread
#1
Ok so I have the following code to make a reddit bot that posts responses to any new comments, but my question is how do I have it post to any posts since X hours prior such as start the bot and respond to all comments with the keyphrases within the past 12 hours so I can turn it on for 5 minutes or so and turn it off every 12+ hours instead of having to have it running 24/7. The code is the following
import praw
import os
import csv
import re
from datetime import datetime
from replit import db
import time

reddit = praw.Reddit(
    client_id = os.getenv('client_id'),
    client_secret = os.getenv('client_secret'),
    username = os.getenv('username'),
    password = os.getenv('password'),
    user_agent = "<ReplyCommentBot1.0>"
)

def clean_string(raw_string):
    cleaned_string = raw_string.lower()
    cleaned_string = re.sub(r'[^A-Za-z0-9 ]+', '', cleaned_string)
    return cleaned_string

class RedditBot:
    def __init__(self, filename):
        self.response_list = []

        if len(db) == 0:
            with open(filename) as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=",")
                for row in csv_reader:
                    self.response_list.append({
                        'phrase': clean_string(row[0]), 
                        'reply': row[1]
                    })
            db['response_list'] = self.response_list
        else:
            print("Pulling from DB")
            self.response_list = db['response_list']

    def find_match(self, comment):
        for i, dictionary in enumerate(self.response_list):
            if dictionary['phrase'] in clean_string(comment.body):
                if self.cooled_down(i):
                    self.make_reply(i, comment)
    
    def cooled_down(self, i):
        dictionary = self.response_list[i]
        if 'last_posted' not in dictionary.keys():
            # Means we have never posted on this phrase!
            return True
        else:
            now = datetime.now()
            duration = now - datetime.fromtimestamp(dictionary['last_posted'])
            duration_seconds = duration.total_seconds()
            hours = divmod(duration_seconds, 1)[0]
            if hours >= 1:
                return True
            else:
                print(f"Couldn't post {dictionary['phrase']} Cool Down time: {24 - hours}")
        
        return False

    def make_reply(self, i, comment):
        dictionary = self.response_list[i]
        try:
            comment.reply(dictionary['reply'])
            print(comment.body)
            print(dictionary['phrase'])
            print(dictionary['reply'])
            # Might want to sleep after posting!
        
        except Exception as e:
            print(e)

        now = datetime.now()
        self.response_list[i]['last_posted'] = now.timestamp()
        db['response_list'] = self.response_list

# Warning clears all your posted times!
# Use if you want to changes phrases replies
#db.clear()
bot = RedditBot("LegolasFinalQuotes.csv")
subreddit = reddit.subreddit("lotrmemes")
for comment in subreddit.stream.comments(skip_existing=True):
    bot.find_match(comment)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error SQLite objects created in a thread can only be used in that same thread. binhduonggttn 3 15,594 Jan-31-2020, 11:08 AM
Last Post: DeaD_EyE
  PRAW and PyQt: Immense slowdown when retrieving Reddit posts and adding them to GUI codebro 2 3,234 Dec-30-2018, 01:19 AM
Last Post: codebro
  Reddit Bot comes up with no errors but wont actually run Rubix3D 0 2,624 Jan-12-2018, 12:53 AM
Last Post: Rubix3D

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020