MCPcopy Create free account
hub / github.com/Roy3838/Observer / telegram_webhook

Function telegram_webhook

api/tools_router.py:424–477  ·  view source on GitHub ↗

Webhook endpoint for the Telegram bot. `/start ` (the deep link in the app's QR) links a private chat to a whitelist code for remote control; after that, the chat's messages go to the user's Observer session (remote.route_inbound). Anything else gets the chat ID reply, for the

(request: Request, update: dict)

Source from the content-addressed store, hash-verified

422
423@tools_router.post("/tools/telegram-webhook", tags=["Tools"])
424async def telegram_webhook(request: Request, update: dict):
425 """
426 Webhook endpoint for the Telegram bot. `/start <code>` (the deep link in the
427 app&#x27;s QR) links a private chat to a whitelist code for remote control; after
428 that, the chat's messages go to the user's Observer session (remote.route_inbound).
429 Anything else gets the chat ID reply, for the paste-a-chat-ID flow.
430
431 Must be registered via setWebhook with a secret_token. The secret is required:
432 this bot can drive a user&#x27;s desktop session, so an unauthenticated webhook
433 would let anyone inject messages as any chat.
434 """
435 webhook_secret = os.getenv("TELEGRAM_WEBHOOK_SECRET")
436 if not webhook_secret:
437 logger.error("TELEGRAM_WEBHOOK_SECRET not configured - rejecting Telegram webhook")
438 raise HTTPException(status_code=403, detail="Forbidden")
439 incoming = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
440 if not hmac.compare_digest(incoming, webhook_secret):
441 raise HTTPException(status_code=403, detail="Forbidden")
442
443 try:
444 message = update.get("message")
445 if not message:
446 return {"ok": True}
447 chat_id = str(message["chat"]["id"])
448 chat_type = message["chat"]["type"]
449 text = message.get("text") or ""
450
451 update_id = update.get("update_id")
452 if not await remote.first_delivery(f"tg:{update_id}" if update_id is not None else None):
453 return {"ok": True}
454
455 async def reply(body: str) -> None:
456 try:
457 await send_telegram_text(chat_id, body)
458 except Exception as e:
459 logger.error(f"Failed to reply to chat_id {chat_id}: {str(e)}")
460
461 # Remote control is for private chats only; a bare /start is a chat ID request.
462 if chat_type == "private" and text.strip() != "/start":
463 body = text[len("/start"):].strip() if text.startswith("/start") else text
464 if await remote.route_inbound("telegram", chat_id, body, reply):
465 return {"ok": True}
466
467 response_text = (
468 f"Your chat ID is: <code>{chat_id}</code>\n\nChat type: {chat_type}\n\n"
469 "Use this ID in your Observer AI agents, or connect with the QR code in Observer "
470 "to chat with it from here!"
471 )
472 await send_telegram_text(chat_id, response_text, parse_mode="HTML")
473 logger.info(f"Auto-responded to chat_id {chat_id} with their chat ID")
474 return {"ok": True}
475 except Exception as e:
476 logger.exception("Error processing Telegram webhook")
477 return {"ok": True} # Always return OK to Telegram to avoid retries
478
479

Callers

nothing calls this directly

Calls 3

send_telegram_textFunction · 0.85
errorMethod · 0.80
infoMethod · 0.80

Tested by

no test coverage detected