import json import requests from dotenv import load_dotenv import os import src.lwb.scrape_image as scrape_image load_dotenv() # Webhook URL from Discord WEBHOOK_URL = os.getenv("WEBHOOK_URL") # Funktion: Nachricht an Discord senden def send_to_discord(property_data): message = ( f"**{property_data['title']}**\n" f"{property_data['subtitle']}\n" f"**Zimmer:** {property_data['rooms']}\n" f"**Wohnfläche:** {property_data['size']}\n" f"**Miete:** {property_data['rent']}\n" f"**Warmmiete:** {property_data['warm_rent']}\n" f"**Verfügbar ab:** {property_data['availability']}\n" f"**Link:** {property_data['link']}\n" f"**Beschreibung:** {property_data['abstract']}" ) # Set headers headers = {"Content-Type": "application/json"} # Check for optional image URL if "image_url" in property_data and property_data["image_url"]: try: # Download the image image_response = scrape_image.scrape_image(property_data["image_url"], property_data["owner"]) # Check if the image was downloaded successfully if image_response == b"": print("Fehler beim Herunterladen des Bildes: Leere Antwort") payload = {"content": message} response = requests.post(WEBHOOK_URL, data=json.dumps(payload), headers=headers) return # Send the message with an image attachment files = {"file": ("image.jpg", image_response)} payload = {"content": message} response = requests.post(WEBHOOK_URL, data=payload, files=files) except requests.exceptions.RequestException as e: print(f"Fehler beim Herunterladen des Bildes: {e}") payload = {"content": message} response = requests.post(WEBHOOK_URL, data=json.dumps(payload), headers=headers) else: # Send the message without an image payload = {"content": message} response = requests.post(WEBHOOK_URL, data=json.dumps(payload), headers=headers) # Check if the message was sent successfully when the status code is >= 200 and < 300 if response.status_code >= 200 and response.status_code < 300: print(f"Benachrichtigung gesendet: {property_data['title']} - response: {response.status_code}") else: print(f"Fehler beim Senden der Benachrichtigung: {response.status_code}")