gluco-api / core /telegram.py
JulianTekles's picture
Create telegram.py
29fd408 verified
# core/telegram.py
from __future__ import annotations
from typing import Any, Dict, Optional
def extract_message(update: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Zieht Text + Chat-IDs aus Telegram Update (Message oder EditedMessage).
Gibt None zurück, wenn kein Text.
"""
if not isinstance(update, dict):
return None
msg = update.get("message") or update.get("edited_message")
if not isinstance(msg, dict):
return None
chat = msg.get("chat") or {}
text = (msg.get("text") or "").strip()
if not text:
return None
chat_id = chat.get("id")
user = msg.get("from") or {}
return {
"chat_id": str(chat_id) if chat_id is not None else None,
"text": text,
"user_id": str(user.get("id")) if user.get("id") is not None else None,
"username": user.get("username") or "",
"is_group": (chat.get("type") in ("group", "supergroup")),
}
def cleanup_text_for_group(text: str, bot_username: Optional[str]) -> str:
"""
In Gruppen wird der Bot oft mit @BotName angesprochen.
Entfernt @<username> am Anfang, damit die Intent-Erkennung sauber greift.
"""
t = (text or "").strip()
if bot_username:
tag = f"@{bot_username.lower()}"
if t.lower().startswith(tag):
t = t[len(tag):].strip()
return t