Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
elebumm
GitHub Repository: elebumm/RedditVideoMakerBot
Path: blob/master/reddit/subreddit.py
327 views
1
import re
2
3
import praw
4
from praw.models import MoreComments
5
from prawcore.exceptions import ResponseException
6
7
from utils import settings
8
from utils.ai_methods import sort_by_similarity
9
from utils.console import print_step, print_substep
10
from utils.posttextparser import posttextparser
11
from utils.subreddit import get_subreddit_undone
12
from utils.videos import check_done
13
from utils.voice import sanitize_text
14
15
16
def get_subreddit_threads(POST_ID: str):
17
"""
18
Returns a list of threads from the AskReddit subreddit.
19
"""
20
21
print_substep("Logging into Reddit.")
22
23
content = {}
24
if settings.config["reddit"]["creds"]["2fa"]:
25
print("\nEnter your two-factor authentication code from your authenticator app.\n")
26
code = input("> ")
27
print()
28
pw = settings.config["reddit"]["creds"]["password"]
29
passkey = f"{pw}:{code}"
30
else:
31
passkey = settings.config["reddit"]["creds"]["password"]
32
username = settings.config["reddit"]["creds"]["username"]
33
if str(username).casefold().startswith("u/"):
34
username = username[2:]
35
try:
36
reddit = praw.Reddit(
37
client_id=settings.config["reddit"]["creds"]["client_id"],
38
client_secret=settings.config["reddit"]["creds"]["client_secret"],
39
user_agent="Accessing Reddit threads",
40
username=username,
41
passkey=passkey,
42
check_for_async=False,
43
)
44
except ResponseException as e:
45
if e.response.status_code == 401:
46
print("Invalid credentials - please check them in config.toml")
47
except:
48
print("Something went wrong...")
49
50
# Ask user for subreddit input
51
print_step("Getting subreddit threads...")
52
similarity_score = 0
53
if not settings.config["reddit"]["thread"][
54
"subreddit"
55
]: # note to user. you can have multiple subreddits via reddit.subreddit("redditdev+learnpython")
56
try:
57
subreddit = reddit.subreddit(
58
re.sub(r"r\/", "", input("What subreddit would you like to pull from? "))
59
# removes the r/ from the input
60
)
61
except ValueError:
62
subreddit = reddit.subreddit("askreddit")
63
print_substep("Subreddit not defined. Using AskReddit.")
64
else:
65
sub = settings.config["reddit"]["thread"]["subreddit"]
66
print_substep(f"Using subreddit: r/{sub} from TOML config")
67
subreddit_choice = sub
68
if str(subreddit_choice).casefold().startswith("r/"): # removes the r/ from the input
69
subreddit_choice = subreddit_choice[2:]
70
subreddit = reddit.subreddit(subreddit_choice)
71
72
if POST_ID: # would only be called if there are multiple queued posts
73
submission = reddit.submission(id=POST_ID)
74
75
elif (
76
settings.config["reddit"]["thread"]["post_id"]
77
and len(str(settings.config["reddit"]["thread"]["post_id"]).split("+")) == 1
78
):
79
submission = reddit.submission(id=settings.config["reddit"]["thread"]["post_id"])
80
elif settings.config["ai"]["ai_similarity_enabled"]: # ai sorting based on comparison
81
threads = subreddit.hot(limit=50)
82
keywords = settings.config["ai"]["ai_similarity_keywords"].split(",")
83
keywords = [keyword.strip() for keyword in keywords]
84
# Reformat the keywords for printing
85
keywords_print = ", ".join(keywords)
86
print(f"Sorting threads by similarity to the given keywords: {keywords_print}")
87
threads, similarity_scores = sort_by_similarity(threads, keywords)
88
submission, similarity_score = get_subreddit_undone(
89
threads, subreddit, similarity_scores=similarity_scores
90
)
91
else:
92
threads = subreddit.hot(limit=25)
93
submission = get_subreddit_undone(threads, subreddit)
94
95
if submission is None:
96
return get_subreddit_threads(POST_ID) # submission already done. rerun
97
98
elif not submission.num_comments and settings.config["settings"]["storymode"] == "false":
99
print_substep("No comments found. Skipping.")
100
exit()
101
102
submission = check_done(submission) # double-checking
103
104
upvotes = submission.score
105
ratio = submission.upvote_ratio * 100
106
num_comments = submission.num_comments
107
threadurl = f"https://new.reddit.com/{submission.permalink}"
108
109
print_substep(f"Video will be: {submission.title} :thumbsup:", style="bold green")
110
print_substep(f"Thread url is: {threadurl} :thumbsup:", style="bold green")
111
print_substep(f"Thread has {upvotes} upvotes", style="bold blue")
112
print_substep(f"Thread has a upvote ratio of {ratio}%", style="bold blue")
113
print_substep(f"Thread has {num_comments} comments", style="bold blue")
114
if similarity_score:
115
print_substep(
116
f"Thread has a similarity score up to {round(similarity_score * 100)}%",
117
style="bold blue",
118
)
119
120
content["thread_url"] = threadurl
121
content["thread_title"] = submission.title
122
content["thread_id"] = submission.id
123
content["is_nsfw"] = submission.over_18
124
content["comments"] = []
125
if settings.config["settings"]["storymode"]:
126
if settings.config["settings"]["storymodemethod"] == 1:
127
content["thread_post"] = posttextparser(submission.selftext)
128
else:
129
content["thread_post"] = submission.selftext
130
else:
131
for top_level_comment in submission.comments:
132
if isinstance(top_level_comment, MoreComments):
133
continue
134
135
if top_level_comment.body in ["[removed]", "[deleted]"]:
136
continue # # see https://github.com/JasonLovesDoggo/RedditVideoMakerBot/issues/78
137
if not top_level_comment.stickied:
138
sanitised = sanitize_text(top_level_comment.body)
139
if not sanitised or sanitised == " ":
140
continue
141
if len(top_level_comment.body) <= int(
142
settings.config["reddit"]["thread"]["max_comment_length"]
143
):
144
if len(top_level_comment.body) >= int(
145
settings.config["reddit"]["thread"]["min_comment_length"]
146
):
147
if (
148
top_level_comment.author is not None
149
and sanitize_text(top_level_comment.body) is not None
150
): # if errors occur with this change to if not.
151
content["comments"].append(
152
{
153
"comment_body": top_level_comment.body,
154
"comment_url": top_level_comment.permalink,
155
"comment_id": top_level_comment.id,
156
}
157
)
158
159
print_substep("Received subreddit threads Successfully.", style="bold green")
160
return content
161
162