首页 > 解决方案 > 如何使用 praw 检查登录凭据是否有效

问题描述

所以我试图制作一个从 subreddit 获取随机帖子 url 并希望它检查登录凭据是否有效的机器人,所以这就是我想出的:

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()

标签: pythonpraw

解决方案


您可以使用reddit.user.me(). 此方法为您提供经过身份验证的用户,作为副作用导致Reddit实例使用凭据。

如果凭据有效,则返回一个Redditor实例。如果您的凭据无效,调用它将导致prawcore.ResponseException.

您可以使用此事实来测试您的凭据:

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 authenticated(reddit):

推荐阅读