"""群管理工具 —— 视频下载。""" from __future__ import annotations import asyncio import re import time from nonebot import logger, on_startswith, require from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent from nonebot_plugin_alconna import UniMessage from ...constants import TEMP_DIR from ...services.video import download_video, get_video_info, local_video from ...utils.text import is_number require("nonebot_plugin_alconna") down_video = on_startswith("/video") @down_video.handle() async def down_video_handle(bot: Bot, ev: GroupMessageEvent): url = ev.message.extract_plain_text().removeprefix("/video").strip() if not url: return match = re.match(r"https?:/{2}w.+$", url) if not match: await UniMessage.text("参数不合法").send() return timespan = int(time.time()) filename = f"{timespan}" file = TEMP_DIR / f"{filename}.mp4" fileabs = str(file) cover = TEMP_DIR / f"{filename}.mp4.jpg" TEMP_DIR.mkdir(parents=True, exist_ok=True) try: info = await asyncio.to_thread(get_video_info, url) match = re.search(r"MPEG-4 video(.*)s*Size:(.*)MiB", info) if not match: await UniMessage.text("参数不正确").send() return info_type = match.group(1).strip() if info_type != "(video/mp4)": await UniMessage.text("未找到视频信息").send() return info_size = match.group(2).strip() if not is_number(info_size): await UniMessage.text("无法获取视频大小").send() return size = float(info_size) if size >= 6.0: await UniMessage.text("视频体积过大").send() return await UniMessage.text("正在发送...").send() await asyncio.to_thread(download_video, url, TEMP_DIR, filename) except Exception as e: logger.error(e) await UniMessage.text("获取视频失败了").send() file.unlink(missing_ok=True) cover.unlink(missing_ok=True) return try: await local_video(f"file:///{fileabs}").send() except Exception: await UniMessage.text("发送失败了").send() file.unlink(missing_ok=True) cover.unlink(missing_ok=True)