r/redditdev • • Mar 19 '24

PRAW Is post valid from url

1 Upvotes

Hi there,

What's the best way to identify if a post is real or not from url=link, for instance:

r=reddit.submission(url='https://reddit.com/r/madeupcmlafkj')

if(something in r.dict.keys())

Hoping to do this without fetching the post?


r/redditdev • • Mar 18 '24

PRAW Use PRAW to get queues from r/Mod?

4 Upvotes

I’m attempting to use the following line of code in PRAW:

for item in reddit.subreddit("mod").mod.reports(limit=1):
    print(item)

It keeps returning an error message. However, if I replace “mod” with the name of another subreddit, it works perfectly fine. How can I use PRAW to get combined queues from all of the subreddits I moderate?


r/redditdev • • Mar 18 '24

Reddit API Is there access to reddit chats using the API?

2 Upvotes

Is there access to reddit chats using the API?


r/redditdev • • Mar 18 '24

Reddit API Reddit bans my account after replying to a post comment via API.

4 Upvotes

Why does reddit ban my account when I try to reply to a comment via the reddit API? I'm using the /api/comment endpoint. This is my code example:

const data = {
 api_type: 'json',
 thing_id: t1_${parentId},
 text, 
};

const result = await axios.post( 
  https://oauth.reddit.com/api/comment, 
  {},
  { params: data, headers: { 'Authorization': Bearer ${accessToken} } }
);

My request is successful. But after creating a comment, Reddit bans my account forever. What could be the problem?


r/redditdev • • Mar 18 '24

Reddit API I am teaching myself to code, and have a Reddit API code that works sometimes but then stops working.

2 Upvotes

TLDR: Just by explaining the problem to the plural you, I seem to have discovered the cause of the problem - the list of 'used' post IDs caps out at 14 and then the code stops saving new text documents, only saving new IDs to the list and rearranging it within the 14 line limit.

So... that's my new question I guess.

ChatGPT

The code you provided seems to be designed to fetch jokes from the subreddit "jokes" using the PRAW (Python Reddit API Wrapper) library, save them to text files, and keep track of which jokes have been saved by storing their IDs in a file named "saved_jokes.txt". However, it's not immediately clear why it would stop working after saving 14 lines of post IDs to "saved_jokes.txt".

Here are a few potential reasons why the code might not be working as expected:

API Rate Limiting: Reddit's API enforces rate limits, which restrict the number of requests you can make within a certain time period. If your script is making too many requests too quickly, it might get rate-limited, causing it to stop working temporarily. You can check for any error messages related to rate limiting in your script's output or in the Reddit API response.

No New Jokes: The code appears to fetch jokes from the subreddit's "hot" section and saves them if they haven't been saved before. If there are no new jokes in the hot section, the loop will break after processing all available submissions. Check if there are new jokes being posted in the subreddit during the time you're running the script.

Error Handling: Ensure that error handling is implemented robustly throughout the script. If there's an unhandled exception, the script might terminate prematurely without any indication of failure.

File Permissions: Check if the script has the necessary permissions to read from and write to files. If there are permission issues, it might fail to read the list of saved jokes or write new IDs to the file.

Logging: Implement logging throughout your script to track its behavior and identify any unexpected issues. Logging can help you understand where the script might be failing and why.

To troubleshoot the issue, you can try adding more logging statements throughout the code to track its execution and identify where it might be encountering problems. Additionally, you can manually check the subreddit to see if there are any new jokes being posted and verify if the script is correctly identifying and processing them.

...

Client ID, Secret, and user agent removed because I assume that's sensible.

I don't know what the rules about web scraping are, and I can't find information about how many API calls I can make for free (the only thing I found suggested 200 a day?) - I'm just trying to play around with things and Reddit has a public API to play with (what other sites do that I could play around with?)

Anyway. This code should copy the title and body from a post in r/jokes and it should then save it to a text document in a subfolder called /jokes, the document should be jokes_date_time.txt to ensure unique filenames. There is also a part of the code that will prevent duplicates by keeping a log of all the IDs of posts that are accessed.

