Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions bot/exts/filtering/_filters/unique/image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import io

import imagehash
from PIL import Image

from bot.exts.filtering._filter_context import Event, FilterContext
from bot.exts.filtering._filters.filter import UniqueFilter

_THRESHOLD = 4
_KNOWN_IMAGE_HASHES = [imagehash.hex_to_hash(s) for s in ["c0d08f2f2f60f0cf", "817c7e9391e46c1b", "973c4178e79492cd"]]


def _image_is_match(image: Image.Image) -> bool:
"""Return whether the one image matches any of those known to be posted by compromised accounts."""
incoming_image_hash = imagehash.phash(image)
has_match = any(
incoming_image_hash - known_image_hash < _THRESHOLD
for known_image_hash in _KNOWN_IMAGE_HASHES
)
return has_match


class ImageFilter(UniqueFilter):
"""Filter messages that contain an image attachment whose perceptual hash matches images associated with scams."""

name = "image"
events = (Event.MESSAGE, )

async def triggered_on(self, ctx: FilterContext) -> bool:
"""Return whether the message has an attached image that is known to be posted by compromised accounts."""
for attachment in ctx.attachments:
if not attachment.content_type.startswith("image"):
continue
image = Image.open(io.BytesIO(await attachment.read()))
if _image_is_match(image):
return True

return False
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ dependencies = [
"tenacity==9.1.2",
"tldextract==5.3.0",
"yarl==1.22.0",
"imagehash>=4.3.2",
"pillow>=12.2.0",
]
name = "bot"
version = "1.0.1"
Expand Down
Loading