Spaces:
Sleeping
Sleeping
Update bot.py
Browse files17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960614 unmodified lines66676869707130 unmodified lines1021031041051061071081091101111121131141151161171181191202 unmodified lines1231241251261271281291 unmodified line13113213313413513613720 unmodified lines15815916016116216316416516616716816917 unmodified linesapp = Flask(__name__)user_conversations = {}# Создаем бота и приложение без инициализации через интернетbot = Bot(token=TELEGRAM_TOKEN)application = Application.builder().token(TELEGRAM_TOKEN).build()async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):user_id = update.effective_user.iduser_conversations[user_id] = []await update.message.reply_text("🤖 Привет! Я Qwen3.5 9B бот.\n""Задайте любой вопрос!\n""/clear - очистить историю\n""/help - помощь")async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):await update.message.reply_text("📝 Просто напишите сообщение.\n""/clear - очистить историю\n""/start - начать сначала")async def clear_command(update: Update, context: ContextTypes.DEFAULT_TYPE):user_id = update.effective_user.iduser_conversations[user_id] = []await update.message.reply_text("🧹 История очищена!")async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):user_id = update.effective_user.iduser_message = update.message.textlogger.info(f"Сообщение от {user_id}: {user_message[:50]}...")if user_id not in user_conversations:user_conversations[user_id] = []user_conversations[user_id].append({"role": "user", "content": user_message})try:# Проверка доступности сервераtry:response = requests.get("http://localhost:7861/health", timeout=3)4 unmodified linesawait update.message.reply_text("⏳ Сервер загружается. Попробуйте через минуту.")returnpayload = {"model": "Qwen3.5-9B","messages": user_conversations[user_id][-10:],30 unmodified linesexcept requests.exceptions.Timeout:await update.message.reply_text("⏰ Модель долго думает. Попробуйте упростить вопрос.")except Exception as e:logger.error(f"Error: {str(e)}")await update.message.reply_text(f"❌ Произошла ошибка. Попробуйте позже.")async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):logger.error(f"Update {update} caused error {context.error}")# Регистрируем обработчикиapplication.add_handler(CommandHandler("start", start))application.add_handler(CommandHandler("help", help_command))application.add_handler(CommandHandler("clear", clear_command))application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))application.add_error_handler(error_handler)@app.route('/webhook', methods=['POST'])def webhook():"""Обработка webhook от Telegram"""2 unmodified linesif not data:return jsonify({"status": "error", "message": "No data"}), 400logger.info(f"Получен webhook от {data.get('message', {}).get('from', {}).get('username', 'unknown')}: {data.get('message', {}).get('text', 'no text')[:50]}")# Создаем объект Updateupdate = Update.de_json(data, bot)1 unmodified line# Обрабатываем update в асинхронном режимеloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.run_until_complete(application.process_update(update))loop.close()return jsonify({"status": "ok"}), 20020 unmodified lines"webhook": "/webhook (POST)","health": "/health (GET)"},"webhook_url": "https://softltd-softltd-ai.hf.space/webhook","instructions": "Set webhook: https://api.telegram.org/bot<YOUR_TOKEN>/setWebhook?url=https://softltd-softltd-ai.hf.space/webhook"}), 200if __name__ == "__main__":logger.info("🚀 Запуск Flask сервера на порту 7860...")logger.info("📌 Не забудьте установить webhook:")logger.info(" https://api.telegram.org/bot8715390060:AAHT0IeCllzTJXgY4CusGDiHyBGMwQIxYEw/setWebhook?url=https://softltd-softltd-ai.hf.space/webhook")app.run(host='0.0.0.0', port=7860, debug=False, threaded=True)17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566674 unmodified lines7273747576777830 unmodified lines1091101111121131141151161172 unmodified lines1201211221231241251261271281291301 unmodified line13213313413513613713820 unmodified lines15916016116216316416516616716816917017 unmodified linesapp = Flask(__name__)user_conversations = {}# Создаем ботаbot = Bot(token=TELEGRAM_TOKEN)# Функции-обработчикиasync def handle_update(update: Update):"""Обработка входящего обновления"""try:# Проверяем, что это сообщениеif not update.message:returnuser_id = update.effective_user.iduser_message = update.message.textlogger.info(f"Сообщение от {user_id}: {user_message[:50]}...")# Обработка командif user_message.startswith('/'):if user_message == '/start':await update.message.reply_text("🤖 Привет! Я Qwen3.5 9B бот.\n""Задайте любой вопрос!\n""/clear - очистить историю\n""/help - помощь")returnelif user_message == '/help':await update.message.reply_text("📝 Просто напишите сообщение.\n""/clear - очистить историю\n""/start - начать сначала")returnelif user_message == '/clear':user_conversations[user_id] = []await update.message.reply_text("🧹 История очищена!")return# Обычное сообщениеif user_id not in user_conversations:user_conversations[user_id] = []user_conversations[user_id].append({"role": "user", "content": user_message})# Проверка доступности сервераtry:response = requests.get("http://localhost:7861/health", timeout=3)4 unmodified linesawait update.message.reply_text("⏳ Сервер загружается. Попробуйте через минуту.")return# Запрос к моделиpayload = {"model": "Qwen3.5-9B","messages": user_conversations[user_id][-10:],30 unmodified linesexcept requests.exceptions.Timeout:await update.message.reply_text("⏰ Модель долго думает. Попробуйте упростить вопрос.")except Exception as e:logger.error(f"Error in handle_update: {str(e)}")await update.message.reply_text(f"❌ Произошла ошибка. Попробуйте позже.")@app.route('/webhook', methods=['POST'])def webhook():"""Обработка webhook от Telegram"""2 unmodified linesif not data:return jsonify({"status": "error", "message": "No data"}), 400# Получаем информацию о сообщении для логаmsg = data.get('message', {})username = msg.get('from', {}).get('username', 'unknown')text = msg.get('text', 'no text')logger.info(f"Получен webhook от @{username}: {text[:50]}")# Создаем объект Updateupdate = Update.de_json(data, bot)1 unmodified line# Обрабатываем update в асинхронном режимеloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.run_until_complete(handle_update(update))loop.close()return jsonify({"status": "ok"}), 20020 unmodified lines"webhook": "/webhook (POST)","health": "/health (GET)"},"webhook_url": "https://softltd-softltd-ai.hf.space/webhook"}), 200if __name__ == "__main__":logger.info("🚀 Запуск Flask сервера на порту 7860...")logger.info("✅ Webhook уже должен быть установлен")logger.info("📌 Если нет, установите:")logger.info(" https://api.telegram.org/bot8715390060:AAHT0IeCllzTJXgY4CusGDiHyBGMwQIxYEw/setWebhook?url=https://softltd-softltd-ai.hf.space/webhook")app.run(host='0.0.0.0', port=7860, debug=False, threaded=True)
bot.py+52-51