nonebot-plugin-splatoon3-schedule 2.0.4__tar.gz → 2.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/PKG-INFO +2 -1
  2. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/config.py +15 -2
  3. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/util.py +24 -15
  4. nonebot_plugin_splatoon3_schedule-2.0.6/nonebot_plugin_splatoon3_schedule/utils/cos_upload.py +381 -0
  5. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/utils/utils.py +10 -2
  6. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/pyproject.toml +2 -1
  7. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/LICENSE +0 -0
  8. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/README.md +0 -0
  9. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/__init__.py +0 -0
  10. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/check.py +0 -0
  11. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/data/__init__.py +0 -0
  12. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/data/data_source.py +0 -0
  13. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/data/db_control.py +0 -0
  14. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/data/db_image.py +0 -0
  15. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/data/static_data_getter.py +0 -0
  16. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/image/__init__.py +0 -0
  17. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/image/image.py +0 -0
  18. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/image/image_processer.py +0 -0
  19. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/image/image_processer_tools.py +0 -0
  20. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/10024.png +0 -0
  21. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/10025.ico +0 -0
  22. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/10026.png +0 -0
  23. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/AREA.png +0 -0
  24. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/CLAM.png +0 -0
  25. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Cohozuna.png +0 -0
  26. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/GOAL.png +0 -0
  27. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Horrorboros.png +0 -0
  28. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/LOFT.png +0 -0
  29. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Megalodontia.png +0 -0
  30. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Random.png +0 -0
  31. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Ranked-Challenge.png +0 -0
  32. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Ranked-Open.png +0 -0
  33. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Ranked.png +0 -0
  34. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Regular.png +0 -0
  35. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/TURF_WAR.png +0 -0
  36. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/Triumvirate.png +0 -0
  37. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/X.png +0 -0
  38. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/bg.png +0 -0
  39. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/bg2.png +0 -0
  40. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/bg3.png +0 -0
  41. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/big_run.png +0 -0
  42. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/black-texture.png +0 -0
  43. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/cat_paw_mask.png +0 -0
  44. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/coop.png +0 -0
  45. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/coop_bg2.png +0 -0
  46. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/coop_fish.png +0 -0
  47. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/coop_mask.png +0 -0
  48. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/event_bg.png +0 -0
  49. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/festival_mask.png +0 -0
  50. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/fight_mask.png +0 -0
  51. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/filleted_corner.png +0 -0
  52. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/private.png +0 -0
  53. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/swim_ring.png +0 -0
  54. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/team_coop.png +0 -0
  55. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/ImageData/time_head_bg.png +0 -0
  56. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/db/image.db +0 -0
  57. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/font/Splatfont1.otf +0 -0
  58. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/font/Splatfont2.otf +0 -0
  59. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/font/cn.ttf +0 -0
  60. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/resource/font/common.otf +0 -0
  61. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/utils/__init__.py +0 -0
  62. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/utils/bot.py +0 -0
  63. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/utils/dataClass.py +0 -0
  64. {nonebot_plugin_splatoon3_schedule-2.0.4 → nonebot_plugin_splatoon3_schedule-2.0.6}/nonebot_plugin_splatoon3_schedule/utils/translation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nonebot-plugin-splatoon3-schedule
3
- Version: 2.0.4
3
+ Version: 2.0.6
4
4
  Summary: 一个基于nonebot2框架的splatoon3游戏日程查询插件
5
5
  License-File: LICENSE
6
6
  Author: cypas
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.14
16
16
  Requires-Dist: Pillow (>=11.3.0,<12.0.0)
17
17
  Requires-Dist: beautifulsoup4 (>=4.12.2,<5.0.0)
18
18
  Requires-Dist: cloudscraper (>=1.2.71,<2.0.0)
19
+ Requires-Dist: cos_python_sdk_v5 (>=1.9.30,<2.0.0)
19
20
  Requires-Dist: httpx (>=0.28.1,<0.29.0)
20
21
  Requires-Dist: nonebot-adapter-kaiheila (>=0.3.4,<0.4.0)
21
22
  Requires-Dist: nonebot-adapter-onebot (>=2.4.6,<3.0.0)
@@ -1,9 +1,20 @@
1
1
  from typing import List, Union
2
2
 
3
- # from nonebot import get_driver
3
+ from nonebot import get_driver
4
4
 
5
5
  from nonebot import get_driver, get_plugin_config
