zhenxun_bot/plugins/image_management/upload_image/data_source.py

47 lines
1.7 KiB
Python
Raw Normal View History

2021-11-23 21:44:59 +08:00
from configs.config import NICKNAME
from typing import List
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.utils import cn2py
from utils.http_utils import AsyncHttpx
import os
2022-02-19 18:20:19 +08:00
_path = IMAGE_PATH / "image_management"
2021-12-16 11:16:28 +08:00
2021-11-23 21:44:59 +08:00
async def upload_image_to_local(
2021-12-16 11:16:28 +08:00
img_list: List[str], path_: str, user_id: int, group_id: int = 0
2021-11-23 21:44:59 +08:00
) -> str:
2021-12-16 11:16:28 +08:00
_path_name = path_
path = _path / cn2py(path_)
if not path.exists() and (path.parent.parent / cn2py(path_)).exists():
path = path.parent.parent / cn2py(path_)
2021-11-23 21:44:59 +08:00
path.mkdir(parents=True, exist_ok=True)
img_id = len(os.listdir(path))
failed_list = []
success_id = ""
for img_url in img_list:
if await AsyncHttpx.download_file(img_url, path / f"{img_id}.jpg"):
success_id += str(img_id) + ""
img_id += 1
else:
failed_list.append(img_url)
failed_result = ""
for img in failed_list:
failed_result += str(img) + "\n"
logger.info(
f"USER {user_id} GROUP {group_id}"
2021-12-16 11:16:28 +08:00
f" 上传图片至 {_path_name}{len(img_list)} 张,失败 {len(failed_list)}id={success_id[:-1]}"
2021-11-23 21:44:59 +08:00
)
if failed_list:
return (
2021-12-16 11:16:28 +08:00
f"这次一共为 {_path_name}库 添加了 {len(img_list) - len(failed_list)} 张图片\n"
2021-11-23 21:44:59 +08:00
f"依次的Id为{success_id[:-1]}\n上传失败:{failed_result[:-1]}\n{NICKNAME}感谢您对图库的扩充!WW"
)
else:
return (
2021-12-16 11:16:28 +08:00
f"这次一共为 {_path_name}库 添加了 {len(img_list)} 张图片\n依次的Id为"
2021-11-23 21:44:59 +08:00
f"{success_id[:-1]}\n{NICKNAME}感谢您对图库的扩充!WW"
)