Skip to content

Commit

Permalink
Merge pull request #1112 from Teahouse-Studios/py312
Browse files Browse the repository at this point in the history
update python version to 3.12
  • Loading branch information
OasisAkari authored Feb 20, 2024
2 parents 30e4acc + 28e3872 commit dc565be
Show file tree
Hide file tree
Showing 12 changed files with 2,114 additions and 2,112 deletions.
11 changes: 7 additions & 4 deletions bots/aiogram/bot.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import asyncio
import os
import sys

from aiogram import types, executor
from aiogram import types
from aiogram.types import ContentType

from bots.aiogram.client import dp
from bots.aiogram.client import dp, bot
from bots.aiogram.info import client_name
from bots.aiogram.message import MessageSession, FetchTarget
from core.builtins import PrivateAssets, Url
Expand All @@ -17,7 +18,7 @@
Url.disable_mm = True


@dp.message_handler(content_types=[ContentType.TEXT, ContentType.PHOTO, ContentType.AUDIO])
@dp.message()
async def msg_handler(message: types.Message):
target_id = f'Telegram|{message.chat.type}|{message.chat.id}'
reply_id = None
Expand All @@ -42,4 +43,6 @@ async def on_startup(dispatcher):
if 'subprocess' in sys.argv:
Info.subprocess = True

executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
dp.startup.register(on_startup)

asyncio.run(dp.start_polling(bot))
4 changes: 2 additions & 2 deletions bots/aiogram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
token = Config('tg_token')

if token:
bot = Bot(token=token, proxy=Config('proxy'))
dp = Dispatcher(bot)
bot = Bot(token=token)
dp = Dispatcher()
else:
bot = dp = False
36 changes: 17 additions & 19 deletions bots/aiogram/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import List, Union

