-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
73 lines (69 loc) · 2.37 KB
/
main.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
import operator
import os
import random
import time
import traceback
from datetime import datetime
import requests
def main(subr: str, trg_hook: str, log_hook: str, sleep_dur: float):
requests.post(
log_hook,
json={
"content": f"r/{subr} webhook started",
"username": f"r/{subr} webhook log",
},
)
min_time = datetime.utcnow()
while True:
try:
permalinks = []
req = requests.get(
f"https://www.reddit.com/r/{subr}/new.json",
headers={
"User-Agent": fr"{chr(random.randint(33,126))}{''.join(chr(random.randint(32, 126)) for _ in range(15))}"
},
)
assert (
req.status_code == 200
), f"request to {req.url} returned {req.status_code}"
for data in map(
operator.itemgetter("data"), req.json()["data"]["children"]
):
post_time = datetime.utcfromtimestamp(data["created_utc"])
if post_time <= min_time:
break
permalinks.append((data["permalink"], post_time))
else:
requests.post(
log_hook,
json={
"content": f"LOG: more than 25 posts were made in the last {sleep_dur} seconds on r/{subr}",
"username": f"r/{subr} webhook log",
},
)
for permalink in map(operator.itemgetter(0), reversed(permalinks)):
requests.post(
trg_hook,
json={"content": f"https://www.reddit.com{permalink}"},
)
if permalinks:
min_time = permalinks[0][1]
except Exception:
requests.post(
log_hook,
json={
"content": "```\n{}```".format(
traceback.format_exc().replace("```", "\\`\\`\\`")
),
"username": f"r/{subr} webhook log",
},
)
finally:
time.sleep(sleep_dur)
if __name__ == "__main__":
main(
os.environ["IRH_SUBREDDIT_NAME"],
os.environ["IRH_TARGET_WEBHOOK_URL"],
os.environ["IRH_LOG_WEBHOOK_URL"],
float(os.environ["IRH_SLEEP_DURATION"]),
)