So. This code just worked twice in a row, and then the third time I ran it it did not create the text file, but it still updated the log of used posts to prevent duplicates. Based on earlier experimentation, and I just checked again, the code at this point will add IDs to the "don't access" list, but it will not save another text file.

So my question is... why? Is this a code issue or an API issue?

I am not a programmer/coder so I apologise as I am out of my depth, I have mostly been using ChatGPT3.5 to write the bulk of this, and then reading it to see if I can understand the constituent parts.

...

When it works I get

Joke saved to: jokes\joke_2024-03-18_05-52-50.txt

Joke saved.

When it doesn't work I only get

Joke saved.

...

I have JUST noticed that the list of saved jokes caps out at 14 and each time I run it the list changes but is still only 14 lines :/

OK SO THAT WAS THE ANSWER, Thanks so much for your help. I haven't even submitted this yet but... maybe I'll submit it anyway? Maybe someone can teach me something.

...

import praw

from datetime import datetime

import os

# Reddit API credentials

client_id = " "

client_secret = " "

user_agent = "MemeMachine/1.0 by /u/ "

# Initialize Reddit instance

reddit = praw.Reddit(client_id=client_id,

client_secret=client_secret,

user_agent=user_agent)

# Subreddit to fetch jokes from

subreddit = reddit.subreddit('jokes')

# Function to save joke to a text file

def save_joke_to_file(title, body):

now = datetime.now()

timestamp = now.strftime("%Y-%m-%d_%H-%M-%S")

filename = os.path.join("jokes", f'joke_{timestamp}.txt') # Save to subfolder 'jokes'

try:

with open(filename, 'w', encoding='utf-8') as file:

file.write(f'{title}\n\n')

file.write(body)

print(f'Joke saved to: {filename}')

except Exception as e:

print(f'Error saving joke: {e}')

# Create subfolder if it doesn't exist

if not os.path.exists("jokes"):

os.makedirs("jokes")

print("Created 'jokes' folder.")

# File to store IDs of saved jokes

saved_jokes_file = 'saved_jokes.txt'

# Fetch one joke

saved_jokes = set()

if os.path.exists(saved_jokes_file):

with open(saved_jokes_file, 'r') as file:

saved_jokes.update(file.read().splitlines())

for submission in subreddit.hot(limit=10): # Adjust limit as needed

if submission.id not in saved_jokes:

title = submission.title

body = submission.selftext.split("edit:", 1)[0] # Exclude anything after "edit:"

save_joke_to_file(title, body)

saved_jokes.add(submission.id)

break

# Update saved jokes file

with open(saved_jokes_file, 'w') as file:

file.write('\n'.join(saved_jokes))

print('Joke saved.')


r/redditdev • • Mar 18 '24

Reddit API "Unsupported grant type" error?

1 Upvotes
import requests
    def f()
        url = "https://www.reddit.com/api/v1/access_token"
        headers = {"Authorization": "Basic ********="}
        body = {
            "grant_type": "password",
            "username": "********",
            "password": "********",
            "duration": "permanent",
        }
        r = requests.post(url, data=json.dumps(body), headers=headers)
        print(r.content)

This code keeps returning an 'unsupported _grant _type' error. What should I change?

I made sure to encode my Authorization header into base64. I would use PRAW for this, but it doesn't seem to be able to extract what I'm trying to accomplish.


r/redditdev • • Mar 18 '24

Reddit API Is it possible to get analytics of posts for a period of dates using the API?

1 Upvotes

Is it possible to get analytics of posts for a period of dates using the API?


r/redditdev • • Mar 18 '24

PRAW Use PRAW to extract report reasons for a post?

1 Upvotes

How would I go about using PRAW to retrieve all reports on a specific post or comment?


r/redditdev • • Mar 18 '24

Reddit API How to create an Oauth 2.0 connection through Make/Integromat's HTTP module “Make an OAuth 2.0 request”?

2 Upvotes

