elahe-dashboards/dashboards/ops/cockpit/telegram_poller.py

124 lines
5.3 KiB
Python
Executable file

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Telegram Real-time Poller Daemon for @assistant_hf_bot
Token: 8808629942:AAE2enGoLit6DX4jJs4SWQzTrgGs1lt_pa4
Polls Telegram getUpdates every 2 seconds, writes incoming messages
directly to data_store.json in Telegram Triage, and logs to audit trail.
"""
import json
import time
import urllib.request
import urllib.parse
import os
import sys
BASE_DIR = "/workspace/hameds_executive_cockpit"
DATA_FILE = os.path.join(BASE_DIR, "data_store.json")
BOT_TOKEN = "8808629942:AAE2enGoLit6DX4jJs4SWQzTrgGs1lt_pa4"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
def load_data():
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print(f"[Poller] Error reading data: {e}", file=sys.stderr)
return {}
def save_data(data):
try:
tmp_path = DATA_FILE + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp_path, DATA_FILE)
except Exception as e:
print(f"[Poller] Error saving data: {e}", file=sys.stderr)
def get_updates(offset=None, timeout=10):
url = f"{API_URL}/getUpdates?timeout={timeout}"
if offset:
url += f"&offset={offset}"
req = urllib.request.Request(url, headers={"User-Agent": "ExecutivePoller/1.0"})
try:
with urllib.request.urlopen(req, timeout=timeout+5) as resp:
return json.loads(resp.read().decode("utf-8"))
except Exception as e:
return {"ok": False, "error": str(e)}
def poll_loop():
print(f"[Poller] Starting Telegram listener for @assistant_hf_bot...")
offset = None
# Load last offset if stored
data = load_data()
offset = data.get("system_meta", {}).get("last_telegram_update_id")
while True:
try:
res = get_updates(offset=offset, timeout=5)
if res.get("ok") and res.get("result"):
data = load_data()
triage = data.setdefault("telegram_triage", {"quick_ack": [], "holding_queue": [], "escalate_to_ceo": []})
audit = data.setdefault("audit_trail", [])
for update in res["result"]:
update_id = update["update_id"]
offset = update_id + 1
data.setdefault("system_meta", {})["last_telegram_update_id"] = offset
msg = update.get("message") or update.get("edited_message")
if not msg:
continue
sender_obj = msg.get("from", {})
first_name = sender_obj.get("first_name", "")
last_name = sender_obj.get("last_name", "")
username = sender_obj.get("username", "")
sender = f"{first_name} {last_name}".strip() or (f"@{username}" if username else f"User {sender_obj.get('id')}")
text = msg.get("text", "")
caption = msg.get("caption", "")
content = text or caption or "[فایل یا مدیا ارسال شد]"
# Heuristic triage categorization
lower = content.lower()
queue = "holding_queue"
if any(k in content for k in ["فوری", "اضطراری", "قرارداد", "حامد", "مهم", "پول", "واریز", "چک"]):
queue = "escalate_to_ceo"
elif len(content) < 30 or any(k in content for k in ["سلام", "ممنون", "تشکر", "درود"]):
queue = "quick_ack"
t_item = {
"id": f"tg-{update_id}",
"sender": sender,
"message": content,
"chat_id": msg.get("chat", {}).get("id"),
"timestamp": time.strftime("%Y/%m/%d %H:%M"),
"draft_reply": f"سلام {first_name} عزیز، پیامت دریافت شد و در دست بررسی است." if queue != "escalate_to_ceo" else "در اسرع وقت با حامد فلاحی هماهنگ می‌شود.",
"source": "telegram_bot"
}
triage.setdefault(queue, []).unshift if hasattr(list, 'unshift') else triage.setdefault(queue, []).insert(0, t_item)
# Add to audit trail
audit.insert(0, {
"id": f"aud-tg-{update_id}",
"timestamp": time.strftime("%Y/%m/%d %H:%M:%S"),
"actor": f"تلگرام: {sender}",
"action": "دریافت پیام زنده در تریاژ",
"details": f"پیام '{content[:40]}...' به صف {queue} منتقل شد.",
"changed_by_hamed": False
})
print(f"[Poller] Ingested message from {sender} into {queue}")
save_data(data)
time.sleep(1.5)
except Exception as ex:
print(f"[Poller] Loop error: {ex}", file=sys.stderr)
time.sleep(3)
if __name__ == "__main__":
poll_loop()