- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsquareModBot.py
More file actions
Latest commit
309 lines (278 loc) · 11.8 KB
/
Copy pathsquareModBot.py
File metadata and controls
309 lines (278 loc) · 11.8 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
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
#!/usr/bin/python
# -*- coding: UTF8 -*-
fromtimeimporttime, sleep
frompythorheadimportLemmy
frompythorhead.types.sortimportSortType
frompythorhead.types.listingimportListingType
importre
importjson
fromtimeout_decoratorimporttimeout, TimeoutError
try:
importconfig
except:
print("ERROR: Configuration missing.")
print(" Please copy config.py.example to config.py and adjust the configuration.")
print(" Exiting now.")
exit(1)
lemmy=None
communityConfig= {}
communityData= {}
MODBOT_USERID=0
deftemplateString(template, data):
output=""
inBracket=False
bracketContent=""
forcintemplate:
ifinBracket:
ifc=="}":
tokens=bracketContent.split(".")
field=data[tokens.pop(0)]
whiletokens:
field=field[tokens.pop(0)]
output+=str(field)
bracketContent=""
inBracket=False
else:
bracketContent+=c
else:
ifc=="{":
ifoutputandoutput[-1]=="\\":
output+=c
else:
inBracket=True
else:
output+=c
returnoutput
@timeout(seconds=config.REGEX_TIME_LIMIT_SECONDS)
def_reMatchTimeout(regex, string, flags, invertResult):
ifinvertResult:
returnnotre.match(regex, string, flags)
else:
returnre.match(regex, string, flags)
defreMatchTimeout(regex, string, flags=0, invertResult=False):
try:
return_reMatchTimeout(regex, string, flags, invertResult)
exceptTimeoutError:
print("ERROR: Regex /{regex}/ timed out!")
returnNone
defgetNewComments(oldComments, printPageNr=False, community=None):
oldCommentIds= [ x["comment"]["id"] forxinoldComments ]
newComments= []
current= [None]
page=0
whilecurrent:
page+=1
ifconfig.VERBOSE_MODEandprintPageNr:
print(f"Page: {page}")
current=lemmy.comment.list(community_name=community, limit=50, page=page, sort=SortType.New, type_=ListingType.Subscribed)
current= [ xforxincurrentifx["comment"]["creator_id"] !=MODBOT_USERID ]
newComments+= [ xforxincurrentifx["comment"]["id"] notinoldCommentIds ]
ifany([ xforxincurrentifx["comment"]["id"] inoldCommentIds ]):
break
sleep(config.RATE_LIMIT_SECONDS)
ifconfig.VERBOSE_MODE:
print(f"New comments found: {len(newComments)}")
returnnewComments
defgetPostUrlMap(allPosts):
return { x["post"]["url"] : xforxinallPostsif"url"inx["post"] }
defisPostFeatured(post):
returnpost["post"]["featured_community"] orpost["post"]["featured_local"]
defgetNewPosts(oldPosts, printPageNr=False, community=None):
oldPostIds= [ x["post"]["id"] forxinoldPosts ]
newPosts= []
current= [None]
page=0
whilecurrent:
page+=1
ifconfig.VERBOSE_MODEandprintPageNr:
print(f"Page: {page}")
current=lemmy.post.list(community_name=community, limit=50, page=page, sort=SortType.New, type_=ListingType.Subscribed)
current= [ xforxincurrentifx["post"]["creator_id"] !=MODBOT_USERID ]
newPosts+= [ xforxincurrentifx["post"]["id"] notinoldPostIds ]
ifany([ xforxincurrentif (notisPostFeatured(x)) andx["post"]["id"] inoldPostIds ]):
break
sleep(config.RATE_LIMIT_SECONDS)
ifconfig.VERBOSE_MODE:
print(f"New posts found: {len(newPosts)}")
returnnewPosts
defcheckForNewDuplicatePosts(newPosts, oldPosts):
urlMap=getPostUrlMap(oldPosts)
return [ (x, urlMap[x["post"]["url"]]) forxinnewPostsif"url"inx["post"] andx["post"]["url"] inurlMap ]
defcheckPostTrigger(trigger, newPosts, oldPosts):
actionSubjectList= []
iftrigger["triggerType"] =="post_DuplicateUrl":
newDuplicates=checkForNewDuplicatePosts(newPosts, oldPosts)
actionSubjectList= [{
"targetPost" : x[0],
"existingPost" : x[1]
} forxinnewDuplicates]
eliftrigger["triggerType"] =="post_Regex":
actionSubjectList= [{
"targetPost": x,
"existingPost": x
} forxingetPostsRegexMatch(trigger["regex"], newPosts, trigger["fields"], trigger.get("invert"))]
returnactionSubjectList
defexecutePostActions(trigger, actionSubjectList):
foractionintrigger["actions"]:
forsubjectinactionSubjectList:
postId=subject['targetPost']['post']['id']
ifaction["type"] =="postComment":
content=templateString(action["content"], {"targetPost": subject["targetPost"], "existingPost": subject["existingPost"]})
print(f"-> Creating comment: {content}")
newComment=lemmy.comment.create(post_id=postId, content=content)
ifaction["distinguish"] ==True:
print(f"-> Distinguishing (Mark as Modcomment) comment: {content}")
lemmy.comment.distinguish(newComment["comment_view"]["comment"]["id"], True)
elifaction["type"] =="lock":
print(f"-> Locking post: {postId}")
lemmy.post.lock(post_id=postId, locked=action.get("value", True))
elifaction["type"] =="remove":
reason=templateString(action["reason"], {"targetPost": subject["targetPost"], "existingPost": subject["existingPost"]})
print(f"-> Removing post {postId} with the following reason: {reason}")
lemmy.post.remove(post_id=postId, removed=action.get("value", True), reason=reason)
elifaction["type"] =="report":
reason=templateString(action["reason"], {"targetPost": subject["targetPost"]})
print(f"-> Reporting post {postId} for the following reason: {reason}")
lemmy.post.report(post_id=postId, reason=reason)
defcheckCommentTrigger(trigger, newComments, oldComments):
actionSubjectList= []
iftrigger["triggerType"] =="comment_Regex":
actionSubjectList= [{
"targetComment": x,
} forxinnewCommentsifreMatchTimeout(trigger["regex"], x["comment"]["content"], re.I, trigger.get("invert"))]
returnactionSubjectList
defexecuteCommentActions(trigger, actionSubjectList):
foractionintrigger["actions"]:
forsubjectinactionSubjectList:
commentId=subject['targetComment']['comment']['id']
ifaction["type"] =="postComment":
content=templateString(action["content"], {"targetComment": subject["targetComment"]})
print(f"-> Creating comment: {content}")
newComment=lemmy.comment.create(post_id=subject["targetComment"]["post"]["id"], parent_id=commentId, content=content)
ifaction["distinguish"] ==True:
print(f"-> Distinguishing (Mark as Modcomment) comment: {content}")
lemmy.comment.distinguish(newComment["comment_view"]["comment"]["id"], True)
elifaction["type"] =="remove":
reason=templateString(action["reason"], {"targetComment": subject["targetComment"]})
print(f"-> Removing comment {commentId} with the following reason: {reason}")
lemmy.comment.remove(comment_id=commentId, removed=action.get("value", True), reason=reason)
elifaction["type"] =="report":
reason=templateString(action["reason"], {"targetComment": subject["targetComment"]})
print(f"-> Reporting commend {commentId} for the following reason: {reason}")
lemmy.comment.report(comment_id=commentId, reason=reason)
defprocessTriggers(newPosts, newComments, communityData):
fortriggerincommunityConfig[community]["triggers"]:
iftrigger["triggerType"].startswith("post_"):
actionSubjectList=checkPostTrigger(trigger, newPosts, communityData[community]["oldPosts"])
executePostActions(trigger, actionSubjectList)
eliftrigger["triggerType"].startswith("comment_"):
actionSubjectList=checkCommentTrigger(trigger, newComments, communityData[community]["oldComments"])
executeCommentActions(trigger, actionSubjectList)
defgetPostsRegexMatch(regex, posts, fields, invertResult):
out= []
forpostinposts:
forfieldinfields:
iffieldinpost["post"] andreMatchTimeout(regex, post["post"][field], re.I, invertResult):
out.append(post)
break
returnout
definitializeCommunityData():
globalcommunityData, allOldPosts, allOldComments
try:
withopen("communityDataCache.json", "r") asf:
communityData=json.load(f)
print("## Using cached community data")
except:
print("## Couldn't find cached community data, reading from API instead")
forcommunityincommunityConfig:
ifcommunitynotincommunityData:
communityData[community] = {}
if"oldPosts"notincommunityData[community]:
print(f"## Reading all existing posts in {community}")
communityData[community]["oldPosts"] =getNewPosts([], True, community)
if"oldComments"notincommunityData[community]:
print(f"## Reading all existing comments in {community}")
communityData[community]["oldComments"] =getNewComments([], True, community)
allOldPosts=sum([ communityData[x]["oldPosts"] forxincommunityConfig ], [])
allOldComments=sum([ communityData[x]["oldComments"] forxincommunityConfig ], [])
print("## Done reading posts/comments. Starting loop.\n")
deflogin():
globallemmy
lemmy=Lemmy(config.API_URL)
ifnotlemmy.log_in(config.USERNAME, config.PASSWORD):
print("ERROR: Login failed.")
print("Exiting now")
exit(1)
defcheckModBotUserData():
globalMODBOT_USERID
user=lemmy.user.get(username=config.USERNAME, limit=1)
MODBOT_USERID=user["person_view"]["person"]["id"]
forcommunityincommunityConfig:
ifcommunitynotin [ x["community"]["name"] forxinuser["moderates"] ]:
print(f"ERROR: {config.USERNAME} is not moderator in community {community}.")
print("Exiting now.")
exit(1)
returnuser
defupdateCommunitySubscriptions(userData):
currentSubscriptions= [ x["community"]["id"] forxinlemmy.community.list(type_=ListingType.Subscribed) ]
targetSubscriptions= [ x["community"]["id"] forxinuserData["moderates"] ]
needsSubscription= [ xforxintargetSubscriptionsifxnotincurrentSubscriptions ]
needsUnsubscription= [ xforxincurrentSubscriptionsifxnotintargetSubscriptions ]
forcommunityIdinneedsSubscription:
lemmy.community.follow(id=communityId, follow=True)
forcommunityIdinneedsUnsubscription:
lemmy.community.follow(id=communityId, follow=False)
defsplitPostsAndCommentsByCommunity(allNewPosts, allNewComments):
newPostsByCommunity= {}
newCommentsByCommunity= {}
forcommunityincommunityConfig:
newPostsByCommunity[community] = [ xforxinallNewPostsifx["community"]["name"] ==community ]
newCommentsByCommunity[community] = [ xforxinallNewCommentsifx["community"]["name"] ==community ]
return (newPostsByCommunity, newCommentsByCommunity)
defreloadCommunityConfig():
globalcommunityConfig
ifconfig.VERBOSE_MODE:
print(f"## Reloading community config")
text=None
try:
withopen("communityConfig.json") asf:
text=f.read()
except:
print("ERROR: Could not read communityConfig.json. Did you create it?")
print("Exiting now")
exit(1)
try:
communityConfig=json.loads(text)
except:
print("ERROR: communityConfig.json is not valid JSON. Please run it through a JSON validator.")
print("Exiting now")
exit(1)
if__name__=="__main__":
login()
userData=checkModBotUserData()
reloadCommunityConfig()
updateCommunitySubscriptions(userData)
initializeCommunityData()
whileTrue:
print("## Start polling all communities")
startTime=time()
reloadCommunityConfig()
allNewPosts=getNewPosts(allOldPosts)
allNewComments=getNewComments(allOldComments)
newPostsByCommunity, newCommentsByCommunity=splitPostsAndCommentsByCommunity(allNewPosts, allNewComments)
forcommunityincommunityConfig:
ifconfig.VERBOSE_MODE:
print(f"## Start processing community \"{community}\"")
processTriggers(newPostsByCommunity[community], newCommentsByCommunity[community], communityData)
communityData[community]["oldPosts"] +=newPostsByCommunity[community]
communityData[community]["oldComments"] +=newCommentsByCommunity[community]
allOldPosts+=allNewPosts
allOldComments+=allNewComments
ifconfig.VERBOSE_MODE:
print("## Finished polling all communities\n")
ifallNewPostsorallNewComments:
ifconfig.VERBOSE_MODE:
print("## Updating community data cache\n")
withopen("communityDataCache.json", "w") asf:
json.dump(communityData, f)
sleep(max(0,config.CHECK_INTERVAL_SECONDS-(time()-startTime)))