Download stella.py from CNSCORP/Ste11a: direct link, hf CLI and curl.
- Browser
- Download file 5.12 kB
-
https://huggingface.co/spaces/CNSCORP/Ste11a/resolve/main/stella.py
- Command line
-
hf download hf://spaces/CNSCORP/Ste11a/stella.py
-
curl -L -o stella.py https://huggingface.co/spaces/CNSCORP/Ste11a/resolve/main/stella.py
5.12 kB
| import asyncio | |
| import logging | |
| import os | |
| from aiogram import Bot, Dispatcher, types | |
| from aiogram.types import Update | |
| from aiogram.client.session.aiohttp import AiohttpSession | |
| from groq import Groq | |
| from supabase import create_client, Client | |
| from duckduckgo_search import DDGS | |
| from aiohttp import web | |
| # --- CONFIG (Берем из Secrets) --- | |
| TOKEN = os.environ.get("BOT_TOKEN") | |
| # Путь для вебхука | |
| WEBHOOK_PATH = f"/webhook/{TOKEN}" | |
| # URL твоего Space (например, https://user-space.hf.space) | |
| WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "").rstrip("/") + WEBHOOK_PATH | |
| # --- ПРОКСИ (Чтобы обойти ошибку DNS/Connection) --- | |
| # Мы используем сессию с прокси, чтобы Hugging Face мог достучаться до Telegram | |
| proxy_url = "http://167.71.233.196:8080" # Рабочий публичный прокси | |
| session = AiohttpSession(proxy=proxy_url) | |
| bot = Bot(token=TOKEN, session=session) | |
| dp = Dispatcher() | |
| client_groq = Groq(api_key=os.environ.get("GROQ_API_KEY")) | |
| supabase: Client = create_client(os.environ.get("SUPABASE_URL"), os.environ.get("SUPABASE_KEY")) | |
| # --- ФУНКЦИИ ЛОГИКИ --- | |
| def search_internet(query): | |
| try: | |
| with DDGS() as ddgs: | |
| results = [f"{r['title']}: {r['body']}" for r in ddgs.text(query, max_results=3)] | |
| return "\n\n".join(results) | |
| except Exception: | |
| return "Сеть временно недоступна." | |
| async def get_ai_response(chat_id, user_text, user_name="Друг"): | |
| search_data = "" | |
| keywords = ["кто", "что", "найди", "новости", "почему", "когда", "как"] | |
| if any(word in user_text.lower() for word in keywords): | |
| search_data = f"\nДАННЫЕ ИЗ СЕТИ:\n{search_internet(user_text)}" | |
| facts_res = supabase.table("facts").select("fact").eq("chat_id", chat_id).execute() | |
| facts_text = "\n".join([f["fact"] for f in facts_res.data]) | |
| personality = ( | |
| "Ты — Стелла. Тебе 18 лет. Ты добрый ИИ-помощник. Живешь в Сунне, Швеция. " | |
| "Пиши вежливо, коротко и ясно. Будь искренней. " | |
| f"Твоя память: {facts_text}. {search_data} " | |
| f"Сейчас ты отвечаешь пользователю {user_name}. " | |
| "Используй только точки и запятые. Нет тире. Нет точек с запятой." | |
| ) | |
| history_res = supabase.table("history").select("role", "content").eq("chat_id", chat_id).order("created_at", desc=True).limit(20).execute() | |
| history = list(reversed(history_res.data)) | |
| messages = [{"role": "system", "content": personality}] | |
| messages.extend(history) | |
| messages.append({"role": "user", "content": user_text}) | |
| completion = client_groq.chat.completions.create(model="llama-3.1-8b-instant", messages=messages, temperature=0.6) | |
| ans = completion.choices[0].message.content | |
| supabase.table("history").insert({"chat_id": chat_id, "role": "user", "content": user_text}).execute() | |
| supabase.table("history").insert({"chat_id": chat_id, "role": "assistant", "content": ans}).execute() | |
| return ans | |
| # --- ОБРАБОТЧИК --- | |
| async def handle_message(msg: types.Message): | |
| TARGET_CHAT_ID = -1003503805392 | |
| if msg.chat.id != TARGET_CHAT_ID or not msg.text: | |
| return | |
| text_lower = msg.text.lower() | |
| bot_info = await bot.get_me() | |
| is_post = msg.is_automatic_forward or (msg.forward_from_chat and msg.forward_from_chat.type == 'channel') | |
| is_reply = msg.reply_to_message and msg.reply_to_message.from_user.id == bot_info.id | |
| is_called = "стелла" in text_lower or "stella" in text_lower | |
| if is_post or is_reply or is_called: | |
| await bot.send_chat_action(msg.chat.id, "typing") | |
| user_name = msg.from_user.first_name if msg.from_user else "Канал" | |
| res = await get_ai_response(msg.chat.id, msg.text, user_name) | |
| await msg.reply(res) | |
| # --- WEBHOOK СЕРВЕР --- | |
| async def handle_webhook(request): | |
| try: | |
| data = await request.json() | |
| update = Update(**data) | |
| await dp.feed_update(bot, update) | |
| return web.Response(text="OK") | |
| except Exception as e: | |
| logging.error(f"Error handling webhook: {e}") | |
| return web.Response(status=500) | |
| async def on_startup(app): | |
| # Установка вебхука через прокси | |
| await bot.set_webhook(WEBHOOK_URL) | |
| logging.info(f"--- WEBHOOK SUCCESS: {WEBHOOK_URL} ---") | |
| async def main(): | |
| logging.basicConfig(level=logging.INFO) | |
| app = web.Application() | |
| app.router.add_post(WEBHOOK_PATH, handle_webhook) | |
| app.router.add_get("/", lambda r: web.Response(text="Stella AI is Active with Proxy!")) | |
| app.on_startup.append(on_startup) | |
| runner = web.AppRunner(app) | |
| await runner.setup() | |
| site = web.TCPSite(runner, '0.0.0.0', 7860) | |
| await site.start() | |
| while True: | |
| await asyncio.sleep(3600) | |
| if __name__ == "__main__": | |
| asyncio.run(main()) |