-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbestof.py
executable file
Β·448 lines (384 loc) Β· 14.7 KB
/
bestof.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#!/usr/bin/python3
import json
import sys
import string
import random
import mimetypes
import tldr
import yt
import news
import deepseek
import requests
import urllib.parse
import datetime
import issues
import shorten
from urllib.parse import urlparse
from pythorhead import Lemmy
from pythorhead.types import SortType
def sortfunc(e):
return e['score']['score']
def get_contenttype(url):
try:
r = requests.head(url, allow_redirects=True, headers={"User-Agent":"Mozilla/5.0"})
ct = r.headers['Content-Type']
print(f'content-type retrieved from URL: {ct}')
return ct
except Exception as e:
print(f'err getting remote content-type: {e}')
def get_commlist(cfg):
try:
with open(cfg) as f:
commlist = json.load(f)
#commlist.sort()
return commlist
except Exception as e:
print("error reading config file: {e}")
return None
def get_comminfo(lemmy, c):
try:
id = lemmy.discover_community(c)
except Exception as e:
print(f'cannot discover {c}: {e}')
return None
return lemmy.community.get(id)["community_view"]["community"]
def extract_desc(ci):
if "description" in ci:
desc = ci["description"]
d = desc.splitlines()
for l in d:
if (len(l) > 0):
if (l[:1] != '#') and (l[:1] != '-') and (l[:1] != '*'):
return l
return "No description"
def add_embed(p):
if "embed_title" in p:
t = f'*{p["embed_title"]}*\n\n'
else:
t = ""
if "embed_description" in p:
t += f'{p["embed_description"]}\n\n'
return t
def gen_shield(c):
mbin = [ 'fedia.io',
'kbin.social'
]
dom = c.split('@')[1]
if dom in mbin:
serv = "mbin"
else:
serv = "lemmy"
cenc = urllib.parse.quote_plus(c)
return f''
def run(user, pw, instance, postcomm, cfg, post_title, images_only, nsfw_b, moduser, modpw, rapidkey, ghtoken, ghrepo):
topposts = 0
toppost = []
noposts = 0
nopostsc = []
nsfw = False
if nsfw_b == 1:
# force nsfw
nsfw = True
# add date to post title
today = datetime.date.today()
today_text = today.strftime("%d %b %Y")
post_title += f' ({today_text})'
print(post_title)
skip_urls = ["rabbitea.rs", "file.coffee", "sffa.community"]
lemmy = Lemmy(f'https://{instance}', raise_exceptions=True, request_timeout=30)
try:
lemmy.log_in(user, pw)
except Exception as e:
print(f'login failed: {e}\n')
sys.exit(1)
communities = get_commlist(cfg)
if communities is None:
print('no communities')
sys.exit(1)
for comm in communities:
try:
community_id = lemmy.discover_community(comm)
except Exception as e:
print(f'discover {comm} failed: {e}\n')
try:
issues.raise_issue(ghtoken, ghrepo, f'Remove {comm}', f'discover_community returned:\n\n```\n{e}\n```\n')
except Exception as ghe:
print(f'error raising github issue: {ghe}\n')
continue # skip communities we can't find
if community_id is not None:
try:
lemmy.community.follow(community_id) # ensure we get new posts
except Exception as e:
print(f'cannot follow {comm}: {e}\n')
try:
posts = lemmy.post.list(community_id = community_id, limit = 5, sort = SortType.TopMonth)
except Exception as e:
print(f'cannot get posts for {comm}: {e}\n')
found = False
if (len(posts) > 0):
for p in posts:
if ('nsfw' in p['post']) and (p['post']['nsfw']) is True:
if nsfw_b == 2:
continue
if p['counts']['score'] < 0:
break
if('url' in p['post']):
if images_only is True:
if 'url_content_type' in p['post']:
# if there's no url_content_type we accept it regardless
mime = p['post']['url_content_type']
else:
mime = get_contenttype(p['post']['url'])
if mime is None:
mime, encoding = mimetypes.guess_type(p['post']['url'])
print(f'guessed {mime} for {p["post"]["id"]}')
if mime is None:
found = True
break
# we accept application/octet-stream as cara seems to return it lots, and text/html
# as Lemmy seems to get a bit confused and use this sometimes.
if(mime[:5] != "image") and (mime[:11] != "application"):
continue
if (mime[:9] == "text/html"):
# 2nd opinion
contenttype = get_contenttype(p['post']['url'])
if contenttype is None:
contenttype, encoding = mimetypes.guess_type(p['post']['url'])
if (contenttype is not None) and contenttype[:5] != "image":
continue
found = True
break
else:
if images_only is True:
continue
else:
found = True
break
if found is True:
if p['post']['nsfw'] is True:
nsfw = True
toppost.append(0)
toppost[topposts] = {}
toppost[topposts]['post'] = p['post']
toppost[topposts]['score'] = p['counts']
toppost[topposts]['community'] = comm
toppost[topposts]['comminfo'] = p['community']
toppost[topposts]['author'] = p['creator']
topposts += 1
if found is not True:
print(f"no posts in {comm} this month")
nopostsc.append(0)
nopostsc[noposts] = comm
noposts += 1
else:
print(f"cannot find {comm}\n")
if len(toppost) == 0:
print('no active communities!')
try:
user = lemmy.user.get(username=f'{moduser}@{instance}')
except Exception as e:
print(f'err looking up user {moduser}@{instance}: {e}')
if user is not None:
try:
lemmy.private_message.create(content = f'{post_title} was not posted due to no active communities.', recipient_id=user["person_view"]["person"]["id"])
except Exception as e:
print(f'err sending PM to {moduser}@{instance}: {e}')
sys.exit(0)
print('sorting...')
toppost.sort(reverse = True, key = sortfunc)
found = False
if (len(nopostsc) > 0):
comm = random.choice(nopostsc)
try:
community_id = lemmy.discover_community(comm)
except:
print(f'cannot discover {comm}: {e}\n')
if community_id is not None:
for sorttype in [SortType.TopYear, SortType.TopAll]:
try:
posts = lemmy.post.list(community_id = community_id, limit = 5, sort = sorttype)
except Exception as e:
print(f'cannot get posts in {comm}: {e}\n')
if (len(posts) > 0):
for p in posts:
if p['post']['nsfw'] is True:
if nsfw_b == 2:
continue
if('url' in p['post']):
host = urlparse(p['post']['url'])
if(host.netloc in skip_urls):
print(f'skipping {host.netloc}\n')
break
if images_only is True:
if 'url_content_type' in p['post']:
mime = p['post']['url_content_type']
if(mime[:5] != "image") and (mime[:11] != "application"):
continue
found = True
break
else:
if images_only is True:
continue
else:
found = True
break
if found is True:
if p['post']['nsfw'] is True:
nsfw = True
toppost.append(0)
toppost[topposts] = {}
toppost[topposts]['post'] = p['post']
toppost[topposts]['score'] = p['counts']
toppost[topposts]['community'] = comm
toppost[topposts]['comminfo'] = p['community']
toppost[topposts]['author'] = p['creator']
topposts += 1
break
posttext = ''
n = 0
for p in toppost:
#print(p['post'])
n += 1
if "url" in p['post']:
if "url_content_type" in p['post']:
if (p['post']['url_content_type'][:5] == "image") or (images_only is True):
emoji = 'πΌοΈ'
elif (p['post']['url_content_type'][:5] == "video") or ("embed_video_url" in p['post']):
emoji = 'π¦'
else:
emoji = 'π°'
elif ("video_embed_url" in p['post']) or (p['post']['url'].endswith(('.avi', '.mp4', '.mpg'))):
emoji = 'π¦'
elif (p['post']['url'].endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))) or (images_only is True):
emoji = 'πΌοΈ'
else:
emoji = 'π°'
else:
emoji = 'π¬'
# set nsfw tag
if p['post']['nsfw'] is True:
nsfw_txt = "[**NSFW**]"
else:
nsfw_txt = ""
# check if this is a random inactive community
lemmyverselink = "https://lemmyverse.link/" + p['post']['ap_id'][8:]
if (n < len(toppost)) or (found is False):
shield = gen_shield(p['community'])
title = p['comminfo']['title'].strip()
if n > 1:
posttext += '\n----\n'
posttext = posttext + f"### {n}. {emoji} [{p['post']['name']}]({lemmyverselink}) {nsfw_txt} ([direct link]({p['post']['ap_id']})) (π{p['score']['upvotes']} π{p['score']['downvotes']})\n\nfrom **{title}** (!{p['community']}) {shield}\n\n"
else:
posttext = posttext + f'\n----\n# Inactive communities π»\n\nThese communities have had no posts in the last month:\n\n'
for c in nopostsc:
shield = gen_shield(c)
comminfo = get_comminfo(lemmy, c)
posttext = posttext + f'- [{comminfo["title"]}](/c/{c}) {shield}\n'
commdesc = extract_desc(comminfo)
if commdesc is not None:
posttext += f' - {commdesc}\n'
posttext = posttext + "\n\n### Here is a popular post from one of the inactive communities. πͺ¦β»οΈ\n\n"
posttext = posttext + f"{emoji} [{p['post']['name']}]({lemmyverselink}) {nsfw_txt} ([direct link]({p['post']['ap_id']})), posted in [{p['comminfo']['title']}](/c/{p['community']}) (π{p['score']['upvotes']} π{p['score']['downvotes']})\n\n"
#if 'url_content_type' in p['post']:
# print(f'{p["post"]["name"]} - {p["post"]["url_content_type"]}')
if(images_only is True) or ("url" in p['post'] and (("url_content_type" not in p['post']) or (("url_content_type" in p['post']) and (p['post']['url_content_type'][:5] == "image")))):
posttext = posttext + f"\n\n"
if images_only is not True:
if 'body' in p['post']:
posttext += shorten.shorten_text(p['post']['body'], rapidkey)
elif "url" in p['post']:
print(f"* {p['post']['name']} - {p['post']['url']}")
if "url_content_type" in p['post']:
if p['post']['url_content_type'][:9] == 'text/html':
# try youtube
print('youtube...')
t = yt.get(p['post']['url'])
if t is not None:
posttext += t
else:
# run through tldr
print('tldr...')
t = tldr.tldrthis(rapidkey, p['post']['url'])
if t is not None:
posttext += t
else:
# use news3k to get an article image
print('news...')
try:
t = news.article(p['post']['url'], rapidkey)
except Exception as e:
print(f'failed to use news3k to get article: {e}')
t = None
if t is not None:
posttext += t
else:
# add title/desc from lemmy api
print('lemmy fallback 1...')
t = add_embed(p['post'])
if t is not None:
posttext += t
else:
print('lemmy fallback 2...')
if 'body' in p['post']:
posttext += shorten.shorten_text(p['post']['body'], rapidkey)
elif p['post']['url_content_type'][:6] == 'video/':
# embed video url
posttext = posttext + f"\n\n"
if 'body' in p['post']:
posttext += shorten.shorten_text(p['post']['body'], rapidkey)
else:
'''no content type'''
t = add_embed(p['post'])
if t is not None:
posttext += t
else:
# use news3k to get an article image
t = news.article_image(p['post']['url'])
if t is not None:
posttext += t
if 'body' in p['post']:
posttext += shorten.shorten_text(p['post']['body'], rapidkey)
else:
'''not url'''
if 'body' in p['post']:
posttext += shorten.shorten_text(p['post']['body'], rapidkey)
posttext = posttext + f"Posted by [{p['author']['name']}]({p['author']['actor_id']})\n\n"
posttext += "\n\n----\n\nThe main links are using lemmyverse.link which should redirect to the post on your own instance. If you have not used this before, you may need to go direct to https://lemmyverse.link/ and click on 'configure instance'. Some apps will open posts correctly when using the direct link."
if images_only is not True:
posttext += "\n\nοΈπ€ indicates a summary generated using AI - ποΈ TLDR This, ποΈ news3k, π Deepseek. It is possible that the summary does not accurately convey the meaning of the original article, refer to the source material if in any doubt."
print(posttext)
if nsfw is True:
print("** nsfw posts detected **")
if postcomm is None:
return posttext
try:
community_id = lemmy.discover_community(postcomm)
except Exception as e:
print(f'cannot discover {postcomm}: {e}')
sys.exit(1)
if community_id is not None:
'''post'''
try:
post = lemmy.post.create(community_id, post_title, url=toppost[0]['post']['url'], body=posttext, nsfw=nsfw)
except Exception as e:
print(f'cannot post, exception = {e}\n')
return posttext
try:
comment = lemmy.comment.create(post["post_view"]["post"]["id"], "Please comment under the original posts. \n\nThe descriptions of the inactive communities are auto-generated, it will pick up the first non-header line from the sidebar.\n\nIf you have a comment about the monthly posts please create a [META] post in the community. Thanks!")
except Exception as e:
print(f'cannot post comment, exception = {e}\n')
# not critical - continue
if moduser != 0:
# log in as our mod user
try:
lemmy.log_in(moduser, modpw)
except Exception as e:
print(f'login failed: {e}\n')
# non-fatal, we'll try with the regular user
try:
lock = lemmy.post.lock(post["post_view"]["post"]["id"], True)
except Exception as e:
print(f'cannot lock post, exception = {e}\n')
# not critical - exit with success code
return posttext
return posttext