6
- from pydantic import BaseModel, validator
6
+ from pydantic import BaseModel, validator, Field, Extra
7
+
8
+
9
+ class CosConfig(BaseModel, extra=Extra.ignore):
10
+ enabled: bool = False
11
+ secret_id: str = "AKID开头的ID" # 腾讯云API密钥ID
12
+ secret_key: str = "密钥" # 腾讯云API密钥Key
13
+ region: str = "ap-guangzhou" # 存储桶区域
14
+ bucket_name: str = "" # 存储桶名称
15
+ domain: str = "" # 自定义域名(可选)
16
+ upload_path_prefix: str = "meme/" # 默认上传路径前缀
17
+ max_file_size: int = 30 * 1024 * 1024 # 最大文件大小30MB
7
18
 
8
19
 
9
20
  # 其他地方出现的类似 from .. import config,均是从 __init__.py 导入的 Config 实例
@@ -34,6 +45,8 @@ class Config(BaseModel):
34
45
  splatoon3_kk_channel_waste_chat_id: str | int = ""
35
46
  # 部分消息使用qq平台md卡片,开启了也没用,md模版需要在qqbot端进行审核,模板id目前在代码里是写死的
36
47
  splatoon3_qq_md_mode: bool = False
48
+ # 腾讯云cos配置
49
+ splatoon3_cos_config: CosConfig = Field(default_factory=CosConfig)
37
50
 
38
51
 
39
52
  # 本地测试时由于不启动 driver,需要将下面三行注释并取消再下面两行的注释
@@ -10,7 +10,8 @@ from .image.image import (
10
10
  get_coop_stages_image,
11
11
  get_events_image,
12
12
  )
13
- from .utils.utils import get_time_now_china, trigger_with_probability
13
+ from .utils.cos_upload import cos_uploader, cos_upload_file
14
+ from .utils.utils import get_time_now_china, trigger_with_probability, get_image_size
14
15
  from .data import db_control, db_image
15
16
  from .utils.bot import *
16
17
 
@@ -106,7 +107,7 @@ async def send_push(bot: Bot, source_id):
106
107
 
107
108
 
108
109
  async def send_msg(
109
- bot: Bot, event: Event, msg: str | bytes, is_ad=False, is_cache=True
110
+ bot: Bot, event: Event, msg: str | bytes, is_ad=False, is_cache=True
110
111
  ):
111
112
  """公用send_msg"""
112
113
  # 指定回复模式
