Rid3 commited on
Commit
964d4f3
·
verified ·
1 Parent(s): b44f37f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -10
app.py CHANGED
@@ -105,7 +105,8 @@ class ContentAggregator:
105
  - "insights": массив из 5 инсайтов, которых нет в исходных данных
106
  """
107
  try:
108
- response = await genai_client.models.generate_content(
 
109
  model=GEMINI_MODEL_NAME,
110
  contents=prompt
111
  )
@@ -226,10 +227,12 @@ async def ask_ai(update: Update, context: ContextTypes.DEFAULT_TYPE):
226
  return
227
  msg = await update.message.reply_text("🤔 Думаю...")
228
  try:
229
- resp = await genai_client.models.generate_content(model=GEMINI_MODEL_NAME, contents=query)
 
230
  await msg.edit_text(resp.text[:4000], parse_mode='Markdown')
231
  except Exception as e:
232
- await msg.edit_text(f"❌ Ошибка: {e}")
 
233
 
234
  async def create_content(update: Update, context: ContextTypes.DEFAULT_TYPE):
235
  user_id = update.effective_user.id
@@ -291,14 +294,23 @@ async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
291
  user_id = update.effective_user.id
292
  if not bot_state.is_allowed(user_id):
293
  return
 
 
 
 
 
 
 
 
 
 
 
294
  if text.lower().startswith(("ии ", "ai ")):
295
  prompt = text[3:].strip()
296
  if prompt:
297
- resp = await genai_client.models.generate_content(model=GEMINI_MODEL_NAME, contents=prompt)
298
- await update.message.reply_text(resp.text[:4000], parse_mode='Markdown')
299
  elif len(text) > 20 and not text.startswith("/"):
300
- resp = await genai_client.models.generate_content(model=GEMINI_MODEL_NAME, contents=text)
301
- await update.message.reply_text(resp.text[:4000], parse_mode='Markdown')
302
 
303
  async def premium_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
304
  await update.message.reply_text(f"💎 Premium даёт видео, музыку, приоритет.\nПолучите: {BOOST_LINK}")
@@ -334,12 +346,11 @@ async def callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
334
  elif data == "gen_video":
335
  await query.edit_message_text("Premium команда: /video [описание]")
336
 
337
- # ============= MAIN =============
338
  # ============= MAIN =============
339
  def main():
340
  logging.basicConfig(level=logging.INFO)
341
 
342
- # Убираем proxy/proxy_url отсюда, оставляем только настройки таймаутов
343
  request = HTTPXRequest(
344
  connect_timeout=30.0,
345
  read_timeout=40.0,
@@ -348,7 +359,7 @@ def main():
348
  connection_pool_size=20
349
  )
350
 
351
- # Передаем CF_WORKER_URL через метод base_url() (не забудьте добавить /bot)
352
  application = (
353
  Application.builder()
354
  .token(TG_BOT_TOKEN)
 
105
  - "insights": массив из 5 инсайтов, которых нет в исходных данных
106
  """
107
  try:
108
+ # ИСПОЛЬЗУЕМ .aio ДЛЯ АСИНХРОННЫХ ВЫЗОВОВ
109
+ response = await genai_client.aio.models.generate_content(
110
  model=GEMINI_MODEL_NAME,
111
  contents=prompt
112
  )
 
227
  return
228
  msg = await update.message.reply_text("🤔 Думаю...")
229
  try:
230
+ # ИСПОЛЬЗУЕМ .aio
231
+ resp = await genai_client.aio.models.generate_content(model=GEMINI_MODEL_NAME, contents=query)
232
  await msg.edit_text(resp.text[:4000], parse_mode='Markdown')
233
  except Exception as e:
234
+ await msg.edit_text("❌ Извините, сервера Google сейчас перегружены или произошла ошибка. Попробуйте позже.")
235
+ logging.error(f"Ошибка Gemini: {e}")
236
 
237
  async def create_content(update: Update, context: ContextTypes.DEFAULT_TYPE):
238
  user_id = update.effective_user.id
 
294
  user_id = update.effective_user.id
295
  if not bot_state.is_allowed(user_id):
296
  return
297
+
298
+ # Вспомогательная функция с обработкой ошибок API
299
+ async def process_prompt(prompt_text):
300
+ try:
301
+ # ИСПОЛЬЗУЕМ .aio
302
+ resp = await genai_client.aio.models.generate_content(model=GEMINI_MODEL_NAME, contents=prompt_text)
303
+ await update.message.reply_text(resp.text[:4000], parse_mode='Markdown')
304
+ except Exception as e:
305
+ logging.error(f"Gemini API Error: {e}")
306
+ await update.message.reply_text("⚠️ Ошибка: Сервера Google сейчас перегружены. Пожалуйста, попробуйте чуть позже.")
307
+
308
  if text.lower().startswith(("ии ", "ai ")):
309
  prompt = text[3:].strip()
310
  if prompt:
311
+ await process_prompt(prompt)
 
312
  elif len(text) > 20 and not text.startswith("/"):
313
+ await process_prompt(text)
 
314
 
315
  async def premium_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
316
  await update.message.reply_text(f"💎 Premium даёт видео, музыку, приоритет.\nПолучите: {BOOST_LINK}")
 
346
  elif data == "gen_video":
347
  await query.edit_message_text("Premium команда: /video [описание]")
348
 
 
349
  # ============= MAIN =============
350
  def main():
351
  logging.basicConfig(level=logging.INFO)
352
 
353
+ # Оставляем только настройки таймаутов, proxy_url убран
354
  request = HTTPXRequest(
355
  connect_timeout=30.0,
356
  read_timeout=40.0,
 
359
  connection_pool_size=20
360
  )
361
 
362
+ # CF_WORKER_URL передан в base_url
363
  application = (
364
  Application.builder()
365
  .token(TG_BOT_TOKEN)