Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,260 +2,142 @@ import os
|
|
| 2 |
import io
|
| 3 |
import logging
|
| 4 |
import asyncio
|
|
|
|
|
|
|
| 5 |
import time
|
|
|
|
| 6 |
from flask import Flask, request as flask_request
|
| 7 |
from threading import Thread
|
| 8 |
-
from telegram import Update
|
| 9 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
|
| 10 |
-
from telegram.request import HTTPXRequest
|
| 11 |
-
|
| 12 |
-
# Инструменты для загрузки файлов и локального запуска (без API)
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
-
import torch
|
| 15 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 16 |
-
from diffusers import
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# ==========================================
|
| 21 |
-
logging.basicConfig(
|
| 22 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 23 |
-
level=logging.INFO
|
| 24 |
)
|
| 25 |
-
logger = logging.getLogger(__name__)
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
# ДАННЫЕ АВТОРИЗАЦИИ
|
| 31 |
-
# ==========================================
|
| 32 |
TELEGRAM_TOKEN = "8887560175:AAHb2oMpExWAc0Wz29Mt2x2UFiQBSsD4ASE"
|
| 33 |
-
WEBGET_LOGIN = "2.0"
|
| 34 |
CF_PROXY_URL = "https://tg-proxy.artyomanisimov37.workers.dev/bot"
|
| 35 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 36 |
-
|
| 37 |
-
# ==========================================
|
| 38 |
-
# ЛОКАЛЬНАЯ ЗАГРУЗКА ВСЕХ ФАЙЛОВ ИЗ ТВОЕГО РЕПОЗИТОРИЯ
|
| 39 |
-
# ==========================================
|
| 40 |
REPO_ID = "zeroone229/for-bot"
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
logger.info("⏳ Загружаем текстовую модель...")
|
| 48 |
-
try:
|
| 49 |
-
try:
|
| 50 |
-
tokenizer = AutoTokenizer.from_pretrained(REPO_ID, gguf_file=TEXT_FILENAME, token=HF_TOKEN)
|
| 51 |
-
except:
|
| 52 |
-
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it", token=HF_TOKEN)
|
| 53 |
-
|
| 54 |
-
text_model = AutoModelForCausalLM.from_pretrained(
|
| 55 |
-
REPO_ID, gguf_file=TEXT_FILENAME, token=HF_TOKEN, device_map="cpu", torch_dtype=torch.float32
|
| 56 |
-
)
|
| 57 |
-
logger.info("✅ Текст: загружен!")
|
| 58 |
-
except Exception as e:
|
| 59 |
-
logger.error(f"❌ Ошибка текста: {e}")
|
| 60 |
-
text_model, tokenizer = None, None
|
| 61 |
-
|
| 62 |
-
# 2. ЗАГРУЗКА ФОТО (Генерирует медленно на CPU)
|
| 63 |
-
logger.info("⏳ Загружаем фото-модель...")
|
| 64 |
-
try:
|
| 65 |
-
image_path = hf_hub_download(repo_id=REPO_ID, filename=IMAGE_FILENAME, token=HF_TOKEN)
|
| 66 |
-
image_pipe = StableDiffusionPipeline.from_single_file(
|
| 67 |
-
image_path, torch_dtype=torch.float32, use_safetensors=True
|
| 68 |
-
).to("cpu")
|
| 69 |
-
logger.info("✅ Фото: загружено!")
|
| 70 |
-
except Exception as e:
|
| 71 |
-
logger.error(f"❌ Ошибка загрузки фото-файла: {e}")
|
| 72 |
-
image_pipe = None
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
video_path = hf_hub_download(repo_id=REPO_ID, filename=VIDEO_FILENAME, token=HF_TOKEN)
|
| 78 |
-
video_pipe = DiffusionPipeline.from_single_file(
|
| 79 |
-
video_path, torch_dtype=torch.float32, use_safetensors=True
|
| 80 |
-
).to("cpu")
|
| 81 |
-
logger.info("✅ Видео: загружено!")
|
| 82 |
-
except Exception as e:
|
| 83 |
-
logger.error(f"❌ Ошибка загрузки видео-файла: {e}")
|
| 84 |
-
video_pipe = None
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
STICKERS = {
|
| 91 |
-
"hello": "CAACAgIAAxkBAAERRMdqEVyVj1Ig9YmpLqCCQoVnNKc8VgACzpkAAnmqiEjco0PFruuGPDsE",
|
| 92 |
-
"angry": "CAACAgIAAxkBAAERRMxqEWBGRhp2OIHxnsbRli3kmZ0avgACCZQAAiBUiUjyiFhlRlBNjTsE",
|
| 93 |
-
"refuse": "CAACAgIAAxkBAAERRM5qEWBIykgPIzTnZ1QKq_AkuGhy6gAC1Y4AAstiiUgkyKD1My8FRTsE",
|
| 94 |
-
"thinking": "CAACAgIAAxkBAAERRNRqEWBPrm8I-okgu3xqQCddSIdzTwACQ6IAAqXpiUgvwZbRu83PYTsE"
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
def analyze_emotion_and_get_sticker(text: str) -> str:
|
| 98 |
-
text_lower = text.lower()
|
| 99 |
-
if any(word in text_lower for word in ["не могу", "ошибка"]): return STICKERS["refuse"]
|
| 100 |
-
if any(word in text_lower for word in ["злой", "бесит"]): return STICKERS["angry"]
|
| 101 |
-
if any(word in text_lower for word in ["привет", "супер"]): return STICKERS["hello"]
|
| 102 |
-
return None
|
| 103 |
-
|
| 104 |
-
# ==========================================
|
| 105 |
-
# ПАМЯТЬ БОТА
|
| 106 |
-
# ==========================================
|
| 107 |
-
chat_memory = {}
|
| 108 |
-
MAX_HISTORY = 6
|
| 109 |
-
|
| 110 |
-
def add_to_memory(chat_id, role, text):
|
| 111 |
-
if chat_id not in chat_memory: chat_memory[chat_id] = []
|
| 112 |
-
chat_memory[chat_id].append({"role": role, "content": text})
|
| 113 |
-
if len(chat_memory[chat_id]) > MAX_HISTORY: chat_memory[chat_id] = chat_memory[chat_id][-MAX_HISTORY:]
|
| 114 |
-
|
| 115 |
-
# ==========================================
|
| 116 |
-
# WEB СЕРВЕР FLASK
|
| 117 |
-
# ==========================================
|
| 118 |
-
@flask_app.route('/')
|
| 119 |
-
def home():
|
| 120 |
-
return f"Бот онлайн. Локальные файлы загружены."
|
| 121 |
-
|
| 122 |
-
@flask_app.route('/telegram', methods=['POST'])
|
| 123 |
-
def telegram_webhook():
|
| 124 |
-
global main_loop, tg_application
|
| 125 |
-
if tg_application and main_loop:
|
| 126 |
-
try:
|
| 127 |
-
update = Update.de_json(flask_request.get_json(force=True), tg_application.bot)
|
| 128 |
-
asyncio.run_coroutine_threadsafe(tg_application.process_update(update), main_loop)
|
| 129 |
-
except Exception as e:
|
| 130 |
-
pass
|
| 131 |
-
return "OK", 200
|
| 132 |
-
|
| 133 |
-
# ==========================================
|
| 134 |
-
# ИИ ФУНКЦИИ (ЛОКАЛЬНЫЕ)
|
| 135 |
-
# ==========================================
|
| 136 |
-
def call_llm(user_text, chat_id):
|
| 137 |
-
if not text_model or not tokenizer: return "⚠️ Текстовая модель не загрузилась."
|
| 138 |
-
messages = [{"role": "system", "content": "Ты умный ИИ. Отвечай на русском."}]
|
| 139 |
-
if chat_id in chat_memory: messages.extend(chat_memory[chat_id])
|
| 140 |
-
messages.append({"role": "user", "content": user_text})
|
| 141 |
-
|
| 142 |
-
try:
|
| 143 |
-
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 144 |
-
inputs = tokenizer(prompt, return_tensors="pt")
|
| 145 |
-
with torch.no_grad():
|
| 146 |
-
outputs = text_model.generate(**inputs, max_new_tokens=600, temperature=0.7, do_sample=True)
|
| 147 |
-
return tokenizer.decode(outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True).strip()
|
| 148 |
-
except:
|
| 149 |
-
return "⚠️ Ошибка генерации текста."
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
try:
|
| 154 |
-
# Уменьшаем шаги, чтобы CPU не думал вечность (по умолчанию 50, ставим 20)
|
| 155 |
-
image = image_pipe(prompt, num_inference_steps=20).images[0]
|
| 156 |
-
img_byte_arr = io.BytesIO()
|
| 157 |
-
image.save(img_byte_arr, format='JPEG')
|
| 158 |
-
return img_byte_arr.getvalue()
|
| 159 |
-
except Exception as e:
|
| 160 |
-
logger.error(f"Ошибка рисовки: {e}")
|
| 161 |
-
return None
|
| 162 |
|
| 163 |
-
def
|
| 164 |
-
if
|
|
|
|
|
|
|
|
|
|
| 165 |
try:
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
except Exception as e:
|
| 171 |
-
logger.error(f"О
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
# ==========================================
|
| 175 |
-
# ОБРАБОТЧИКИ ��ОМАНД
|
| 176 |
-
# ==========================================
|
| 177 |
-
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 178 |
-
chat_memory[update.effective_chat.id] = []
|
| 179 |
-
await update.message.reply_text("Привет! Я готов к работе локально.")
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
loop = asyncio.get_running_loop()
|
| 188 |
-
ai_response = await loop.run_in_executor(None, call_llm, update.message.text, update.effective_chat.id)
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
if "⚠️" not in ai_response:
|
| 194 |
-
add_to_memory(update.effective_chat.id, "user", update.message.text)
|
| 195 |
-
add_to_memory(update.effective_chat.id, "assistant", ai_response)
|
| 196 |
-
|
| 197 |
-
await update.message.reply_text(text=ai_response)
|
| 198 |
-
|
| 199 |
-
async def photo_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 200 |
-
prompt = " ".join(context.args)
|
| 201 |
-
if not prompt: return await update.message.reply_text("Пример: `/photo кот`")
|
| 202 |
-
|
| 203 |
-
status = await update.message.reply_text("🎨 Рисую (на процессоре это займет несколько минут)...")
|
| 204 |
-
loop = asyncio.get_running_loop()
|
| 205 |
-
photo_bytes = await loop.run_in_executor(None, generate_photo, prompt)
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
else:
|
| 211 |
-
await status.edit_text("❌ Ошибка генерации фото. Проверь логи (возможно нехватка памяти).")
|
| 212 |
|
| 213 |
-
|
|
|
|
|
|
|
| 214 |
prompt = " ".join(context.args)
|
| 215 |
-
if not prompt:
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
loop = asyncio.get_running_loop()
|
| 219 |
-
video_bytes = await loop.run_in_executor(None, generate_video, prompt)
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
await status.edit_text("❌ Видео на процессоре сгенерировать не вышло. Ошибка памяти.")
|
| 225 |
-
|
| 226 |
-
# ==========================================
|
| 227 |
-
# ЗАПУСК БОТА
|
| 228 |
-
# ==========================================
|
| 229 |
-
tg_application = None
|
| 230 |
-
main_loop = None
|
| 231 |
|
| 232 |
-
def
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
loop.run_forever()
|
| 249 |
-
except Exception as err:
|
| 250 |
-
time.sleep(10)
|
| 251 |
|
|
|
|
| 252 |
if __name__ == "__main__":
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import io
|
| 3 |
import logging
|
| 4 |
import asyncio
|
| 5 |
+
import torch
|
| 6 |
+
import random
|
| 7 |
import time
|
| 8 |
+
from collections import deque
|
| 9 |
from flask import Flask, request as flask_request
|
| 10 |
from threading import Thread
|
| 11 |
+
from telegram import Update, constants
|
| 12 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
|
|
|
|
|
|
|
|
|
|
| 13 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 14 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 15 |
+
from diffusers import (
|
| 16 |
+
StableDiffusionPipeline,
|
| 17 |
+
StableVideoDiffusionPipeline,
|
| 18 |
+
AudioLDMPipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
|
|
|
| 20 |
|
| 21 |
+
# --- ЛОГИРОВАНИЕ ---
|
| 22 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 23 |
+
logger = logging.getLogger("AI_BOT")
|
| 24 |
|
| 25 |
+
# --- КОНФИГУРАЦИЯ ---
|
|
|
|
|
|
|
| 26 |
TELEGRAM_TOKEN = "8887560175:AAHb2oMpExWAc0Wz29Mt2x2UFiQBSsD4ASE"
|
|
|
|
| 27 |
CF_PROXY_URL = "https://tg-proxy.artyomanisimov37.workers.dev/bot"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
REPO_ID = "zeroone229/for-bot"
|
| 29 |
|
| 30 |
+
# --- ФАЙЛЫ МОДЕЛЕЙ ---
|
| 31 |
+
TEXT_FILE = "gemma-2-2b-it-IQ3_M.gguf"
|
| 32 |
+
PHOTO_FILE = "diffusion_pytorch_model.safetensors"
|
| 33 |
+
VIDEO_FILE = "stable-diffusion-v1-5-pruned-emaonly-Q8_0.gguf"
|
| 34 |
+
MUSIC_FILE = "compression_state_dict.bin"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# --- СИСТЕМА ПАМЯТИ ---
|
| 37 |
+
# Хранение: {chat_id: deque([(timestamp, user_text, bot_response), ...])}
|
| 38 |
+
chat_histories = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
def get_chat_history(chat_id):
|
| 41 |
+
if chat_id not in chat_histories:
|
| 42 |
+
chat_histories[chat_id] = deque(maxlen=100)
|
| 43 |
+
return chat_histories[chat_id]
|
| 44 |
|
| 45 |
+
def is_message_valid(timestamp):
|
| 46 |
+
# Удаление записей старше 24 часов (86400 секунд)
|
| 47 |
+
return (time.time() - timestamp) < 86400
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# --- ИНИЦИАЛИЗАЦИЯ МОДЕЛЕЙ ---
|
| 50 |
+
models = {"text": None, "tokenizer": None, "photo": None, "video": None, "music": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
def load_model(model_name):
|
| 53 |
+
if models[model_name] is not None:
|
| 54 |
+
return models[model_name]
|
| 55 |
+
|
| 56 |
+
logger.info(f"ЗАГРУЗКА МОДЕЛИ: {model_name}")
|
| 57 |
try:
|
| 58 |
+
if model_name == "text":
|
| 59 |
+
models["tokenizer"] = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
|
| 60 |
+
models["text"] = AutoModelForCausalLM.from_pretrained(REPO_ID, gguf_file=TEXT_FILE, device_map="cpu")
|
| 61 |
+
elif model_name == "photo":
|
| 62 |
+
path = hf_hub_download(repo_id=REPO_ID, filename=PHOTO_FILE)
|
| 63 |
+
models["photo"] = StableDiffusionPipeline.from_single_file(path, torch_dtype=torch.float32).to("cpu")
|
| 64 |
+
elif model_name == "video":
|
| 65 |
+
path = hf_hub_download(repo_id=REPO_ID, filename=VIDEO_FILE)
|
| 66 |
+
models["video"] = StableVideoDiffusionPipeline.from_single_file(path, torch_dtype=torch.float32).to("cpu")
|
| 67 |
+
elif model_name == "music":
|
| 68 |
+
path = hf_hub_download(repo_id=REPO_ID, filename=MUSIC_FILE)
|
| 69 |
+
models["music"] = AudioLDMPipeline.from_single_file(path, torch_dtype=torch.float32).to("cpu")
|
| 70 |
except Exception as e:
|
| 71 |
+
logger.error(f"КРИТИЧЕСКАЯ ОШИБКА ЗАГРУЗКИ {model_name}: {e}")
|
| 72 |
+
return models[model_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
# --- ГЕНЕРАЦИЯ ТЕКСТА ---
|
| 75 |
+
def generate_text_logic(prompt, chat_id):
|
| 76 |
+
load_model("text")
|
| 77 |
+
history = get_chat_history(chat_id)
|
| 78 |
|
| 79 |
+
# Собираем контекст из истории за 24 часа
|
| 80 |
+
context = "\n".join([f"U: {m[1]}\nB: {m[2]}" for m in history if is_message_valid(m[0])])
|
| 81 |
+
full_prompt = f"{context}\nU: {prompt}\nB:"
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
inputs = models["tokenizer"](full_prompt, return_tensors="pt")
|
| 84 |
+
with torch.no_grad():
|
| 85 |
+
out = models["text"].generate(**inputs, max_new_tokens=200, do_sample=True, temperature=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
response = models["tokenizer"].decode(out[0], skip_special_tokens=True).split("B:")[-1].strip()
|
| 88 |
+
history.append((time.time(), prompt, response))
|
| 89 |
+
return response
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# --- КОМАНДЫ И ОБРАБОТЧИКИ ---
|
| 92 |
+
async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 93 |
+
"""Команда /ask для принудительного ответа"""
|
| 94 |
prompt = " ".join(context.args)
|
| 95 |
+
if not prompt:
|
| 96 |
+
await update.message.reply_text("Использование: /ask <ваш вопрос>")
|
| 97 |
+
return
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=constants.ChatAction.TYPING)
|
| 100 |
+
response = await asyncio.to_thread(generate_text_logic, prompt, update.effective_chat.id)
|
| 101 |
+
await update.message.reply_text(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
async def message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 104 |
+
"""Фоновая активность: ответ на реплики, упомина��ия или случайный шанс"""
|
| 105 |
+
if not update.message or not update.message.text: return
|
| 106 |
+
|
| 107 |
+
bot_id = context.bot.id
|
| 108 |
+
user_text = update.message.text
|
| 109 |
+
|
| 110 |
+
# Условия фонового ответа
|
| 111 |
+
is_reply = update.message.reply_to_message and update.message.reply_to_message.from_user.id == bot_id
|
| 112 |
+
is_mention = context.bot.username and context.bot.username.lower() in user_text.lower()
|
| 113 |
+
is_random = random.random() < 0.15
|
| 114 |
+
|
| 115 |
+
if is_reply or is_mention or is_random:
|
| 116 |
+
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=constants.ChatAction.TYPING)
|
| 117 |
+
response = await asyncio.to_thread(generate_text_logic, user_text, update.effective_chat.id)
|
| 118 |
+
await update.message.reply_text(response)
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
# --- ЗАПУСК ---
|
| 121 |
if __name__ == "__main__":
|
| 122 |
+
app = Application.builder().token(TELEGRAM_TOKEN).base_url(CF_PROXY_URL).build()
|
| 123 |
+
|
| 124 |
+
# Регистрация команд
|
| 125 |
+
app.add_handler(CommandHandler("ask", ask_command))
|
| 126 |
+
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, message_handler))
|
| 127 |
|
| 128 |
+
# Вебхук
|
| 129 |
+
flask_app = Flask(__name__)
|
| 130 |
+
@flask_app.route('/telegram', methods=['POST'])
|
| 131 |
+
def telegram_webhook():
|
| 132 |
+
update_data = flask_request.get_json(force=True)
|
| 133 |
+
update = Update.de_json(update_data, app.bot)
|
| 134 |
+
asyncio.run_coroutine_threadsafe(app.process_update(update), asyncio.get_event_loop())
|
| 135 |
+
return "OK", 200
|
| 136 |
+
|
| 137 |
+
Thread(target=lambda: flask_app.run(host="0.0.0.0", port=7860), daemon=True).start()
|
| 138 |
|
| 139 |
+
loop = asyncio.get_event_loop()
|
| 140 |
+
loop.run_until_complete(app.initialize())
|
| 141 |
+
loop.run_until_complete(app.start())
|
| 142 |
+
logger.info("Бот готов к работе (активирован /ask).")
|
| 143 |
+
loop.run_forever()
|