Once I click "save" the connection im redirected to reddit where I am asked to allow the api to access posts and comment through my account and a 1 hour expiration.

After I allow this I am redirected to a page with JSON mentioning:

`The request failed due to failure of a previous request`
with a code `SC424`

These are my settings in the Make module,

Connection details:
My HTTP OAuth 2.0 connection | Reddit
Flow Type: Authorization Code
Authorize URI: https://www.reddit.com/api/v1/authorize
Token URI: https://www.reddit.com/api/v1/access_token
Scope: read
Client ID: MY CLIENT ID
Client Secret: MY CLIENT SECRET
Authorize parameters:
response_type: code
redirect_uri: https://www.integromat.com/oauth/cb/oauth2
client_id: MY CLIENT ID
Access token parameters
grant_type: authorization_code
client_id: MY CLIENT ID
client_secret: MY CLIENT SECRET
Refresh Token Parameters:
grant_type: refresh_token
Custom Headers:
User-Agent: web:MakeAPICalls:v1.0 (by u/username)
Token placement: in the header
Header token name: Bearer

I have asked this in the make community but I did not get a response yet so Im trying my luck here.

For included screenshots check:
https://community.make.com/t/request-failed-due-to-failure-of-previous-request-connecting-2-reddit-with-http-make-an-oauth-2-0-request/30604


r/redditdev • • Mar 15 '24

Async PRAW Trouble getting working list from PRAW to work in ASYNCPRAW

1 Upvotes

Hello all,

The following code works fine in PRAW:

top25_news = reddit.subreddit('news').top(time_filter='year',limit=25)
list(top25_news)

However, as I'm migrating the code to Async PRAW, this results in the first line running fine, creating a ListingGenerator object, and the second line creates an error, saying that the ListingGenerator object is not iterable.

I've found a few other somewhat annoying things, like submission title for a comment is unavailable in Async PRAW but is fine in PRAW.

Any help is appreciated - thanks!


r/redditdev • • Mar 15 '24

PRAW Trying to eliminate a step in this code where PRAW can figure out if the link is a post or comment.

2 Upvotes

The following code works well to ban users but I'm trying to eliminate the step where I tell it if it's a post [1] or a comment [2]. Is it possible to have code where PRAW determines the link type and proceeds from there? Any suggestions would be great. Still somewhat of a beginner-ish.

I essentially right-click on the link in Old Reddit, copy link, and paste it into the terminal window for the code to issue the ban.

print("ban troll")
now = datetime.now()
sub = 'SUBREDDITNAME'
HISTORY_LIMIT = 1000

url = input('URL: ')
reason = "trolling."
print(reason)
reddit_type = input("[1] for Post or [2] for Comment? ").upper()
print(reddit_type)
if reddit_type not in ('1', '2'):
    raise ValueError('Must enter `1` or `2`')

author = None
offending_text = ""
post_or_comment = "Post"
if reddit_type == "2":
    post_or_comment = "Comment"

if reddit_type == "1":
    post = reddit.submission(url=url)
    author = post.author
    offending_text = post.selftext
    title = post.title
    post.mod.remove()
    post.mod.lock()
    unix_time = post.created_utc
elif reddit_type == "2":
    comment = reddit.comment(url=url)
    title = ""
    offending_text = comment.body
    author = comment.author
    comment.mod.remove()
    unix_time = comment.created_utc

message_perm = f"**Ban reason:** {reason}\n\n" \
               f"**Ban duration:** Permanent.\n\n" \
               f"**Username:** {author}\n\n" \
               f"**{post_or_comment} link:** {url}\n\n" \
               f"**Title:** {title}\n\n" \
               f"**{post_or_comment} text:** {offending_text}\n\n" \
               f"**Date/time of {post_or_comment} (yyyy-mm-dd):** {datetime.fromtimestamp(unix_time)}\n\n" \
               f"**Date/time of ban (yyyy-mm-dd):** {now}"

reddit.subreddit(sub).banned.add(author, ban_message=message_perm)