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ler
|
| 3 |
+
Receives webhook updates from Telegram, routes them to the STEW agent,
|
| 4 |
+
and replies in the same chat. Uses python-telegram-bot v20+ (async).
|
| 5 |
+
"""
|
| 6 |
+
import asyncio
|
| 7 |
+
import logging
|
| 8 |
+
from telegram import Update, Bot
|
| 9 |
+
from telegram.constants import ChatAction, ParseMode
|
| 10 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters
|
| 11 |
+
from config import Config
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("stew.telegram")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ββ Command handlers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 17 |
+
|
| 18 |
+
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 19 |
+
await update.message.reply_text(
|
| 20 |
+
"π Hello! I'm *STEW* β your Autonomous Intelligence System.\n\n"
|
| 21 |
+
"I can help you:\n"
|
| 22 |
+
"β’ π» Build software & automate workflows\n"
|
| 23 |
+
"β’ π Research and analyse information\n"
|
| 24 |
+
"β’ π Manage Notion, Slack, Gmail, Google Drive\n"
|
| 25 |
+
"β’ π€ Coordinate multi-step tasks\n\n"
|
| 26 |
+
"Just send me a message to get started!\n\n"
|
| 27 |
+
"Commands:\n"
|
| 28 |
+
"/start β This message\n"
|
| 29 |
+
"/clear β Clear your conversation memory\n"
|
| 30 |
+
"/memory β Show memory stats\n"
|
| 31 |
+
"/model [name] β Switch model (owl-alpha | gpt-oss-120b | nemotron-nano)",
|
| 32 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
async def cmd_clear(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 37 |
+
from agent import STEWAgent
|
| 38 |
+
agent: STEWAgent = context.bot_data["agent"]
|
| 39 |
+
user_id = str(update.effective_user.id)
|
| 40 |
+
msg = agent.clear_memory(user_id)
|
| 41 |
+
await update.message.reply_text(msg)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
async def cmd_memory(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 45 |
+
from agent import STEWAgent
|
| 46 |
+
agent: STEWAgent = context.bot_data["agent"]
|
| 47 |
+
user_id = str(update.effective_user.id)
|
| 48 |
+
msg = agent.memory_summary(user_id)
|
| 49 |
+
await update.message.reply_text(msg)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
async def cmd_model(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 53 |
+
from config import Config
|
| 54 |
+
valid = list(Config.MODELS.keys())
|
| 55 |
+
if context.args and context.args[0] in valid:
|
| 56 |
+
context.user_data["model"] = context.args[0]
|
| 57 |
+
await update.message.reply_text(f"β
Model switched to `{context.args[0]}`", parse_mode=ParseMode.MARKDOWN)
|
| 58 |
+
else:
|
| 59 |
+
current = context.user_data.get("model", Config.DEFAULT_MODEL)
|
| 60 |
+
opts = " | ".join(valid)
|
| 61 |
+
await update.message.reply_text(
|
| 62 |
+
f"Current model: `{current}`\nAvailable: `{opts}`\nUsage: /model <name>",
|
| 63 |
+
parse_mode=ParseMode.MARKDOWN,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ββ Message handler βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 68 |
+
|
| 69 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 70 |
+
from agent import STEWAgent
|
| 71 |
+
agent: STEWAgent = context.bot_data["agent"]
|
| 72 |
+
|
| 73 |
+
user_id = str(update.effective_user.id)
|
| 74 |
+
text = update.message.text or ""
|
| 75 |
+
model = context.user_data.get("model", Config.DEFAULT_MODEL)
|
| 76 |
+
|
| 77 |
+
if not text.strip():
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
# Show typing indicator
|
| 81 |
+
await context.bot.send_chat_action(
|
| 82 |
+
chat_id=update.effective_chat.id,
|
| 83 |
+
action=ChatAction.TYPING,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
reply = agent.chat(message=text, model_key=model, user_id=user_id)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error(f"Agent error for user {user_id}: {e}")
|
| 90 |
+
reply = f"β οΈ STEW encountered an error: {e}"
|
| 91 |
+
|
| 92 |
+
# Telegram messages are limited to 4096 chars; split if needed
|
| 93 |
+
if len(reply) <= 4096:
|
| 94 |
+
await update.message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)
|
| 95 |
+
else:
|
| 96 |
+
for i in range(0, len(reply), 4096):
|
| 97 |
+
await update.message.reply_text(reply[i:i+4096], parse_mode=ParseMode.MARKDOWN)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ββ Build the Application βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 101 |
+
|
| 102 |
+
def build_application(agent) -> Application:
|
| 103 |
+
"""Build and configure the Telegram Application object."""
|
| 104 |
+
app = (
|
| 105 |
+
Application.builder()
|
| 106 |
+
.token(Config.TELEGRAM_BOT_TOKEN)
|
| 107 |
+
.build()
|
| 108 |
+
)
|
| 109 |
+
app.bot_data["agent"] = agent
|
| 110 |
+
|
| 111 |
+
app.add_handler(CommandHandler("start", cmd_start))
|
| 112 |
+
app.add_handler(CommandHandler("clear", cmd_clear))
|
| 113 |
+
app.add_handler(CommandHandler("memory", cmd_memory))
|
| 114 |
+
app.add_handler(CommandHandler("model", cmd_model))
|
| 115 |
+
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 116 |
+
|
| 117 |
+
return app
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ββ Webhook entry point called by FastAPI βββββββββββββββββββββββββββββββββββββ
|
| 121 |
+
|
| 122 |
+
_app_instance: Application | None = None
|
| 123 |
+
|
| 124 |
+
def get_application(agent) -> Application:
|
| 125 |
+
global _app_instance
|
| 126 |
+
if _app_instance is None:
|
| 127 |
+
_app_instance = build_application(agent)
|
| 128 |
+
return _app_instance
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
async def handle_telegram_update(update_data: dict, agent) -> None:
|
| 132 |
+
"""Process a single Telegram update received via webhook."""
|
| 133 |
+
tg_app = get_application(agent)
|
| 134 |
+
async with tg_app:
|
| 135 |
+
update = Update.de_json(update_data, tg_app.bot)
|
| 136 |
+
await tg_app.process_update(update)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
async def register_webhook() -> bool:
|
| 140 |
+
"""Register the Telegram webhook with Hugging Face Space URL."""
|
| 141 |
+
if not Config.TELEGRAM_BOT_TOKEN or not Config.SPACE_URL:
|
| 142 |
+
logger.warning("Cannot register webhook: missing TELEGRAM_BOT_TOKEN or SPACE_URL")
|
| 143 |
+
return False
|
| 144 |
+
webhook_url = Config.SPACE_URL.rstrip("/") + Config.TELEGRAM_WEBHOOK_PATH
|
| 145 |
+
bot = Bot(token=Config.TELEGRAM_BOT_TOKEN)
|
| 146 |
+
async with bot:
|
| 147 |
+
result = await bot.set_webhook(url=webhook_url)
|
| 148 |
+
if result:
|
| 149 |
+
logger.info(f"β
Telegram webhook registered: {webhook_url}")
|
| 150 |
+
else:
|
| 151 |
+
logger.error("β Failed to register Telegram webhook")
|
| 152 |
+
return result
|
| 153 |
+
|