@@ -178,17 +179,14 @@ async def send_msg(
178
179
  await bot.send(event, Tg_File.photo(img))
179
180
  elif isinstance(bot, Kook_Bot):
180
181
  url = await bot.upload_file(img)
181
- logger.info("url:" + url)
182
+ # logger.info("url:" + url)
182
183
  await bot.send(event, Kook_MsgSeg.image(url), reply_sender=reply_mode)
183
184
  elif isinstance(bot, QQ_Bot):
184
185
  # 目前q群只支持url图片,得想办法上传图片获取url
185
- url = await get_image_url(img, is_cache=False)
186
- logger.info("url:" + url)
186
+ url, image_size = await get_image_url_and_size(img)
187
+ # logger.info("url:" + url)
187
188
  try:
188
189
  if plugin_config.splatoon3_qq_md_mode:
189
- image = Image.open(io.BytesIO(img))
190
- image_size = image.size
191
- image.close()
192
190
  user_id = event.get_user_id()
193
191
  qq_md = await get_qq_md(user_id, image_size, url)
194
192
  await bot.send(event, qq_md)
@@ -198,7 +196,7 @@ async def send_msg(
198
196
  if "消息被去重" in str(e):
199
197
  pass
200
198
  elif "富媒体文件格式不支持" in str(e):
201
- url = await get_image_url(img, is_cache=False)
199
+ url, image_size = await get_image_url_and_size(img)
202
200
  logger.info("图片上传失败,重新强制上传,url:" + url)
203
201
  await bot.send(event, message=QQ_MsgSeg.image(url))
204
202
  else:
@@ -210,24 +208,35 @@ async def send_msg(
210
208
  await send_msg(bot, event, ad_msg, is_ad=True)
211
209
 
212
210
 
213
- async def get_image_url(img: bytes, is_cache) -> str:
214
- """通过kook获取图片url"""
211
+ async def get_image_url_and_size(img_data: bytes) -> tuple[str, tuple[int, int]]:
212
+ """通过cos图床或kook图床获取图片url"""
213
+ url = ""
214
+ image_size = (300, 300)
215
+ # 优先使用腾讯cos上传
216
+ if plugin_config.splatoon3_cos_config.enabled and cos_uploader.client is not None:
217
+ url, image_size = cos_upload_file(img_data)
218
+ if url:
219
+ return url, image_size
220
+ else:
221
+ logger.warning("腾讯cos上传失败,使用kook上传")
222
+
223
+ # 使用kook的接口传图片
215
224
  kook_bot = None
216
225
  bots = nonebot.get_bots()
217
226
  for k, b in bots.items():
218
227
  if isinstance(b, Kook_Bot):
219
228
  kook_bot = b
220
229
  break
221
- url = ""
222
230
  if kook_bot is not None:
223
231
  # 使用kook的接口传图片
224
- url = await kook_bot.upload_file(img)
225
- if url and not is_cache:
232
+ url = await kook_bot.upload_file(img_data)
233
+ image_size = get_image_size(img_data)
234
+ if url:
226
235
  channel_id = plugin_config.splatoon3_kk_channel_waste_chat_id
227
236
  await kook_bot.send_channel_msg(
228
237
  channel_id=channel_id, message=Kook_MsgSeg.image(url)
229
238
  )
230
- return url
239
+ return url, image_size
231
240
 
232
241
 
233
242
  async def send_channel_msg(bot: Bot, source_id, msg: str | bytes):
@@ -0,0 +1,381 @@
1
+ import os, logging, mimetypes, re, sys, hashlib
2
+ import traceback
3
+ from datetime import datetime
4
+ from typing import Optional, Dict, Any, Tuple
5
+ from io import BytesIO
6
+
7
+ from nonebot import logger
8
+
9
+ from .utils import get_image_size
10
+ from .. import plugin_config
11
+
12
+ try:
13
+ from qcloud_cos import CosConfig, CosS3Client
14
+ from qcloud_cos.cos_exception import CosServiceError, CosClientError
15
+ except:
16
+ CosConfig = CosS3Client = None
17
+ CosServiceError = CosClientError = Exception
18
+
19
+
20
+ class COSUploader:
21
+ """腾讯云COS文件上传器
22
+
23
+ 提供文件上传、删除、查询等功能
24
+ """
25
+
26
+ def __init__(self):
27
+ """初始化COS上传器
28
+
29
+ 从配置中读取COS相关配置,初始化COS客户端
30
+ """
31
+ self.config = plugin_config.splatoon3_cos_config
32
+ self.client = None
33
+ self.md5_cache: Dict[str, str] = {} # MD5到URL的缓存
34
+ if self.config.enabled and all([CosConfig, CosS3Client]):
35
+ self._init_client()
36
+
37
+ def _calculate_md5(self, file_data: bytes) -> str:
38
+ """计算文件数据的MD5值
39
+
40
+ Args:
41
+ file_data: 文件数据的bytes类型
42
+
43
+ Returns:
44
+ str: 文件的MD5值(32位十六进制字符串)
45
+ """
46
+ return hashlib.md5(file_data).hexdigest()
47
+
48
+ def _get_cached_url(self, md5: str) -> Optional[str]:
49
+ """从缓存中获取URL
50
+
51
+ Args:
52
+ md5: 文件的MD5值
53
+
54
+ Returns:
55
+ Optional[str]: 缓存的URL,如果不存在则返回None
56
+ """
57
+ return self.md5_cache.get(md5)
58
+
59
+ def _cache_url(self, md5: str, url: str):
60
+ """缓存URL
61
+
62
+ Args:
63
+ md5: 文件的MD5值
64
+ url: 文件的URL
65
+ """
66
+ self.md5_cache[md5] = url
67
+
68
+ def _init_client(self):
69
+ """初始化COS客户端
70
+
71
+ 使用配置中的SecretId、SecretKey和Region初始化腾讯云COS客户端
72
+ """
73
+ try:
74
+ cos_config = CosConfig(Region=self.config.region, SecretId=self.config.secret_id,
75
+ SecretKey=self.config.secret_key, Scheme='https')
76
+ self.client = CosS3Client(cos_config)
77
+ logger.info(f"[cos_uploader]cos_uploader初始化完成")
78
+ except:
79
+ pass
80
+
81
+ def _validate_file(self, file_data: bytes) -> bool:
82
+ """文件大小校验
83
+
84
+ Args:
85
+ file_data: 文件数据的bytes类型
86
+
87
+ Returns:
88
+ bool: 文件大小是否在限制范围内
89
+ """
90
+ return sys.getsizeof(file_data) <= self.config.max_file_size
91
+
92
+ def _generate_cos_key(self, user_id: str = None,
93
+ md5: str = None, file_data: bytes = None,
94
+ width: int = 300, height: int = 300) -> str:
95
+ """生成COS上传路径
96
+
97
+ Args:
98
+ user_id: 用户ID
99
+ md5: 文件的MD5值
100
+ file_data: 文件数据的bytes类型(用于获取扩展名)
101
+
102
+ Returns:
103
+ str: COS上传路径,格式为: 用户ID/MD5.扩展名
104
+ """
105
+ # 使用MD5作为文件名
106
+ ext = self._get_file_extension(file_data)
107
+ filename = f"{md5}_w{width}h{height}{ext}"
108
+
109
+ # 获取上传路径前缀
110
+ upload_prefix = self.config.upload_path_prefix
111
+
112
+ # 确保前缀以/结尾,避免路径拼接问题
113
+ if upload_prefix and not upload_prefix.endswith('/'):
114
+ upload_prefix += '/'
115
+
116
+ if user_id:
117
+ return f"{upload_prefix}{user_id}/{filename}"
118
+ else:
119
+ return f"{upload_prefix}{filename}"
120
+
121
+ def _get_content_type(self, file_data: bytes) -> str:
122
+ """获取文件的Content-Type
123
+
124
+ Args:
125
+ file_data: 文件数据的bytes类型
126
+
127
+ Returns:
128
+ str: 文件的MIME类型,默认为image/jpeg
129
+ """
130
+ # 优先从文件数据获取MIME类型
131
+ if file_data:
132
+ # 读取文件头部字节来判断文件类型
133
+ import imghdr
134
+ image_type = imghdr.what(None, h=file_data[:32])
135
+ if image_type:
136
+ return f'image/{image_type}'
137
+ return 'image/jpeg'
138
+
139
+ def _get_file_extension(self, file_data: bytes) -> str:
140
+ """从文件数据或文件名获取文件扩展名
141
+
142
+ Args:
143
+ file_data: 文件数据的bytes类型
144
+
145
+ Returns:
146
+ str: 文件扩展名(包含点),如.jpg
147
+ """
148
+ # 优先从文件数据获取扩展名
149
+ import imghdr
150
+ image_type = imghdr.what(None, h=file_data[:32])
151
+ if image_type:
152
+ return f'.{image_type}'
153
+ return '.jpg'
154
+
155
+ def upload_file(self, file_data: bytes, user_id: str = None) -> Optional[Dict[str, Any]]:
156
+ """上传文件到COS
157
+
158
+ Args:
159
+ file_data: 文件数据的bytes类型
160
+ user_id: 用户ID,用于生成路径
161
+
162
+ Returns:
163
+ Optional[Dict[str, Any]]: 上传结果字典,包含:
164
+ - success: 是否成功
165
+ - cos_key: COS路径
166
+ - file_url: 文件访问URL
167
+ - file_size: 文件大小
168
+ - width: 图片宽度
169
+ - height: 图片高度
170
+ - px: 尺寸字符串
171
+ - cached: 是否来自缓存
172
+ """
173
+ if not self.config.enabled or not self.client:
174
+ return None
175
+ try:
176
+ if not self._validate_file(file_data):
177
+ return None
178
+
179
+ # 计算文件MD5
180
+ md5 = self._calculate_md5(file_data)
181
+
182
+ # 检查缓存中是否已存在该MD5的URL
183
+ cached_url = self._get_cached_url(md5)
184
+ if cached_url:
185
+ # 从URL中提取尺寸信息
186
+ dimensions = get_image_dimensions_from_url(cached_url)
187
+ if dimensions:
188
+ width, height = dimensions
189
+ else:
190
+ # 如果无法从URL中提取尺寸信息,尝试重新获取,否则则使用默认值
191
+ try:
192
+ width, height = get_image_size(file_data)
193
+ except:
194
+ width, height = (300, 300)
195
+
196
+ # 返回缓存的结果
197
+ return {
198
+ 'success': True,
199
+ 'cos_key': cached_url.replace(_get_cos_base_url() + '/', ''),
200
+ 'file_url': cached_url,
201
+ 'filename': os.path.basename(cached_url),
202
+ 'file_size': sys.getsizeof(file_data),
203
+ 'width': width,
204
+ 'height': height,
205
+ 'px': f'#{width}px #{height}px',
206
+ 'cached': True
207
+ }
208
+
209
+ # 获取图片尺寸
210
+ try:
211
+ dimensions = get_image_size(file_data)
212
+ except:
213
+ dimensions = (300, 300)
214
+ width, height = dimensions
215
+
216
+ # 使用MD5作为文件名生成cos_key
217
+ cos_key = self._generate_cos_key(user_id, md5, file_data, width, height)
218
+ response = self.client.put_object(Bucket=self.config.bucket_name, Body=BytesIO(file_data),
219
+ Key=cos_key, ContentType=self._get_content_type(file_data))
220
+ base_url = f"https://{self.config.domain}" if self.config.domain else \
221
+ f"https://{self.config.bucket_name}.cos.{self.config.region}.myqcloud.com"
222
+ file_url = f"{base_url}/{cos_key}"
223
+ # 将URL存入缓存
224
+ self._cache_url(md5, file_url)
225
+ return {
226
+ 'success': True, 'cos_key': cos_key, 'file_url': file_url,
227
+ 'filename': os.path.basename(cos_key), 'file_size': sys.getsizeof(file_data),
228
+ 'width': width, 'height': height, 'px': f'#{width}px #{height}px',
229
+ 'cached': False
230
+ }
231
+ except:
232
+ if response:
233
+ logger.warning(f"cos上传失败:resp为:{response}\ntraceback:{traceback.format_exc()}")
234
+ else:
235
+ logger.warning(f"cos上传失败:traceback:{traceback.format_exc()}")
236
+ return None
237
+
238
+ def delete_file(self, cos_key: str) -> bool:
239
+ """删除COS上的文件
240
+
241
+ Args:
242
+ cos_key: COS路径
243
+
244
+ Returns:
245
+ bool: 是否删除成功
246
+ """
247
+ if not self.client:
248
+ return False
249
+ try:
250
+ self.client.delete_object(Bucket=self.config.bucket_name, Key=cos_key)
251
+ return True
252
+ except:
253
+ return False
254
+
255
+ def get_file_info(self, cos_key: str) -> Optional[Dict[str, Any]]:
256
+ """获取COS文件信息
257
+
258
+ Args:
259
+ cos_key: COS路径
260
+
261
+ Returns:
262
+ Optional[Dict[str, Any]]: 文件信息字典,包含:
263
+ - cos_key: COS路径
264
+ - content_length: 文件大小
265
+ - content_type: 文件类型
266
+ - last_modified: 最后修改时间
267
+ """
268
+ if not self.client:
269
+ return None
270
+ try:
271
+ response = self.client.head_object(Bucket=self.config.bucket_name, Key=cos_key)
272
+ return {'cos_key': cos_key, 'content_length': response.get('Content-Length'),
273
+ 'content_type': response.get('Content-Type'), 'last_modified': response.get('Last-Modified')}
274
+ except:
275
+ return None
276
+
277
+ def list_files(self, prefix: str = None, max_keys: int = 1000) -> Optional[list]:
278
+ """列出COS上的文件
279
+
280
+ Args:
281
+ prefix: 路径前缀,用于筛选文件
282
+ max_keys: 最大返回数量
283
+
284
+ Returns:
285
+ Optional[list]: 文件列表,每个元素包含:
286
+ - key: COS路径
287
+ - size: 文件大小
288
+ - last_modified: 最后修改时间
289
+ """
290
+ if not self.client:
291
+ return None
292
+ try:
293
+ kwargs = {'Bucket': self.config.bucket_name, 'MaxKeys': max_keys}
294
+ if prefix:
295
+ kwargs['Prefix'] = prefix
296
+ response = self.client.list_objects(**kwargs)
297
+ if 'Contents' not in response:
298
+ return []
299
+ return [{'key': obj['Key'], 'size': obj['Size'], 'last_modified': obj['LastModified']} for obj in
300
+ response['Contents']]
301
+ except:
302
+ return None
303
+
304
+
305
+ cos_uploader = COSUploader()
306
+
307
+
308
+ def upload_image(file_data: bytes, user_id: str = None, return_url_only: bool = False):
309
+ """上传图片到COS
310
+
311
+ Args:
312
+ file_data: 图片数据的bytes类型
313
+ user_id: 用户ID
314
+ return_url_only: 是否只返回URL
315
+
316
+ Returns:
317
+ 上传结果或URL
318
+ """
319
+ result = cos_uploader.upload_file(file_data, user_id)
320
+ return result['file_url'] if result and return_url_only else result
321
+
322
+
323
+ def cos_upload_file(file_data: bytes, user_id: str = None):
324
+ """上传文件到COS
325
+
326
+ Args:
327
+ file_data: 文件数据的bytes类型
328
+ user_id: 用户ID
329
+
330
+ Returns:
331
+ 上传结果
332
+ """
333
+ result = upload_image(file_data, user_id)
334
+ url = result.get('file_url')
335
+ width = result.get('width', 300)
336
+ height = result.get('height', 300)
337
+ return url, (width, height)
338
+
339
+
340
+ def cos_simple_upload_file(file_data: bytes, user_id: str = None):
341
+ return upload_image(file_data, user_id, return_url_only=True)
342
+
343
+
344
+ def _get_cos_base_url() -> str:
345
+ base_url = f"https://{cos_uploader.config.domain}" if cos_uploader.config.domain else \
346
+ f"https://{cos_uploader.config.bucket_name}.cos.{cos_uploader.config.region}.myqcloud.com"
347
+ return base_url
348
+
349
+
350
+ def get_upload_url(cos_key: str):
351
+ return f"{_get_cos_base_url()}/{cos_key}"
352
+
353
+
354
+ def delete_by_url(file_url: str):
355
+ if not file_url:
356
+ return False
357
+ base_url = _get_cos_base_url()
358
+ return cos_uploader.delete_file(file_url[len(base_url):]) if file_url.startswith(base_url) else False
359
+
360
+
361
+ def get_image_dimensions_from_url(url: str) -> Optional[Tuple[int, int]]:
362
+ """从URL中提取图片的宽高数据
363
+
364
+ Args:
365
+ url: 图片URL,文件名格式为: {md5}_w{width}h{height}{ext}
366
+
367
+ Returns:
368
+ Optional[Tuple[int, int]]: 图片的宽高元组(width, height),如果解析失败则返回None
369
+ """
370
+ try:
371
+ # 从URL中提取文件名
372
+ filename = os.path.basename(url)
373
+ # 使用正则表达式匹配宽高数据
374
+ match = re.search(r'_w(\d+)h(\d+)', filename)
375
+ if match:
376
+ width = int(match.group(1))
377
+ height = int(match.group(2))
378
+ return (width, height)
379
+ return None
380
+ except:
381
+ return None
@@ -1,10 +1,11 @@
1
1
  import datetime
2
+ import io
2
3
  import os
3
4
  import random
4
5
 
5
6
  import cloudscraper
6
7
  import httpx
7
- from PIL import ImageFont
8
+ from PIL import ImageFont, Image
8
9
  from httpx import Response
9
10
 
10
11
  from .dataClass import TimeUtil
@@ -19,7 +20,6 @@ proxy_address = plugin_config.splatoon3_proxy_address
19
20
 
20
21
  proxies = f"http://{proxy_address}" if proxy_address else None
21
22
 
22
-
23
23
  # 背景 rgb颜色
24
24
  dict_bg_rgb = {
25
25
  "Turf War": (24, 200, 26),
@@ -170,3 +170,11 @@ def ttf_get_size(font: ImageFont.FreeTypeFont, text: str) -> tuple:
170
170
  height = bbox[3] - bbox[1] # 文本高度
171
171
  time_text_size = (width, height) # 与原 getsize() 返回格式一致
172
172
  return time_text_size
173
+
174
+
175
+ def get_image_size(img_data):
176
+ # 通过pillow库获取图片宽高数据
177
+ image = Image.open(io.BytesIO(img_data))
178
+ width, height = image.size
179
+ image.close()
180
+ return width, height
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "nonebot-plugin-splatoon3-schedule"
3
- version = "2.0.4"
3
+ version = "2.0.6"
4
4
  description = "一个基于nonebot2框架的splatoon3游戏日程查询插件"
5
5
  authors = ["cypas <ayano05@outlook.com>"]
6
6
  readme = "README.md"
@@ -21,6 +21,7 @@ nonebot-adapter-kaiheila = "^0.3.4"
21
21
  nonebot-adapter-qq = "^1.6.6"
22
22
  nonebot-plugin-apscheduler = "^0.5.0"
23
23
  nonebot_plugin_datastore = "^1.3.0"
24
+ cos_python_sdk_v5 = "^1.9.30"
24
25
 
25
26
  [tool.poetry.group.test.dependencies]
26
27
  nonebug = "^0.3.5"