Files

86 lines
2.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Flask-App: Impressum-Kontaktformular + Honeypot-Spamschutz
Nachricht wird als JSON-Datei gespeichert + Telegram-Benachrichtigung via API.
"""
import os, json, time, re
from pathlib import Path
from flask import Flask, request
import requests
import collections
_RATE = collections.defaultdict(list) # ip -> [timestamps]
MAX_PER_HOUR = 5
def _rate_limited(ip):
now = time.time()
_RATE[ip] = [t for t in _RATE[ip] if now - t < 3600]
if len(_RATE[ip]) >= MAX_PER_HOUR:
return True
_RATE[ip].append(now)
return False
app = Flask(__name__)
MSG_DIR = Path("/tmp/impressum-kontakt")
ENV_FILE = "/root/.hermes/.env"
def _env(key):
try:
txt = Path(ENV_FILE).read_text()
m = re.search(key + r"\s*=\s*(\S+)", txt)
return m.group(1) if m else ""
except Exception:
return ""
@app.route("/senden", methods=["POST"])
def senden():
name = request.form.get("name", "").strip()
email = request.form.get("email", "").strip()
msg = request.form.get("nachricht", "").strip()
honeypot = request.form.get("website", "").strip() # unsichtbar, Bots füllen es
# Honeypot: wenn gefüllt → Bot, ignorieren
if honeypot:
return "Danke für Ihre Nachricht. (Bot erkannt – ignoriert)"
# Rate-Limit: max 5/Stunde/IP
if _rate_limited(request.remote_addr):
return "Zu viele Anfragen. Bitte später erneut versuchen.", 429
if not name or not email or not msg:
return "Bitte alle Pflichtfelder ausfüllen.", 400
# Speichern
os.makedirs(MSG_DIR, exist_ok=True)
ts = int(time.time())
entry = {
"ts": ts, "name": name, "email": email, "msg": msg,
"ip": request.remote_addr,
"user_agent": request.headers.get("User-Agent", "")
}
safe_name = re.sub(r"[^A-Za-z0-9_-]", "_", name)[:20]
path = MSG_DIR / f"{ts}_{safe_name}.json"
with open(path, "w") as f:
json.dump(entry, f, indent=2, ensure_ascii=False)
# Telegram-Benachrichtigung
t = _env("TELEGRAM_BOT_TOKEN")
c = _env("TELEGRAM_HOME_CHANNEL") or "6417835766"
if t:
text = "📩 *Neue Kontaktanfrage*\nVon: {} ({})\n\n{}".format(name, email, msg[:500])
try:
requests.post(
f"https://api.telegram.org/bot{t}/sendMessage",
json={"chat_id": c, "text": text, "parse_mode": "Markdown"},
timeout=8,
)
except Exception:
pass
return "✅ Nachricht gesendet. Ich melde mich bei Ihnen.", 200
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8096, debug=False)