HollyCorn commited on
Commit
1e4a9fa
·
verified ·
1 Parent(s): 7c251b7

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +37 -25
main.py CHANGED
@@ -45,7 +45,7 @@ logger.add("bot_log.log", rotation="10 MB", level="INFO")
45
  async def upload_to_bucket(url, user_id, prefix="temp"):
46
  try:
47
  async with aiohttp.ClientSession() as session:
48
- async with session.get(url) as resp:
49
  if resp.status == 200:
50
  img_data = await resp.read()
51
  file_name = f"{user_id}/{prefix}_{uuid.uuid4()}.png"
@@ -61,15 +61,21 @@ async def upload_to_bucket(url, user_id, prefix="temp"):
61
  return None, None
62
 
63
 
64
- async def download_file(url):
65
- try:
66
- async with aiohttp.ClientSession() as session:
67
- async with session.get(url) as resp:
68
- if resp.status == 200:
69
- data = await resp.read()
70
- return io.BytesIO(data)
71
- except Exception as e:
72
- logger.error(f"Ошибка скачивания файла для ВК: {e}")
 
 
 
 
 
 
73
  return None
74
 
75
 
@@ -269,16 +275,19 @@ async def free_trial_handler(message: Message):
269
  if res_url_bucket:
270
  try:
271
  file_stream = await download_file(res_url_bucket)
272
- photo_vk = await uploader.upload(file_stream, file_name="result.png")
273
- await message.answer("Отлично! Твоя фотография готова ✨", attachment=photo_vk)
274
-
275
- promo_text = (
276
- "Теперь ты можешь выбрать один из 10 готовых стилей для фото ✨\n"
277
- "или создать собственный образ в Творческом режиме.\n\n"
278
- "Выбирай, с чего начнём 👇"
279
- )
280
- await message.answer(promo_text, keyboard=get_main_menu(True))
281
- supabase.table("users").update({"free_used": True}).eq("id", message.from_id).execute()
 
 
 
282
  except Exception as e:
283
  logger.error(f"Ошибка в free_trial VK upload: {e}")
284
  await message.answer("Техническая ошибка при отправке фото.")
@@ -490,11 +499,14 @@ async def main_handler(message: Message):
490
  if res_url_bucket:
491
  try:
492
  file_stream = await download_file(res_url_bucket)
493
- photo_vk = await uploader.upload(file_stream, file_name="style.png")
494
- await message.answer("Отлично! Твое фото готово ✨", attachment=photo_vk)
495
- supabase.rpc("increment_balance", {"user_id": message.from_id, "amount": -1}).execute()
496
- supabase.table("users").update({"last_style": new_last_style, "status": "main"}).eq("id",
497
- message.from_id).execute()
 
 
 
498
  except Exception as e:
499
  logger.error(f"VK Style Error: {e}")
500
  await message.answer("ВК не принял фото. Баланс сохранен.")
 
45
  async def upload_to_bucket(url, user_id, prefix="temp"):
46
  try:
47
  async with aiohttp.ClientSession() as session:
48
+ async with session.get(url, timeout=30) as resp:
49
  if resp.status == 200:
50
  img_data = await resp.read()
51
  file_name = f"{user_id}/{prefix}_{uuid.uuid4()}.png"
 
61
  return None, None
62
 
63
 
64
+ async def download_file(url, retries=5, delay=2):
65
+ """Пытается скачать файл из бакета несколько раз с задержкой"""
66
+ for i in range(retries):
67
+ try:
68
+ async with aiohttp.ClientSession() as session:
69
+ async with session.get(url, timeout=10) as resp:
70
+ if resp.status == 200:
71
+ data = await resp.read()
72
+ if data and len(data) > 0:
73
+ return io.BytesIO(data)
74
+ logger.warning(f"Попытка {i+1} скачивания файла не удалась, ждем {delay} сек...")
75
+ await asyncio.sleep(delay)
76
+ except Exception as e:
77
+ logger.error(f"Ошибка на попытке {i+1} скачивания файла для ВК: {e}")
78
+ await asyncio.sleep(delay)
79
  return None
80
 
81
 
 
275
  if res_url_bucket:
276
  try:
277
  file_stream = await download_file(res_url_bucket)
278
+ if file_stream:
279
+ photo_vk = await uploader.upload(file_stream, file_name="result.png")
280
+ await message.answer("Отлично! Твоя фотография готова ✨", attachment=photo_vk)
281
+
282
+ promo_text = (
283
+ "Теперь ты можешь выбрать один из 10 готовых стилей для фото ✨\n"
284
+ "или создать собственный образ в Творческом режиме.\n\n"
285
+ "Выбирай, с чего начнём 👇"
286
+ )
287
+ await message.answer(promo_text, keyboard=get_main_menu(True))
288
+ supabase.table("users").update({"free_used": True}).eq("id", message.from_id).execute()
289
+ else:
290
+ await message.answer("Ошибка: не удалось получить файл из хранилища. Попробуйте еще раз позже.")
291
  except Exception as e:
292
  logger.error(f"Ошибка в free_trial VK upload: {e}")
293
  await message.answer("Техническая ошибка при отправке фото.")
 
499
  if res_url_bucket:
500
  try:
501
  file_stream = await download_file(res_url_bucket)
502
+ if file_stream:
503
+ photo_vk = await uploader.upload(file_stream, file_name="style.png")
504
+ await message.answer("Отлично! Твое фото готово ✨", attachment=photo_vk)
505
+ supabase.rpc("increment_balance", {"user_id": message.from_id, "amount": -1}).execute()
506
+ supabase.table("users").update({"last_style": new_last_style, "status": "main"}).eq("id",
507
+ message.from_id).execute()
508
+ else:
509
+ await message.answer("Ошибка: не удалось получить файл из хранилища. Баланс сохранен.")
510
  except Exception as e:
511
  logger.error(f"VK Style Error: {e}")
512
  await message.answer("ВК не принял фото. Баланс сохранен.")