python - 如何使用 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()
解决方案
您可以使用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):
推荐阅读
- regex - 使用 REGEX 从 csv 文件中删除前两列
- python - 无法在python3中打开文件
- c# - 如何在 Google Cloud Build 中正确设置多个环境
- powershell-4.0 - 如何使用 Powershell 脚本单击网页中的复选框?
- java - 记忆具有多个变量的回溯问题
- javascript - 如何从 vite lib 构建中获取全局引用
- javascript - node.js 应用程序在本地工作,而不是在 Heroku 部署
- tcp - 针对缓冲区溢出和数据包崩溃的内核 TCP 调整
- c - 我正在尝试学习 C 语言的子进程和父进程
- .net - 管理组织的内部 .Net 依赖项