Skip to content

Commit

Permalink
Merge branch 'Teahouse-Studios:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
ZoruaFox authored Sep 29, 2024
2 parents 9ddf660 + 7e06207 commit ed06104
Show file tree
Hide file tree
Showing 14 changed files with 53 additions and 51 deletions.
22 changes: 11 additions & 11 deletions bots/aiocqhttp/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,40 +97,40 @@ async def send_message(self, message_chain, quote=True, disable_secret_check=Fal
message_chain = MessageChain(message_chain)
message_chain_assendable = message_chain.as_sendable(self, embed=False)

msg = MessageSegment.text('')
convert_msg_segments = MessageSegment.text('')
if quote and self.target.target_from == 'QQ|Group' and self.session.message:
msg = MessageSegment.reply(self.session.message.message_id)
convert_msg_segments = MessageSegment.reply(self.session.message.message_id)

if not message_chain.is_safe and not disable_secret_check:
return await self.send_message(I18NContext("error.message.chain.unsafe"))
self.sent.append(message_chain)
count = 0
for x in message_chain_assendable:
if isinstance(x, Plain):
msg = msg + MessageSegment.text(('\n' if count != 0 else '') + x.text)
convert_msg_segments = convert_msg_segments + MessageSegment.text(('\n' if count != 0 else '') + x.text)
elif isinstance(x, Image):
msg = msg + MessageSegment.image('base64://' + await x.get_base64())
convert_msg_segments = convert_msg_segments + MessageSegment.image('base64://' + await x.get_base64())
elif isinstance(x, Voice):
if self.target.target_from != 'QQ|Guild':
msg = msg + MessageSegment.record(file=Path(x.path).as_uri())
convert_msg_segments = convert_msg_segments + MessageSegment.record(file=Path(x.path).as_uri())
count += 1
Logger.info(f'[Bot] -> [{self.target.target_id}]: {message_chain_assendable}')
if self.target.target_from == 'QQ|Group':
try:
send = await bot.send_group_msg(group_id=self.session.target, message=msg)
send = await bot.send_group_msg(group_id=self.session.target, message=convert_msg_segments)
except aiocqhttp.exceptions.NetworkError:
send = await bot.send_group_msg(group_id=self.session.target, message=MessageSegment.text(
self.locale.t("error.message.timeout")))
except aiocqhttp.exceptions.ActionFailed:
img_chain = message_chain.copy()
img_chain.insert(0, I18NContext("error.message.limited.msg2img"))
imgs = await msgchain2image(img_chain, self)
msg2img = MessageSegment.text('')
msgsgm = MessageSegment.text('')
for img in imgs:
im = Image(img)
msg2img += MessageSegment.image('base64://' + await im.get_base64())
msgsgm = msgsgm + MessageSegment.image('base64://' + await im.get_base64())
try:
send = await bot.send_group_msg(group_id=self.session.target, message=msg2img)
send = await bot.send_group_msg(group_id=self.session.target, message=msgsgm)
except aiocqhttp.exceptions.ActionFailed as e:
raise SendMessageFailed(e.result['wording'])

Expand All @@ -140,10 +140,10 @@ async def send_message(self, message_chain, quote=True, disable_secret_check=Fal
elif self.target.target_from == 'QQ|Guild':
match_guild = re.match(r'(.*)\|(.*)', self.session.target)
send = await bot.call_action('send_guild_channel_msg', guild_id=int(match_guild.group(1)),
channel_id=int(match_guild.group(2)), message=msg)
channel_id=int(match_guild.group(2)), message=convert_msg_segments)
else:
try:
send = await bot.send_private_msg(user_id=self.session.target, message=msg)
send = await bot.send_private_msg(user_id=self.session.target, message=convert_msg_segments)
except aiocqhttp.exceptions.ActionFailed as e:
if self.session.message.detail_type == 'private' and self.session.message.sub_type == 'group':
return FinishedSession(self, 0, [{}])
Expand Down
8 changes: 4 additions & 4 deletions core/builtins/message/internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import aiohttp
import filetype
from PIL import Image as PImage
from PIL import Image as PILImage
from tenacity import retry, stop_after_attempt

from config import Config
Expand Down Expand Up @@ -165,7 +165,7 @@ def __init__(self,
self.need_get = False
self.path = path
self.headers = headers
if isinstance(path, PImage.Image):
if isinstance(path, PILImage.Image):
save = f'{Config("cache_path", "./cache/")}{str(uuid.uuid4())}.png'
path.convert('RGBA').save(save)
self.path = save
Expand Down Expand Up @@ -204,10 +204,10 @@ def to_dict(self):
return {'type': 'image', 'data': {'path': self.path}}

async def add_random_noise(self) -> Self:
image = PImage.open(await self.get())
image = PILImage.open(await self.get())
image = image.convert('RGBA')

noise_image = PImage.new('RGBA', (50, 50))
noise_image = PILImage.new('RGBA', (50, 50))
for i in range(50):
for j in range(50):
noise_image.putpixel((i, j), (i, j, i, random.randint(0, 1)))
Expand Down
4 changes: 2 additions & 2 deletions core/console/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import List, Union

from inputimeout import inputimeout, TimeoutOccurred
from PIL import Image as PImage
from PIL import Image as PILImage

from config import Config
from core.builtins import (Plain, I18NContext, Image, confirm_command, Bot, FetchTarget as FetchTargetT,
Expand Down Expand Up @@ -42,7 +42,7 @@ async def send_message(self, message_chain, quote=True, disable_secret_check=Fal
Logger.info(f'[Bot] -> [{self.target.target_id}]: {x.text}')
elif isinstance(x, Image):
image_path = await x.get()
img = PImage.open(image_path)
img = PILImage.open(image_path)
img.show()
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {image_path}')
return FinishedSession(self, [0], ['Should be a callable here... hmm...'])
Expand Down
4 changes: 2 additions & 2 deletions core/types/message/internal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Union, List

from PIL import Image as PImage
from PIL import Image as PILImage


class Plain:
Expand Down Expand Up @@ -90,7 +90,7 @@ class Image:
"""

def __init__(self,
path: Union[str, PImage.Image], headers=None):
path: Union[str, PILImage.Image], headers=None):
"""
:param path: 图片路径或PIL.Image对象
:param headers: 获取图片时的请求头
Expand Down
12 changes: 6 additions & 6 deletions core/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import aiohttp
import filetype as ft
import ujson as json
from PIL import Image as PImage
from PIL import Image as PILImage
from aiofile import async_open

from core.builtins import Plain, Image, Voice, Embed, MessageChain, MessageSession
Expand All @@ -17,7 +17,7 @@


async def image_split(i: Image) -> List[Image]:
i = PImage.open(await i.get())
i = PILImage.open(await i.get())
iw, ih = i.size
if ih <= 1500:
return [Image(i)]
Expand All @@ -41,7 +41,7 @@ def get_fontsize(font, text):
save_source = True


async def msgchain2image(message_chain: Union[List, MessageChain], msg: MessageSession = None, use_local=True) -> Union[List[PImage], bool]:
async def msgchain2image(message_chain: Union[List, MessageChain], msg: MessageSession = None, use_local=True) -> Union[List[PILImage], bool]:
'''使用Webrender将消息链转换为图片。
:param message_chain: 消息链或消息链列表。
Expand Down Expand Up @@ -151,12 +151,12 @@ async def msgchain2image(message_chain: Union[List, MessageChain], msg: MessageS
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = PImage.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)
return img_lst


async def svg_render(file_path: str, use_local=True) -> Union[List[PImage], bool]:
async def svg_render(file_path: str, use_local=True) -> Union[List[PILImage], bool]:
'''使用Webrender渲染svg文件。
:param message_chain: svg文件路径。
Expand Down Expand Up @@ -260,6 +260,6 @@ async def svg_render(file_path: str, use_local=True) -> Union[List[PImage], bool
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = PImage.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)
return img_lst
6 changes: 3 additions & 3 deletions core/utils/image_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .http import download
from .web_render import WebRender, webrender

from PIL import Image as PImage
from PIL import Image as PILImage


class ImageTable:
Expand All @@ -23,7 +23,7 @@ def __init__(self, data, headers):
self.headers = headers


async def image_table_render(table: Union[ImageTable, List[ImageTable]], save_source=True, use_local=True) -> Union[List[PImage], bool]:
async def image_table_render(table: Union[ImageTable, List[ImageTable]], save_source=True, use_local=True) -> Union[List[PILImage], bool]:
if not WebRender.status:
return False
elif not WebRender.local:
Expand Down Expand Up @@ -97,7 +97,7 @@ async def image_table_render(table: Union[ImageTable, List[ImageTable]], save_so
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = PImage.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)
return img_lst

Expand Down
4 changes: 2 additions & 2 deletions modules/bugtracker/bugtracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import aiohttp
import ujson as json
from PIL import Image
from PIL import Image as PILImage

from core.logger import Logger
from core.utils.http import download, get_url
Expand Down Expand Up @@ -40,7 +40,7 @@ async def make_screenshot(page_link, use_local=True):
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = Image.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)
return img_lst
else:
Expand Down
4 changes: 2 additions & 2 deletions modules/mcplayer/mojang_api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ujson as json
from PIL import Image
from PIL import Image as PILImage

from core.logger import Logger
from core.utils.http import get_url, download
Expand Down Expand Up @@ -28,7 +28,7 @@ async def uuid_to_skin_and_cape(uuid):
is_cape = False
path = None
if is_cape:
cape = Image.open(await download(
cape = PILImage.open(await download(
'https://crafatar.com/capes/' + uuid))
cape.crop((0, 0, 10, 16))
path = 'cache/' + uuid + '_fixed.png'
Expand Down
6 changes: 3 additions & 3 deletions modules/tweet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from core.utils.http import download, get_url
from core.utils.text import isint
from core.utils.web_render import webrender
from PIL import Image as PImage
from PIL import Image as PILImage


t = module('tweet',
Expand Down Expand Up @@ -98,7 +98,7 @@ async def _(msg: Bot.MessageSession, tweet: str):
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = PImage.open(bio)
img_lst.append(bimg)
bimg = PILImage.open(bio)
img_lst.append(Image(bimg))
img_lst.append(Url(f"https://twitter.com/{res_json['data']['user']['screen_name']}/status/{tweet_id}"))
await msg.finish(img_lst)
12 changes: 7 additions & 5 deletions modules/wiki/inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,15 @@ async def bgtask():
if get_page.sections:
session_data = [[str(i + 1), get_page.sections[i]] for i in
range(len(get_page.sections))]
i_msg_lst.append(I18NContext('wiki.message.invalid_section.prompt' if (
get_page.invalid_section and wiki_.wiki_info.in_allowlist) else 'wiki.message.talk_page.prompt'))
i_msg_lst.append(
I18NContext(
'wiki.message.invalid_section.prompt' if (
get_page.invalid_section and wiki_.wiki_info.in_allowlist) else 'wiki.message.talk_page.prompt'))
i_msg_lst += [Image(ii) for ii in await
image_table_render(
ImageTable(session_data,
image_table_render(
ImageTable(session_data,
[msg.locale.t('wiki.message.table.header.id'),
msg.locale.t('wiki.message.table.header.section')]))]
msg.locale.t('wiki.message.table.header.section')]))]
i_msg_lst.append(I18NContext('wiki.message.invalid_section.select'))
i_msg_lst.append(I18NContext('message.reply.prompt'))

Expand Down
12 changes: 6 additions & 6 deletions modules/wiki/utils/screenshot_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
from core.utils.http import download
from core.utils.web_render import WebRender, webrender

from PIL import Image
from PIL import Image as PILImage

elements = ['.notaninfobox', '.portable-infobox', '.infobox', '.tpl-infobox', '.infoboxtable', '.infotemplatebox',
'.skin-infobox', '.arcaeabox', '.moe-infobox', '.rotable']


async def generate_screenshot_v2(page_link: str, section: str = None, allow_special_page=False, content_mode=False, use_local=True,
element=None) -> Union[List[Image], bool]:
element=None) -> Union[List[PILImage], bool]:
elements_ = elements.copy()
if element and isinstance(element, List):
elements_ += element
Expand Down Expand Up @@ -89,12 +89,12 @@ async def generate_screenshot_v2(page_link: str, section: str = None, allow_spec
for x in load_img:
b = base64.b64decode(x)
bio = BytesIO(b)
bimg = Image.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)
return img_lst


async def generate_screenshot_v1(link, page_link, headers, use_local=True, section=None, allow_special_page=False) -> Union[List[Image], bool]:
async def generate_screenshot_v1(link, page_link, headers, use_local=True, section=None, allow_special_page=False) -> Union[List[PILImage], bool]:
if not WebRender.status:
return False
elif not WebRender.local:
Expand Down Expand Up @@ -358,7 +358,7 @@ def is_comment(e):
for img in imgs_data:
b = base64.b64decode(img)
bio = BytesIO(b)
bimg = Image.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)

except aiohttp.ClientConnectorError:
Expand All @@ -374,7 +374,7 @@ def is_comment(e):
for img in imgs_data:
b = base64.b64decode(img)
bio = BytesIO(b)
bimg = Image.open(bio)
bimg = PILImage.open(bio)
img_lst.append(bimg)

return img_lst
Expand Down
4 changes: 2 additions & 2 deletions modules/wiki/utils/wikilib.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ async def search_something(srwhat):
page_info.link = full_url
page_info.file = file
page_info.desc = page_desc
if not _iw and not page_info.args and page_info.id != -1:
if not _iw and not page_info.args and page_info.id != -1 and page_info.id:
page_info.link = self.wiki_info.script + f'?curid={page_info.id}'
else:
page_info.title = query_langlinks.title
Expand Down Expand Up @@ -874,7 +874,7 @@ async def search_something(srwhat):
page_info.before_title = before_page_info.title
t = page_info.title
if t:
if before_page_info.args or page_info.id == -1:
if before_page_info.args or page_info.id == -1 or not page_info.id:
page_info.before_title += urllib.parse.unquote(before_page_info.args)
t += urllib.parse.unquote(before_page_info.args)
if page_info.link:
Expand Down
2 changes: 1 addition & 1 deletion modules/wiki/wiki.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ async def query_pages(session: Union[Bot.MessageSession, QueryInfo], title: Unio
if r.invalid_section and r.info.in_allowlist
else 'wiki.message.talk_page.prompt')))
i_msg_lst += [Image(ii) for ii in await
image_table_render(
image_table_render(
ImageTable(session_data,
[session.locale.t('wiki.message.table.header.id'),
session.locale.t('wiki.message.table.header.section')]))]
Expand Down
4 changes: 2 additions & 2 deletions modules/wolframalpha/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
import urllib.parse
from PIL import Image
from PIL import Image as PILImage

from config import Config
from core.builtins import Bot, Image as BImage
Expand Down Expand Up @@ -33,7 +33,7 @@ async def _(msg: Bot.MessageSession, query: str):
try:
img_path = await download(url, status_code=200)
if img_path:
with Image.open(img_path) as img:
with PILImage.open(img_path) as img:
output = os.path.splitext(img_path)[0] + ".png"
img.save(output, "PNG")
os.remove(img_path)
Expand Down

0 comments on commit ed06104

Please sign in to comment.