How can i check if the login credentials are valid using praw

Viewed 384

So im trying to make a bot that fetch random post url's from a subreddit and want it to check if the login credentials are valid so heres what i came up with:

import praw
import pandas as pd
import datetime as dt

username = input("Your user name:\n")
password = input("Your Password:\n")



reddit = praw.Reddit(client_id='xxxxxxxxxxxxx', \
                     client_secret='xxxxxxxxxxxxxxxxxxxxxxxx', \
                     user_agent='Fetch', \
                     username=username, \
                     password=password)

if reddit == thats where i dont know what to type
    submission = reddit.subreddit("gtaonline").random()
    print(submission.url)

else:
    print("Enter valid credentials")
    quit()
1 Answers

You can use reddit.user.me(). This method gives you the authenticated user, which as a side effect causes the Reddit instance to use the credentials.

If the credentials are valid, this returns a Redditor instance. If your credentials are invalid, calling it will result in a prawcore.ResponseException.

You can use this fact to test your credentials:

from prawcore import ResponseException

def authenticated(reddit):
    """Determine whether the given Reddit instance has valid credentials."""
    try:
        reddit.user.me()
    except ResponseException:
        return False
    else:
        return True

If you define this function in your script, your condition becomes

if authenticated(reddit):
Related