-
-
Notifications
You must be signed in to change notification settings - Fork 750
New UniqueFilter for images associated with compromised accounts. #3519
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
swfarnsworth
wants to merge
12
commits into
main
Choose a base branch
from
swfarnsworth/image-filter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+84
−0
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
539ab1c
New UniqueFilter for images associated with compromised accounts.
swfarnsworth c146b3a
Use `asyncio.to_thread` to make expensive actions awaitable.
swfarnsworth 0354e66
Handle case that `attachment.content_type` is None
swfarnsworth b8e3015
Handle (and ignore) exceptions from reading file attachments.
swfarnsworth 9fb7f38
Only consider attachments less than 30mb
swfarnsworth 3b9b3d6
Add comments describing the image associated with each perceptual hash.
swfarnsworth a29f99c
Use Rhodium API instead of PIL, imagehash to load and hash images, re…
swfarnsworth 4df265b
Change attachment limit to 5mb
swfarnsworth 9d3d20b
Store Rhodium API URL in constants.py; use http session from the bot …
swfarnsworth 97d9eb2
refactoring hash matching logic
swfarnsworth c401377
Add logging for exceptions
swfarnsworth f4154cd
Add two new perceptual hashes
swfarnsworth File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import os | ||
|
|
||
| import aiohttp | ||
|
|
||
| import bot | ||
| from bot import constants | ||
| from bot.exts.filtering._filter_context import Event, FilterContext | ||
| from bot.exts.filtering._filters.filter import UniqueFilter | ||
| from bot.log import get_logger | ||
|
|
||
| log = get_logger(__name__) | ||
|
|
||
| # Maximum perceptual hash difference for positive predictions | ||
| _THRESHOLD = 4 | ||
| # Maximum number of seconds to wait for Rhodium API | ||
| _TIMEOUT = 0.5 | ||
| _KNOWN_IMAGE_HASHES = [ | ||
| # A camera-taken image of a tweet attributed to @MrBeast about the purported launch of a crypto casino; | ||
| # there is a URL in the image that varies by instance | ||
| 219481626328303491, | ||
| # An image saying "Activate Code for Bonus!" | ||
| 6997610946676476306, | ||
| # An image saying "Withdrawal Success!" | ||
| -9135984495352994088, | ||
| # A collage of four images, the first being a purported tweet from Elon Musk about the opening a crypto casino, | ||
| # and the rest of similar character to the previous two | ||
| 231962884035511073, | ||
| # Text centered on a background of a field and sky, the text saying "I've helped 15+ people earn ... | ||
| # in stock market and crypto trading" | ||
| 360569449461317633, | ||
| ] | ||
|
|
||
|
|
||
| def _is_match(image_hash: int) -> bool: | ||
| return any( | ||
| int.bit_count(image_hash ^ candidate_hash) <= _THRESHOLD | ||
| for candidate_hash in _KNOWN_IMAGE_HASHES | ||
| ) | ||
|
|
||
|
|
||
| async def _get_hash(image_url: str) -> int: | ||
| async with bot.instance.http_session.post( | ||
| url=constants.URLs.rhodium_api, | ||
| headers={"Authorization": f"Bearer {os.getenv('RHODIUM_AUTH_TOKEN')}"}, | ||
| data=image_url, | ||
| timeout=_TIMEOUT, | ||
| ) as response: | ||
| response.raise_for_status() | ||
| response_data = await response.json() | ||
| return response_data["i64"] | ||
|
|
||
|
|
||
| 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.""" | ||
| log.trace("Entering image filter") | ||
| for attachment in ctx.attachments: | ||
| if ( | ||
| attachment.content_type is None | ||
| or not attachment.content_type.startswith("image") | ||
| or attachment.size > 5e6 # 5mb | ||
| ): | ||
| continue | ||
|
|
||
| try: | ||
| image_hash = await _get_hash(attachment.url) | ||
| except aiohttp.ClientError: | ||
| log.exception("Error getting image hash") | ||
| return False | ||
| except aiohttp.TimeoutError: | ||
| log.error("Timed out getting image hash") | ||
| return False | ||
|
|
||
| if _is_match(image_hash): | ||
| return True | ||
|
|
||
| return False | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.