Webseite überarbeitet und Telegram Bot funktion hinzugefügt #1
36
main.py
36
main.py
@@ -172,20 +172,33 @@ async def get_ai_response(user_input, system_prompt):
|
|||||||
return ai_msg
|
return ai_msg
|
||||||
|
|
||||||
async def handle_telegram_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def handle_telegram_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
# Sicherheits-Check: Nur deine Chat-ID wird akzeptiert
|
# Den eigenen @Benutzernamen des Bots dynamisch abfragen
|
||||||
if str(update.effective_chat.id) != ALLOWED_ID:
|
bot_username = f"@{context.bot.username}"
|
||||||
await update.message.reply_text("Zugriff verweigert. 🔒")
|
|
||||||
return
|
|
||||||
|
|
||||||
|
chat_type = update.effective_chat.type
|
||||||
user_msg = update.message.text
|
user_msg = update.message.text
|
||||||
|
user_id = str(update.message.from_user.id)
|
||||||
|
|
||||||
# "Tippt..." Status in Telegram anzeigen (schöne UX)
|
# 1. Gruppen-Logik: Nur reagieren, wenn der Bot @erwähnt wird
|
||||||
|
if chat_type in ['group', 'supergroup']:
|
||||||
|
if bot_username not in user_msg:
|
||||||
|
return # Bot wurde nicht erwähnt, Nachricht ignorieren
|
||||||
|
|
||||||
|
# Den @Namen aus dem Text entfernen, damit die KI nicht verwirrt wird
|
||||||
|
user_msg = user_msg.replace(bot_username, "").strip()
|
||||||
|
else:
|
||||||
|
# Im Einzelchat kann optional weiterhin nur der Admin zugelassen werden.
|
||||||
|
# Wenn du willst, dass auch andere den Bot privat nutzen können, entferne diesen Block:
|
||||||
|
if user_id != ALLOWED_ID:
|
||||||
|
await update.message.reply_text("Zugriff auf den privaten Chat verweigert. 🔒")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Tipp-Status anzeigen
|
||||||
await update.message.reply_chat_action(action="typing")
|
await update.message.reply_chat_action(action="typing")
|
||||||
|
|
||||||
# 1. KI Antwort holen
|
# 2. KI fragen
|
||||||
ai_response = await get_ai_response(user_msg, get_system_prompt())
|
ai_response = await get_ai_response(user_msg, get_system_prompt())
|
||||||
|
|
||||||
# 2. Befehle extrahieren
|
|
||||||
commands = re.findall(r'<EXECUTE target="(.*?)">(.*?)</EXECUTE>', ai_response, re.I | re.S)
|
commands = re.findall(r'<EXECUTE target="(.*?)">(.*?)</EXECUTE>', ai_response, re.I | re.S)
|
||||||
clean_msg = re.sub(r'<EXECUTE.*?>.*?</EXECUTE>', '', ai_response, flags=re.I | re.S).strip()
|
clean_msg = re.sub(r'<EXECUTE.*?>.*?</EXECUTE>', '', ai_response, flags=re.I | re.S).strip()
|
||||||
|
|
||||||
@@ -193,8 +206,12 @@ async def handle_telegram_message(update: Update, context: ContextTypes.DEFAULT_
|
|||||||
if clean_msg:
|
if clean_msg:
|
||||||
await update.message.reply_text(clean_msg)
|
await update.message.reply_text(clean_msg)
|
||||||
|
|
||||||
# 3. Befehle ausführen und Ergebnisse als Telegram-Nachricht senden
|
# 3. Befehle ausführen (mit strengem Sicherheits-Check!)
|
||||||
if commands:
|
if commands:
|
||||||
|
if user_id != ALLOWED_ID:
|
||||||
|
await update.message.reply_text("⚠️ **Sicherheits-Sperre:** Die KI wollte einen Server-Befehl ausführen, aber du hast keine Administrator-Rechte dafür.")
|
||||||
|
return
|
||||||
|
|
||||||
for target, cmd in commands:
|
for target, cmd in commands:
|
||||||
await update.message.reply_text(f"⏳ Führe aus auf *{target}*:\n`{cmd}`", parse_mode='Markdown')
|
await update.message.reply_text(f"⏳ Führe aus auf *{target}*:\n`{cmd}`", parse_mode='Markdown')
|
||||||
|
|
||||||
@@ -204,7 +221,6 @@ async def handle_telegram_message(update: Update, context: ContextTypes.DEFAULT_
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
if n:
|
if n:
|
||||||
# Befehl ausführen und Output abfangen
|
|
||||||
try:
|
try:
|
||||||
proc = await asyncio.create_subprocess_shell(
|
proc = await asyncio.create_subprocess_shell(
|
||||||
f"ssh -o StrictHostKeyChecking=no {n['user']}@{n['ip']} '{cmd}'",
|
f"ssh -o StrictHostKeyChecking=no {n['user']}@{n['ip']} '{cmd}'",
|
||||||
@@ -214,11 +230,9 @@ async def handle_telegram_message(update: Update, context: ContextTypes.DEFAULT_
|
|||||||
stdout, _ = await proc.communicate()
|
stdout, _ = await proc.communicate()
|
||||||
output = stdout.decode('utf-8', errors='ignore').strip()
|
output = stdout.decode('utf-8', errors='ignore').strip()
|
||||||
|
|
||||||
# Ergebnis an Telegram senden (abgeschnitten auf 4000 Zeichen, da Telegram Limits hat)
|
|
||||||
result_text = output[:4000] if output else "✅ Befehl ohne Output ausgeführt."
|
result_text = output[:4000] if output else "✅ Befehl ohne Output ausgeführt."
|
||||||
await update.message.reply_text(f"💻 **Output von {n['name']}:**\n```\n{result_text}\n```", parse_mode='Markdown')
|
await update.message.reply_text(f"💻 **Output von {n['name']}:**\n```\n{result_text}\n```", parse_mode='Markdown')
|
||||||
|
|
||||||
# Auch ins KI-Gedächtnis schreiben
|
|
||||||
chat_history.append({"role": "user", "content": f"[SYSTEM] Befehl '{cmd}' auf {target} fertig:\n{result_text}"})
|
chat_history.append({"role": "user", "content": f"[SYSTEM] Befehl '{cmd}' auf {target} fertig:\n{result_text}"})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await update.message.reply_text(f"❌ Fehler bei der Ausführung: {e}")
|
await update.message.reply_text(f"❌ Fehler bei der Ausführung: {e}")
|
||||||
|
|||||||
Reference in New Issue
Block a user