Skip to content

Commit

Permalink
drop nonebot_plugin_saa
Browse files Browse the repository at this point in the history
  • Loading branch information
MeetWq committed Mar 2, 2024
1 parent ec5e112 commit eacfb1f
Show file tree
Hide file tree
Showing 11 changed files with 694 additions and 1,155 deletions.
31 changes: 0 additions & 31 deletions .github/workflows/update_poetry_lock.yml

This file was deleted.

9 changes: 1 addition & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,10 @@ pip install nonebot_plugin_imagetools
- 默认:`20`
- 说明:输出图片数量大于该数目时,打包为zip文件并上传

#### `imagetools_max_forward_msg_num`
- 类型:`int`
- 默认:`99`
- 说明:输出图片数量小于该数目时,发送合并转发消息


> [!NOTE]
>
> 本插件使用 [nonebot-plugin-saa](https://github.com/felinae98/nonebot-plugin-send-anything-anywhere) 插件来发送图片和合并转发消息,具体支持的平台和行为请参考该插件的文档
>
> 本插件使用 [nonebot-plugin-alconna](https://github.com/nonebot/plugin-alconna) 插件来发送文件,具体支持的平台和行为请参考该插件的文档
> 本插件使用 [nonebot-plugin-alconna](https://github.com/nonebot/plugin-alconna) 插件来发送图片和文件,具体支持的平台和行为请参考该插件的文档

### 使用
Expand Down
47 changes: 13 additions & 34 deletions nonebot_plugin_imagetools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import imghdr
import math
import traceback
from datetime import datetime
from io import BytesIO
from typing import List, Union
from zipfile import ZIP_BZIP2, ZipFile

from nonebot import on_command, require
from nonebot.adapters import Bot, Event
from nonebot.log import logger
from nonebot.matcher import Matcher
from nonebot.params import Depends
from nonebot.plugin import PluginMetadata, inherit_supported_adapters
Expand All @@ -17,11 +14,9 @@
from PIL.Image import Image as IMG
from pil_utils import BuildImage, Text2Image

require("nonebot_plugin_saa")
require("nonebot_plugin_alconna")

from nonebot_plugin_alconna import File, UniMessage
from nonebot_plugin_saa import AggregatedMessageFactory, Image, MessageFactory
from nonebot_plugin_alconna import Image, UniMessage

from .config import Config, imagetools_config
from .data_source import commands
Expand All @@ -34,14 +29,9 @@
type="application",
homepage="https://github.com/noneplugin/nonebot-plugin-imagetools",
config=Config,
supported_adapters=inherit_supported_adapters(
"nonebot_plugin_saa", "nonebot_plugin_alconna"
),
supported_adapters=inherit_supported_adapters("nonebot_plugin_alconna"),
extra={
"unique_name": "imagetools",
"example": "旋转 [图片]",
"author": "meetwq <[email protected]>",
"version": "0.3.0",
},
)

Expand All @@ -67,8 +57,8 @@ def cmd_text(commands: List[Command], start: int = 1) -> str:
for idx in range(0, len(commands), num_per_col):
text = cmd_text(commands[idx : idx + num_per_col], start=idx + 1)
imgs.append(Text2Image.from_text(text, 30).to_image(padding=(20, 10)))
w = max(sum((img.width for img in imgs)), head.width)
h = head.height + max((img.height for img in imgs))
w = max(sum(img.width for img in imgs), head.width)
h = head.height + max(img.height for img in imgs)
frame = BuildImage.new("RGBA", (w, h), "white")
frame.paste(head, alpha=True)
current_w = 0
Expand All @@ -81,39 +71,28 @@ def cmd_text(commands: List[Command], start: int = 1) -> str:
@help_cmd.handle()
async def _():
img = await help_image()
await MessageFactory([Image(img)]).send()
await UniMessage.image(raw=img).send()


def handler(command: Command) -> T_Handler:
async def handle(
bot: Bot,
event: Event,
matcher: Matcher,
res: Union[str, BytesIO, List[BytesIO]] = Depends(command.func),
):
if isinstance(res, str):
await matcher.finish(res)
elif isinstance(res, BytesIO):
await MessageFactory([Image(res)]).send()
await UniMessage.image(raw=res).send()
else:
if len(res) > imagetools_config.imagetools_zip_threshold:
zip_file = zip_images(res)
filename = f"{command.keywords[0]}_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.zip"
try:
file = File(
raw=zip_file.getvalue(),
name=filename,
mimetype="application/zip",
)
await UniMessage([file]).send(event, bot)
except:
logger.warning(f"上传文件失败:{traceback.format_exc()}")

if len(res) <= imagetools_config.imagetools_max_forward_msg_num:
try:
await AggregatedMessageFactory([Image(img) for img in res]).send()
except:
logger.warning(f"合并消息发送失败: {traceback.format_exc()}")
time_str = datetime.now().strftime("%Y-%m-%d_%H%M%S")
filename = f"{command.keywords[0]}_{time_str}.zip"
await UniMessage.file(
raw=zip_file.getvalue(), name=filename, mimetype="application/zip"
).send()
else:
await UniMessage(Image(raw=img) for img in res).send()

return handle

Expand Down
3 changes: 0 additions & 3 deletions nonebot_plugin_imagetools/color_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@
"暗绿": "#006400",
"绿色": "#008000",
"鲜绿色": "#00FF00",
"孔雀石绿": "#22C32E",
"薄荷绿": "#16982B",
"青瓷绿": "#ACE1AF",
"孔雀石绿": "#73E68C",
Expand Down Expand Up @@ -194,7 +193,6 @@
"亮岩灰": "#778899",
"蓝紫": "#8A2BE2",
"暗洋红": "#8B008B",
"梅红色": "#8E4585",
"天空蓝": "#87CEEB",
"浅天蓝": "#87CEFA",
"勃艮第酒红": "#800020",
Expand All @@ -210,7 +208,6 @@
"优品紫红": "#B784A7",
"淡紫丁香色": "#E6CFE6",
"矿紫": "#A39DAE",
"亮紫": "#B09DB9",
"紫藤色": "#C9A0DC",
"紫丁香色": "#C8A2C8",
"梅红色": "#DDA0DD",
Expand Down
14 changes: 5 additions & 9 deletions nonebot_plugin_imagetools/config.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
from nonebot import get_driver
from pydantic import BaseModel, Extra
from nonebot import get_plugin_config
from pydantic import BaseModel


class Config(BaseModel, extra=Extra.ignore):
imagetools_zip_threshold: int = 20
class Config(BaseModel):
imagetools_zip_threshold: int = 10
"""
输出图片数量大于该数目时,打包为zip以文件形式发送
"""
imagetools_max_forward_msg_num: int = 99
"""
合并转发消息条数上限
"""


imagetools_config = Config.parse_obj(get_driver().config.dict())
imagetools_config = get_plugin_config(Config)
28 changes: 27 additions & 1 deletion nonebot_plugin_imagetools/data_source.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,30 @@
from .functions import *
from .functions import (
blur,
color_image,
color_mask,
contour,
crop,
emboss,
flip_horizontal,
flip_vertical,
four_grid,
gif_change_fps,
gif_join,
gif_obverse_reverse,
gif_reverse,
gif_split,
gradient_image,
grey,
horizontal_join,
invert,
nine_grid,
pixelate,
resize,
rotate,
sharpen,
t2p,
vertical_join,
)
from .utils import Command

commands = [
Expand Down
4 changes: 2 additions & 2 deletions nonebot_plugin_imagetools/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async def dependency(
)
if isinstance(result, bytes):
imgs.append(result)
except:
except Exception:
logger.warning(f"Fail to fetch image: {traceback.format_exc()}")

return [BuildImage.open(BytesIO(img)) for img in imgs]
Expand All @@ -63,7 +63,7 @@ def Args():
async def dependency(arg: str = Arg()):
try:
args = shlex.split(arg)
except:
except Exception:
args = arg.split()
args = [a for a in args if a]
return args
Expand Down
30 changes: 15 additions & 15 deletions nonebot_plugin_imagetools/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,12 @@ def gif_join(imgs: List[BuildImage] = Imgs(), arg: str = Arg()):

def four_grid(img: BuildImage = Img(), arg=NoArg()):
img = img.square()
l = img.width // 2
a = img.width // 2
boxes = [
(0, 0, l, l),
(l, 0, l * 2, l),
(0, l, l, l * 2),
(l, l, l * 2, l * 2),
(0, 0, a, a),
(a, 0, a * 2, a),
(0, a, a, a * 2),
(a, a, a * 2, a * 2),
]
output: List[BytesIO] = []
for box in boxes:
Expand All @@ -289,17 +289,17 @@ def four_grid(img: BuildImage = Img(), arg=NoArg()):
def nine_grid(img: BuildImage = Img(), arg=NoArg()):
img = img.square()
w = img.width
l = img.width // 3
a = img.width // 3
boxes = [
(0, 0, l, l),
(l, 0, l * 2, l),
(l * 2, 0, w, l),
(0, l, l, l * 2),
(l, l, l * 2, l * 2),
(l * 2, l, w, l * 2),
(0, l * 2, l, w),
(l, l * 2, l * 2, w),
(l * 2, l * 2, w, w),
(0, 0, a, a),
(a, 0, a * 2, a),
(a * 2, 0, w, a),
(0, a, a, a * 2),
(a, a, a * 2, a * 2),
(a * 2, a, w, a * 2),
(0, a * 2, a, w),
(a, a * 2, a * 2, w),
(a * 2, a * 2, w, w),
]
output: List[BytesIO] = []
for box in boxes:
Expand Down
3 changes: 1 addition & 2 deletions nonebot_plugin_imagetools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ async def download_url(url: str) -> bytes:


class Maker(Protocol):
def __call__(self, img: BuildImage) -> BuildImage:
...
def __call__(self, img: BuildImage) -> BuildImage: ...


def get_avg_duration(image: IMG) -> float:
Expand Down
Loading

0 comments on commit eacfb1f

Please sign in to comment.