-
Notifications
You must be signed in to change notification settings - Fork 1
/
crossposter.py
executable file
·236 lines (211 loc) · 7.59 KB
/
crossposter.py
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from constants import *
from entry import get_entry, get_entry_details
from screenshotter import get_screenshot
from update_entry import update_entry_with_social_ids
from webdriver import get_driver
from toot import send_toot
from tweet import send_tweet
from skeet import send_skeet
from insta import send_instagram
from threads import send_threads
import argparse
import json
import logging
import os.path
import re
import subprocess
ANSI = {"GREEN": "\033[92m", "YELLOW": "\033[93m", "ENDC": "\033[0m"}
ZWSP = "\u200B"
URL_REGEX = re.compile(
r"[a-z](\.)[a-z]", flags=re.IGNORECASE
) # This is a naive regex in that it doesn't check if it's a legit TLD, but it should serve the purpose
def cleanup():
"""Clean up output directory before run, or create it if it doesn't exist."""
if os.path.exists(OUTPUT_DIR):
# Erase all files in the output directory from last run
for f in os.listdir(OUTPUT_DIR):
os.remove(os.path.join(OUTPUT_DIR, f))
else:
# Create the output directory if it's missing
os.mkdir(OUTPUT_DIR)
def format_post_title(post_title):
title_result = post_title
match = re.search(URL_REGEX, title_result)
while match:
title_result = (
title_result[: match.regs[1][0]]
+ ZWSP
+ title_result[match.regs[1][0] : match.regs[1][1]]
+ title_result[match.regs[1][1] :]
)
match = re.search(URL_REGEX, title_result)
return title_result
def make_posts(
post_text,
url,
num_screenshots,
entry_details,
tweet,
toot,
skeet,
insta,
threads,
):
post_ids = {}
post_text_with_url = f"{post_text}\n{url}"
if tweet:
post_ids["twitter"] = send_tweet(post_text, url, num_screenshots, entry_details)
elif toot:
post_ids["mastodon"] = send_toot(
post_text_with_url, num_screenshots, entry_details
)
elif skeet:
post_ids["bluesky"] = send_skeet(
post_text_with_url, num_screenshots, entry_details
)
elif insta:
post_ids["instagram"] = send_instagram(
post_text_with_url, num_screenshots, entry_details
)
elif threads:
post_ids["threads"] = send_threads(
post_text_with_url, num_screenshots, entry_details
)
else:
post_ids["twitter"] = send_tweet(post_text, url, num_screenshots, entry_details)
post_ids["mastodon"] = send_toot(
post_text_with_url, num_screenshots, entry_details
)
post_ids["bluesky"] = send_skeet(
post_text_with_url, num_screenshots, entry_details
)
post_ids["instagram"] = send_instagram(
post_text_with_url, num_screenshots, entry_details
)
post_ids["threads"] = send_threads(
post_text_with_url, num_screenshots, entry_details
)
return post_ids
def print_results(results):
logger = logging.getLogger(__name__)
if results["error"]:
logger.error("⚠️ Posted with errors:")
else:
logger.info("✅ Posted without errors:")
for service in SERVICES:
if service in results:
if results[service] == "Success":
logger.info("✅ " + service)
else:
logger.error("⚠️" + results[service])
def crosspost(
entry_id=None,
no_confirm=False,
use_prev=False,
debug=False,
tweet=False,
toot=False,
skeet=False,
insta=False,
threads=False,
):
num_screenshots = None
entry_details = None
driver = None
logger = logging.getLogger(__name__)
sh = logging.StreamHandler()
if debug:
logger.setLevel(logging.DEBUG)
sh.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
sh.setLevel(logging.INFO)
logger.addHandler(sh)
if entry_id is None:
print("Entry ID required.")
else:
try:
if not use_prev:
# Clear out output directory and fetch new data and screenshots
cleanup()
driver = get_driver()
entry = get_entry(driver, entry_id)
if entry is not None:
screenshot_splits = get_screenshot(entry)
num_screenshots = len(screenshot_splits)
entry_details = get_entry_details(entry, screenshot_splits)
with open(
os.path.join(OUTPUT_DIR, "entry.json"), "w+"
) as json_file:
json.dump(
{
"num_screenshots": num_screenshots,
"entry_details": entry_details,
},
json_file,
)
else:
# Use existing stored data and screenshots without fetch
with open(os.path.join(OUTPUT_DIR, "entry.json"), "r") as json_file:
stored = json.load(json_file)
num_screenshots = stored["num_screenshots"]
entry_details = stored["entry_details"]
if entry_details:
post_text = f"{format_post_title(entry_details['title'])}\n\n{entry_details['date']}"
if no_confirm:
logger.debug("Skipping confirmation step.")
confirm = True
else:
# Open output directory to confirm images
subprocess.call(["open", "-R", OUTPUT_DIR])
print("=" * 20 + "\n" + post_text + "\n" + "=" * 20 + "\n\n")
confirm = input("Ready to post? [y/n] ").lower()
confirm = True if confirm == "y" else False
if confirm:
post_ids = make_posts(
post_text,
entry_details["url"],
num_screenshots,
entry_details,
tweet,
toot,
skeet,
insta,
threads,
)
result = update_entry_with_social_ids(entry_id, post_ids)
print_results(result)
else:
print("Exiting without posting.")
else:
print(f"Entry with ID {entry_id} not found.")
finally:
if driver is not None:
driver.quit()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Crosspost a Web3 is Going Just Great entry to social media."
)
parser.add_argument("entry_id", help="ID of the W3IGG entry, in numerical format.")
parser.add_argument(
"--no-confirm",
action="store_true",
help="Send posts without prompting to confirm",
)
parser.add_argument(
"--use-prev",
action="store_true",
help="Use screenshots and post information from previous run without re-fetching",
)
parser.add_argument(
"--debug", action="store_true", help="Print verbose debugging information"
)
# Option to only post to one of the services
service_group = parser.add_mutually_exclusive_group()
service_group.add_argument("--tweet", action="store_true")
service_group.add_argument("--toot", action="store_true")
service_group.add_argument("--skeet", action="store_true")
service_group.add_argument("--insta", action="store_true")
service_group.add_argument("--threads", action="store_true")
args = parser.parse_args()
crosspost(**vars(args))