from bots.aiogram.client import dp, bot, token
from aiogram.types import FSInputFile
from bots.aiogram.info import client_name
from config import Config
from core.builtins import Bot, Plain, Image, Voice, MessageSession as MessageSessionT, ErrorMessage, MessageTaskManager
Expand Down Expand Up @@ -58,33 +59,30 @@ async def send_message(self, message_chain, quote=True, disable_secret_check=Fal
if allow_split_image:
split = await image_split(x)
for xs in split:
with open(await xs.get(), 'rb') as image:
send_ = await bot.send_photo(self.session.target, image,
reply_to_message_id=self.session.message.message_id
if quote
and count == 0
and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(xs.__dict__)}')
send.append(send_)
count += 1
else:
with open(await x.get(), 'rb') as image:
send_ = await bot.send_photo(self.session.target, image,
send_ = await bot.send_photo(self.session.target, FSInputFile(await xs.get()),
reply_to_message_id=self.session.message.message_id
if quote
and count == 0
and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(x.__dict__)}')
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(xs.__dict__)}')
send.append(send_)
count += 1
elif isinstance(x, Voice):
with open(x.path, 'rb') as voice:
send_ = await bot.send_audio(self.session.target, voice,
reply_to_message_id=self.session.message.message_id if quote
and count == 0 and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Voice: {str(x.__dict__)}')
else:
send_ = await bot.send_photo(self.session.target, FSInputFile(await x.get()),
reply_to_message_id=self.session.message.message_id
if quote
and count == 0
and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(x.__dict__)}')
send.append(send_)
count += 1
elif isinstance(x, Voice):
send_ = await bot.send_audio(self.session.target, FSInputFile(x.path),
reply_to_message_id=self.session.message.message_id if quote
and count == 0 and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Voice: {str(x.__dict__)}')
send.append(send_)
count += 1

msg_ids = []
for x in send:
Expand Down
2 changes: 1 addition & 1 deletion console.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def send_command(msg):

if __name__ == '__main__':
init_bot()
loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
loop.create_task(console_scheduler())
loop.create_task(console_command())
loop.run_forever()
2 changes: 1 addition & 1 deletion core/loader/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def load_modules():
continue
modules = 'modules.' + fun_file
importlib.import_module(modules)
Logger.debug(f'Successfully loaded modules. {fun_file}!')
Logger.debug(f'Successfully loaded modules.{fun_file}!')
except Exception:
tb = traceback.format_exc()
errmsg = f'Failed to load modules.{fun_file}: \n{tb}'
Expand Down
9 changes: 7 additions & 2 deletions core/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ async def image_split(i: Image) -> List[Image]:
return i_list


def get_fontsize(font, text):
left, top, right, bottom = font.getbbox(text)
return right - left, bottom - top


save_source = True


Expand Down Expand Up @@ -102,8 +107,8 @@ async def msgchain2image(message_chain: Union[List, MessageChain], msg: MessageS
data = await fi.read()
try:
ftt = ft.match(data)
lst.append(
f'<img src="data:{ftt.mime};base64,{(base64.encodebytes(data)).decode("utf-8")}" width="720" />')
lst.append(f'<img src="data:{ftt.mime};base64,{
(base64.encodebytes(data)).decode("utf-8")}" width="720" />')
except TypeError:
traceback.print_exc()
if isinstance(m, Voice):
Expand Down
2 changes: 1 addition & 1 deletion docs/DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

1. 一台可运行 Python 的服务器或主机(电脑、树莓派、安装了 Termux 的手机、etc...)。

2. 主机已安装并可运行 [Python 3 环境](https://www.python.org/)版本大于 3.9 皆可部署
2. 主机已安装并可运行 [Python 3 环境](https://www.python.org/)版本需大于等于 3.12,低于该版本的运行时环境将不受支持

3. 对应你需要运行的平台所需要的必要内容(环境、token 等)。

Expand Down
19 changes: 11 additions & 8 deletions modules/cytoid/rating.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from core.utils.http import get_url
from core.utils.html2text import html2text
from core.utils.text import parse_time_string
from core.utils.image import get_fontsize


async def get_rating(msg: Bot.MessageSession, uid, query_type):
Expand Down Expand Up @@ -147,7 +148,7 @@ async def mkresources(msg: Bot.MessageSession, x, rank):
mask = Image.new('L', bigsize, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + bigsize, fill=255)
mask = mask.resize(im.size, Image.ANTIALIAS)
mask = mask.resize(im.size, Image.Resampling.LANCZOS)
im.putalpha(mask)
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
Expand All @@ -158,23 +159,25 @@ async def mkresources(msg: Bot.MessageSession, x, rank):

font4 = ImageFont.truetype(os.path.abspath('./assets/Nunito-Regular.ttf'), 35)
drawtext = ImageDraw.Draw(b30img)
get_name_width = font4.getsize(nick)[0]
get_name_width = get_fontsize(font4, nick)[0]
get_img_width = b30img.width
drawtext.text((get_img_width - get_name_width - 150, 30), nick, '#ffffff', font=font4)

font5 = ImageFont.truetype(os.path.abspath('./assets/Noto Sans CJK DemiLight.otf'), 20)
level_text = f'{msg.locale.t("cytoid.message.b30.level")} {profile_level}'
level_text_width = font5.getsize(level_text)[0]
level_text_height = font5.getsize(level_text)[1]
level_text_size = get_fontsize(font5, level_text)
level_text_width = level_text_size[0]
level_text_height = level_text_size[1]
img_level = Image.new("RGBA", (level_text_width + 20, 40), '#050a1a')
drawtext_level = ImageDraw.Draw(img_level)
drawtext_level.text(((img_level.width - level_text_width) / 2, (img_level.height - level_text_height) / 2),
level_text, '#ffffff', font=font5)
b30img.alpha_composite(img_level, (1825 - img_level.width - 20, 85))
font6 = ImageFont.truetype(os.path.abspath('./assets/Nunito-Light.ttf'), 20)
rating_text = f'Rating {str(round(float(profile_rating), 2))}'
rating_text_width = font6.getsize(rating_text)[0]
rating_text_height = font6.getsize(rating_text)[1]
rating_text_size = get_fontsize(font6, rating_text)
rating_text_width = rating_text_size[0]
rating_text_height = rating_text_size[1]
img_rating = Image.new("RGBA", (rating_text_width + 20, 40), '#050a1a')
drawtext_level = ImageDraw.Draw(img_rating)
drawtext_level.text(((img_rating.width - rating_text_width) / 2, (img_rating.height - rating_text_height) / 2),
Expand Down Expand Up @@ -309,13 +312,13 @@ async def make_songcard(coverpath, chart_type, difficulty, chart_name, score, ac
f'Acc: {round(acc, 4)} Perfect: {details["perfect"]} Great: {details["great"]} Good: {details["good"]}'
f'\nRating: {round(rt, 4)} Bad: {details["bad"]} Miss: {details["miss"]}', font=font2)
playtime = f'{playtime} #{rank}'
playtime_width = font3.getsize(playtime)[0]
playtime_width = get_fontsize(font3, playtime)[0]
songimg_width = 384
drawtext.text((songimg_width - playtime_width - 15, 205), playtime, '#ffffff', font=font3)
type_ = str(difficulty)
type_text = Image.new('RGBA', (32, 32))
draw_typetext = ImageDraw.Draw(type_text)
draw_typetext.text(((32 - font3.getsize(type_)[0] - font.getoffset(type_)[0]) / 2, 0), type_, "#ffffff", font=font3)
draw_typetext.text(((32 - get_fontsize(font3, type_)[0]) / 2, 0), type_, "#ffffff", font=font3)
img.alpha_composite(type_text, (23, 29))
Logger.debug('Image generated: ' + str(rank))
return {int(rank): img}
5 changes: 3 additions & 2 deletions modules/maimai/libraries/maimaidx_best50.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from core.builtins import ErrorMessage
from core.utils.http import post_url
from core.utils.image import get_fontsize
from .maimaidx_music import get_cover_len5_id, TotalList

total_list = TotalList()
Expand Down Expand Up @@ -349,8 +350,8 @@ def draw(self):
font2 = ImageFont.truetype('assets/Noto Sans CJK DemiLight.otf', 14, encoding='utf-8')
playCountInfo = f'SD: {self.sdRating} + DX: {self.dxRating} = {self.playerRating}'
shougouImgW, shougouImgH = shougouImg.size
playCountInfoW, playCountInfoH = shougouDraw.textsize(playCountInfo, font2)
textPos = ((shougouImgW - playCountInfoW - font2.getoffset(playCountInfo)[0]) / 2, 5)
playCountInfoW, playCountInfoH = get_fontsize(font2, playCountInfo)
textPos = ((shougouImgW - playCountInfoW) / 2, 5)
shougouDraw.text((textPos[0] - 1, textPos[1]), playCountInfo, 'black', font2)
shougouDraw.text((textPos[0] + 1, textPos[1]), playCountInfo, 'black', font2)
shougouDraw.text((textPos[0], textPos[1] - 1), playCountInfo, 'black', font2)
Expand Down
Loading

0 comments on commit dc565be

Please sign in to comment.