- Joined
- Mar 24, 2025
- Messages
- 1,153
- Reaction Score
- 3,135
Steps to Create a Google Cloud Project & Run subreddit checker
- Go to the Google Cloud Console
- Visit: https://console.cloud.google.com/
- Log in with your Google account.
- Create a New Project
- Click on the project drop-down at the top of the page (next to "Google Cloud").
- Select New Project.
- Enter the Project Name (e.g., "Reddit Tracker").
- Choose your Organization and Location (optional).
- Click Create.
- Enable APIs and Services
- Go to the Navigation Menu (☰) > APIs & Services > Library.
- Search for the following APIs and enable them:
- Google Sheets API
- Google Drive API
- Click Enable for each.
- Create Service Account Credentials
- Go to APIs & Services > Credentials.
- Click + CREATE CREDENTIALS > Service Account.
- Provide a Name, ID, and Description.
- Click Create and Continue.
- Grant it Editor permissions (or specific permissions required for your project).
- Click Done.
- Generate and Download JSON Key
- After creating the service account, click on it in the Credentials page.
- Go to the Keys tab and click Add Key > Create New Key.
- Select JSON and download the key file.
- Save this file securely and update the path in your script (path/to/credentials.json).
- Share the Spreadsheet with the Service Account
- Open your Google Spreadsheet.
- Click Share and add the email address of the service account (visible in the JSON key file).
- Give it Editor access.
- Test the Script
- Ensure all dependencies (praw, gspread, oauth2client) are installed.
- Run the script and verify updates in the spreadsheet.
Out put will be like this.
Code:
import praw
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import time
# Reddit API Credentials
REDDIT_CLIENT_ID = 'your_client_id'
REDDIT_CLIENT_SECRET = 'your_client_secret'
REDDIT_USERNAME = 'your_username'
REDDIT_PASSWORD = 'your_password'
REDDIT_USER_AGENT = 'script:subreddit_checker:v1.0 (by /u/your_username)'
# Google Sheets API Credentials File
GOOGLE_SHEETS_CREDENTIALS = 'path/to/credentials.json' # Path to your credentials.json file
SPREADSHEET_NAME = 'SubredditChecker' # Name of your Google Spreadsheet
# Initialize Reddit Instance
reddit = praw.Reddit(
client_id=REDDIT_CLIENT_ID,
client_secret=REDDIT_CLIENT_SECRET,
username=REDDIT_USERNAME,
password=REDDIT_PASSWORD,
user_agent=REDDIT_USER_AGENT
)
# Google Sheets Authentication Scope
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_SHEETS_CREDENTIALS, scope)
client = gspread.authorize(creds)
sheet = client.open(SPREADSHEET_NAME).sheet1 # Access the first sheet
def check_subreddit_details(subreddit_name):
"""Fetch subreddit details such as ban status, crosspostability, and members."""
try:
subreddit = reddit.subreddit(subreddit_name)
is_banned = False
is_crosspost_enabled = subreddit.allow_crosspost
member_count = subreddit.subscribers
except Exception as e:
# If subreddit is banned or inaccessible
print(f"Error fetching subreddit {subreddit_name}: {e}")
is_banned = True
is_crosspost_enabled = 'N/A'
member_count = 'N/A'
return is_banned, is_crosspost_enabled, member_count
def update_google_sheet():
"""Read or populate subreddit list in Google Sheet and update with details."""
print("Fetching subreddit list from Google Sheets...")
subreddits = sheet.col_values(1) # Read all values from Column A
# If Column A is empty (excluding headers), populate it with a sample list
if len(subreddits) <= 1: # Only the header row exists
print("Column A is empty. Populating it with sample subreddit names...")
sample_subreddits = ["AskReddit", "Python", "learnprogramming", "gaming", "worldnews"]
sheet.update('A2:A{}'.format(len(sample_subreddits) + 1), [[sub] for sub in sample_subreddits])
subreddits = sheet.col_values(1)
print("Sample subreddits added to Column A.")
subreddits = subreddits[1:] # Exclude the header row
# Write headers if they are missing
headers = ["Subreddit", "Banned", "Crosspost Enabled", "Members"]
if sheet.cell(1, 2).value != "Banned":
sheet.insert_row(headers, 1)
# Check and update subreddit details
for i, subreddit_name in enumerate(subreddits, start=2): # Start from row 2
print(f"Working on row {i}: Checking subreddit: {subreddit_name}")
is_banned, crosspost_enabled, member_count = check_subreddit_details(subreddit_name)
# Update the sheet with the results
sheet.update_cell(i, 2, "Yes" if is_banned else "No") # Banned column
sheet.update_cell(i, 3, "Yes" if crosspost_enabled else "No") # Crosspost column
sheet.update_cell(i, 4, member_count) # Member count
print(f"Finished row {i}: Updated subreddit {subreddit_name}")
time.sleep(2) # Avoid hitting rate limits
print("Google Sheet updated successfully!")
if __name__ == "__main__":
update_google_sheet()