Files
payphone/payphone/core/censorship.py
T
2024-11-15 23:24:11 -03:00

50 lines
1.2 KiB
Python

import re
words = []
with open("censored.txt", encoding="UTF-8") as f:
for line in f:
words.append(line.strip())
WORDS = re.compile(r"\w+")
PATTERN = re.compile(
f"^({"|".join(words + [word + "s" for word in words])})$",
re.IGNORECASE,
)
URL_PATTERN = re.compile(r"https?://[^\s]+", re.IGNORECASE)
INVITES_PATTERN = re.compile(r"(discord)?.gg/[^\s]+", re.IGNORECASE)
def censor(message: str, is_gif_allowed: bool = False) -> str:
"""Returns the first censored word or pattern found.
Args:
message (str): The message to moderate.
is_gif_allowed (bool, optional): If GIFs are allowed. Defaults to False.
Returns:
str | None: The blocked pattern found as it was found.
"""
for word in WORDS.finditer(message):
word = message[word.start() : word.end()]
if PATTERN.match(word):
return word
for match in URL_PATTERN.finditer(message):
string = message[match.start() : match.end()]
if is_gif_allowed and string.startswith("https://tenor.com/view/"):
continue
return string
match = next(INVITES_PATTERN.finditer(message), None)
if match is not None:
return message[match.start() : match.end()]
return None