Search code examples
pythonpython-3.xlistpraw

Trying to create alternating list of posts from 2 subreddits in praw


I'm trying to fetch posts from two different subreddits and create a list of the top posts that day (from most upvoted to least upvoted order) that alternates betweens subreddits. Here is my code:

import praw

user = "username"
passWord = "notmyactualpassword"
clientID = "id"
clientSecret = "secret"
userAgent = "useragent"
reddit = praw.Reddit(client_id=clientID,
                client_secret=clientSecret,
                user_agent=userAgent,
                username = user,
                password = passWord)

submissions = []
if submissions == []:
    test = reddit.subreddit("test", fetch = True)
    testPosts = test.top("day", limit = 50)
    redditdev = reddit.subreddit("redditdev", fetch = True)
    redditdevPosts = redditdev.top("day", limit = 50)
    switch = False
    if switch == False:
        submissions.append(testPosts[0])
        testPosts.pop()
        switch = True
    else:
        submissions.append(redditdevPosts[0])
        testPosts.pop()
        switch = False
else:
    selectedPost = submissions[0]

    name = selectedPost.title
    url = selectedPost.url

When I run this it gives me this error:

https://i.sstatic.net/3NMms.jpg

Apologies for not making the error copy and pasteable, I'm on my laptop and I haven't yet figured out how to make it let me copy from command prompt.

Also if it matters at all I'm using async praw in my actual code, the above is just basically the same thing I'm trying to do.

Basically I want to know if testPosts and redditdevPosts are list objects with with 50 submission objects inside of them, if they are, then why isn't my code working, if they aren't, how can I get them to be?


Solution

  • this would give you an alternating list of posts in submissions depending on which subreddit you would like to have first.

    testPosts = list(reddit.subreddit("test").top("day", limit=50))
    redditdevPosts = list(reddit.subreddit("redditdev").top("day", limit=50))
    switch = False
    if not switch:
        for c,item in enumerate(testPosts):
            submissions.append(item)
            submissions.append(redditdevPosts[c])
    else:
        for c,item in enumerate(redditdevPosts):
            submissions.append(item)
            submissions.append(testPosts[c])