Skip to content

Commit 45809b7

Browse files
committed
refactor: reduce complexity of filterbot's on_message
1 parent f66d5a3 commit 45809b7

1 file changed

Lines changed: 58 additions & 42 deletions

File tree

scratchattach/eventhandlers/filterbot.py

Lines changed: 58 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
import requests as _requests
6+
57
from .message_events import MessageEvents
68
import time
79
from collections import deque
@@ -158,59 +160,73 @@ def add_genalpha_nonsense_filter(self):
158160
self.add_filter(HardFilter("[genalpha_nonsene_filter) 'rizzler'", contains="rizzler"))
159161
self.add_filter(HardFilter("(genalpha_nonsene_filter) 'fanum tax'", contains="fanum tax"))
160162

161-
def on_message(self, message: activity.Activity):
162-
if message.type != activity.ActivityTypes.addcomment:
163-
return
164-
source_id = None
163+
def _apply_filters(self, message: activity.Activity, source_id: int | str | None) -> tuple[bool, str]:
164+
"""
165+
Applies the filterbot filters and returns whether the message violates the filters, and why
166+
returns tuple of whether to delete, and the reason
167+
"""
168+
assert message.type == activity.ActivityTypes.addcomment
169+
165170
content = message.comment_fragment
166-
if message.comment_type == 0: # project comment
167-
source_id = message.comment_obj_id
168-
if self.user._session.connect_project(message.comment_obj_id).author_name != self.user.username:
169-
return # no permission to delete comments that aren't on our own project
170-
elif message.comment_type == 1: # profile comment
171-
source_id = message.comment_obj_title
172-
if source_id != self.user.username:
173-
return # no permission to delete messages that are not on our profile
174-
elif message.comment_type == 2: # studio comment
175-
return # studio comments aren't handled
176-
else:
177-
return
178-
delete = False
179-
reason = ""
180171

181172
# Apply hard filters
182173
for hard_filter in self.hard_filters:
183174
if hard_filter.apply(content, message.actor_username, source_id):
184-
delete = True
185-
reason = f"hard filter: {hard_filter.filter_name}"
186-
break
175+
return True, f"hard filter: {hard_filter.filter_name}"
187176

188177
# Apply spam filters
189-
if not delete:
190-
for spam_filter in self.spam_filters:
191-
if spam_filter.apply(content, message.actor_username, source_id):
192-
delete = True
193-
reason = f"spam filter: {spam_filter.filter_name}"
194-
break
178+
for spam_filter in self.spam_filters:
179+
if spam_filter.apply(content, message.actor_username, source_id):
180+
return True, f"spam filter: {spam_filter.filter_name}"
195181

196182
# Apply soft filters
197-
if not delete:
198-
score = 0
199-
violated_filters = []
200-
for soft_filter in self.soft_filters:
201-
if soft_filter.apply(content, message.actor_username, source_id):
202-
score += soft_filter.score
203-
violated_filters.append(soft_filter.filter_name)
204-
if score >= 1:
205-
delete = True
206-
reason = f"too many soft filters: {violated_filters}"
183+
score = 0
184+
violated_filters = []
185+
for soft_filter in self.soft_filters:
186+
if soft_filter.apply(content, message.actor_username, source_id):
187+
score += soft_filter.score
188+
violated_filters.append(soft_filter.filter_name)
189+
190+
if score >= 1:
191+
return True, f"too many soft filters: {violated_filters}"
192+
193+
return False, ""
194+
195+
def _determine_source_and_deletable(self, message: activity.Activity) -> tuple[int | str | None, bool]:
196+
if message.comment_type == 0: # project comment
197+
project_id = message.comment_obj_id
198+
if self.user._session.connect_project(message.comment_obj_id).author_name == self.user.username:
199+
return project_id, True # only permission to delete comments that are on our own project
200+
201+
elif message.comment_type == 1: # profile comment
202+
if message.comment_obj_title == self.user.username:
203+
return message.comment_obj_title, True # no permission to delete messages that are not on our profile
204+
# elif message.comment_type == 2: # studio comment
205+
# studio comments aren't handled
206+
return None, False
207+
208+
def _print_if_logging(self, *args, **kwargs):
209+
if self.log_deletions:
210+
print(*args, **kwargs)
211+
212+
def on_message(self, message: activity.Activity):
213+
if message.type != activity.ActivityTypes.addcomment:
214+
return
215+
216+
source_id, deletable = self._determine_source_and_deletable(message)
217+
if not deletable:
218+
return
219+
220+
content = message.comment_fragment
221+
delete, reason = self._apply_filters(message, source_id)
222+
207223
if delete:
208-
if self.log_deletions:
209-
print(f"DETECTED: #{message.comment_id} violates {reason}")
224+
self._print_if_logging(f"DETECTED: #{message.comment_id} violates {reason}")
210225
try:
211-
resp = message.target().delete()
212-
if self.log_deletions:
213-
print(
226+
if target := message.target_comment():
227+
resp = target.delete()
228+
assert isinstance(resp, _requests.Response)
229+
self._print_if_logging(
214230
f"DELETED: #{message.comment_id} by {message.actor_username!r}: '{content}' with message {resp.content!r} & headers {resp.headers!r}"
215231
)
216232
except Exception as e:

0 commit comments

Comments
 (0)