-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
128 lines (109 loc) · 4.13 KB
/
main.py
File metadata and controls
128 lines (109 loc) · 4.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import praw
import os
import json
import time
def load_config():
with open('config.json', 'r') as f:
return json.load(f)
def read_txt_file(filename):
if os.path.isfile(filename):
with open(filename, 'r', encoding='utf-8') as f:
return f.read().strip()
return ""
def read_subreddits(file_path):
if os.path.isfile(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return [line.strip() for line in f if line.strip()]
return []
def authenticate_reddit(config):
return praw.Reddit(
client_id=config['client_id'],
client_secret=config['client_secret'],
username=config['username'],
password=config['password'],
user_agent=config['user_agent']
)
def get_image_files(image_dir):
return sorted([
f for f in os.listdir(image_dir)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))
])
def select_post_flair(subreddit):
try:
flairs = list(subreddit.flair.link_templates)
except Exception as e:
print(f"Could not fetch flairs for r/{subreddit.display_name}: {e}")
return None, None
if not flairs:
print(f"No post flairs available in r/{subreddit.display_name}.")
return None, None
print(f"\nAvailable post flairs in r/{subreddit.display_name}:")
for idx, flair in enumerate(flairs, start=1):
flair_text = flair['text'] or 'No Text'
print(f"{idx}. {flair_text} (ID: {flair['id']})")
while True:
try:
choice = int(input("Enter the number of the flair you want to apply to the post: "))
if 1 <= choice <= len(flairs):
selected_flair = flairs[choice - 1]
flair_id = selected_flair['id']
flair_text = selected_flair['text']
return flair_id, flair_text
else:
print("Invalid choice. Please enter a valid number.")
except ValueError:
print("Invalid input. Please enter a number.")
def preview_post(subreddit_name, title, images, flair_text, comment):
print(f"\n--- Preview for r/{subreddit_name} ---")
print(f"Title: {title}")
print(f"Images: {', '.join(images)}")
print(f"Flair: {flair_text or 'None'}")
print(f"Comment: {comment[:150]}..." if comment else "Comment: None")
return input("Post this? (y/n): ").strip().lower() == 'y'
def submit_gallery_post(subreddit, title, image_dir, flair_id, flair_text, comment):
image_files = get_image_files(image_dir)
if not image_files:
print(f"No images found in directory: {image_dir}")
return
media = []
for img in image_files:
img_path = os.path.join(image_dir, img)
media.append({"image_path": img_path, "caption": ""})
if not preview_post(subreddit.display_name, title, image_files, flair_text, comment):
print(f"Skipped posting to r/{subreddit.display_name}")
return
try:
print(f"Posting gallery to r/{subreddit.display_name}...")
submission = subreddit.submit_gallery(
title=title,
images=media,
flair_id=flair_id,
flair_text=flair_text
)
shortlink = submission.shortlink
print(f"Posted to r/{subreddit.display_name}: {shortlink}")
if comment:
submission.reply(comment)
print("Comment posted.")
return shortlink
except Exception as e:
print(f"Failed to post to r/{subreddit.display_name}: {e}")
return None
def main():
config = load_config()
reddit = authenticate_reddit(config)
links = []
title = read_txt_file("title.txt")
comment = read_txt_file("comment.txt")
subreddits = read_subreddits("subs.txt")
image_dir = "img"
for sub_name in subreddits:
subreddit = reddit.subreddit(sub_name)
flair_id, flair_text = select_post_flair(subreddit)
link = submit_gallery_post(subreddit, title, image_dir, flair_id, flair_text, comment)
if link:
links.append(link)
time.sleep(10)
print("These are the links :\n", "\n".join(links))
if __name__ == "__main__":
main()