-
Notifications
You must be signed in to change notification settings - Fork 0
/
R.py
72 lines (57 loc) · 2.22 KB
/
R.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
from urllib.parse import urljoin
from urllib.request import pathname2url
from nonebot import MessageSegment, get_bot
from PIL import Image
import hoshino
from hoshino import logger, util
class ResObj:
def __init__(self, res_path):
res_dir = os.path.expanduser(hoshino.config.RES_DIR)
fullpath = os.path.abspath(os.path.join(res_dir, res_path))
if not fullpath.startswith(os.path.abspath(res_dir)):
raise ValueError('Cannot access outside RESOUCE_DIR')
self.__path = os.path.normpath(res_path)
@property
def url(self):
"""资源文件的url,供酷Q(或其他远程服务)使用"""
return urljoin(hoshino.config.RES_URL, pathname2url(self.__path))
@property
def path(self):
"""资源文件的路径,供bot内部使用"""
return os.path.join(hoshino.config.RES_DIR, self.__path)
@property
def exist(self):
return os.path.exists(self.path)
class ResImg(ResObj):
@property
def cqcode(self) -> MessageSegment:
if hoshino.config.RES_PROTOCOL == 'http':
return MessageSegment.image(self.url)
elif hoshino.config.RES_PROTOCOL == 'file':
return MessageSegment.image(f'file:///{os.path.abspath(self.path)}')
else:
try:
return MessageSegment.image(util.pic2b64(self.open()))
except Exception as e:
hoshino.logger.exception(e)
return MessageSegment.text('[图片出错]')
def open(self) -> Image:
try:
return Image.open(self.path)
except FileNotFoundError:
hoshino.logger.error(f'缺少图片资源:{self.path}')
raise
class ResRec(ResObj):
@property
def cqcode(self) -> MessageSegment:
if hoshino.config.RES_PROTOCOL == 'http':
return MessageSegment.record(self.url)
elif hoshino.config.RES_PROTOCOL == 'file':
return MessageSegment.record(f'file:///{os.path.abspath(self.path)}')
def get(path, *paths):
return ResObj(os.path.join(path, *paths))
def img(path, *paths):
return ResImg(os.path.join('img', path, *paths))
def rec(path, *paths):
return ResRec(os.path.join('record', path, *paths))