toot_screenshot_detector/bot_mastodon.py

46 lines
1.9 KiB
Python

from mastodon import Mastodon, StreamListener
from PIL import Image
import pytesseract
import requests
import io
# Configuration of the Mastodon client
mastodon = Mastodon(
access_token='YOUR_API_TOKEN',
api_base_url='https://YOUR_MASTODON_INSTANCE'
)
class ImageCheckListener(StreamListener):
def on_update(self, status):
# If the toot contains an image
if status['media_attachments']:
for media in status['media_attachments']:
if media['type'] == 'image':
image_url = media['url']
response = requests.get(image_url)
# Process the image in memory
with io.BytesIO(response.content) as image_binary:
img = Image.open(image_binary)
# Extract text using OCR
text_in_image = pytesseract.image_to_string(img)
print(f"Detected text: {text_in_image}") # Print detected text for debugging
# Check if it contains fragments of your posts
if 'nickname' in text_in_image or 'Name' in text_in_image:
print(f"📸 Potential screenshot detected at: {status['url']}")
# Send a notification on Mastodon
notification_message = (
f"📸 Detected potential screenshot in a toot: {status['url']}\n\n"
"Check if it is a screenshot of one of your posts."
)
mastodon.status_post(notification_message, visibility='direct')
# The image is automatically removed from memory when the with block ends
# Start the listener
listener = ImageCheckListener()
mastodon.stream_public(listener)