| import os |
| import requests |
| import json |
| import asyncio |
| from telegram import Update |
| from telegram.ext import Application, MessageHandler, filters, ContextTypes |
| from telegram.request import HTTPXRequest |
|
|
| |
| BOT_TOKEN = os.getenv("BOT_TOKEN") |
| API_URL = "http://31.57.118.152:8082/v1/messages" |
| API_KEY = os.getenv("API_KEY") |
|
|
| MAX_LEN = 3500 |
|
|
| def extract_text(raw: str): |
| text = "" |
| for line in raw.split("\n"): |
| if '"text_delta"' in line: |
| try: |
| json_part = line.split("data:")[-1].strip() |
| data = json.loads(json_part) |
| if data and "delta" in data and "text" in data["delta"]: |
| text += data["delta"]["text"] |
| except: pass |
| elif '"text":"' in line: |
| try: |
| text += line.split('"text":"')[1].split('"')[0] |
| except: pass |
| return text.strip() if text else "No response text found." |
|
|
| def split_text(text, size=MAX_LEN): |
| return [text[i:i+size] for i in range(0, len(text), size)] |
|
|
| async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): |
| if not update.message or not update.message.text: |
| return |
| |
| payload = { |
| "model": "claude-sonnet-4-20250514", |
| "messages": [{"role": "user", "content": update.message.text}], |
| "max_tokens": 500 |
| } |
| headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} |
|
|
| try: |
| r = requests.post(API_URL, json=payload, headers=headers, timeout=120) |
| text = extract_text(r.text) |
| for part in split_text(text): |
| await update.message.reply_text(part) |
| except Exception as e: |
| print(f"Post Error: {e}") |
|
|
| async def run_bot(): |
| if not BOT_TOKEN: |
| print("❌ BOT_TOKEN is missing!") |
| return |
|
|
| |
| |
| t_request = HTTPXRequest( |
| connect_timeout=60, |
| read_timeout=60, |
| write_timeout=60, |
| pool_timeout=60 |
| ) |
| |
| app = Application.builder().token(BOT_TOKEN).request(t_request).build() |
| app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) |
|
|
| print("🤖 Bot is starting and trying to connect to Telegram...") |
| |
| try: |
| await app.initialize() |
| await app.start() |
| print("✅ Connection Successful! Bot is polling...") |
| await app.updater.start_polling(drop_pending_updates=True) |
| while True: |
| await asyncio.sleep(1) |
| except Exception as e: |
| print(f"💥 Failed to start bot: {e}") |
|
|
| if __name__ == "__main__": |
| try: |
| asyncio.run(run_bot()) |
| except (KeyboardInterrupt, SystemExit): |
| pass |
|
|