id
int64 0
190k
| prompt
stringlengths 21
13.4M
| docstring
stringlengths 1
12k
⌀ |
---|---|---|
188,131 | import re
from typing import Any, Dict
from nonebot.adapters.onebot.v11 import Bot, Message, unescape
from nonebot.exception import MockApiException
from services.log import logger
from utils.manager import group_manager
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def _(bot: Bot, api: str, data: Dict[str, Any]):
r = None
task = None
group_id = None
try:
if (
api == "send_msg" and data.get("message_type") == "group"
) or api == "send_group_msg":
msg = unescape(
data["message"].strip()
if isinstance(data["message"], str)
else str(data["message"]["text"]).strip()
)
if r := re.search(
"^\[\[_task\|(.*)]]",
msg,
):
if r.group(1) in group_manager.get_task_data().keys():
task = r.group(1)
group_id = data["group_id"]
except Exception as e:
logger.error(f"TaskHook ERROR", "HOOK", e=e)
else:
if task and group_id:
if group_manager.get_group_level(
group_id
) < 0 or not group_manager.check_task_status(task, group_id):
logger.debug(f"被动技能 {task} 处于关闭状态")
raise MockApiException(f"被动技能 {task} 处于关闭状态...")
else:
msg = str(data["message"]).strip()
msg = msg.replace(f"[[_task|{task}]]", "").replace(
f"[[_task|{task}]]", ""
)
data["message"] = Message(msg) | null |
188,132 | from nonebot.adapters.onebot.v11 import (
ActionFailed,
Bot,
GroupMessageEvent,
MessageEvent,
)
from nonebot.matcher import Matcher
from nonebot.message import IgnoredException, run_preprocessor
from nonebot.typing import T_State
from configs.config import Config
from models.ban_user import BanUser
from services.log import logger
from utils.message_builder import at
from utils.utils import BanCheckLimiter
miter(
malicious_check_time,
malicious_ban_count,
)
class BanUser(Model):
async def check_ban_level(cls, user_id: Union[int, str], level: int) -> bool:
async def check_ban_time(cls, user_id: Union[int, str]) -> Union[str, int]:
async def is_ban(cls, user_id: Union[int, str]) -> bool:
async def is_super_ban(cls, user_id: Union[int, str]) -> bool:
async def ban(cls, user_id: Union[int, str], ban_level: int, duration: int):
async def unban(cls, user_id: Union[int, str]) -> bool:
async def _run_script(cls):
class logger:
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
def at(qq: Union[int, str]) -> MessageSegment:
async def _(matcher: Matcher, bot: Bot, event: GroupMessageEvent, state: T_State):
user_id = getattr(event, "user_id", None)
group_id = getattr(event, "group_id", None)
if not isinstance(event, MessageEvent):
return
malicious_ban_time = Config.get_config("hook", "MALICIOUS_BAN_TIME")
if not malicious_ban_time:
raise ValueError("模块: [hook], 配置项: [MALICIOUS_BAN_TIME] 为空或小于0")
if matcher.type == "message" and matcher.priority not in [1, 999]:
if state["_prefix"]["raw_command"]:
if _blmt.check(f'{event.user_id}{state["_prefix"]["raw_command"]}'):
await BanUser.ban(
event.user_id,
9,
malicious_ban_time * 60,
)
logger.info(
f"触发了恶意触发检测: {matcher.plugin_name}", "HOOK", user_id, group_id
)
if isinstance(event, GroupMessageEvent):
try:
await bot.send_group_msg(
group_id=event.group_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
except ActionFailed:
pass
else:
try:
await bot.send_private_msg(
user_id=event.user_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
except ActionFailed:
pass
logger.debug(
f"触发了恶意触发检测: {matcher.plugin_name}", "HOOK", user_id, group_id
)
raise IgnoredException("检测到恶意触发命令")
_blmt.add(f'{event.user_id}{state["_prefix"]["raw_command"]}') | null |
188,133 | from typing import Optional
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
Event,
)
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, run_postprocessor
from nonebot.typing import T_State
from ._utils import (
set_block_limit_false,
AuthChecker,
)
class AuthChecker:
"""
权限检查
"""
def __init__(self):
check_notice_info_cd = Config.get_config("hook", "CHECK_NOTICE_INFO_CD")
if check_notice_info_cd is None or check_notice_info_cd < 0:
raise ValueError("模块: [hook], 配置项: [CHECK_NOTICE_INFO_CD] 为空或小于0")
self._flmt = FreqLimiter(check_notice_info_cd)
self._flmt_g = FreqLimiter(check_notice_info_cd)
self._flmt_s = FreqLimiter(check_notice_info_cd)
self._flmt_c = FreqLimiter(check_notice_info_cd)
async def auth(self, matcher: Matcher, bot: Bot, event: Event):
"""
说明:
权限检查
参数:
:param matcher: matcher
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
group_id = getattr(event, "group_id", None)
try:
if plugin_name := matcher.plugin_name:
# self.auth_hidden(matcher, plugin_name)
cost_gold = await self.auth_cost(plugin_name, bot, event)
user_id = getattr(event, "user_id", None)
group_id = getattr(event, "group_id", None)
# if user_id and str(user_id) not in bot.config.superusers:
await self.auth_basic(plugin_name, bot, event)
self.auth_group(plugin_name, bot, event)
await self.auth_admin(plugin_name, matcher, bot, event)
await self.auth_plugin(plugin_name, matcher, bot, event)
await self.auth_limit(plugin_name, bot, event)
if cost_gold and user_id and group_id:
await BagUser.spend_gold(user_id, group_id, cost_gold)
logger.debug(f"调用功能花费金币: {cost_gold}", "HOOK", user_id, group_id)
except IsSuperuserException:
logger.debug(f"超级用户或被ban跳过权限检测...", "HOOK", user_id, group_id)
# def auth_hidden(self, matcher: Matcher):
# if plugin_data := plugin_data_manager.get(matcher.plugin_name): # type: ignore
async def auth_limit(self, plugin_name: str, bot: Bot, event: Event):
"""
说明:
插件限制
参数:
:param plugin_name: 模块名
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
if not user_id:
return
group_id = getattr(event, "group_id", None)
if plugins2cd_manager.check_plugin_cd_status(plugin_name):
if (
plugin_cd_data := plugins2cd_manager.get_plugin_cd_data(plugin_name)
) and (plugin_data := plugins2cd_manager.get_plugin_data(plugin_name)):
check_type = plugin_cd_data.check_type
limit_type = plugin_cd_data.limit_type
msg = plugin_cd_data.rst
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or plugin_data.check_type == "all"
):
cd_type_ = user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
cd_type_ = event.group_id
if not plugins2cd_manager.check(plugin_name, cd_type_):
if msg:
await send_msg(msg, bot, event) # type: ignore
logger.debug(
f"{plugin_name} 正在cd中...", "HOOK", user_id, group_id
)
raise IgnoredException(f"{plugin_name} 正在cd中...")
else:
plugins2cd_manager.start_cd(plugin_name, cd_type_)
# Block
if plugins2block_manager.check_plugin_block_status(plugin_name):
if plugin_block_data := plugins2block_manager.get_plugin_block_data(
plugin_name
):
check_type = plugin_block_data.check_type
limit_type = plugin_block_data.limit_type
msg = plugin_block_data.rst
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or check_type == "all"
):
block_type_ = user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
block_type_ = event.group_id
if plugins2block_manager.check(block_type_, plugin_name):
if msg:
await send_msg(msg, bot, event) # type: ignore
logger.debug(f"正在调用{plugin_name}...", "HOOK", user_id, group_id)
raise IgnoredException(f"{user_id}正在调用{plugin_name}....")
else:
plugins2block_manager.set_true(block_type_, plugin_name)
# Count
if (
plugins2count_manager.check_plugin_count_status(plugin_name)
and user_id not in bot.config.superusers
):
if plugin_count_data := plugins2count_manager.get_plugin_count_data(
plugin_name
):
limit_type = plugin_count_data.limit_type
msg = plugin_count_data.rst
count_type_ = user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
count_type_ = event.group_id
if not plugins2count_manager.check(plugin_name, count_type_):
if msg:
await send_msg(msg, bot, event) # type: ignore
logger.debug(
f"{plugin_name} count次数限制...", "HOOK", user_id, group_id
)
raise IgnoredException(f"{plugin_name} count次数限制...")
else:
plugins2count_manager.increase(plugin_name, count_type_)
async def auth_plugin(
self, plugin_name: str, matcher: Matcher, bot: Bot, event: Event
):
"""
说明:
插件状态
参数:
:param plugin_name: 模块名
:param matcher: matcher
:param bot: bot
:param event: event
"""
if plugin_name in plugins2settings_manager.keys() and matcher.priority not in [
1,
999,
]:
user_id = getattr(event, "user_id", None)
if not user_id:
return
group_id = getattr(event, "group_id", None)
# 戳一戳单独判断
if (
isinstance(event, GroupMessageEvent)
or isinstance(event, PokeNotifyEvent)
or matcher.plugin_name in other_limit_plugins
) and group_id:
if status_message_manager.get(group_id) is None:
status_message_manager.delete(group_id)
if plugins2settings_manager[
plugin_name
].level > group_manager.get_group_level(group_id):
try:
if (
self._flmt_g.check(user_id)
and plugin_name not in ignore_rst_module
):
self._flmt_g.start_cd(user_id)
await bot.send_group_msg(
group_id=group_id, message="群权限不足..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(group_id)
set_block_limit_false(event, plugin_name)
logger.debug(f"{plugin_name} 群权限不足...", "HOOK", user_id, group_id)
raise IgnoredException("群权限不足")
# 插件状态
if not group_manager.get_plugin_status(plugin_name, group_id):
try:
if plugin_name not in ignore_rst_module and self._flmt_s.check(
group_id
):
self._flmt_s.start_cd(group_id)
await bot.send_group_msg(
group_id=group_id, message="该群未开启此功能.."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(group_id)
set_block_limit_false(event, plugin_name)
logger.debug(f"{plugin_name} 未开启此功能...", "HOOK", user_id, group_id)
raise IgnoredException("未开启此功能...")
# 管理员禁用
if not group_manager.get_plugin_status(
f"{plugin_name}:super", group_id
):
try:
if (
self._flmt_s.check(group_id)
and plugin_name not in ignore_rst_module
):
self._flmt_s.start_cd(group_id)
await bot.send_group_msg(
group_id=group_id, message="管理员禁用了此群该功能..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(group_id)
set_block_limit_false(event, plugin_name)
logger.debug(
f"{plugin_name} 管理员禁用了此群该功能...", "HOOK", user_id, group_id
)
raise IgnoredException("管理员禁用了此群该功能...")
# 群聊禁用
if not plugins_manager.get_plugin_status(
plugin_name, block_type="group"
):
try:
if (
self._flmt_c.check(group_id)
and plugin_name not in ignore_rst_module
):
self._flmt_c.start_cd(group_id)
await bot.send_group_msg(
group_id=group_id, message="该功能在群聊中已被禁用..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(group_id)
set_block_limit_false(event, plugin_name)
logger.debug(
f"{plugin_name} 该插件在群聊中已被禁用...", "HOOK", user_id, group_id
)
raise IgnoredException("该插件在群聊中已被禁用...")
else:
# 私聊禁用
if not plugins_manager.get_plugin_status(
plugin_name, block_type="private"
):
try:
if self._flmt_c.check(user_id):
self._flmt_c.start_cd(user_id)
await bot.send_private_msg(
user_id=user_id, message="该功能在私聊中已被禁用..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(user_id)
set_block_limit_false(event, plugin_name)
logger.debug(
f"{plugin_name} 该插件在私聊中已被禁用...", "HOOK", user_id, group_id
)
raise IgnoredException("该插件在私聊中已被禁用...")
# 维护
if not plugins_manager.get_plugin_status(plugin_name, block_type="all"):
if isinstance(
event, GroupMessageEvent
) and group_manager.check_group_is_white(event.group_id):
raise IsSuperuserException()
try:
if isinstance(event, GroupMessageEvent):
if (
self._flmt_c.check(event.group_id)
and plugin_name not in ignore_rst_module
):
self._flmt_c.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="此功能正在维护..."
)
else:
await bot.send_private_msg(
user_id=user_id, message="此功能正在维护..."
)
except ActionFailed:
pass
if event.is_tome():
id_ = group_id or user_id
status_message_manager.add(id_)
set_block_limit_false(event, plugin_name)
logger.debug(f"{plugin_name} 此功能正在维护...", "HOOK", user_id, group_id)
raise IgnoredException("此功能正在维护...")
async def auth_admin(
self, plugin_name: str, matcher: Matcher, bot: Bot, event: Event
):
"""
说明:
管理员命令 个人权限
参数:
:param plugin_name: 模块名
:param matcher: matcher
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
if not user_id:
return
group_id = getattr(event, "group_id", None)
if plugin_name in admin_manager.keys() and matcher.priority not in [1, 999]:
if isinstance(event, GroupMessageEvent):
# 个人权限
if (
not await LevelUser.check_level(
event.user_id,
event.group_id,
admin_manager.get_plugin_level(plugin_name),
)
and admin_manager.get_plugin_level(plugin_name) > 0
):
try:
if self._flmt.check(event.user_id):
self._flmt.start_cd(event.user_id)
await bot.send_group_msg(
group_id=event.group_id,
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
f"{admin_manager.get_plugin_level(plugin_name)}",
)
except ActionFailed:
pass
set_block_limit_false(event, plugin_name)
if event.is_tome():
status_message_manager.add(event.group_id)
logger.debug(f"{plugin_name} 管理员权限不足...", "HOOK", user_id, group_id)
raise IgnoredException("管理员权限不足")
else:
if not await LevelUser.check_level(
user_id, 0, admin_manager.get_plugin_level(plugin_name)
):
try:
await bot.send_private_msg(
user_id=user_id,
message=f"你的权限不足喔,该功能需要的权限等级:{admin_manager.get_plugin_level(plugin_name)}",
)
except ActionFailed:
pass
set_block_limit_false(event, plugin_name)
if event.is_tome():
status_message_manager.add(user_id)
logger.debug(f"{plugin_name} 管理员权限不足...", "HOOK", user_id, group_id)
raise IgnoredException("权限不足")
def auth_group(self, plugin_name: str, bot: Bot, event: Event):
"""
说明:
群黑名单检测 群总开关检测
参数:
:param plugin_name: 模块名
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
group_id = getattr(event, "group_id", None)
if not group_id:
return
if (
group_manager.get_group_level(group_id) < 0
and str(user_id) not in bot.config.superusers
):
logger.debug(f"{plugin_name} 群黑名单, 群权限-1...", "HOOK", user_id, group_id)
raise IgnoredException("群黑名单")
if not group_manager.check_group_bot_status(group_id):
try:
if str(event.get_message()) != "醒来":
logger.debug(
f"{plugin_name} 功能总开关关闭状态...", "HOOK", user_id, group_id
)
raise IgnoredException("功能总开关关闭状态")
except ValueError:
logger.debug(f"{plugin_name} 功能总开关关闭状态...", "HOOK", user_id, group_id)
raise IgnoredException("功能总开关关闭状态")
async def auth_basic(self, plugin_name: str, bot: Bot, event: Event):
"""
说明:
检测是否满足超级用户权限,是否被ban等
参数:
:param plugin_name: 模块名
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
if not user_id:
return
plugin_setting = plugins2settings_manager.get_plugin_data(plugin_name)
if (
(
not isinstance(event, MessageEvent)
and plugin_name not in other_limit_plugins
)
or await BanUser.is_ban(user_id)
and str(user_id) not in bot.config.superusers
) or (
str(user_id) in bot.config.superusers
and plugin_setting
and not plugin_setting.limit_superuser
):
raise IsSuperuserException()
if plugin_data := plugin_data_manager.get(plugin_name):
if (
plugin_data.plugin_type == PluginType.SUPERUSER
and str(user_id) in bot.config.superusers
):
raise IsSuperuserException()
async def auth_cost(self, plugin_name: str, bot: Bot, event: Event) -> int:
"""
说明:
检测是否满足金币条件
参数:
:param plugin_name: 模块名
:param bot: bot
:param event: event
"""
user_id = getattr(event, "user_id", None)
if not user_id:
return 0
group_id = getattr(event, "group_id", None)
cost_gold = 0
if isinstance(event, GroupMessageEvent) and (
psm := plugins2settings_manager.get_plugin_data(plugin_name)
):
if psm.cost_gold > 0:
if (
await BagUser.get_gold(event.user_id, event.group_id)
< psm.cost_gold
):
await send_msg(f"金币不足..该功能需要{psm.cost_gold}金币..", bot, event)
logger.debug(
f"{plugin_name} 金币限制..该功能需要{psm.cost_gold}金币..",
"HOOK",
user_id,
group_id,
)
raise IgnoredException(f"{plugin_name} 金币限制...")
# 当插件不阻塞超级用户时,超级用户提前扣除金币
if (
str(event.user_id) in bot.config.superusers
and not psm.limit_superuser
):
await BagUser.spend_gold(
event.user_id, event.group_id, psm.cost_gold
)
await UserShopGoldLog.create(
user_id=str(event.user_id),
group_id=str(event.group_id),
type=2,
name=plugin_name,
num=1,
spend_gold=psm.cost_gold,
)
cost_gold = psm.cost_gold
return cost_gold
async def _(matcher: Matcher, bot: Bot, event: Event):
await AuthChecker().auth(matcher, bot, event) | null |
188,134 | from typing import Optional
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
Event,
)
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, run_postprocessor
from nonebot.typing import T_State
from ._utils import (
set_block_limit_false,
AuthChecker,
)
def set_block_limit_false(event, module):
async def _(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: Event,
state: T_State,
):
if not isinstance(event, MessageEvent) and matcher.plugin_name != "poke":
return
module = matcher.plugin_name
set_block_limit_false(event, module) | null |
188,135 | from nonebot.adapters.onebot.v11 import ActionFailed, Bot, Event, GroupMessageEvent
from nonebot.matcher import Matcher
from nonebot.message import IgnoredException, run_preprocessor
from nonebot.typing import T_State
from configs.config import Config
from models.ban_user import BanUser
from services.log import logger
from utils.message_builder import at
from utils.utils import FreqLimiter, is_number, static_flmt
from ._utils import ignore_rst_module, other_limit_plugins
Config.add_plugin_config(
"hook",
"BAN_RESULT",
"才不会给你发消息.",
help_="对被ban用户发送的消息",
)
_flmt = FreqLimiter(300)
class BanUser(Model):
user_id = fields.CharField(255, pk=True)
"""用户id"""
ban_level = fields.IntField()
"""使用ban命令的用户等级"""
ban_time = fields.BigIntField()
"""ban开始的时间"""
duration = fields.BigIntField()
"""ban时长"""
class Meta:
table = "ban_users"
table_description = ".ban/b了 封禁人员数据表"
async def check_ban_level(cls, user_id: Union[int, str], level: int) -> bool:
"""
说明:
检测ban掉目标的用户与unban用户的权限等级大小
参数:
:param user_id: unban用户的用户id
:param level: ban掉目标用户的权限等级
"""
user = await cls.filter(user_id=str(user_id)).first()
if user:
logger.debug(
f"检测用户被ban等级,user_level: {user.ban_level},level: {level}",
target=str(user_id),
)
return bool(user and user.ban_level > level)
return False
async def check_ban_time(cls, user_id: Union[int, str]) -> Union[str, int]:
"""
说明:
检测用户被ban时长
参数:
:param user_id: 用户id
"""
logger.debug(f"获取用户ban时长", target=str(user_id))
if user := await cls.filter(user_id=str(user_id)).first():
if (
time.time() - (user.ban_time + user.duration) > 0
and user.duration != -1
):
return ""
if user.duration == -1:
return "∞"
return int(time.time() - user.ban_time - user.duration)
return ""
async def is_ban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
判断用户是否被ban
参数:
:param user_id: 用户id
"""
logger.debug(f"检测是否被ban", target=str(user_id))
if await cls.check_ban_time(str(user_id)):
return True
else:
await cls.unban(user_id)
return False
async def is_super_ban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
判断用户是否被超级用户ban / b了
参数:
:param user_id: 用户id
"""
logger.debug(f"检测是否被超级用户权限封禁", target=str(user_id))
if user := await cls.filter(user_id=str(user_id)).first():
if user.ban_level == 10:
return True
return False
async def ban(cls, user_id: Union[int, str], ban_level: int, duration: int):
"""
说明:
ban掉目标用户
参数:
:param user_id: 目标用户id
:param ban_level: 使用ban命令用户的权限
:param duration: ban时长,秒
"""
logger.debug(f"封禁用户,等级:{ban_level},时长: {duration}", target=str(user_id))
if await cls.filter(user_id=str(user_id)).first():
await cls.unban(user_id)
await cls.create(
user_id=str(user_id),
ban_level=ban_level,
ban_time=time.time(),
duration=duration,
)
async def unban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
unban用户
参数:
:param user_id: 用户id
"""
if user := await cls.filter(user_id=str(user_id)).first():
logger.debug("解除封禁", target=str(user_id))
await user.delete()
return True
return False
async def _run_script(cls):
return ["ALTER TABLE ban_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE ban_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
]
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
def at(qq: Union[int, str]) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.at 消息
参数:
:param qq: qq号
"""
return MessageSegment.at(qq)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
static_flmt = FreqLimiter(15)
ignore_rst_module = ["ai", "poke", "dialogue"]
other_limit_plugins = ["poke"]
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
user_id = getattr(event, "user_id", None)
group_id = getattr(event, "group_id", None)
if user_id and (
matcher.priority not in [1, 999] or matcher.plugin_name in other_limit_plugins
):
if (
await BanUser.is_super_ban(user_id)
and str(user_id) not in bot.config.superusers
):
logger.debug(f"用户处于超级黑名单中...", "HOOK", user_id, group_id)
raise IgnoredException("用户处于超级黑名单中")
if await BanUser.is_ban(user_id) and str(user_id) not in bot.config.superusers:
time = await BanUser.check_ban_time(user_id)
if isinstance(time, int):
time = abs(int(time))
if time < 60:
time = str(time) + " 秒"
else:
time = str(int(time / 60)) + " 分钟"
else:
time = str(time) + " 分钟"
if isinstance(event, GroupMessageEvent):
if not static_flmt.check(user_id):
logger.debug(f"用户处于黑名单中...", "HOOK", user_id, group_id)
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(user_id)
if matcher.priority != 999:
try:
ban_result = Config.get_config("hook", "BAN_RESULT")
if (
ban_result
and _flmt.check(user_id)
and matcher.plugin_name not in ignore_rst_module
):
_flmt.start_cd(user_id)
await bot.send_group_msg(
group_id=event.group_id,
message=at(user_id)
+ ban_result
+ f" 在..在 {time} 后才会理你喔",
)
except ActionFailed:
pass
else:
if not static_flmt.check(user_id):
logger.debug(f"用户处于黑名单中...", "HOOK", user_id, group_id)
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(user_id)
if matcher.priority != 999:
ban_result = Config.get_config("hook", "BAN_RESULT")
if ban_result and matcher.plugin_name not in ignore_rst_module:
await bot.send_private_msg(
user_id=user_id,
message=at(user_id) + ban_result + f" 在..在 {time}后才会理你喔",
)
logger.debug(f"用户处于黑名单中...", "HOOK", user_id, group_id)
raise IgnoredException("用户处于黑名单中") | null |
188,136 | from nonebot import on_command
from utils.message_builder import image
update_info = on_command("更新信息", aliases={"更新日志"}, priority=5, block=True)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
async def _():
if img := image("update_info.png"):
await update_info.finish(img)
else:
await update_info.finish("目前没有更新信息哦") | null |
188,137 | from typing import Optional, Union
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
from configs.config import NICKNAME
from models.ban_user import BanUser
from models.level_user import LevelUser
from services.log import logger
from utils.utils import is_number
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
The provided code snippet includes necessary dependencies for implementing the `parse_ban_time` function. Write a Python function `def parse_ban_time(msg: str) -> Union[int, str]` to solve the following problem:
解析ban时长 :param msg: 文本消息
Here is the function:
def parse_ban_time(msg: str) -> Union[int, str]:
"""
解析ban时长
:param msg: 文本消息
"""
try:
if not msg:
return -1
msg_split = msg.split()
if len(msg_split) == 1:
if not is_number(msg_split[0].strip()):
return "参数必须是数字!"
return int(msg_split[0]) * 60 * 60
else:
if not is_number(msg_split[0].strip()) or not is_number(
msg_split[1].strip()
):
return "参数必须是数字!"
return int(msg_split[0]) * 60 * 60 + int(msg_split[1]) * 60
except ValueError as e:
logger.error("解析ban时长错误", ".ban", e=e)
return "时间解析错误!" | 解析ban时长 :param msg: 文本消息 |
188,138 | from typing import Optional, Union
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
from configs.config import NICKNAME
from models.ban_user import BanUser
from models.level_user import LevelUser
from services.log import logger
from utils.utils import is_number
class BanUser(Model):
user_id = fields.CharField(255, pk=True)
"""用户id"""
ban_level = fields.IntField()
"""使用ban命令的用户等级"""
ban_time = fields.BigIntField()
"""ban开始的时间"""
duration = fields.BigIntField()
"""ban时长"""
class Meta:
table = "ban_users"
table_description = ".ban/b了 封禁人员数据表"
async def check_ban_level(cls, user_id: Union[int, str], level: int) -> bool:
"""
说明:
检测ban掉目标的用户与unban用户的权限等级大小
参数:
:param user_id: unban用户的用户id
:param level: ban掉目标用户的权限等级
"""
user = await cls.filter(user_id=str(user_id)).first()
if user:
logger.debug(
f"检测用户被ban等级,user_level: {user.ban_level},level: {level}",
target=str(user_id),
)
return bool(user and user.ban_level > level)
return False
async def check_ban_time(cls, user_id: Union[int, str]) -> Union[str, int]:
"""
说明:
检测用户被ban时长
参数:
:param user_id: 用户id
"""
logger.debug(f"获取用户ban时长", target=str(user_id))
if user := await cls.filter(user_id=str(user_id)).first():
if (
time.time() - (user.ban_time + user.duration) > 0
and user.duration != -1
):
return ""
if user.duration == -1:
return "∞"
return int(time.time() - user.ban_time - user.duration)
return ""
async def is_ban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
判断用户是否被ban
参数:
:param user_id: 用户id
"""
logger.debug(f"检测是否被ban", target=str(user_id))
if await cls.check_ban_time(str(user_id)):
return True
else:
await cls.unban(user_id)
return False
async def is_super_ban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
判断用户是否被超级用户ban / b了
参数:
:param user_id: 用户id
"""
logger.debug(f"检测是否被超级用户权限封禁", target=str(user_id))
if user := await cls.filter(user_id=str(user_id)).first():
if user.ban_level == 10:
return True
return False
async def ban(cls, user_id: Union[int, str], ban_level: int, duration: int):
"""
说明:
ban掉目标用户
参数:
:param user_id: 目标用户id
:param ban_level: 使用ban命令用户的权限
:param duration: ban时长,秒
"""
logger.debug(f"封禁用户,等级:{ban_level},时长: {duration}", target=str(user_id))
if await cls.filter(user_id=str(user_id)).first():
await cls.unban(user_id)
await cls.create(
user_id=str(user_id),
ban_level=ban_level,
ban_time=time.time(),
duration=duration,
)
async def unban(cls, user_id: Union[int, str]) -> bool:
"""
说明:
unban用户
参数:
:param user_id: 用户id
"""
if user := await cls.filter(user_id=str(user_id)).first():
logger.debug("解除封禁", target=str(user_id))
await user.delete()
return True
return False
async def _run_script(cls):
return ["ALTER TABLE ban_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE ban_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
]
class LevelUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
user_level = fields.BigIntField()
"""用户权限等级"""
group_flag = fields.IntField(default=0)
"""特殊标记,是否随群管理员变更而设置权限"""
class Meta:
table = "level_users"
table_description = "用户权限数据库"
unique_together = ("user_id", "group_id")
async def get_user_level(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取用户在群内的等级
参数:
:param user_id: 用户id
:param group_id: 群组id
"""
if user := await cls.get_or_none(user_id=str(user_id), group_id=str(group_id)):
return user.user_level
return -1
async def set_level(
cls, user_id: Union[int, str], group_id: Union[int, str], level: int, group_flag: int = 0
):
"""
说明:
设置用户在群内的权限
参数:
:param user_id: 用户id
:param group_id: 群组id
:param level: 权限等级
:param group_flag: 是否被自动更新刷新权限 0:是,1:否
"""
await cls.update_or_create(
user_id=str(user_id),
group_id=str(group_id),
defaults={"user_level": level, "group_flag": group_flag},
)
async def delete_level(cls, user_id: Union[int, str], group_id: Union[int, str]) -> bool:
"""
说明:
删除用户权限
参数:
:param user_id: 用户id
:param group_id: 群组id
"""
if user := await cls.get_or_none(user_id=str(user_id), group_id=str(group_id)):
await user.delete()
return True
return False
async def check_level(cls, user_id: Union[int, str], group_id: Union[int, str], level: int) -> bool:
"""
说明:
检查用户权限等级是否大于 level
参数:
:param user_id: 用户id
:param group_id: 群组id
:param level: 权限等级
"""
if group_id:
if user := await cls.get_or_none(user_id=str(user_id), group_id=str(group_id)):
return user.user_level >= level
else:
user_list = await cls.filter(user_id=str(user_id)).all()
user = max(user_list, key=lambda x: x.user_level)
return user.user_level >= level
return False
async def is_group_flag(cls, user_id: Union[int, str], group_id: Union[int, str]) -> bool:
"""
说明:
检测是否会被自动更新刷新权限
参数:
:param user_id: 用户id
:param group_id: 群组id
"""
if user := await cls.get_or_none(user_id=str(user_id), group_id=str(group_id)):
return user.group_flag == 1
return False
async def _run_script(cls):
return ["ALTER TABLE level_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE level_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE level_users ALTER COLUMN group_id TYPE character varying(255);"
]
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
The provided code snippet includes necessary dependencies for implementing the `a_ban` function. Write a Python function `async def a_ban( qq: int, time: int, user_name: str, event: MessageEvent, ban_level: Optional[int] = None, ) -> str` to solve the following problem:
ban :param qq: qq :param time: ban时长 :param user_name: ban用户昵称 :param event: event :param ban_level: ban级别
Here is the function:
async def a_ban(
qq: int,
time: int,
user_name: str,
event: MessageEvent,
ban_level: Optional[int] = None,
) -> str:
"""
ban
:param qq: qq
:param time: ban时长
:param user_name: ban用户昵称
:param event: event
:param ban_level: ban级别
"""
group_id = None
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
ban_level = await LevelUser.get_user_level(event.user_id, event.group_id)
if not ban_level:
return "未查询到ban级用户权限"
if await BanUser.ban(qq, ban_level, time):
logger.info(
f"封禁 时长 {time / 60} 分钟", ".ban", event.user_id, group_id, qq
)
result = f"已经将 {user_name} 加入{NICKNAME}的黑名单了!"
if time != -1:
result += f"将在 {time / 60} 分钟后解封"
else:
result += f"将在 ∞ 分钟后解封"
else:
ban_time = await BanUser.check_ban_time(qq)
if isinstance(ban_time, int):
ban_time = abs(float(ban_time))
if ban_time < 60:
ban_time = str(ban_time) + " 秒"
else:
ban_time = str(int(ban_time / 60)) + " 分钟"
else:
ban_time += " 分钟"
result = f"{user_name} 已在黑名单!预计 {ban_time}后解封"
return result | ban :param qq: qq :param time: ban时长 :param user_name: ban用户昵称 :param event: event :param ban_level: ban级别 |
188,139 | from utils.manager import plugins2settings_manager
def init():
if plugins2settings_manager.get("update_pic"):
plugins2settings_manager["update_picture"] = plugins2settings_manager["update_pic"]
plugins2settings_manager.delete("update_pic")
if plugins2settings_manager.get("white2black_img"):
plugins2settings_manager["white2black_image"] = plugins2settings_manager["white2black_img"]
plugins2settings_manager.delete("white2black_img")
if plugins2settings_manager.get("send_img"):
plugins2settings_manager["send_image"] = plugins2settings_manager["send_img"]
plugins2settings_manager.delete("send_img") | null |
188,140 | from utils.manager import (
plugins2cd_manager,
plugins2block_manager,
plugins2count_manager,
plugin_data_manager,
)
from utils.utils import get_matchers
from configs.path_config import DATA_PATH
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_plugins_cd_limit` function. Write a Python function `def init_plugins_cd_limit()` to solve the following problem:
加载 cd 限制
Here is the function:
def init_plugins_cd_limit():
"""
加载 cd 限制
"""
plugins2cd_file = DATA_PATH / "configs" / "plugins2cd.yaml"
plugins2cd_file.parent.mkdir(exist_ok=True, parents=True)
for matcher in get_matchers(True):
if not plugins2cd_manager.get_plugin_cd_data(matcher.plugin_name) and (
plugin_data := plugin_data_manager.get(matcher.plugin_name)
):
if plugin_data.plugin_cd:
plugins2cd_manager.add_cd_limit(
matcher.plugin_name, plugin_data.plugin_cd
)
if not plugins2cd_manager.keys():
plugins2cd_manager.add_cd_limit("这是一个示例")
plugins2cd_manager.save()
plugins2cd_manager.reload_cd_limit() | 加载 cd 限制 |
188,141 | from utils.manager import (
plugins2cd_manager,
plugins2block_manager,
plugins2count_manager,
plugin_data_manager,
)
from utils.utils import get_matchers
from configs.path_config import DATA_PATH
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_plugins_block_limit` function. Write a Python function `def init_plugins_block_limit()` to solve the following problem:
加载阻塞限制
Here is the function:
def init_plugins_block_limit():
"""
加载阻塞限制
"""
for matcher in get_matchers(True):
if not plugins2block_manager.get_plugin_block_data(matcher.plugin_name) and (
plugin_data := plugin_data_manager.get(matcher.plugin_name)
):
if plugin_data.plugin_block:
plugins2block_manager.add_block_limit(
matcher.plugin_name, plugin_data.plugin_block
)
if not plugins2block_manager.keys():
plugins2block_manager.add_block_limit("这是一个示例")
plugins2block_manager.save()
plugins2block_manager.reload_block_limit() | 加载阻塞限制 |
188,142 | from utils.manager import (
plugins2cd_manager,
plugins2block_manager,
plugins2count_manager,
plugin_data_manager,
)
from utils.utils import get_matchers
from configs.path_config import DATA_PATH
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_plugins_count_limit` function. Write a Python function `def init_plugins_count_limit()` to solve the following problem:
加载次数限制
Here is the function:
def init_plugins_count_limit():
"""
加载次数限制
"""
for matcher in get_matchers(True):
if not plugins2count_manager.get_plugin_count_data(matcher.plugin_name) and (
plugin_data := plugin_data_manager.get(matcher.plugin_name)
):
if plugin_data.plugin_count:
plugins2count_manager.add_count_limit(
matcher.plugin_name, plugin_data.plugin_count
)
if not plugins2count_manager.keys():
plugins2count_manager.add_count_limit("这是一个示例")
plugins2count_manager.save()
plugins2count_manager.reload_count_limit() | 加载次数限制 |
188,143 | from utils.manager import plugins_manager
from nonebot.adapters.onebot.v11 import Bot
The provided code snippet includes necessary dependencies for implementing the `check_plugin_status` function. Write a Python function `async def check_plugin_status(bot: Bot)` to solve the following problem:
遍历查看插件加载情况
Here is the function:
async def check_plugin_status(bot: Bot):
"""
遍历查看插件加载情况
"""
msg = ""
for plugin in plugins_manager.keys():
data = plugins_manager.get(plugin)
if data.error:
msg += f'{plugin}:{data.plugin_name}\n'
if msg and bot.config.superusers:
msg = "以下插件加载失败..\n" + msg
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=msg.strip()
) | 遍历查看插件加载情况 |
188,144 | from utils.manager import resources_manager, plugin_data_manager
from utils.utils import get_matchers
from services.log import logger
from pathlib import Path
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
The provided code snippet includes necessary dependencies for implementing the `init_plugins_resources` function. Write a Python function `def init_plugins_resources()` to solve the following problem:
资源文件路径的移动
Here is the function:
def init_plugins_resources():
"""
资源文件路径的移动
"""
for matcher in get_matchers(True):
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
try:
_module = matcher.plugin.module
except AttributeError:
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,资源控制未加载...")
else:
if resources := plugin_data.plugin_resources:
path = Path(_module.__getattribute__("__file__")).parent
for resource in resources.keys():
resources_manager.add_resource(
matcher.plugin_name, path / resource, resources[resource]
)
resources_manager.save()
resources_manager.start_move() | 资源文件路径的移动 |
188,145 | import nonebot
from services.log import logger
from utils.manager import admin_manager, plugin_data_manager, plugins2settings_manager
from utils.manager.models import PluginType
from utils.utils import get_matchers
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
lass PluginType(Enum):
"""
插件类型
"""
NORMAL = "normal"
ADMIN = "admin"
HIDDEN = "hidden"
SUPERUSER = "superuser"
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_plugins_settings` function. Write a Python function `def init_plugins_settings()` to solve the following problem:
初始化插件设置,从插件中获取 __zx_plugin_name__,__plugin_cmd__,__plugin_settings__
Here is the function:
def init_plugins_settings():
"""
初始化插件设置,从插件中获取 __zx_plugin_name__,__plugin_cmd__,__plugin_settings__
"""
# for x in plugins2settings_manager.keys():
# try:
# _plugin = nonebot.plugin.get_plugin(x)
# _module = _plugin.module
# _module.__getattribute__("__zx_plugin_name__")
# except (KeyError, AttributeError) as e:
# logger.warning(f"配置文件 模块:{x} 获取 plugin_name 失败...{e}")
for matcher in get_matchers(True):
try:
if (
matcher.plugin_name
and matcher.plugin_name not in plugins2settings_manager.keys()
):
if _plugin := matcher.plugin:
try:
_module = _plugin.module
except AttributeError:
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,插件控制未加载.")
else:
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
if plugin_settings := plugin_data.plugin_setting:
if (
name := _module.__getattribute__(
"__zx_plugin_name__"
)
) not in plugin_settings.cmd:
plugin_settings.cmd.append(name)
# 管理员命令
if plugin_data.plugin_type == PluginType.ADMIN:
admin_manager.add_admin_plugin_settings(
matcher.plugin_name,
plugin_settings.cmd,
plugin_settings.level,
)
else:
plugins2settings_manager.add_plugin_settings(
matcher.plugin_name, plugin_settings
)
except Exception as e:
logger.error(
f"{matcher.plugin_name} 初始化 plugin_settings 发生错误 {type(e)}:{e}"
)
plugins2settings_manager.save()
logger.info(f"已成功加载 {len(plugins2settings_manager.get_data())} 个非限制插件.") | 初始化插件设置,从插件中获取 __zx_plugin_name__,__plugin_cmd__,__plugin_settings__ |
188,146 | from pathlib import Path
from ruamel import yaml
from ruamel.yaml import YAML, round_trip_dump, round_trip_load
from configs.config import Config
from configs.path_config import DATA_PATH
from services.log import logger
from utils.manager import admin_manager, plugin_data_manager, plugins_manager
from utils.text_utils import prompt2cn
from utils.utils import get_matchers
def _replace_config():
"""
说明:
定时任务加载的配置读取替换
"""
# 再开始读取用户配置
user_config_file = Path() / "configs" / "config.yaml"
_data = {}
_tmp_data = {}
if user_config_file.exists():
with open(user_config_file, "r", encoding="utf8") as f:
_data = _yaml.load(f)
# 数据替换
for plugin in Config.keys():
_tmp_data[plugin] = {}
for k in Config[plugin].configs.keys():
try:
if _data.get(plugin) and k in _data[plugin].keys():
Config.set_config(plugin, k, _data[plugin][k])
if level2module := Config.get_level2module(plugin, k):
try:
admin_manager.set_admin_level(
level2module, _data[plugin][k]
)
except KeyError:
logger.warning(
f"{level2module} 设置权限等级失败:{_data[plugin][k]}"
)
_tmp_data[plugin][k] = Config.get_config(plugin, k)
except AttributeError as e:
raise AttributeError(
f"{e}\n" + prompt2cn("可能为config.yaml配置文件填写不规范", 46)
)
Config.save()
temp_file = Path() / "configs" / "temp_config.yaml"
try:
with open(temp_file, "w", encoding="utf8") as wf:
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
with open(temp_file, "r", encoding="utf8") as rf:
_data = round_trip_load(rf)
# 添加注释
for plugin in _data.keys():
rst = ""
plugin_name = None
try:
if config_group := Config.get(plugin):
for key in list(config_group.configs.keys()):
try:
if config := config_group.configs[key]:
if config.name:
plugin_name = config.name
except AttributeError:
pass
except (KeyError, AttributeError):
plugin_name = None
if not plugin_name:
try:
plugin_name = plugins_manager.get(plugin).plugin_name
except (AttributeError, TypeError):
plugin_name = plugin
plugin_name = (
plugin_name.replace("[Hidden]", "")
.replace("[Superuser]", "")
.replace("[Admin]", "")
.strip()
)
rst += plugin_name + "\n"
for k in _data[plugin].keys():
rst += f"{k}: {Config[plugin].configs[k].help}" + "\n"
_data[plugin].yaml_set_start_comment(rst[:-1], indent=2)
with open(Path() / "configs" / "config.yaml", "w", encoding="utf8") as wf:
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
except Exception as e:
logger.error(f"生成简易配置注释错误 {type(e)}:{e}")
if temp_file.exists():
temp_file.unlink()
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_plugins_config` function. Write a Python function `def init_plugins_config()` to solve the following problem:
初始化插件数据配置
Here is the function:
def init_plugins_config():
"""
初始化插件数据配置
"""
plugins2config_file = DATA_PATH / "configs" / "plugins2config.yaml"
_data = Config.get_data()
# 优先使用 metadata 数据
for matcher in get_matchers(True):
if matcher.plugin_name:
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
# 插件配置版本更新或为Version为None或不在存储配置内,当使用metadata时,必定更新
version = plugin_data.plugin_status.version
config = _data.get(matcher.plugin_name)
plugin = plugins_manager.get(matcher.plugin_name)
if plugin_data.plugin_configs and (
isinstance(version, str)
or (
version is None
or (
config
and config.configs.keys()
!= plugin_data.plugin_configs.keys()
)
or version > int(plugin.version or 0)
or matcher.plugin_name not in _data.keys()
)
):
plugin_configs = plugin_data.plugin_configs
for key in plugin_configs:
if isinstance(plugin_data.plugin_configs[key], dict):
Config.add_plugin_config(
matcher.plugin_name,
key,
plugin_configs[key].get("value"),
help_=plugin_configs[key].get("help"),
default_value=plugin_configs[key].get("default_value"),
_override=True,
type=plugin_configs[key].get("type"),
)
else:
config = plugin_configs[key]
Config.add_plugin_config(
matcher.plugin_name,
key,
config.value,
name=config.name,
help_=config.help,
default_value=config.default_value,
_override=True,
type=config.type,
)
elif plugin_configs := _data.get(matcher.plugin_name):
for key in plugin_configs.configs:
Config.add_plugin_config(
matcher.plugin_name,
key,
plugin_configs.configs[key].value,
help_=plugin_configs.configs[key].help,
default_value=plugin_configs.configs[key].default_value,
_override=True,
type=plugin_configs.configs[key].type,
)
if not Config.is_empty():
Config.save()
_data = round_trip_load(open(plugins2config_file, encoding="utf8"))
for plugin in _data.keys():
try:
plugin_name = plugins_manager.get(plugin).plugin_name
except (AttributeError, TypeError):
plugin_name = plugin
_data[plugin].yaml_set_start_comment(plugin_name, indent=2)
# 初始化未设置的管理员权限等级
for k, v in Config.get_admin_level_data():
admin_manager.set_admin_level(k, v)
# 存完插件基本设置
with open(plugins2config_file, "w", encoding="utf8") as wf:
round_trip_dump(
_data, wf, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True
)
_replace_config() | 初始化插件数据配置 |
188,147 | import random
from types import ModuleType
from typing import Any, Dict
from configs.config import Config
from services import logger
from utils.manager import (
plugin_data_manager,
plugins2block_manager,
plugins2cd_manager,
plugins2count_manager,
plugins2settings_manager,
plugins_manager,
)
from utils.manager.models import (
Plugin,
PluginBlock,
PluginCd,
PluginCount,
PluginData,
PluginSetting,
PluginType,
)
from utils.utils import get_matchers
def get_attr(module: ModuleType, name: str, default: Any = None) -> Any:
"""
说明:
获取属性
参数:
:param module: module
:param name: name
:param default: default
"""
return getattr(module, name, None) or default
class PluginBlock(BaseModel):
"""
插件阻断
"""
status: bool = True # 限制状态
check_type: Literal["private", "group", "all"] = "all" # 检查类型
limit_type: Literal["user", "group"] = "user" # 监听对象
rst: Optional[str] # 阻断时回复
class PluginCd(BaseModel):
"""
插件阻断
"""
cd: int = 5 # cd
status: bool = True # 限制状态
check_type: Literal["private", "group", "all"] = "all" # 检查类型
limit_type: Literal["user", "group"] = "user" # 监听对象
rst: Optional[str] # 阻断时回复
class PluginCount(BaseModel):
"""
插件阻断
"""
max_count: int # 次数
status: bool = True # 限制状态
limit_type: Literal["user", "group"] = "user" # 监听对象
rst: Optional[str] # 阻断时回复
class PluginSetting(BaseModel):
"""
插件设置
"""
cmd: List[str] = [] # 命令 或 命令别名
default_status: bool = True # 默认开关状态
level: int = 5 # 功能权限等级
limit_superuser: bool = False # 功能状态是否限制超级用户
plugin_type: Tuple[Union[str, int], ...] = ("normal",) # 插件类型
cost_gold: int = 0 # 需要消费的金币
class Plugin(BaseModel):
"""
插件数据
"""
plugin_name: str # 模块名
status: Optional[bool] = True # 开关状态
error: Optional[bool] = False # 是否加载报错
block_type: Optional[str] = None # 关闭类型
author: Optional[str] = None # 作者
version: Optional[Union[int, str]] = None # 版本
class PluginType(Enum):
"""
插件类型
"""
NORMAL = "normal"
ADMIN = "admin"
HIDDEN = "hidden"
SUPERUSER = "superuser"
class PluginData(BaseModel):
model: str
name: str
plugin_type: PluginType # 插件内部类型,根据name [Hidden] [Admin] [SUPERUSER]
usage: Optional[str]
superuser_usage: Optional[str]
des: Optional[str]
task: Optional[Dict[str, str]]
menu_type: Tuple[Union[str, int], ...] = ("normal",) # 菜单类型
plugin_setting: Optional[PluginSetting]
plugin_cd: Optional[PluginCd]
plugin_block: Optional[PluginBlock]
plugin_count: Optional[PluginCount]
plugin_resources: Optional[Dict[str, Union[str, Path]]]
plugin_configs: Optional[Dict[str, zConfig]]
plugin_status: Plugin
class Config:
arbitrary_types_allowed = True
def __eq__(self, other: "PluginData"):
return (
isinstance(other, PluginData)
and self.name == other.name
and self.menu_type == other.menu_type
)
def __hash__(self):
return hash(self.name + str(self.menu_type[0]))
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
def init_plugin_info():
for matcher in [x for x in get_matchers(True)]:
try:
if (plugin := matcher.plugin) and matcher.plugin_name:
metadata = plugin.metadata
extra = metadata.extra if metadata else {}
if hasattr(plugin, "module"):
module = plugin.module
plugin_model = matcher.plugin_name
plugin_name = (
metadata.name
if metadata and metadata.name
else get_attr(module, "__zx_plugin_name__", matcher.plugin_name)
)
if not plugin_name:
logger.warning(f"配置文件 模块:{plugin_model} 获取 plugin_name 失败...")
continue
if "[Admin]" in plugin_name:
plugin_type = PluginType.ADMIN
plugin_name = plugin_name.replace("[Admin]", "").strip()
elif "[Hidden]" in plugin_name:
plugin_type = PluginType.HIDDEN
plugin_name = plugin_name.replace("[Hidden]", "").strip()
elif "[Superuser]" in plugin_name:
plugin_type = PluginType.SUPERUSER
plugin_name = plugin_name.replace("[Superuser]", "").strip()
else:
plugin_type = PluginType.NORMAL
plugin_usage = (
metadata.usage
if metadata and metadata.usage
else get_attr(module, "__plugin_usage__")
)
plugin_des = (
metadata.description
if metadata and metadata.description
else get_attr(module, "__plugin_des__")
)
menu_type = get_attr(module, "__plugin_type__") or ("normal",)
plugin_setting = get_attr(module, "__plugin_settings__")
if plugin_setting:
plugin_setting = PluginSetting(**plugin_setting)
plugin_setting.plugin_type = menu_type
plugin_superuser_usage = get_attr(
module, "__plugin_superuser_usage__"
)
plugin_task = get_attr(module, "__plugin_task__")
plugin_version = extra.get("__plugin_version__") or get_attr(
module, "__plugin_version__"
)
plugin_author = extra.get("__plugin_author__") or get_attr(
module, "__plugin_author__"
)
plugin_cd = get_attr(module, "__plugin_cd_limit__")
if plugin_cd:
plugin_cd = PluginCd(**plugin_cd)
plugin_block = get_attr(module, "__plugin_block_limit__")
if plugin_block:
plugin_block = PluginBlock(**plugin_block)
plugin_count = get_attr(module, "__plugin_count_limit__")
if plugin_count:
plugin_count = PluginCount(**plugin_count)
plugin_resources = get_attr(module, "__plugin_resources__")
plugin_configs = get_attr(module, "__plugin_configs__")
if settings := plugins2settings_manager.get(plugin_model):
plugin_setting = settings
if plugin_cd_limit := plugins2cd_manager.get(plugin_model):
plugin_cd = plugin_cd_limit
if plugin_block_limit := plugins2block_manager.get(plugin_model):
plugin_block = plugin_block_limit
if plugin_count_limit := plugins2count_manager.get(plugin_model):
plugin_count = plugin_count_limit
if plugin_cfg := Config.get(plugin_model):
if plugin_configs:
for config_name in plugin_configs:
config: Dict[str, Any] = plugin_configs[config_name] # type: ignore
Config.add_plugin_config(
plugin_model,
config_name,
config.get("value"),
help_=config.get("help"),
default_value=config.get("default_value"),
type=config.get("type"),
)
plugin_configs = plugin_cfg.configs
plugin_status = plugins_manager.get(plugin_model)
if not plugin_status:
plugin_status = Plugin(plugin_name=plugin_model)
plugin_status.author = plugin_author
plugin_status.version = plugin_version
plugin_data = PluginData(
model=plugin_model,
name=plugin_name.strip(),
plugin_type=plugin_type,
usage=plugin_usage,
superuser_usage=plugin_superuser_usage,
des=plugin_des,
task=plugin_task,
menu_type=menu_type,
plugin_setting=plugin_setting,
plugin_cd=plugin_cd,
plugin_block=plugin_block,
plugin_count=plugin_count,
plugin_resources=plugin_resources,
plugin_configs=plugin_configs, # type: ignore
plugin_status=plugin_status,
)
plugin_data_manager.add_plugin_info(plugin_data)
except Exception as e:
logger.error(f"构造插件数据失败 {matcher.plugin_name}", e=e) | null |
188,148 | from utils.manager import (
none_plugin_count_manager,
plugins2count_manager,
plugins2cd_manager,
plugins2settings_manager,
plugins2block_manager,
plugins_manager,
)
from services.log import logger
from utils.utils import get_matchers
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
The provided code snippet includes necessary dependencies for implementing the `init_none_plugin_count_manager` function. Write a Python function `def init_none_plugin_count_manager()` to solve the following problem:
清除已删除插件数据
Here is the function:
def init_none_plugin_count_manager():
"""
清除已删除插件数据
"""
modules = [x.plugin_name for x in get_matchers(True)]
plugins_manager_list = list(plugins_manager.keys())
for module in plugins_manager_list:
try:
if module not in modules or none_plugin_count_manager.check(module):
try:
plugin_name = plugins_manager.get(module).plugin_name
except (AttributeError, KeyError):
plugin_name = ""
if none_plugin_count_manager.check(module):
try:
plugins2settings_manager.delete(module)
plugins2count_manager.delete(module)
plugins2cd_manager.delete(module)
plugins2block_manager.delete(module)
plugins_manager.delete(module)
plugins_manager.save()
# resources_manager.remove_resource(module)
none_plugin_count_manager.delete(module)
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...")
except Exception as e:
logger.exception(
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}"
)
else:
none_plugin_count_manager.add_count(module)
logger.info(
f"{module}:{plugin_name} 插件疑似已删除,"
f"加载{none_plugin_count_manager._max_count}次失败后将清除对应插件数据,"
f"当前次数:{none_plugin_count_manager.get(module)}"
)
else:
none_plugin_count_manager.reset(module)
except Exception as e:
logger.error(f"清除插件数据错误 {type(e)}:{e}")
plugins2settings_manager.save()
plugins2count_manager.save()
plugins2cd_manager.save()
plugins2block_manager.save()
plugins_manager.save()
none_plugin_count_manager.save() | 清除已删除插件数据 |
188,149 | from ruamel.yaml import YAML
from utils.manager import plugins_manager, plugin_data_manager
from utils.utils import get_matchers
from services.log import logger
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_matchers(distinct: bool = False) -> List[Type[Matcher]]:
"""
说明:
获取所有matcher
参数:
distinct: 去重
"""
_matchers = []
temp = []
for i in matchers.keys():
for matcher in matchers[i]:
if distinct and matcher.plugin_name in temp:
continue
temp.append(matcher.plugin_name)
_matchers.append(matcher)
return _matchers
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
The provided code snippet includes necessary dependencies for implementing the `init_plugins_data` function. Write a Python function `def init_plugins_data()` to solve the following problem:
初始化插件数据信息
Here is the function:
def init_plugins_data():
"""
初始化插件数据信息
"""
for matcher in get_matchers(True):
_plugin = matcher.plugin
if not _plugin:
continue
try:
_module = _plugin.module
except AttributeError:
if matcher.plugin_name not in plugins_manager.keys():
plugins_manager.add_plugin_data(
matcher.plugin_name, matcher.plugin_name, error=True
)
else:
plugins_manager[matcher.plugin_name].error = True
else:
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
try:
plugin_version = plugin_data.plugin_status.version
plugin_name = plugin_data.name
plugin_author = plugin_data.plugin_status.author
if matcher.plugin_name in plugins_manager.keys():
plugins_manager[matcher.plugin_name].error = False
if matcher.plugin_name not in plugins_manager.keys():
plugins_manager.add_plugin_data(
matcher.plugin_name,
plugin_name=plugin_name,
author=plugin_author,
version=plugin_version,
)
elif isinstance(plugin_version, str) or plugins_manager[matcher.plugin_name].version is None or (
plugin_version is not None
and plugin_version > float(plugins_manager[matcher.plugin_name].version)
):
plugins_manager[matcher.plugin_name].plugin_name = plugin_name
plugins_manager[matcher.plugin_name].author = plugin_author
plugins_manager[matcher.plugin_name].version = plugin_version
except Exception as e:
logger.error(f"插件数据 {matcher.plugin_name} 加载发生错误 {type(e)}:{e}")
plugins_manager.save() | 初始化插件数据信息 |
188,150 | from typing import Dict, List, Optional
from models.bag_user import BagUser
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
async def _init_prop(
props: Dict[str, int], _props: List[GoodsInfo]
) -> Optional[BuildImage]:
"""
说明:
构造道具列表图片
参数:
:param props: 道具仓库字典
:param _props: 道具列表
"""
active_name = [x.goods_name for x in _props]
name_list = [x for x in props.keys() if x in active_name]
if not name_list:
return None
temp_img = BuildImage(0, 0, font_size=20)
image_list = []
num_list = []
for i, name in enumerate(name_list):
img = BuildImage(
temp_img.getsize(name)[0] + 50,
30,
font="msyh.ttf",
font_size=20,
color="#f9f6f2",
)
await img.atext((30, 5), f"{i + 1}.{name}")
goods = [x for x in _props if x.goods_name == name][0]
if goods.icon and (icon_path / goods.icon).exists():
icon = BuildImage(30, 30, background=icon_path / goods.icon)
await img.apaste(icon, alpha=True)
image_list.append(img)
num_list.append(
BuildImage(
30, 30, font_size=20, font="msyh.ttf", plain_text=f"×{props[name]}"
)
)
max_w = 0
num_max_w = 0
h = 0
for img, num in zip(image_list, num_list):
h += img.h
max_w = max_w if max_w > img.w else img.w
num_max_w = num_max_w if num_max_w > num.w else num.w
A = BuildImage(max_w + num_max_w + 30, h, color="#f9f6f2")
curr_h = 0
for img, num in zip(image_list, num_list):
await A.apaste(img, (0, curr_h))
await A.apaste(num, (max_w + 20, curr_h + 5), True)
curr_h += img.h
return A
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
The provided code snippet includes necessary dependencies for implementing the `create_bag_image` function. Write a Python function `async def create_bag_image(props: Dict[str, int])` to solve the following problem:
说明: 创建背包道具图片 参数: :param props: 道具仓库字典
Here is the function:
async def create_bag_image(props: Dict[str, int]):
"""
说明:
创建背包道具图片
参数:
:param props: 道具仓库字典
"""
goods_list = await GoodsInfo.get_all_goods()
active_props = await _init_prop(props, [x for x in goods_list if not x.is_passive])
passive_props = await _init_prop(props, [x for x in goods_list if x.is_passive])
active_w = 0
active_h = 0
passive_w = 0
passive_h = 0
if active_props:
img = BuildImage(
active_props.w,
active_props.h + 70,
font="CJGaoDeGuo.otf",
font_size=30,
color="#f9f6f2",
)
await img.apaste(active_props, (0, 70))
await img.atext((0, 30), "主动道具")
active_props = img
active_w = img.w
active_h = img.h
if passive_props:
img = BuildImage(
passive_props.w,
passive_props.h + 70,
font="CJGaoDeGuo.otf",
font_size=30,
color="#f9f6f2",
)
await img.apaste(passive_props, (0, 70))
await img.atext((0, 30), "被动道具")
passive_props = img
passive_w = img.w
passive_h = img.h
A = BuildImage(
active_w + passive_w + 100,
max(active_h, passive_h) + 60,
font="CJGaoDeGuo.otf",
font_size=30,
color="#f9f6f2",
)
curr_w = 50
if active_props:
await A.apaste(active_props, (curr_w, 0))
curr_w += active_props.w + 10
if passive_props:
await A.apaste(passive_props, (curr_w, 0))
if active_props and passive_props:
await A.aline(
(active_props.w + 45, 70, active_props.w + 45, A.h - 20), fill=(0, 0, 0)
)
return A.pic2bs4() | 说明: 创建背包道具图片 参数: :param props: 道具仓库字典 |
188,151 | import time
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import CommandArg
from models.bag_user import BagUser
from models.goods_info import GoodsInfo
from models.user_shop_gold_log import UserShopGoldLog
from services.log import logger
from utils.utils import is_number
buy = on_command("购买", aliases={"购买道具"}, priority=5, block=True, permission=GROUP)
class BagUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
gold = fields.IntField(default=100)
"""金币数量"""
spend_total_gold = fields.IntField(default=0)
"""花费金币总数"""
get_total_gold = fields.IntField(default=0)
"""获取金币总数"""
get_today_gold = fields.IntField(default=0)
"""今日获取金币"""
spend_today_gold = fields.IntField(default=0)
"""今日获取金币"""
property: Dict[str, int] = fields.JSONField(default={})
"""道具"""
class Meta:
table = "bag_users"
table_description = "用户道具数据表"
unique_together = ("user_id", "group_id")
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取金币概况
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取当前金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return user.gold
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
"""
说明:
获取当前道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param only_active: 仅仅获取主动使用的道具
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
if only_active and user.property:
data = {}
name_list = [
x.goods_name
for x in await GoodsInfo.get_all_goods()
if not x.is_passive
]
for key in [x for x in user.property if x in name_list]:
data[key] = user.property[key]
return data
return user.property
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
增加金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold + num
user.get_total_gold = user.get_total_gold + num
user.get_today_gold = user.get_today_gold + num
await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"])
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
花费金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold - num
user.spend_total_gold = user.spend_total_gold + num
user.spend_today_gold = user.spend_today_gold + num
await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"])
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
"""
说明:
增加道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 道具数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if property_.get(name) is None:
property_[name] = 0
property_[name] += num
user.property = property_
await user.save(update_fields=["property"])
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
"""
说明:
使用/删除 道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 使用个数
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if name in property_:
if (n := property_.get(name, 0)) < num:
return False
if n == num:
del property_[name]
else:
property_[name] -= num
await user.save(update_fields=["property"])
return True
return False
async def _run_script(cls):
return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段
"ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);"
]
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
class UserShopGoldLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
type = fields.IntField()
"""金币使用类型 0: 购买, 1: 使用, 2: 插件"""
name = fields.CharField(255)
"""商品/插件 名称"""
spend_gold = fields.IntField(default=0)
"""花费金币"""
num = fields.IntField()
"""数量"""
create_time = fields.DatetimeField(auto_now_add=True)
"""创建时间"""
class Meta:
table = "user_shop_gold_log"
table_description = "金币使用日志表"
def _run_script(cls):
return [
"ALTER TABLE user_shop_gold_log RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE user_shop_gold_log ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE user_shop_gold_log ALTER COLUMN group_id TYPE character varying(255);",
]
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
goods = None
if arg.extract_plain_text().strip() in ["神秘药水"]:
await buy.finish("你们看看就好啦,这是不可能卖给你们的~", at_sender=True)
goods_list = [
x
for x in await GoodsInfo.get_all_goods()
if x.goods_limit_time > time.time() or x.goods_limit_time == 0
]
goods_name_list = [x.goods_name for x in goods_list]
msg = arg.extract_plain_text().strip().split()
num = 1
if len(msg) > 1:
if is_number(msg[1]) and int(msg[1]) > 0:
num = int(msg[1])
else:
await buy.finish("购买的数量要是数字且大于0!", at_sender=True)
if is_number(msg[0]):
msg = int(msg[0])
if msg > len(goods_name_list) or msg < 1:
await buy.finish("请输入正确的商品id!", at_sender=True)
goods = goods_list[msg - 1]
else:
if msg[0] in goods_name_list:
for i in range(len(goods_name_list)):
if msg[0] == goods_name_list[i]:
goods = goods_list[i]
break
else:
await buy.finish("请输入正确的商品名称!")
else:
await buy.finish("请输入正确的商品名称!", at_sender=True)
if (
await BagUser.get_gold(event.user_id, event.group_id)
) < goods.goods_price * num * goods.goods_discount:
await buy.finish("您的金币好像不太够哦", at_sender=True)
flag, n = await GoodsInfo.check_user_daily_purchase(
goods, event.user_id, event.group_id, num
)
if flag:
await buy.finish(f"该次购买将超过每日次数限制,目前该道具还可以购买{n}次哦", at_sender=True)
spend_gold = int(goods.goods_discount * goods.goods_price * num)
await BagUser.spend_gold(event.user_id, event.group_id, spend_gold)
await BagUser.add_property(event.user_id, event.group_id, goods.goods_name, num)
await GoodsInfo.add_user_daily_purchase(goods, event.user_id, event.group_id, num)
await buy.send(
f"花费 {goods.goods_price * num * goods.goods_discount} 金币购买 {goods.goods_name} ×{num} 成功!",
at_sender=True,
)
logger.info(
f"花费 {goods.goods_price*num} 金币购买 {goods.goods_name} ×{num} 成功!",
"购买道具",
event.user_id,
event.group_id,
)
await UserShopGoldLog.create(
user_id=str(event.user_id),
group_id=str(event.group_id),
type=0,
name=goods.goods_name,
num=num,
spend_gold=goods.goods_price * num * goods.goods_discount,
)
# else:
# await buy.send(f"{goods.goods_name} 购买失败!", at_sender=True)
# logger.info(
# f"USER {event.user_id} GROUP {event.group_id} "
# f"花费 {goods.goods_price * num * goods.goods_discount} 金币购买 {goods.goods_name} ×{num} 失败!"
# ) | null |
188,152 | from nonebot import on_command
from nonebot.adapters.onebot.v11 import ActionFailed, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import CommandArg
from models.bag_user import BagUser
from utils.data_utils import init_rank
from utils.image_utils import text2image
from utils.message_builder import image
from utils.utils import is_number
my_gold = on_command("我的金币", priority=5, block=True, permission=GROUP)
class BagUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
gold = fields.IntField(default=100)
"""金币数量"""
spend_total_gold = fields.IntField(default=0)
"""花费金币总数"""
get_total_gold = fields.IntField(default=0)
"""获取金币总数"""
get_today_gold = fields.IntField(default=0)
"""今日获取金币"""
spend_today_gold = fields.IntField(default=0)
"""今日获取金币"""
property: Dict[str, int] = fields.JSONField(default={})
"""道具"""
class Meta:
table = "bag_users"
table_description = "用户道具数据表"
unique_together = ("user_id", "group_id")
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取金币概况
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取当前金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return user.gold
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
"""
说明:
获取当前道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param only_active: 仅仅获取主动使用的道具
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
if only_active and user.property:
data = {}
name_list = [
x.goods_name
for x in await GoodsInfo.get_all_goods()
if not x.is_passive
]
for key in [x for x in user.property if x in name_list]:
data[key] = user.property[key]
return data
return user.property
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
增加金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold + num
user.get_total_gold = user.get_total_gold + num
user.get_today_gold = user.get_today_gold + num
await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"])
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
花费金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold - num
user.spend_total_gold = user.spend_total_gold + num
user.spend_today_gold = user.spend_today_gold + num
await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"])
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
"""
说明:
增加道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 道具数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if property_.get(name) is None:
property_[name] = 0
property_[name] += num
user.property = property_
await user.save(update_fields=["property"])
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
"""
说明:
使用/删除 道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 使用个数
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if name in property_:
if (n := property_.get(name, 0)) < num:
return False
if n == num:
del property_[name]
else:
property_[name] -= num
await user.save(update_fields=["property"])
return True
return False
async def _run_script(cls):
return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段
"ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = "black",
padding: Union[int, Tuple[int, int, int, int]] = 0,
_add_height: float = 0,
) -> BuildImage:
"""
说明:
解析文本并转为图片
使用标签
<f> </f>
可选配置项
font: str -> 特殊文本字体
fs / font_size: int -> 特殊文本大小
fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色
示例
在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>,
你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过,
<f font_size=25>抽卡抽不到金色</f>,这让我很痛苦
参数:
:param text: 文本
:param auto_parse: 是否自动解析,否则原样发送
:param font_size: 普通字体大小
:param color: 背景颜色
:param font: 普通字体
:param font_color: 普通字体颜色
:param padding: 文本外边距,元组类型时为 (上,左,下,右)
:param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度
"""
pw = ph = top_padding = left_padding = 0
if padding:
if isinstance(padding, int):
pw = padding * 2
ph = padding * 2
top_padding = left_padding = padding
elif isinstance(padding, tuple):
pw = padding[0] + padding[2]
ph = padding[1] + padding[3]
top_padding = padding[0]
left_padding = padding[1]
if auto_parse and re.search(r"<f(.*)>(.*)</f>", text):
_data = []
new_text = ""
placeholder_index = 0
for s in text.split("</f>"):
r = re.search(r"<f(.*)>(.*)", s)
if r:
start, end = r.span()
if start != 0 and (t := s[:start]):
new_text += t
_data.append(
[
(start, end),
f"[placeholder_{placeholder_index}]",
r.group(1).strip(),
r.group(2),
]
)
new_text += f"[placeholder_{placeholder_index}]"
placeholder_index += 1
new_text += text.split("</f>")[-1]
image_list = []
current_placeholder_index = 0
# 切分换行,每行为单张图片
for s in new_text.split("\n"):
_tmp_text = s
img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1]
img_width = 0
_tmp_index = current_placeholder_index
for _ in range(s.count("[placeholder_")):
placeholder = _data[_tmp_index]
if "font_size" in placeholder[2]:
r = re.search(r"font_size=['\"]?(\d+)", placeholder[2])
if r:
w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize(
placeholder[3]
)
img_height = img_height if img_height > h else h
img_width += w
else:
img_width += BuildImage(0, 0, font_size=font_size).getsize(
placeholder[3]
)[0]
_tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "")
_tmp_index += 1
img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0]
# img_width += len(_tmp_text) * font_size
# 开始画图
A = BuildImage(
img_width, img_height, color=color, font=font, font_size=font_size
)
basic_font_h = A.getsize("正")[1]
current_width = 0
# 遍历占位符
for _ in range(s.count("[placeholder_")):
if not s.startswith(f"[placeholder_{current_placeholder_index}]"):
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext(
(current_width, A.h - basic_font_h - 1), slice_[0], font_color
)
current_width += A.getsize(slice_[0])[0]
placeholder = _data[current_placeholder_index]
# 解析配置
_font = font
_font_size = font_size
_font_color = font_color
for e in placeholder[2].split():
if e.startswith("font="):
_font = e.split("=")[-1]
if e.startswith("font_size=") or e.startswith("fs="):
_font_size = int(e.split("=")[-1])
if _font_size > 1000:
_font_size = 1000
if _font_size < 1:
_font_size = 1
if e.startswith("font_color") or e.startswith("fc="):
_font_color = e.split("=")[-1]
text_img = BuildImage(
0,
0,
plain_text=placeholder[3],
font_size=_font_size,
font_color=_font_color,
font=_font,
)
_img_h = (
int(A.h / 2 - text_img.h / 2)
if new_text == "[placeholder_0]"
else A.h - text_img.h
)
await A.apaste(text_img, (current_width, _img_h - 1), True)
current_width += text_img.w
s = s[
s.index(f"[placeholder_{current_placeholder_index}]")
+ len(f"[placeholder_{current_placeholder_index}]") :
]
current_placeholder_index += 1
if s:
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext((current_width, A.h - basic_font_h), slice_[0])
current_width += A.getsize(slice_[0])[0]
A.crop((0, 0, current_width, A.h))
# A.show()
image_list.append(A)
height = 0
width = 0
for img in image_list:
height += img.h
width = width if width > img.w else img.w
width += pw
height += ph
A = BuildImage(width + left_padding, height + top_padding, color=color)
current_height = top_padding
for img in image_list:
await A.apaste(img, (left_padding, current_height), True)
current_height += img.h
else:
width = 0
height = 0
_tmp = BuildImage(0, 0, font=font, font_size=font_size)
_, h = _tmp.getsize("正")
line_height = int(font_size / 3)
image_list = []
for x in text.split("\n"):
w, _ = _tmp.getsize(x.strip() or "正")
height += h + line_height
width = width if width > w else w
image_list.append(
BuildImage(
w,
h,
font=font,
font_size=font_size,
plain_text=x.strip(),
color=color,
)
)
width += pw
height += ph
A = BuildImage(
width + left_padding,
height + top_padding + 2,
color=color,
)
cur_h = ph
for img in image_list:
await A.apaste(img, (pw, cur_h), True)
cur_h += img.h + line_height
return A
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
async def _(event: GroupMessageEvent):
msg = await BagUser.get_user_total_gold(event.user_id, event.group_id)
try:
await my_gold.send(msg)
except ActionFailed:
await my_gold.send(
image(b64=(await text2image(msg, color="#f9f6f2", padding=10)).pic2bs4())
) | null |
188,153 | from nonebot import on_command
from nonebot.adapters.onebot.v11 import ActionFailed, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import CommandArg
from models.bag_user import BagUser
from utils.data_utils import init_rank
from utils.image_utils import text2image
from utils.message_builder import image
from utils.utils import is_number
ank = on_command("金币排行", priority=5, block=True, permission=GROUP)
class BagUser(Model):
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
async def _run_script(cls):
async def init_rank(
title: str,
all_user_id: List[str],
all_user_data: List[Union[int, float]],
group_id: int,
total_count: int = 10,
) -> BuildMat:
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
num = arg.extract_plain_text().strip()
if is_number(num) and 51 > int(num) > 10:
num = int(num)
else:
num = 10
all_users = await BagUser.filter(group_id=event.group_id)
all_user_id = [user.user_id for user in all_users]
all_user_data = [user.gold for user in all_users]
rank_image = await init_rank(
"金币排行", all_user_id, all_user_data, event.group_id, num
)
if rank_image:
await gold_rank.finish(image(b64=rank_image.pic2bs4())) | null |
188,154 | import time
from typing import List, Optional, Tuple, Union
from PIL import Image
from configs.path_config import IMAGE_PATH
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage, text2image
from utils.utils import GDict, is_number
icon_path = IMAGE_PATH / "shop_icon"
goods_lst = await GoodsInfo.get_all_goods()
_dc = {}
font_h = BuildImage(0, 0).getsize("正")[1]
h = 10
_list: List[GoodsInfo] = []
for goods in goods_lst:
if goods.goods_limit_time == 0 or time.time() < goods.goods_limit_time:
_list.append(goods)
total_n = 0
image_list = []
for idx, goods in enumerate(_list):
name_image = BuildImage(
580, 40, font_size=25, color="#e67b6b", font="CJGaoDeGuo.otf"
)
await name_image.atext(
(15, 0), f"{idx + 1}.{goods.goods_name}", center_type="by_height"
)
await name_image.aline((380, -5, 280, 45), "#a29ad6", 5)
await name_image.atext((390, 0), "售价:", center_type="by_height")
if goods.goods_discount != 1:
discount_price = int(goods.goods_discount * goods.goods_price)
old_price_image = BuildImage(
0,
0,
plain_text=str(goods.goods_price),
font_color=(194, 194, 194),
font="CJGaoDeGuo.otf",
font_size=15,
)
await old_price_image.aline(
(
0,
int(old_price_image.h / 2),
old_price_image.w + 1,
int(old_price_image.h / 2),
),
(0, 0, 0),
)
await name_image.apaste(old_price_image, (440, 0), True)
await name_image.atext((440, 15), str(discount_price), (255, 255, 255))
else:
await name_image.atext(
(440, 0),
str(goods.goods_price),
(255, 255, 255),
center_type="by_height",
)
await name_image.atext(
(
440
+ BuildImage(0, 0, plain_text=str(goods.goods_price), font_size=25).w,
0,
),
f" 金币",
center_type="by_height",
)
des_image = None
font_img = BuildImage(
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
)
p = font_img.getsize("简介:")[0] + 20
if goods.goods_description:
des_list = goods.goods_description.split("\n")
desc = ""
for des in des_list:
if font_img.getsize(des)[0] > font_img.w - p - 20:
msg = ""
tmp = ""
for i in range(len(des)):
if font_img.getsize(tmp)[0] < font_img.w - p - 20:
tmp += des[i]
else:
msg += tmp + "\n"
tmp = des[i]
desc += msg
if tmp:
desc += tmp
else:
desc += des + "\n"
if desc[-1] == "\n":
desc = desc[:-1]
des_image = await text2image(desc, color="#a29ad6")
goods_image = BuildImage(
600,
(50 + des_image.h) if des_image else 50,
font_size=20,
color="#a29ad6",
font="CJGaoDeGuo.otf",
)
if des_image:
await goods_image.atext((15, 50), "简介:")
await goods_image.apaste(des_image, (p, 50))
await name_image.acircle_corner(5)
await goods_image.apaste(name_image, (0, 5), True, center_type="by_width")
await goods_image.acircle_corner(20)
bk = BuildImage(
1180,
(50 + des_image.h) if des_image else 50,
font_size=15,
color="#f9f6f2",
font="CJGaoDeGuo.otf",
)
if goods.icon and (icon_path / goods.icon).exists():
icon = BuildImage(70, 70, background=icon_path / goods.icon)
await bk.apaste(icon)
await bk.apaste(goods_image, (70, 0), alpha=True)
n = 0
_w = 650
# 添加限时图标和时间
if goods.goods_limit_time > 0:
n += 140
_limit_time_logo = BuildImage(
40, 40, background=f"{IMAGE_PATH}/other/time.png"
)
await bk.apaste(_limit_time_logo, (_w + 50, 0), True)
await bk.apaste(
BuildImage(0, 0, plain_text="限时!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 10),
True,
)
limit_time = time.strftime(
"%Y-%m-%d %H:%M", time.localtime(goods.goods_limit_time)
).split()
y_m_d = limit_time[0]
_h_m = limit_time[1].split(":")
h_m = _h_m[0] + "时 " + _h_m[1] + "分"
await bk.atext((_w + 55, 38), str(y_m_d))
await bk.atext((_w + 65, 57), str(h_m))
_w += 140
if goods.goods_discount != 1:
n += 140
_discount_logo = BuildImage(
30, 30, background=f"{IMAGE_PATH}/other/discount.png"
)
await bk.apaste(_discount_logo, (_w + 50, 10), True)
await bk.apaste(
BuildImage(0, 0, plain_text="折扣!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 15),
True,
)
await bk.apaste(
BuildImage(
0,
0,
plain_text=f"{10 * goods.goods_discount:.1f} 折",
font_size=30,
font="CJGaoDeGuo.otf",
font_color=(85, 156, 75),
),
(_w + 50, 44),
True,
)
_w += 140
if goods.daily_limit != 0:
n += 140
_daily_limit_logo = BuildImage(
35, 35, background=f"{IMAGE_PATH}/other/daily_limit.png"
)
await bk.apaste(_daily_limit_logo, (_w + 50, 10), True)
await bk.apaste(
BuildImage(0, 0, plain_text="限购!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 20),
True,
)
await bk.apaste(
BuildImage(
0,
0,
plain_text=f"{goods.daily_limit}",
font_size=30,
font="CJGaoDeGuo.otf",
),
(_w + 72, 45),
True,
)
if total_n < n:
total_n = n
if n:
await bk.aline((650, -1, 650 + n, -1), "#a29ad6", 5)
# await bk.aline((650, 80, 650 + n, 80), "#a29ad6", 5)
# 添加限时图标和时间
image_list.append(bk)
# await A.apaste(bk, (0, current_h), True)
# current_h += 90
h = 0
current_h = 0
for img in image_list:
h += img.h + 10
A = BuildImage(1100, h, color="#f9f6f2")
for img in image_list:
await A.apaste(img, (0, current_h), True)
current_h += img.h + 10
w = 950
if total_n:
w += total_n
h = A.h + 230 + 100
h = 1000 if h < 1000 else h
shop_logo = BuildImage(100, 100, background=f"{IMAGE_PATH}/other/shop_text.png")
shop = BuildImage(w, h, font_size=20, color="#f9f6f2")
zx_img = BuildImage(0, 0, background=f"{IMAGE_PATH}/zhenxun/toukan_3.png")
zx_img.transpose(Image.FLIP_LEFT_RIGHT)
zx_img.replace_color_tran(((240, 240, 240), (255, 255, 255)), (249, 246, 242))
await shop.apaste(zx_img, (0, 100))
shop.paste(A, (20 + zx_img.w, 230))
await shop.apaste(shop_logo, (450, 30), True)
shop.text(
(int((1000 - shop.getsize("注【通过 序号 或者 商品名称 购买】")[0]) / 2), 170),
"注【通过 序号 或者 商品名称 购买】",
)
shop.text((20 + zx_img.w, h - 100), "神秘药水\t\t售价:9999999金币\n\t\t鬼知道会有什么效果~")
return shop.pic2bs4(
goods_lst = await GoodsInfo.get_all_goods()
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = "black",
padding: Union[int, Tuple[int, int, int, int]] = 0,
_add_height: float = 0,
) -> BuildImage:
"""
说明:
解析文本并转为图片
使用标签
<f> </f>
可选配置项
font: str -> 特殊文本字体
fs / font_size: int -> 特殊文本大小
fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色
示例
在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>,
你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过,
<f font_size=25>抽卡抽不到金色</f>,这让我很痛苦
参数:
:param text: 文本
:param auto_parse: 是否自动解析,否则原样发送
:param font_size: 普通字体大小
:param color: 背景颜色
:param font: 普通字体
:param font_color: 普通字体颜色
:param padding: 文本外边距,元组类型时为 (上,左,下,右)
:param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度
"""
pw = ph = top_padding = left_padding = 0
if padding:
if isinstance(padding, int):
pw = padding * 2
ph = padding * 2
top_padding = left_padding = padding
elif isinstance(padding, tuple):
pw = padding[0] + padding[2]
ph = padding[1] + padding[3]
top_padding = padding[0]
left_padding = padding[1]
if auto_parse and re.search(r"<f(.*)>(.*)</f>", text):
_data = []
new_text = ""
placeholder_index = 0
for s in text.split("</f>"):
r = re.search(r"<f(.*)>(.*)", s)
if r:
start, end = r.span()
if start != 0 and (t := s[:start]):
new_text += t
_data.append(
[
(start, end),
f"[placeholder_{placeholder_index}]",
r.group(1).strip(),
r.group(2),
]
)
new_text += f"[placeholder_{placeholder_index}]"
placeholder_index += 1
new_text += text.split("</f>")[-1]
image_list = []
current_placeholder_index = 0
# 切分换行,每行为单张图片
for s in new_text.split("\n"):
_tmp_text = s
img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1]
img_width = 0
_tmp_index = current_placeholder_index
for _ in range(s.count("[placeholder_")):
placeholder = _data[_tmp_index]
if "font_size" in placeholder[2]:
r = re.search(r"font_size=['\"]?(\d+)", placeholder[2])
if r:
w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize(
placeholder[3]
)
img_height = img_height if img_height > h else h
img_width += w
else:
img_width += BuildImage(0, 0, font_size=font_size).getsize(
placeholder[3]
)[0]
_tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "")
_tmp_index += 1
img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0]
# img_width += len(_tmp_text) * font_size
# 开始画图
A = BuildImage(
img_width, img_height, color=color, font=font, font_size=font_size
)
basic_font_h = A.getsize("正")[1]
current_width = 0
# 遍历占位符
for _ in range(s.count("[placeholder_")):
if not s.startswith(f"[placeholder_{current_placeholder_index}]"):
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext(
(current_width, A.h - basic_font_h - 1), slice_[0], font_color
)
current_width += A.getsize(slice_[0])[0]
placeholder = _data[current_placeholder_index]
# 解析配置
_font = font
_font_size = font_size
_font_color = font_color
for e in placeholder[2].split():
if e.startswith("font="):
_font = e.split("=")[-1]
if e.startswith("font_size=") or e.startswith("fs="):
_font_size = int(e.split("=")[-1])
if _font_size > 1000:
_font_size = 1000
if _font_size < 1:
_font_size = 1
if e.startswith("font_color") or e.startswith("fc="):
_font_color = e.split("=")[-1]
text_img = BuildImage(
0,
0,
plain_text=placeholder[3],
font_size=_font_size,
font_color=_font_color,
font=_font,
)
_img_h = (
int(A.h / 2 - text_img.h / 2)
if new_text == "[placeholder_0]"
else A.h - text_img.h
)
await A.apaste(text_img, (current_width, _img_h - 1), True)
current_width += text_img.w
s = s[
s.index(f"[placeholder_{current_placeholder_index}]")
+ len(f"[placeholder_{current_placeholder_index}]") :
]
current_placeholder_index += 1
if s:
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext((current_width, A.h - basic_font_h), slice_[0])
current_width += A.getsize(slice_[0])[0]
A.crop((0, 0, current_width, A.h))
# A.show()
image_list.append(A)
height = 0
width = 0
for img in image_list:
height += img.h
width = width if width > img.w else img.w
width += pw
height += ph
A = BuildImage(width + left_padding, height + top_padding, color=color)
current_height = top_padding
for img in image_list:
await A.apaste(img, (left_padding, current_height), True)
current_height += img.h
else:
width = 0
height = 0
_tmp = BuildImage(0, 0, font=font, font_size=font_size)
_, h = _tmp.getsize("正")
line_height = int(font_size / 3)
image_list = []
for x in text.split("\n"):
w, _ = _tmp.getsize(x.strip() or "正")
height += h + line_height
width = width if width > w else w
image_list.append(
BuildImage(
w,
h,
font=font,
font_size=font_size,
plain_text=x.strip(),
color=color,
)
)
width += pw
height += ph
A = BuildImage(
width + left_padding,
height + top_padding + 2,
color=color,
)
cur_h = ph
for img in image_list:
await A.apaste(img, (pw, cur_h), True)
cur_h += img.h + line_height
return A
The provided code snippet includes necessary dependencies for implementing the `create_shop_help` function. Write a Python function `async def create_shop_help() -> str` to solve the following problem:
制作商店图片 :return: 图片base64
Here is the function:
async def create_shop_help() -> str:
"""
制作商店图片
:return: 图片base64
"""
goods_lst = await GoodsInfo.get_all_goods()
_dc = {}
font_h = BuildImage(0, 0).getsize("正")[1]
h = 10
_list: List[GoodsInfo] = []
for goods in goods_lst:
if goods.goods_limit_time == 0 or time.time() < goods.goods_limit_time:
_list.append(goods)
# A = BuildImage(1100, h, color="#f9f6f2")
total_n = 0
image_list = []
for idx, goods in enumerate(_list):
name_image = BuildImage(
580, 40, font_size=25, color="#e67b6b", font="CJGaoDeGuo.otf"
)
await name_image.atext(
(15, 0), f"{idx + 1}.{goods.goods_name}", center_type="by_height"
)
await name_image.aline((380, -5, 280, 45), "#a29ad6", 5)
await name_image.atext((390, 0), "售价:", center_type="by_height")
if goods.goods_discount != 1:
discount_price = int(goods.goods_discount * goods.goods_price)
old_price_image = BuildImage(
0,
0,
plain_text=str(goods.goods_price),
font_color=(194, 194, 194),
font="CJGaoDeGuo.otf",
font_size=15,
)
await old_price_image.aline(
(
0,
int(old_price_image.h / 2),
old_price_image.w + 1,
int(old_price_image.h / 2),
),
(0, 0, 0),
)
await name_image.apaste(old_price_image, (440, 0), True)
await name_image.atext((440, 15), str(discount_price), (255, 255, 255))
else:
await name_image.atext(
(440, 0),
str(goods.goods_price),
(255, 255, 255),
center_type="by_height",
)
await name_image.atext(
(
440
+ BuildImage(0, 0, plain_text=str(goods.goods_price), font_size=25).w,
0,
),
f" 金币",
center_type="by_height",
)
des_image = None
font_img = BuildImage(
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
)
p = font_img.getsize("简介:")[0] + 20
if goods.goods_description:
des_list = goods.goods_description.split("\n")
desc = ""
for des in des_list:
if font_img.getsize(des)[0] > font_img.w - p - 20:
msg = ""
tmp = ""
for i in range(len(des)):
if font_img.getsize(tmp)[0] < font_img.w - p - 20:
tmp += des[i]
else:
msg += tmp + "\n"
tmp = des[i]
desc += msg
if tmp:
desc += tmp
else:
desc += des + "\n"
if desc[-1] == "\n":
desc = desc[:-1]
des_image = await text2image(desc, color="#a29ad6")
goods_image = BuildImage(
600,
(50 + des_image.h) if des_image else 50,
font_size=20,
color="#a29ad6",
font="CJGaoDeGuo.otf",
)
if des_image:
await goods_image.atext((15, 50), "简介:")
await goods_image.apaste(des_image, (p, 50))
await name_image.acircle_corner(5)
await goods_image.apaste(name_image, (0, 5), True, center_type="by_width")
await goods_image.acircle_corner(20)
bk = BuildImage(
1180,
(50 + des_image.h) if des_image else 50,
font_size=15,
color="#f9f6f2",
font="CJGaoDeGuo.otf",
)
if goods.icon and (icon_path / goods.icon).exists():
icon = BuildImage(70, 70, background=icon_path / goods.icon)
await bk.apaste(icon)
await bk.apaste(goods_image, (70, 0), alpha=True)
n = 0
_w = 650
# 添加限时图标和时间
if goods.goods_limit_time > 0:
n += 140
_limit_time_logo = BuildImage(
40, 40, background=f"{IMAGE_PATH}/other/time.png"
)
await bk.apaste(_limit_time_logo, (_w + 50, 0), True)
await bk.apaste(
BuildImage(0, 0, plain_text="限时!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 10),
True,
)
limit_time = time.strftime(
"%Y-%m-%d %H:%M", time.localtime(goods.goods_limit_time)
).split()
y_m_d = limit_time[0]
_h_m = limit_time[1].split(":")
h_m = _h_m[0] + "时 " + _h_m[1] + "分"
await bk.atext((_w + 55, 38), str(y_m_d))
await bk.atext((_w + 65, 57), str(h_m))
_w += 140
if goods.goods_discount != 1:
n += 140
_discount_logo = BuildImage(
30, 30, background=f"{IMAGE_PATH}/other/discount.png"
)
await bk.apaste(_discount_logo, (_w + 50, 10), True)
await bk.apaste(
BuildImage(0, 0, plain_text="折扣!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 15),
True,
)
await bk.apaste(
BuildImage(
0,
0,
plain_text=f"{10 * goods.goods_discount:.1f} 折",
font_size=30,
font="CJGaoDeGuo.otf",
font_color=(85, 156, 75),
),
(_w + 50, 44),
True,
)
_w += 140
if goods.daily_limit != 0:
n += 140
_daily_limit_logo = BuildImage(
35, 35, background=f"{IMAGE_PATH}/other/daily_limit.png"
)
await bk.apaste(_daily_limit_logo, (_w + 50, 10), True)
await bk.apaste(
BuildImage(0, 0, plain_text="限购!", font_size=23, font="CJGaoDeGuo.otf"),
(_w + 90, 20),
True,
)
await bk.apaste(
BuildImage(
0,
0,
plain_text=f"{goods.daily_limit}",
font_size=30,
font="CJGaoDeGuo.otf",
),
(_w + 72, 45),
True,
)
if total_n < n:
total_n = n
if n:
await bk.aline((650, -1, 650 + n, -1), "#a29ad6", 5)
# await bk.aline((650, 80, 650 + n, 80), "#a29ad6", 5)
# 添加限时图标和时间
image_list.append(bk)
# await A.apaste(bk, (0, current_h), True)
# current_h += 90
h = 0
current_h = 0
for img in image_list:
h += img.h + 10
A = BuildImage(1100, h, color="#f9f6f2")
for img in image_list:
await A.apaste(img, (0, current_h), True)
current_h += img.h + 10
w = 950
if total_n:
w += total_n
h = A.h + 230 + 100
h = 1000 if h < 1000 else h
shop_logo = BuildImage(100, 100, background=f"{IMAGE_PATH}/other/shop_text.png")
shop = BuildImage(w, h, font_size=20, color="#f9f6f2")
zx_img = BuildImage(0, 0, background=f"{IMAGE_PATH}/zhenxun/toukan_3.png")
zx_img.transpose(Image.FLIP_LEFT_RIGHT)
zx_img.replace_color_tran(((240, 240, 240), (255, 255, 255)), (249, 246, 242))
await shop.apaste(zx_img, (0, 100))
shop.paste(A, (20 + zx_img.w, 230))
await shop.apaste(shop_logo, (450, 30), True)
shop.text(
(int((1000 - shop.getsize("注【通过 序号 或者 商品名称 购买】")[0]) / 2), 170),
"注【通过 序号 或者 商品名称 购买】",
)
shop.text((20 + zx_img.w, h - 100), "神秘药水\t\t售价:9999999金币\n\t\t鬼知道会有什么效果~")
return shop.pic2bs4() | 制作商店图片 :return: 图片base64 |
188,155 | import time
from typing import List, Optional, Tuple, Union
from PIL import Image
from configs.path_config import IMAGE_PATH
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage, text2image
from utils.utils import GDict, is_number
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
The provided code snippet includes necessary dependencies for implementing the `register_goods` function. Write a Python function `async def register_goods( name: str, price: int, des: str, discount: Optional[float] = 1, limit_time: Optional[int] = 0, daily_limit: Optional[int] = 0, is_passive: Optional[bool] = False, icon: Optional[str] = None, ) -> bool` to solve the following problem:
添加商品 例如: 折扣:可选参数↓ 限时时间:可选,单位为小时 添加商品 name:萝莉酒杯 price:9999 des:普通的酒杯,但是里面.. discount:0.4 limit_time:90 添加商品 name:可疑的药 price:5 des:效果未知 :param name: 商品名称 :param price: 商品价格 :param des: 商品简介 :param discount: 商品折扣 :param limit_time: 商品限时销售时间,单位为小时 :param daily_limit: 每日购买次数限制 :param is_passive: 是否为被动 :param icon: 图标 :return: 是否添加成功
Here is the function:
async def register_goods(
name: str,
price: int,
des: str,
discount: Optional[float] = 1,
limit_time: Optional[int] = 0,
daily_limit: Optional[int] = 0,
is_passive: Optional[bool] = False,
icon: Optional[str] = None,
) -> bool:
"""
添加商品
例如: 折扣:可选参数↓ 限时时间:可选,单位为小时
添加商品 name:萝莉酒杯 price:9999 des:普通的酒杯,但是里面.. discount:0.4 limit_time:90
添加商品 name:可疑的药 price:5 des:效果未知
:param name: 商品名称
:param price: 商品价格
:param des: 商品简介
:param discount: 商品折扣
:param limit_time: 商品限时销售时间,单位为小时
:param daily_limit: 每日购买次数限制
:param is_passive: 是否为被动
:param icon: 图标
:return: 是否添加成功
"""
if not await GoodsInfo.get_or_none(goods_name=name):
limit_time_ = float(limit_time) if limit_time else limit_time
discount = discount if discount is not None else 1
limit_time_ = (
int(time.time() + limit_time_ * 60 * 60)
if limit_time_ is not None and limit_time_ != 0
else 0
)
await GoodsInfo.create(
goods_name=name,
goods_price=int(price),
goods_description=des,
goods_discount=float(discount),
goods_limit_time=limit_time_,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
return True
return False | 添加商品 例如: 折扣:可选参数↓ 限时时间:可选,单位为小时 添加商品 name:萝莉酒杯 price:9999 des:普通的酒杯,但是里面.. discount:0.4 limit_time:90 添加商品 name:可疑的药 price:5 des:效果未知 :param name: 商品名称 :param price: 商品价格 :param des: 商品简介 :param discount: 商品折扣 :param limit_time: 商品限时销售时间,单位为小时 :param daily_limit: 每日购买次数限制 :param is_passive: 是否为被动 :param icon: 图标 :return: 是否添加成功 |
188,156 | import time
from typing import List, Optional, Tuple, Union
from PIL import Image
from configs.path_config import IMAGE_PATH
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage, text2image
from utils.utils import GDict, is_number
goods_lst = await GoodsInfo.get_all_goods()
goods_lst = await GoodsInfo.get_all_goods()
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
The provided code snippet includes necessary dependencies for implementing the `delete_goods` function. Write a Python function `async def delete_goods(name: str, id_: int) -> Tuple[str, str, int]` to solve the following problem:
删除商品 :param name: 商品名称 :param id_: 商品id :return: 删除状况
Here is the function:
async def delete_goods(name: str, id_: int) -> Tuple[str, str, int]:
"""
删除商品
:param name: 商品名称
:param id_: 商品id
:return: 删除状况
"""
goods_lst = await GoodsInfo.get_all_goods()
if id_:
if id_ < 1 or id_ > len(goods_lst):
return "序号错误,没有该序号商品...", "", 999
goods_name = goods_lst[id_ - 1].goods_name
if await GoodsInfo.delete_goods(goods_name):
return f"删除商品 {goods_name} 成功!", goods_name, 200
else:
return f"删除商品 {goods_name} 失败!", goods_name, 999
if name:
if await GoodsInfo.delete_goods(name):
return f"删除商品 {name} 成功!", name, 200
else:
return f"删除商品 {name} 失败!", name, 999
return "获取商品失败", "", 999 | 删除商品 :param name: 商品名称 :param id_: 商品id :return: 删除状况 |
188,157 | import time
from typing import List, Optional, Tuple, Union
from PIL import Image
from configs.path_config import IMAGE_PATH
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage, text2image
from utils.utils import GDict, is_number
goods_lst = await GoodsInfo.get_all_goods()
for goods in goods_lst:
if goods.goods_limit_time == 0 or time.time() < goods.goods_limit_time:
_list.append(goods)
goods_lst = await GoodsInfo.get_all_goods()
if await GoodsInfo.delete_goods(name):
return f"删除商品 {name} 成功!", name, 200
else:
return f"删除商品 {name} 失败!", name, 999
if kwargs:
goods_lst = await GoodsInfo.get_all_goods()
if is_number(kwargs["name"]):
if int(kwargs["name"]) < 1 or int(kwargs["name"]) > len(goods_lst):
return False, "序号错误,没有该序号的商品...", ""
goods = goods_lst[int(kwargs["name"]) - 1]
else:
goods = await GoodsInfo.filter(goods_name=kwargs["name"]).first()
if not goods:
return False, "名称错误,没有该名称的商品...", ""
name: str = goods.goods_name
price = goods.goods_price
des = goods.goods_description
discount = goods.goods_discount
limit_time = goods.goods_limit_time
daily_limit = goods.daily_limit
is_passive = goods.is_passive
new_time = 0
tmp = ""
if kwargs.get("price"):
tmp += f'价格:{price} --> {kwargs["price"]}\n'
price = kwargs["price"]
if kwargs.get("des"):
tmp += f'描述:{des} --> {kwargs["des"]}\n'
des = kwargs["des"]
if kwargs.get("discount"):
tmp += f'折扣:{discount} --> {kwargs["discount"]}\n'
discount = kwargs["discount"]
if kwargs.get("limit_time"):
kwargs["limit_time"] = float(kwargs["limit_time"])
new_time = (
time.strftime(
"%Y-%m-%d %H:%M:%S",
time.localtime(time.time() + kwargs["limit_time"] * 60 * 60),
)
if kwargs["limit_time"] != 0
else 0
)
tmp += f"限时至: {new_time}\n" if new_time else "取消了限时\n"
limit_time = kwargs["limit_time"]
if kwargs.get("daily_limit"):
tmp += (
f'每日购买限制:{daily_limit} --> {kwargs["daily_limit"]}\n'
if daily_limit
else "取消了购买限制\n"
)
daily_limit = int(kwargs["daily_limit"])
if kwargs.get("is_passive"):
tmp += f'被动道具:{is_passive} --> {kwargs["is_passive"]}\n'
des = kwargs["is_passive"]
await GoodsInfo.update_goods(
name,
int(price),
des,
float(discount),
int(
time.time() + limit_time * 60 * 60
if limit_time != 0 and new_time
else 0
),
daily_limit,
is_passive,
)
return (
True,
name,
tmp[:-1],
)
class GoodsInfo(Model):
__tablename__ = "goods_info"
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
goods_name = fields.CharField(255, unique=True)
"""商品名称"""
goods_price = fields.IntField()
"""价格"""
goods_description = fields.TextField()
"""描述"""
goods_discount = fields.FloatField(default=1)
"""折扣"""
goods_limit_time = fields.BigIntField(default=0)
"""限时"""
daily_limit = fields.IntField(default=0)
"""每日限购"""
daily_purchase_limit: Dict[str, Dict[str, int]] = fields.JSONField(default={})
"""用户限购记录"""
is_passive = fields.BooleanField(default=False)
"""是否为被动道具"""
icon = fields.TextField(null=True)
"""图标路径"""
class Meta:
table = "goods_info"
table_description = "商品数据表"
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
daily_limit: int = 0,
is_passive: bool = False,
icon: Optional[str] = None,
):
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
:param daily_limit: 每日购买限制
:param is_passive: 是否为被动道具
:param icon: 图标
"""
if not await cls.filter(goods_name=goods_name).first():
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
daily_limit=daily_limit,
is_passive=is_passive,
icon=icon,
)
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await goods.delete()
return True
return False
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
daily_limit: Optional[int] = None,
is_passive: Optional[bool] = None,
icon: Optional[str] = None,
):
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
:param daily_limit: 每日次数限制
:param is_passive: 是否为被动
:param icon: 图标
"""
if goods := await cls.get_or_none(goods_name=goods_name):
await cls.update_or_create(
goods_name=goods_name,
defaults={
"goods_price": goods_price or goods.goods_price,
"goods_description": goods_description or goods.goods_description,
"goods_discount": goods_discount or goods.goods_discount,
"goods_limit_time": goods_limit_time
if goods_limit_time is not None
else goods.goods_limit_time,
"daily_limit": daily_limit
if daily_limit is not None
else goods.daily_limit,
"is_passive": is_passive
if is_passive is not None
else goods.is_passive,
"icon": icon or goods.icon,
},
)
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.all()
id_lst = [x.id for x in query]
goods_lst = []
for _ in range(len(query)):
min_id = min(id_lst)
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
async def add_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
):
"""
说明:
添加用户明日购买限制
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit and goods.daily_limit > 0:
if not goods.daily_purchase_limit.get(group_id):
goods.daily_purchase_limit[group_id] = {}
if not goods.daily_purchase_limit[group_id].get(user_id):
goods.daily_purchase_limit[group_id][user_id] = 0
goods.daily_purchase_limit[group_id][user_id] += num
await goods.save(update_fields=["daily_purchase_limit"])
async def check_user_daily_purchase(
cls, goods: "GoodsInfo", user_id_: Union[int, str], group_id_: Union[int, str], num: int = 1
) -> Tuple[bool, int]:
"""
说明:
检测用户每日购买上限
参数:
:param goods: 商品
:param user_id: 用户id
:param group_id: 群号
:param num: 数量
"""
user_id = str(user_id_)
group_id = str(group_id_)
if goods and goods.daily_limit > 0:
if (
not goods.daily_limit
or not goods.daily_purchase_limit.get(group_id)
or not goods.daily_purchase_limit[group_id].get(user_id)
):
return goods.daily_limit - num < 0, goods.daily_limit
if goods.daily_purchase_limit[group_id][user_id] + num > goods.daily_limit:
return (
True,
goods.daily_limit - goods.daily_purchase_limit[group_id][user_id],
)
return False, 0
def _run_script(cls):
return [
"ALTER TABLE goods_info ADD daily_limit Integer DEFAULT 0;",
"ALTER TABLE goods_info ADD daily_purchase_limit Json DEFAULT '{}';",
"ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;",
"ALTER TABLE goods_info ADD icon VARCHAR(255);",
]
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
The provided code snippet includes necessary dependencies for implementing the `update_goods` function. Write a Python function `async def update_goods(**kwargs) -> Tuple[bool, str, str]` to solve the following problem:
更新商品信息 :param kwargs: kwargs :return: 更新状况
Here is the function:
async def update_goods(**kwargs) -> Tuple[bool, str, str]:
"""
更新商品信息
:param kwargs: kwargs
:return: 更新状况
"""
if kwargs:
goods_lst = await GoodsInfo.get_all_goods()
if is_number(kwargs["name"]):
if int(kwargs["name"]) < 1 or int(kwargs["name"]) > len(goods_lst):
return False, "序号错误,没有该序号的商品...", ""
goods = goods_lst[int(kwargs["name"]) - 1]
else:
goods = await GoodsInfo.filter(goods_name=kwargs["name"]).first()
if not goods:
return False, "名称错误,没有该名称的商品...", ""
name: str = goods.goods_name
price = goods.goods_price
des = goods.goods_description
discount = goods.goods_discount
limit_time = goods.goods_limit_time
daily_limit = goods.daily_limit
is_passive = goods.is_passive
new_time = 0
tmp = ""
if kwargs.get("price"):
tmp += f'价格:{price} --> {kwargs["price"]}\n'
price = kwargs["price"]
if kwargs.get("des"):
tmp += f'描述:{des} --> {kwargs["des"]}\n'
des = kwargs["des"]
if kwargs.get("discount"):
tmp += f'折扣:{discount} --> {kwargs["discount"]}\n'
discount = kwargs["discount"]
if kwargs.get("limit_time"):
kwargs["limit_time"] = float(kwargs["limit_time"])
new_time = (
time.strftime(
"%Y-%m-%d %H:%M:%S",
time.localtime(time.time() + kwargs["limit_time"] * 60 * 60),
)
if kwargs["limit_time"] != 0
else 0
)
tmp += f"限时至: {new_time}\n" if new_time else "取消了限时\n"
limit_time = kwargs["limit_time"]
if kwargs.get("daily_limit"):
tmp += (
f'每日购买限制:{daily_limit} --> {kwargs["daily_limit"]}\n'
if daily_limit
else "取消了购买限制\n"
)
daily_limit = int(kwargs["daily_limit"])
if kwargs.get("is_passive"):
tmp += f'被动道具:{is_passive} --> {kwargs["is_passive"]}\n'
des = kwargs["is_passive"]
await GoodsInfo.update_goods(
name,
int(price),
des,
float(discount),
int(
time.time() + limit_time * 60 * 60
if limit_time != 0 and new_time
else 0
),
daily_limit,
is_passive,
)
return (
True,
name,
tmp[:-1],
) | 更新商品信息 :param kwargs: kwargs :return: 更新状况 |
188,158 | import time
from typing import List, Optional, Tuple, Union
from PIL import Image
from configs.path_config import IMAGE_PATH
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage, text2image
from utils.utils import GDict, is_number
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
The provided code snippet includes necessary dependencies for implementing the `parse_goods_info` function. Write a Python function `def parse_goods_info(msg: str) -> Union[dict, str]` to solve the following problem:
解析格式数据 :param msg: 消息 :return: 解析完毕的数据data
Here is the function:
def parse_goods_info(msg: str) -> Union[dict, str]:
"""
解析格式数据
:param msg: 消息
:return: 解析完毕的数据data
"""
if "name:" not in msg:
return "必须指定修改的商品名称或序号!"
data = {}
for x in msg.split():
sp = x.split(":", maxsplit=1)
if str(sp[1]).strip():
sp[1] = sp[1].strip()
if sp[0] == "name":
data["name"] = sp[1]
elif sp[0] == "price":
if not is_number(sp[1]) or int(sp[1]) < 0:
return "price参数不合法,必须大于等于0!"
data["price"] = sp[1]
elif sp[0] == "des":
data["des"] = sp[1]
elif sp[0] == "discount":
if not is_number(sp[1]) or float(sp[1]) < 0:
return "discount参数不合法,必须大于0!"
data["discount"] = sp[1]
elif sp[0] == "limit_time":
if not is_number(sp[1]) or float(sp[1]) < 0:
return "limit_time参数不合法,必须为数字且大于0!"
data["limit_time"] = sp[1]
elif sp[0] == "daily_limit":
if not is_number(sp[1]) or float(sp[1]) < 0:
return "daily_limit参数不合法,必须为数字且大于0!"
data["daily_limit"] = sp[1]
return data | 解析格式数据 :param msg: 消息 :return: 解析完毕的数据data |
188,159 | from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment, Message
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot
from pydantic import create_model
from utils.models import ShopParam
from typing import Optional, Union, Callable, List, Tuple, Dict, Any
from types import MappingProxyType
import inspect
import asyncio
func_manager = GoodsUseFuncManager()
def build_params(
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int, text: str
) -> Tuple[ShopParam, Dict[str, Any]]:
"""
说明:
构造参数
参数:
:param bot: bot
:param event: event
:param goods_name: 商品名称
:param num: 数量
:param text: 其他信息
"""
_kwargs = func_manager.get_kwargs(goods_name)
return (
func_manager.init_model(goods_name, bot, event, num, text),
{
**_kwargs,
"_bot": bot,
"event": event,
"group_id": event.group_id,
"user_id": event.user_id,
"num": num,
"text": text,
"message": event.message,
"goods_name": goods_name,
},
)
The provided code snippet includes necessary dependencies for implementing the `effect` function. Write a Python function `async def effect( bot: Bot, event: GroupMessageEvent, goods_name: str, num: int, text: str, message: Message ) -> Optional[Union[str, MessageSegment]]` to solve the following problem:
商品生效 :param bot: Bot :param event: GroupMessageEvent :param goods_name: 商品名称 :param num: 使用数量 :param text: 其他信息 :param message: Message :return: 使用是否成功
Here is the function:
async def effect(
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int, text: str, message: Message
) -> Optional[Union[str, MessageSegment]]:
"""
商品生效
:param bot: Bot
:param event: GroupMessageEvent
:param goods_name: 商品名称
:param num: 使用数量
:param text: 其他信息
:param message: Message
:return: 使用是否成功
"""
# 优先使用注册的商品插件
# try:
if func_manager.exists(goods_name):
_kwargs = func_manager.get_kwargs(goods_name)
model, kwargs = build_params(bot, event, goods_name, num, text)
return await func_manager.use(model, **kwargs)
# except Exception as e:
# logger.error(f"use 商品生效函数effect 发生错误 {type(e)}:{e}")
return None | 商品生效 :param bot: Bot :param event: GroupMessageEvent :param goods_name: 商品名称 :param num: 使用数量 :param text: 其他信息 :param message: Message :return: 使用是否成功 |
188,160 | from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment, Message
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot
from pydantic import create_model
from utils.models import ShopParam
from typing import Optional, Union, Callable, List, Tuple, Dict, Any
from types import MappingProxyType
import inspect
import asyncio
func_manager = GoodsUseFuncManager()
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class ShopParam(BaseModel):
goods_name: str
"""商品名称"""
user_id: int
"""用户id"""
group_id: int
"""群聊id"""
bot: Any
"""bot"""
event: MessageEvent
"""event"""
num: int
"""道具单次使用数量"""
message: Message
"""message"""
text: str
"""text"""
send_success_msg: bool = True
"""是否发送使用成功信息"""
max_num_limit: int = 1
"""单次使用最大次数"""
The provided code snippet includes necessary dependencies for implementing the `register_use` function. Write a Python function `def register_use(goods_name: str, func: Callable, **kwargs)` to solve the following problem:
注册商品使用方法 :param goods_name: 商品名称 :param func: 使用函数 :param kwargs: kwargs
Here is the function:
def register_use(goods_name: str, func: Callable, **kwargs):
"""
注册商品使用方法
:param goods_name: 商品名称
:param func: 使用函数
:param kwargs: kwargs
"""
if func_manager.exists(goods_name):
raise ValueError("该商品使用函数已被注册!")
# 发送使用成功信息
kwargs["send_success_msg"] = kwargs.get("send_success_msg", True)
kwargs["max_num_limit"] = kwargs.get("max_num_limit", 1)
func_manager.register_use(
goods_name,
**{
"func": func,
"model": create_model(f"{goods_name}_model", __base__=ShopParam, **kwargs),
"kwargs": kwargs,
},
)
logger.info(f"register_use 成功注册商品:{goods_name} 的使用函数") | 注册商品使用方法 :param goods_name: 商品名称 :param func: 使用函数 :param kwargs: kwargs |
188,161 | import nonebot
from nonebot import Driver
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.image_template import help_template
from utils.image_utils import BuildImage, build_sort_image, group_image, text2image
from utils.manager import plugin_data_manager
from utils.manager.models import PluginType
SUPERUSER_HELP_IMAGE = IMAGE_PATH / "superuser_help.png"
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def help_template(title: str, usage: BuildImage) -> BuildImage:
"""
说明:
生成单个功能帮助模板
参数:
:param title: 标题
:param usage: 说明图片
"""
title_image = BuildImage(
0,
0,
font_size=35,
plain_text=title,
font_color=(255, 255, 255),
font="CJGaoDeGuo.otf",
)
background_image = BuildImage(
max(title_image.w, usage.w) + 50,
max(title_image.h, usage.h) + 100,
color=(114, 138, 204),
)
await background_image.apaste(usage, (25, 80), True)
await background_image.apaste(title_image, (25, 20), True)
await background_image.aline(
(25, title_image.h + 22, 25 + title_image.w, title_image.h + 22),
(204, 196, 151),
3,
)
return background_image
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = "black",
padding: Union[int, Tuple[int, int, int, int]] = 0,
_add_height: float = 0,
) -> BuildImage:
"""
说明:
解析文本并转为图片
使用标签
<f> </f>
可选配置项
font: str -> 特殊文本字体
fs / font_size: int -> 特殊文本大小
fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色
示例
在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>,
你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过,
<f font_size=25>抽卡抽不到金色</f>,这让我很痛苦
参数:
:param text: 文本
:param auto_parse: 是否自动解析,否则原样发送
:param font_size: 普通字体大小
:param color: 背景颜色
:param font: 普通字体
:param font_color: 普通字体颜色
:param padding: 文本外边距,元组类型时为 (上,左,下,右)
:param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度
"""
pw = ph = top_padding = left_padding = 0
if padding:
if isinstance(padding, int):
pw = padding * 2
ph = padding * 2
top_padding = left_padding = padding
elif isinstance(padding, tuple):
pw = padding[0] + padding[2]
ph = padding[1] + padding[3]
top_padding = padding[0]
left_padding = padding[1]
if auto_parse and re.search(r"<f(.*)>(.*)</f>", text):
_data = []
new_text = ""
placeholder_index = 0
for s in text.split("</f>"):
r = re.search(r"<f(.*)>(.*)", s)
if r:
start, end = r.span()
if start != 0 and (t := s[:start]):
new_text += t
_data.append(
[
(start, end),
f"[placeholder_{placeholder_index}]",
r.group(1).strip(),
r.group(2),
]
)
new_text += f"[placeholder_{placeholder_index}]"
placeholder_index += 1
new_text += text.split("</f>")[-1]
image_list = []
current_placeholder_index = 0
# 切分换行,每行为单张图片
for s in new_text.split("\n"):
_tmp_text = s
img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1]
img_width = 0
_tmp_index = current_placeholder_index
for _ in range(s.count("[placeholder_")):
placeholder = _data[_tmp_index]
if "font_size" in placeholder[2]:
r = re.search(r"font_size=['\"]?(\d+)", placeholder[2])
if r:
w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize(
placeholder[3]
)
img_height = img_height if img_height > h else h
img_width += w
else:
img_width += BuildImage(0, 0, font_size=font_size).getsize(
placeholder[3]
)[0]
_tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "")
_tmp_index += 1
img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0]
# img_width += len(_tmp_text) * font_size
# 开始画图
A = BuildImage(
img_width, img_height, color=color, font=font, font_size=font_size
)
basic_font_h = A.getsize("正")[1]
current_width = 0
# 遍历占位符
for _ in range(s.count("[placeholder_")):
if not s.startswith(f"[placeholder_{current_placeholder_index}]"):
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext(
(current_width, A.h - basic_font_h - 1), slice_[0], font_color
)
current_width += A.getsize(slice_[0])[0]
placeholder = _data[current_placeholder_index]
# 解析配置
_font = font
_font_size = font_size
_font_color = font_color
for e in placeholder[2].split():
if e.startswith("font="):
_font = e.split("=")[-1]
if e.startswith("font_size=") or e.startswith("fs="):
_font_size = int(e.split("=")[-1])
if _font_size > 1000:
_font_size = 1000
if _font_size < 1:
_font_size = 1
if e.startswith("font_color") or e.startswith("fc="):
_font_color = e.split("=")[-1]
text_img = BuildImage(
0,
0,
plain_text=placeholder[3],
font_size=_font_size,
font_color=_font_color,
font=_font,
)
_img_h = (
int(A.h / 2 - text_img.h / 2)
if new_text == "[placeholder_0]"
else A.h - text_img.h
)
await A.apaste(text_img, (current_width, _img_h - 1), True)
current_width += text_img.w
s = s[
s.index(f"[placeholder_{current_placeholder_index}]")
+ len(f"[placeholder_{current_placeholder_index}]") :
]
current_placeholder_index += 1
if s:
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext((current_width, A.h - basic_font_h), slice_[0])
current_width += A.getsize(slice_[0])[0]
A.crop((0, 0, current_width, A.h))
# A.show()
image_list.append(A)
height = 0
width = 0
for img in image_list:
height += img.h
width = width if width > img.w else img.w
width += pw
height += ph
A = BuildImage(width + left_padding, height + top_padding, color=color)
current_height = top_padding
for img in image_list:
await A.apaste(img, (left_padding, current_height), True)
current_height += img.h
else:
width = 0
height = 0
_tmp = BuildImage(0, 0, font=font, font_size=font_size)
_, h = _tmp.getsize("正")
line_height = int(font_size / 3)
image_list = []
for x in text.split("\n"):
w, _ = _tmp.getsize(x.strip() or "正")
height += h + line_height
width = width if width > w else w
image_list.append(
BuildImage(
w,
h,
font=font,
font_size=font_size,
plain_text=x.strip(),
color=color,
)
)
width += pw
height += ph
A = BuildImage(
width + left_padding,
height + top_padding + 2,
color=color,
)
cur_h = ph
for img in image_list:
await A.apaste(img, (pw, cur_h), True)
cur_h += img.h + line_height
return A
def group_image(image_list: List[BuildImage]) -> Tuple[List[List[BuildImage]], int]:
"""
说明:
根据图片大小进行分组
参数:
:param image_list: 排序图片列表
"""
image_list.sort(key=lambda x: x.h, reverse=True)
max_image = max(image_list, key=lambda x: x.h)
image_list.remove(max_image)
max_h = max_image.h
total_w = 0
# 图片分组
image_group = [[max_image]]
is_use = []
surplus_list = image_list[:]
for image in image_list:
if image.uid not in is_use:
group = [image]
is_use.append(image.uid)
curr_h = image.h
while True:
surplus_list = [x for x in surplus_list if x.uid not in is_use]
for tmp in surplus_list:
temp_h = curr_h + tmp.h + 10
if temp_h < max_h or abs(max_h - temp_h) < 100:
curr_h += tmp.h + 15
is_use.append(tmp.uid)
group.append(tmp)
break
else:
break
total_w += max([x.w for x in group]) + 15
image_group.append(group)
while surplus_list:
surplus_list = [x for x in surplus_list if x.uid not in is_use]
if not surplus_list:
break
surplus_list.sort(key=lambda x: x.h, reverse=True)
for img in surplus_list:
if img.uid not in is_use:
_w = 0
index = -1
for i, ig in enumerate(image_group):
if s := sum([x.h for x in ig]) > _w:
_w = s
index = i
if index != -1:
image_group[index].append(img)
is_use.append(img.uid)
max_h = 0
max_w = 0
for ig in image_group:
if (_h := sum([x.h + 15 for x in ig])) > max_h:
max_h = _h
max_w += max([x.w for x in ig]) + 30
is_use.clear()
while abs(max_h - max_w) > 200 and len(image_group) - 1 >= len(image_group[-1]):
for img in image_group[-1]:
_min_h = 999999
_min_index = -1
for i, ig in enumerate(image_group):
# if i not in is_use and (_h := sum([x.h for x in ig]) + img.h) > _min_h:
if (_h := sum([x.h for x in ig]) + img.h) < _min_h:
_min_h = _h
_min_index = i
is_use.append(_min_index)
image_group[_min_index].append(img)
max_w -= max([x.w for x in image_group[-1]]) - 30
image_group.pop(-1)
max_h = max([sum([x.h + 15 for x in ig]) for ig in image_group])
return image_group, max(max_h + 250, max_w + 70)
async def build_sort_image(
image_group: List[List[BuildImage]],
h: Optional[int] = None,
padding_top: int = 200,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = (
255,
255,
255,
),
background_path: Optional[Path] = None,
background_handle: Callable[[BuildImage], Optional[Awaitable]] = None,
) -> BuildImage:
"""
说明:
对group_image的图片进行组装
参数:
:param image_group: 分组图片列表
:param h: max(宽,高),一般为group_image的返回值,有值时,图片必定为正方形
:param padding_top: 图像列表与最顶层间距
:param color: 背景颜色
:param background_path: 背景图片文件夹路径(随机)
:param background_handle: 背景图额外操作
"""
bk_file = None
if background_path:
random_bk = os.listdir(background_path)
if random_bk:
bk_file = random.choice(random_bk)
image_w = 0
image_h = 0
if not h:
for ig in image_group:
_w = max([x.w + 30 for x in ig])
image_w += _w + 30
_h = sum([x.h + 10 for x in ig])
if _h > image_h:
image_h = _h
image_h += padding_top
else:
image_w = h
image_h = h
A = BuildImage(
image_w,
image_h,
font_size=24,
font="CJGaoDeGuo.otf",
color=color,
background=(background_path / bk_file) if bk_file else None,
)
if background_handle:
if is_coroutine_callable(background_handle):
await background_handle(A)
else:
background_handle(A)
curr_w = 50
for ig in image_group:
curr_h = padding_top - 20
for img in ig:
await A.apaste(img, (curr_w, curr_h), True)
curr_h += img.h + 10
curr_w += max([x.w for x in ig]) + 30
return A
lass PluginType(Enum):
"""
插件类型
"""
NORMAL = "normal"
ADMIN = "admin"
HIDDEN = "hidden"
SUPERUSER = "superuser"
The provided code snippet includes necessary dependencies for implementing the `create_help_image` function. Write a Python function `async def create_help_image()` to solve the following problem:
创建超级用户帮助图片
Here is the function:
async def create_help_image():
"""
创建超级用户帮助图片
"""
if SUPERUSER_HELP_IMAGE.exists():
return
plugin_data_ = plugin_data_manager.get_data()
image_list = []
task_list = []
for plugin_data in [
plugin_data_[x]
for x in plugin_data_
if plugin_data_[x].name != "超级用户帮助 [Superuser]"
]:
try:
if plugin_data.plugin_type in [PluginType.SUPERUSER, PluginType.ADMIN]:
usage = None
if (
plugin_data.plugin_type == PluginType.SUPERUSER
and plugin_data.usage
):
usage = await text2image(
plugin_data.usage, padding=5, color=(204, 196, 151)
)
if plugin_data.superuser_usage:
usage = await text2image(
plugin_data.superuser_usage, padding=5, color=(204, 196, 151)
)
if usage:
await usage.acircle_corner()
image = await help_template(plugin_data.name, usage)
image_list.append(image)
if plugin_data.task:
for x in plugin_data.task.keys():
task_list.append(plugin_data.task[x])
except Exception as e:
logger.warning(
f"获取超级用户插件 {plugin_data.model}: {plugin_data.name} 设置失败...", e=e
)
task_str = "\n".join(task_list)
task_str = "通过私聊 开启被动/关闭被动 + [被动名称] 来控制全局被动\n----------\n" + task_str
task_image = await text2image(task_str, padding=5, color=(204, 196, 151))
task_image = await help_template("被动任务", task_image)
image_list.append(task_image)
image_group, _ = group_image(image_list)
A = await build_sort_image(image_group, color="#f9f6f2", padding_top=180)
await A.apaste(
BuildImage(0, 0, font="CJGaoDeGuo.otf", plain_text="超级用户帮助", font_size=50),
(50, 30),
True,
)
await A.apaste(
BuildImage(
0,
0,
font="CJGaoDeGuo.otf",
plain_text="注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数",
font_size=30,
font_color="red",
),
(50, 90),
True,
)
await A.asave(SUPERUSER_HELP_IMAGE)
logger.info(f"已成功加载 {len(image_list)} 条超级用户命令") | 创建超级用户帮助图片 |
188,162 | from nonebot.adapters.onebot.v11 import Event, MessageEvent
from configs.config import Config
def rule(event: Event) -> bool:
return bool(
Config.get_config("chat_history", "FLAG") and isinstance(event, MessageEvent)
) | null |
188,163 | from datetime import datetime, timedelta
from typing import Any, Tuple
import pytz
from nonebot import on_regex
from nonebot.adapters.onebot.v11 import GroupMessageEvent
from nonebot.params import RegexGroup
from models.chat_history import ChatHistory
from models.group_member_info import GroupInfoUser
from utils.image_utils import BuildImage, text2image
from utils.message_builder import image
from utils.utils import is_number
msg_handler = on_regex(
r"^(周|月|日)?消息统计(des|DES)?(n=[0-9]{1,2})?$", priority=5, block=True
)
class ChatHistory(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255, null=True)
"""群聊id"""
text = fields.TextField(null=True)
"""文本内容"""
plain_text = fields.TextField(null=True)
"""纯文本"""
create_time = fields.DatetimeField(auto_now_add=True)
"""创建时间"""
bot_id = fields.CharField(255, null=True)
"""bot记录id"""
class Meta:
table = "chat_history"
table_description = "聊天记录数据表"
async def get_group_msg_rank(
cls,
gid: Union[int, str],
limit: int = 10,
order: str = "DESC",
date_scope: Optional[Tuple[datetime, datetime]] = None,
) -> List["ChatHistory"]:
"""
说明:
获取排行数据
参数:
:param gid: 群号
:param limit: 获取数量
:param order: 排序类型,desc,des
:param date_scope: 日期范围
"""
o = "-" if order == "DESC" else ""
query = cls.filter(group_id=str(gid))
if date_scope:
query = query.filter(create_time__range=date_scope)
return list(
await query.annotate(count=Count("user_id"))
.order_by(o + "count")
.group_by("user_id")
.limit(limit)
.values_list("user_id", "count")
) # type: ignore
async def get_group_first_msg_datetime(
cls, group_id: Union[int, str]
) -> Optional[datetime]:
"""
说明:
获取群第一条记录消息时间
参数:
:param group_id: 群组id
"""
if (
message := await cls.filter(group_id=str(group_id))
.order_by("create_time")
.first()
):
return message.create_time
async def get_message(
cls,
uid: Union[int, str],
gid: Union[int, str],
type_: Literal["user", "group"],
msg_type: Optional[Literal["private", "group"]] = None,
days: Optional[Union[int, Tuple[datetime, datetime]]] = None,
) -> List["ChatHistory"]:
"""
说明:
获取消息查询query
参数:
:param uid: 用户id
:param gid: 群聊id
:param type_: 类型,私聊或群聊
:param msg_type: 消息类型,用户或群聊
:param days: 限制日期
"""
if type_ == "user":
query = cls.filter(user_id=str(uid))
if msg_type == "private":
query = query.filter(group_id__isnull=True)
elif msg_type == "group":
query = query.filter(group_id__not_isnull=True)
else:
query = cls.filter(group_id=str(gid))
if uid:
query = query.filter(user_id=str(uid))
if days:
if isinstance(days, int):
query = query.filter(
create_time__gte=datetime.now() - timedelta(days=days)
)
elif isinstance(days, tuple):
query = query.filter(create_time__range=days)
return await query.all() # type: ignore
async def _run_script(cls):
return [
"alter table chat_history alter group_id drop not null;", # 允许 group_id 为空
"alter table chat_history alter text drop not null;", # 允许 text 为空
"alter table chat_history alter plain_text drop not null;", # 允许 plain_text 为空
"ALTER TABLE chat_history RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE chat_history ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE chat_history ALTER COLUMN group_id TYPE character varying(255);",
"ALTER TABLE chat_history ADD bot_id VARCHAR(255);", # 添加bot_id字段
"ALTER TABLE chat_history ALTER COLUMN bot_id TYPE character varying(255);",
]
class GroupInfoUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
user_name = fields.CharField(255, default="")
"""用户昵称"""
group_id = fields.CharField(255)
"""群聊id"""
user_join_time: datetime = fields.DatetimeField(null=True)
"""用户入群时间"""
nickname = fields.CharField(255, null=True)
"""群聊昵称"""
uid = fields.BigIntField(null=True)
"""用户uid"""
class Meta:
table = "group_info_users"
table_description = "群员信息数据表"
unique_together = ("user_id", "group_id")
async def get_group_member_id_list(cls, group_id: Union[int, str]) -> Set[int]:
"""
说明:
获取该群所有用户id
参数:
:param group_id: 群号
"""
return set(
await cls.filter(group_id=str(group_id)).values_list("user_id", flat=True)
) # type: ignore
async def set_user_nickname(cls, user_id: Union[int, str], group_id: Union[int, str], nickname: str):
"""
说明:
设置群员在该群内的昵称
参数:
:param user_id: 用户id
:param group_id: 群号
:param nickname: 昵称
"""
await cls.update_or_create(
user_id=str(user_id),
group_id=str(group_id),
defaults={"nickname": nickname},
)
async def get_user_all_group(cls, user_id: Union[int, str]) -> List[int]:
"""
说明:
获取该用户所在的所有群聊
参数:
:param user_id: 用户id
"""
return list(
await cls.filter(user_id=str(user_id)).values_list("group_id", flat=True)
) # type: ignore
async def get_user_nickname(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取用户在该群的昵称
参数:
:param user_id: 用户id
:param group_id: 群号
"""
if user := await cls.get_or_none(user_id=str(user_id), group_id=str(group_id)):
if user.nickname:
nickname = ""
if black_word := Config.get_config("nickname", "BLACK_WORD"):
for x in user.nickname:
nickname += "*" if x in black_word else x
return nickname
return user.nickname
return ""
async def get_group_member_uid(cls, user_id: Union[int, str], group_id: Union[int, str]) -> Optional[int]:
logger.debug(
f"GroupInfoUser 尝试获取 用户[<u><e>{user_id}</e></u>] 群聊[<u><e>{group_id}</e></u>] UID"
)
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
_max_uid_user, _ = await cls.get_or_create(user_id="114514", group_id="114514")
_max_uid = _max_uid_user.uid
if not user.uid:
all_user = await cls.filter(user_id=str(user_id)).all()
for x in all_user:
if x.uid:
return x.uid
user.uid = _max_uid + 1
_max_uid_user.uid = _max_uid + 1
await cls.bulk_update([user, _max_uid_user], ["uid"])
logger.debug(
f"GroupInfoUser 获取 用户[<u><e>{user_id}</e></u>] 群聊[<u><e>{group_id}</e></u>] UID: {user.uid}"
)
return user.uid
async def _run_script(cls):
return [
"alter table group_info_users alter user_join_time drop not null;", # 允许 user_join_time 为空
"ALTER TABLE group_info_users ALTER COLUMN user_join_time TYPE timestamp with time zone USING user_join_time::timestamp with time zone;",
"ALTER TABLE group_info_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE group_info_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE group_info_users ALTER COLUMN group_id TYPE character varying(255);"
]
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = "black",
padding: Union[int, Tuple[int, int, int, int]] = 0,
_add_height: float = 0,
) -> BuildImage:
"""
说明:
解析文本并转为图片
使用标签
<f> </f>
可选配置项
font: str -> 特殊文本字体
fs / font_size: int -> 特殊文本大小
fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色
示例
在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>,
你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过,
<f font_size=25>抽卡抽不到金色</f>,这让我很痛苦
参数:
:param text: 文本
:param auto_parse: 是否自动解析,否则原样发送
:param font_size: 普通字体大小
:param color: 背景颜色
:param font: 普通字体
:param font_color: 普通字体颜色
:param padding: 文本外边距,元组类型时为 (上,左,下,右)
:param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度
"""
pw = ph = top_padding = left_padding = 0
if padding:
if isinstance(padding, int):
pw = padding * 2
ph = padding * 2
top_padding = left_padding = padding
elif isinstance(padding, tuple):
pw = padding[0] + padding[2]
ph = padding[1] + padding[3]
top_padding = padding[0]
left_padding = padding[1]
if auto_parse and re.search(r"<f(.*)>(.*)</f>", text):
_data = []
new_text = ""
placeholder_index = 0
for s in text.split("</f>"):
r = re.search(r"<f(.*)>(.*)", s)
if r:
start, end = r.span()
if start != 0 and (t := s[:start]):
new_text += t
_data.append(
[
(start, end),
f"[placeholder_{placeholder_index}]",
r.group(1).strip(),
r.group(2),
]
)
new_text += f"[placeholder_{placeholder_index}]"
placeholder_index += 1
new_text += text.split("</f>")[-1]
image_list = []
current_placeholder_index = 0
# 切分换行,每行为单张图片
for s in new_text.split("\n"):
_tmp_text = s
img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1]
img_width = 0
_tmp_index = current_placeholder_index
for _ in range(s.count("[placeholder_")):
placeholder = _data[_tmp_index]
if "font_size" in placeholder[2]:
r = re.search(r"font_size=['\"]?(\d+)", placeholder[2])
if r:
w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize(
placeholder[3]
)
img_height = img_height if img_height > h else h
img_width += w
else:
img_width += BuildImage(0, 0, font_size=font_size).getsize(
placeholder[3]
)[0]
_tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "")
_tmp_index += 1
img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0]
# img_width += len(_tmp_text) * font_size
# 开始画图
A = BuildImage(
img_width, img_height, color=color, font=font, font_size=font_size
)
basic_font_h = A.getsize("正")[1]
current_width = 0
# 遍历占位符
for _ in range(s.count("[placeholder_")):
if not s.startswith(f"[placeholder_{current_placeholder_index}]"):
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext(
(current_width, A.h - basic_font_h - 1), slice_[0], font_color
)
current_width += A.getsize(slice_[0])[0]
placeholder = _data[current_placeholder_index]
# 解析配置
_font = font
_font_size = font_size
_font_color = font_color
for e in placeholder[2].split():
if e.startswith("font="):
_font = e.split("=")[-1]
if e.startswith("font_size=") or e.startswith("fs="):
_font_size = int(e.split("=")[-1])
if _font_size > 1000:
_font_size = 1000
if _font_size < 1:
_font_size = 1
if e.startswith("font_color") or e.startswith("fc="):
_font_color = e.split("=")[-1]
text_img = BuildImage(
0,
0,
plain_text=placeholder[3],
font_size=_font_size,
font_color=_font_color,
font=_font,
)
_img_h = (
int(A.h / 2 - text_img.h / 2)
if new_text == "[placeholder_0]"
else A.h - text_img.h
)
await A.apaste(text_img, (current_width, _img_h - 1), True)
current_width += text_img.w
s = s[
s.index(f"[placeholder_{current_placeholder_index}]")
+ len(f"[placeholder_{current_placeholder_index}]") :
]
current_placeholder_index += 1
if s:
slice_ = s.split(f"[placeholder_{current_placeholder_index}]")
await A.atext((current_width, A.h - basic_font_h), slice_[0])
current_width += A.getsize(slice_[0])[0]
A.crop((0, 0, current_width, A.h))
# A.show()
image_list.append(A)
height = 0
width = 0
for img in image_list:
height += img.h
width = width if width > img.w else img.w
width += pw
height += ph
A = BuildImage(width + left_padding, height + top_padding, color=color)
current_height = top_padding
for img in image_list:
await A.apaste(img, (left_padding, current_height), True)
current_height += img.h
else:
width = 0
height = 0
_tmp = BuildImage(0, 0, font=font, font_size=font_size)
_, h = _tmp.getsize("正")
line_height = int(font_size / 3)
image_list = []
for x in text.split("\n"):
w, _ = _tmp.getsize(x.strip() or "正")
height += h + line_height
width = width if width > w else w
image_list.append(
BuildImage(
w,
h,
font=font,
font_size=font_size,
plain_text=x.strip(),
color=color,
)
)
width += pw
height += ph
A = BuildImage(
width + left_padding,
height + top_padding + 2,
color=color,
)
cur_h = ph
for img in image_list:
await A.apaste(img, (pw, cur_h), True)
cur_h += img.h + line_height
return A
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
gid = event.group_id
date_scope = None
date, order, num = reg_group
num = num.split("=")[-1] if num else 10
if num and is_number(num) and 10 < int(num) < 50:
num = int(num)
time_now = datetime.now()
zero_today = time_now - timedelta(
hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second
)
if date in ["日"]:
date_scope = (zero_today, time_now)
elif date in ["周"]:
date_scope = (time_now - timedelta(days=7), time_now)
elif date in ["月"]:
date_scope = (time_now - timedelta(days=30), time_now)
if rank_data := await ChatHistory.get_group_msg_rank(
gid, num, order or "DESC", date_scope
):
name = "昵称:\n\n"
num_str = "发言次数:\n\n"
idx = 1
for uid, num in rank_data:
if user := await GroupInfoUser.filter(user_id=uid, group_id=gid).first():
user_name = user.user_name
else:
user_name = uid
name += f"\t{idx}.{user_name} \n\n"
num_str += f"\t{num}\n\n"
idx += 1
name_img = await text2image(name.strip(), padding=10, color="#f9f6f2")
num_img = await text2image(num_str.strip(), padding=10, color="#f9f6f2")
if not date_scope:
if date_scope := await ChatHistory.get_group_first_msg_datetime(gid):
date_scope = date_scope.astimezone(
pytz.timezone("Asia/Shanghai")
).replace(microsecond=0)
else:
date_scope = time_now.replace(microsecond=0)
date_str = f"日期:{date_scope} - 至今"
else:
date_str = f"日期:{date_scope[0].replace(microsecond=0)} - {date_scope[1].replace(microsecond=0)}"
date_w = BuildImage(0, 0, font_size=15).getsize(date_str)[0]
img_w = date_w if date_w > name_img.w + num_img.w else name_img.w + num_img.w
A = BuildImage(
img_w + 15,
num_img.h + 30,
color="#f9f6f2",
font="CJGaoDeGuo.otf",
font_size=15,
)
await A.atext((10, 10), date_str)
await A.apaste(name_img, (0, 30))
await A.apaste(num_img, (name_img.w, 30))
await msg_handler.send(image(b64=A.pic2bs4())) | null |
188,164 | from nonebot import on_message
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent
from configs.config import Config
from models.chat_history import ChatHistory
from services.log import logger
from utils.depends import PlaintText
from utils.utils import scheduler
from ._rule import rule
TEMP_LIST = []
class ChatHistory(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255, null=True)
"""群聊id"""
text = fields.TextField(null=True)
"""文本内容"""
plain_text = fields.TextField(null=True)
"""纯文本"""
create_time = fields.DatetimeField(auto_now_add=True)
"""创建时间"""
bot_id = fields.CharField(255, null=True)
"""bot记录id"""
class Meta:
table = "chat_history"
table_description = "聊天记录数据表"
async def get_group_msg_rank(
cls,
gid: Union[int, str],
limit: int = 10,
order: str = "DESC",
date_scope: Optional[Tuple[datetime, datetime]] = None,
) -> List["ChatHistory"]:
"""
说明:
获取排行数据
参数:
:param gid: 群号
:param limit: 获取数量
:param order: 排序类型,desc,des
:param date_scope: 日期范围
"""
o = "-" if order == "DESC" else ""
query = cls.filter(group_id=str(gid))
if date_scope:
query = query.filter(create_time__range=date_scope)
return list(
await query.annotate(count=Count("user_id"))
.order_by(o + "count")
.group_by("user_id")
.limit(limit)
.values_list("user_id", "count")
) # type: ignore
async def get_group_first_msg_datetime(
cls, group_id: Union[int, str]
) -> Optional[datetime]:
"""
说明:
获取群第一条记录消息时间
参数:
:param group_id: 群组id
"""
if (
message := await cls.filter(group_id=str(group_id))
.order_by("create_time")
.first()
):
return message.create_time
async def get_message(
cls,
uid: Union[int, str],
gid: Union[int, str],
type_: Literal["user", "group"],
msg_type: Optional[Literal["private", "group"]] = None,
days: Optional[Union[int, Tuple[datetime, datetime]]] = None,
) -> List["ChatHistory"]:
"""
说明:
获取消息查询query
参数:
:param uid: 用户id
:param gid: 群聊id
:param type_: 类型,私聊或群聊
:param msg_type: 消息类型,用户或群聊
:param days: 限制日期
"""
if type_ == "user":
query = cls.filter(user_id=str(uid))
if msg_type == "private":
query = query.filter(group_id__isnull=True)
elif msg_type == "group":
query = query.filter(group_id__not_isnull=True)
else:
query = cls.filter(group_id=str(gid))
if uid:
query = query.filter(user_id=str(uid))
if days:
if isinstance(days, int):
query = query.filter(
create_time__gte=datetime.now() - timedelta(days=days)
)
elif isinstance(days, tuple):
query = query.filter(create_time__range=days)
return await query.all() # type: ignore
async def _run_script(cls):
return [
"alter table chat_history alter group_id drop not null;", # 允许 group_id 为空
"alter table chat_history alter text drop not null;", # 允许 text 为空
"alter table chat_history alter plain_text drop not null;", # 允许 plain_text 为空
"ALTER TABLE chat_history RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE chat_history ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE chat_history ALTER COLUMN group_id TYPE character varying(255);",
"ALTER TABLE chat_history ADD bot_id VARCHAR(255);", # 添加bot_id字段
"ALTER TABLE chat_history ALTER COLUMN bot_id TYPE character varying(255);",
]
def PlaintText(msg: Optional[str] = None, contain_reply: bool = True) -> str:
"""
说明:
获取纯文本且(包括回复时),含有msg时不能为空,为空时提示并结束事件
参数:
:param msg: 提示文本
:param contain_reply: 包含回复内容
"""
async def dependency(matcher: Matcher, event: MessageEvent):
return await _match(matcher, event, msg, get_message_text, contain_reply)
return Depends(dependency)
async def _(bot: Bot, event: MessageEvent, msg: str = PlaintText()):
group_id = None
if isinstance(event, GroupMessageEvent):
group_id = str(event.group_id)
TEMP_LIST.append(
ChatHistory(
user_id=str(event.user_id),
group_id=group_id,
text=str(event.get_message()),
plain_text=msg,
bot_id=str(bot.self_id),
)
) | null |
188,165 | from nonebot import on_message
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent
from configs.config import Config
from models.chat_history import ChatHistory
from services.log import logger
from utils.depends import PlaintText
from utils.utils import scheduler
from ._rule import rule
TEMP_LIST = []
class ChatHistory(Model):
async def get_group_msg_rank(
cls,
gid: Union[int, str],
limit: int = 10,
order: str = "DESC",
date_scope: Optional[Tuple[datetime, datetime]] = None,
) -> List["ChatHistory"]:
async def get_group_first_msg_datetime(
cls, group_id: Union[int, str]
) -> Optional[datetime]:
async def get_message(
cls,
uid: Union[int, str],
gid: Union[int, str],
type_: Literal["user", "group"],
msg_type: Optional[Literal["private", "group"]] = None,
days: Optional[Union[int, Tuple[datetime, datetime]]] = None,
) -> List["ChatHistory"]:
async def _run_script(cls):
class logger:
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
async def _():
try:
message_list = TEMP_LIST.copy()
TEMP_LIST.clear()
if message_list:
await ChatHistory.bulk_create(message_list)
logger.debug(f"批量添加聊天记录 {len(message_list)} 条", "定时任务")
except Exception as e:
logger.error(f"定时批量添加聊天记录", "定时任务", e=e) | null |
188,166 | from pathlib import Path
import os
def load_path():
old_img_dir = Path() / "resources" / "img"
if not IMAGE_PATH.exists() and old_img_dir.exists():
os.rename(old_img_dir, IMAGE_PATH)
old_voice_dir = Path() / "resources" / "voice"
if not RECORD_PATH.exists() and old_voice_dir.exists():
os.rename(old_voice_dir, RECORD_PATH)
old_ttf_dir = Path() / "resources" / "ttf"
if not FONT_PATH.exists() and old_ttf_dir.exists():
os.rename(old_ttf_dir, FONT_PATH)
old_txt_dir = Path() / "resources" / "txt"
if not TEXT_PATH.exists() and old_txt_dir.exists():
os.rename(old_txt_dir, TEXT_PATH)
IMAGE_PATH.mkdir(parents=True, exist_ok=True)
RECORD_PATH.mkdir(parents=True, exist_ok=True)
TEXT_PATH.mkdir(parents=True, exist_ok=True)
LOG_PATH.mkdir(parents=True, exist_ok=True)
FONT_PATH.mkdir(parents=True, exist_ok=True)
DATA_PATH.mkdir(parents=True, exist_ok=True)
TEMP_PATH.mkdir(parents=True, exist_ok=True) | null |
188,167 | from typing import List
from nonebot.utils import is_coroutine_callable
from tortoise import Tortoise, fields
from tortoise.connection import connections
from tortoise.models import Model as Model_
from tortoise.queryset import RawSQLQuery
from configs.config import address, bind, database, password, port, sql_name, user
from utils.text_utils import prompt2cn
from .log import logger
MODELS: List[str] = []
SCRIPT_METHOD = []
class TestSQL(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
class Meta:
table = "test_sql"
table_description = "执行SQL命令,不记录任何数据"
user: str = "" str = "" str = "" = "" str = "" r] = None g = ConfigsManager(Path() / "data" / "configs" / "plugins2config.yaml")
def prompt2cn(text: str, count: int, s: str = "#") -> str:
"""
格式化中文提示
:param text: 文本
:param count: 个数
:param s: #
"""
return s * count + "\n" + s * 6 + " " + text + " " + s * 6 + "\n" + s * count
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def init():
if not bind and not any([user, password, address, port, database]):
raise ValueError("\n" + prompt2cn("数据库配置未填写", 28))
i_bind = bind
if not i_bind:
i_bind = f"{sql_name}://{user}:{password}@{address}:{port}/{database}"
try:
await Tortoise.init(
db_url=i_bind,
modules={"models": MODELS},
# timezone="Asia/Shanghai"
)
await Tortoise.generate_schemas()
logger.info(f"Database loaded successfully!")
except Exception as e:
raise Exception(f"数据库连接错误.... {type(e)}: {e}")
if SCRIPT_METHOD:
logger.debug(f"即将运行SCRIPT_METHOD方法, 合计 <u><y>{len(SCRIPT_METHOD)}</y></u> 个...")
sql_list = []
for module, func in SCRIPT_METHOD:
try:
if is_coroutine_callable(func):
sql = await func()
else:
sql = func()
if sql:
sql_list += sql
except Exception as e:
logger.debug(f"{module} 执行SCRIPT_METHOD方法出错...", e=e)
for sql in sql_list:
logger.debug(f"执行SQL: {sql}")
try:
await TestSQL.raw(sql)
except Exception as e:
logger.debug(f"执行SQL: {sql} 错误...", e=e) | null |
188,168 | from typing import List
from nonebot.utils import is_coroutine_callable
from tortoise import Tortoise, fields
from tortoise.connection import connections
from tortoise.models import Model as Model_
from tortoise.queryset import RawSQLQuery
from configs.config import address, bind, database, password, port, sql_name, user
from utils.text_utils import prompt2cn
from .log import logger
async def disconnect():
await connections.close_all() | null |
188,169 |
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def remind(bot: Bot):
if str(platform.system()).lower() != "windows":
restart = Path() / "restart.sh"
if not restart.exists():
with open(restart, "w", encoding="utf8") as f:
f.write(
f"pid=$(netstat -tunlp | grep "
+ str(bot.config.port)
+ " | awk '{print $7}')\n"
"pid=${pid%/*}\n"
"kill -9 $pid\n"
"sleep 3\n"
"python3 bot.py"
)
os.system("chmod +x ./restart.sh")
logger.info("已自动生成 restart.sh(重启) 文件,请检查脚本是否与本地指令符合...")
is_restart_file = Path() / "is_restart"
if is_restart_file.exists():
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"真寻重启完毕...",
)
is_restart_file.unlink() | null |
188,170 | import asyncio
import os
import platform
import shutil
import tarfile
from pathlib import Path
from typing import List, Tuple
import nonebot
import ujson as json
from nonebot.adapters.onebot.v11 import Bot, Message
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage
from utils.message_builder import image
driver = nonebot.get_driver()
release_url = "https://api.github.com/repos/HibiKier/zhenxun_bot/releases/latest"
_version_file = Path() / "__version__"
zhenxun_latest_tar_gz = Path() / "zhenxun_latest_file.tar.gz"
temp_dir = Path() / "temp"
backup_dir = Path() / "backup"
def _file_handle(latest_version: str) -> str:
if not temp_dir.exists():
temp_dir.mkdir(exist_ok=True, parents=True)
if backup_dir.exists():
shutil.rmtree(backup_dir)
tf = None
error = ""
# try:
backup_dir.mkdir(exist_ok=True, parents=True)
logger.info("开始解压真寻文件压缩包....")
tf = tarfile.open(zhenxun_latest_tar_gz)
tf.extractall(temp_dir)
logger.info("解压真寻文件压缩包完成....")
zhenxun_latest_file = Path(temp_dir) / os.listdir(temp_dir)[0]
update_info_file = Path(zhenxun_latest_file) / "update_info.json"
update_info = json.load(open(update_info_file, "r", encoding="utf8"))
update_file = update_info["update_file"]
add_file = update_info["add_file"]
delete_file = update_info["delete_file"]
config_file = Path() / "configs" / "config.py"
config_path_file = Path() / "configs" / "path_config.py"
# for file in [config_file.name]:
# tmp = ""
# new_file = Path(zhenxun_latest_file) / "configs" / file
# old_file = Path() / "configs" / file
# new_lines = open(new_file, "r", encoding="utf8").readlines()
# old_lines = open(old_file, "r", encoding="utf8").readlines()
# for nl in new_lines:
# tmp += check_old_lines(old_lines, nl)
# with open(old_file, "w", encoding="utf8") as f:
# f.write(tmp)
for file in delete_file + update_file:
if file != "configs":
file = Path() / file
backup_file = Path(backup_dir) / file
if file.exists():
backup_file.parent.mkdir(parents=True, exist_ok=True)
if backup_file.exists():
backup_file.unlink()
if file not in [config_file, config_path_file]:
shutil.move(file.absolute(), backup_file.absolute())
else:
with open(file, "r", encoding="utf8") as rf:
data = rf.read()
with open(backup_file, "w", encoding="utf8") as wf:
wf.write(data)
logger.info(f"已备份文件:{file}")
for file in add_file + update_file:
new_file = Path(zhenxun_latest_file) / file
old_file = Path() / file
if old_file not in [config_file, config_path_file] and file != "configs":
if not old_file.exists() and new_file.exists():
shutil.move(new_file.absolute(), old_file.absolute())
logger.info(f"已更新文件:{file}")
# except Exception as e:
# error = f'{type(e)}:{e}'
if tf:
tf.close()
if temp_dir.exists():
shutil.rmtree(temp_dir)
if zhenxun_latest_tar_gz.exists():
zhenxun_latest_tar_gz.unlink()
local_update_info_file = Path() / "update_info.json"
if local_update_info_file.exists():
local_update_info_file.unlink()
with open(_version_file, "w", encoding="utf8") as f:
f.write(f"__version__: {latest_version}")
os.system(f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}")
return error
_latest_version_data() -> dict:
for _ in range(3):
try:
res = await AsyncHttpx.get(release_url)
if res.status_code == 200:
return res.json()
except TimeoutError:
pass
except Exception as e:
logger.error(f"检查更新真寻获取版本失败 {type(e)}:{e}")
return {}
ck_old_lines(lines: List[str], line: str) -> str:
if "=" not in line:
return line
for l in lines:
if "=" in l and l.split("=")[0].strip() == line.split("=")[0].strip():
return l
return line
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
async def check_update(bot: Bot) -> Tuple[int, str]:
logger.info("开始检查更新真寻酱....")
_version = "v0.0.0"
if _version_file.exists():
_version = (
open(_version_file, "r", encoding="utf8").readline().split(":")[-1].strip()
)
data = await get_latest_version_data()
if data:
latest_version = data["name"]
if _version != latest_version:
tar_gz_url = data["tarball_url"]
logger.info(f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....",
)
logger.info(f"开始下载真寻最新版文件....")
tar_gz_url = (await AsyncHttpx.get(tar_gz_url)).headers.get("Location")
if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz):
logger.info("下载真寻最新版文件完成....")
error = await asyncio.get_event_loop().run_in_executor(
None, _file_handle, latest_version
)
if error:
return 998, error
logger.info("真寻更新完毕,清理文件完成....")
logger.info("开始获取真寻更新日志.....")
update_info = data["body"]
width = 0
height = len(update_info.split("\n")) * 24
A = BuildImage(width, height, font_size=20)
for m in update_info.split("\n"):
w, h = A.getsize(m)
if w > width:
width = w
A = BuildImage(width + 50, height, font_size=20)
A.text((10, 10), update_info)
A.save(f"{IMAGE_PATH}/update_info.png")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=Message(
f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"更新日期:{data['created_at']}\n"
f"更新日志:\n"
f"{image('update_info.png')}"
),
)
return 200, ""
else:
logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"下载真寻最新版本失败...版本号:{latest_version}.",
)
else:
logger.info(f"自动获取真寻版本成功:{latest_version},当前版本为最新版,无需更新...")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"自动获取真寻版本成功:{latest_version},当前版本为最新版,无需更新...",
)
else:
logger.warning("自动获取真寻版本失败....")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=f"自动获取真寻版本失败...."
)
return 999, "" | null |
188,171 |
def check_old_lines(lines: List[str], line: str) -> str:
if "=" not in line:
return line
for l in lines:
if "=" in l and l.split("=")[0].strip() == line.split("=")[0].strip():
return l
return line | null |
188,172 |
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
The provided code snippet includes necessary dependencies for implementing the `get_weather_of_city` function. Write a Python function `async def get_weather_of_city(city: str) -> str` to solve the following problem:
获取城市天气数据 :param city: 城市
Here is the function:
async def get_weather_of_city(city: str) -> str:
"""
获取城市天气数据
:param city: 城市
"""
code = _check_exists_city(city)
if code == 999:
return "不要查一个省份的天气啊,很累人的!"
elif code == 998:
return f"{NICKNAME}没查到!!试试查火星的天气?"
else:
data_json = (
await AsyncHttpx.get(
f"https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city={city[:-1]}"
)
).json()
if wh := data_json.get('data'):
w_type = wh[0]["wea_day"]
w_max = wh[0]["tem1"]
w_min = wh[0]["tem2"]
fengli = wh[0]["win_speed"]
ganmao = wh[0]["narrative"]
fengxiang = ','.join(wh[0].get('win', []))
repass = f"{city}的天气是 {w_type} 天\n最高温度: {w_max}\n最低温度: {w_min}\n风力: {fengli} {fengxiang}\n{ganmao}"
return repass
else:
return data_json.get("errmsg") or "好像出错了?再试试?" | 获取城市天气数据 :param city: 城市 |
188,173 | from utils.message_builder import image
from configs.path_config import TEXT_PATH
from configs.config import NICKNAME
from typing import List
from nonebot import Driver
from utils.http_utils import AsyncHttpx
import ujson as json
import nonebot
china_city = TEXT_PATH / "china_city.json"
data = {}
The provided code snippet includes necessary dependencies for implementing the `get_city_list` function. Write a Python function `def get_city_list() -> List[str]` to solve the following problem:
获取城市列表
Here is the function:
def get_city_list() -> List[str]:
"""
获取城市列表
"""
global data
if not data:
try:
with open(china_city, "r", encoding="utf8") as f:
data = json.load(f)
except FileNotFoundError:
data = {}
city_list = []
for p in data.keys():
for c in data[p]:
city_list.append(c)
city_list.append(p)
return city_list | 获取城市列表 |
188,174 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
RESULT_MESSAGE = {
"BLUE": ["这样看着才舒服", "是自己人,大伙把刀收好", "非常舒适~"],
"PURPLE": ["还行吧,勉强接受一下下", "居然不是蓝色,太假了", "运气-1-1-1-1-1..."],
"PINK": ["开始不适....", "你妈妈买菜必涨价!涨三倍!", "你最近不适合出门,真的"],
"RED": ["已经非常不适", "好兄弟你开的什么箱子啊,一般箱子不是只有蓝色的吗", "开始拿阳寿开箱子了?"],
"KNIFE": ["你的好运我收到了,你可以去喂鲨鱼了", "最近该吃啥就迟点啥吧,哎,好好的一个人怎么就....哎", "众所周知,欧皇寿命极短."],
}
_count(user: OpenCasesUser, skin: BuffSkin, case_price: float):
if skin.color == "BLUE":
if skin.is_stattrak:
user.blue_st_count += 1
else:
user.blue_count += 1
elif skin.color == "PURPLE":
if skin.is_stattrak:
user.purple_st_count += 1
else:
user.purple_count += 1
elif skin.color == "PINK":
if skin.is_stattrak:
user.pink_st_count += 1
else:
user.pink_count += 1
elif skin.color == "RED":
if skin.is_stattrak:
user.red_st_count += 1
else:
user.red_count += 1
elif skin.color == "KNIFE":
if skin.is_stattrak:
user.knife_st_count += 1
else:
user.knife_count += 1
user.make_money += skin.sell_min_price
user.spend_money += 17 + case_price
async def get_user_max_count(
user_id: Union[int, str], group_id: Union[str, int]
) -> int:
"""获取用户每日最大开箱次数
Args:
user_id (str): 用户id
group_id (int): 群号
Returns:
int: 最大开箱次数
"""
user, _ = await SignGroupUser.get_or_create(
user_id=str(user_id), group_id=str(group_id)
)
impression = int(user.impression)
initial_open_case_count = Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
each_impression_add_count = Config.get_config(
"open_cases", "EACH_IMPRESSION_ADD_COUNT"
)
return int(initial_open_case_count + impression / each_impression_add_count) # type: ignore
def _handle_is_MAX_COUNT() -> str:
return f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)"
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def cn2py(word: str) -> str:
"""
说明:
将字符串转化为拼音
参数:
:param word: 文本
"""
temp = ""
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
temp += "".join(i)
return temp
async def draw_card(skin: BuffSkin, rand: str) -> BuildImage:
"""构造抽取图片
Args:
skin (BuffSkin): BuffSkin
rand (str): 磨损
Returns:
BuildImage: BuildImage
"""
name = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
file_path = BASE_PATH / cn2py(skin.case_name.split(",")[0]) / f"{cn2py(name)}.jpg"
if not file_path.exists():
logger.warning(f"皮肤图片: {name} 不存在", "开箱")
skin_bk = BuildImage(
460, 200, color=(25, 25, 25, 100), font_size=25, font="CJGaoDeGuo.otf"
)
if file_path.exists():
skin_image = BuildImage(205, 153, background=file_path)
await skin_bk.apaste(skin_image, (10, 30), alpha=True)
await skin_bk.aline((220, 10, 220, 180))
await skin_bk.atext((10, 10), skin.name, (255, 255, 255))
name_icon = BuildImage(20, 20, background=ICON_PATH / "name_white.png")
await skin_bk.apaste(name_icon, (240, 13), True)
await skin_bk.atext((265, 15), f"名称:", (255, 255, 255), font_size=20)
await skin_bk.atext(
(300, 9),
f"{skin.skin_name + ('(St)' if skin.is_stattrak else '')}",
(255, 255, 255),
)
tone_icon = BuildImage(20, 20, background=ICON_PATH / "tone_white.png")
await skin_bk.apaste(tone_icon, (240, 45), True)
await skin_bk.atext((265, 45), "品质:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 40), COLOR2NAME[skin.color][:2], COLOR2COLOR[skin.color])
type_icon = BuildImage(20, 20, background=ICON_PATH / "type_white.png")
await skin_bk.apaste(type_icon, (240, 73), True)
await skin_bk.atext((265, 75), "类型:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 70), skin.weapon_type, (255, 255, 255))
price_icon = BuildImage(20, 20, background=ICON_PATH / "price_white.png")
await skin_bk.apaste(price_icon, (240, 103), True)
await skin_bk.atext((265, 105), "价格:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 102), str(skin.sell_min_price), (0, 255, 98))
abrasion_icon = BuildImage(20, 20, background=ICON_PATH / "abrasion_white.png")
await skin_bk.apaste(abrasion_icon, (240, 133), True)
await skin_bk.atext((265, 135), "磨损:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 130), skin.abrasion, (255, 255, 255))
await skin_bk.atext((228, 165), f"({rand})", (255, 255, 255))
return skin_bk
import random
async def random_skin(num: int, case_name: str) -> List[Tuple[BuffSkin, float]]:
"""
随机抽取皮肤
"""
case_name = case_name.replace("武器箱", "").replace(" ", "")
color_map = {}
for _ in range(num):
rand = random.random()
# 尝试降低磨损
if rand > MINIMAL_WEAR_E:
for _ in range(2):
if random.random() < 0.5:
logger.debug(f"[START]开箱随机磨损触发降低磨损条件: {rand}")
if random.random() < 0.2:
rand /= 3
else:
rand /= 2
logger.debug(f"[END]开箱随机磨损触发降低磨损条件: {rand}")
break
abrasion = get_wear(rand)
logger.debug(f"开箱随机磨损: {rand} | {abrasion}")
color, is_stattrak = random_color_and_st(rand)
if not color_map.get(color):
color_map[color] = {}
if is_stattrak:
if not color_map[color].get(f"{abrasion}_st"):
color_map[color][f"{abrasion}_st"] = []
color_map[color][f"{abrasion}_st"].append(rand)
else:
if not color_map[color].get(abrasion):
color_map[color][f"{abrasion}"] = []
color_map[color][f"{abrasion}"].append(rand)
skin_list = []
for color in color_map:
for abrasion in color_map[color]:
rand_list = color_map[color][abrasion]
is_stattrak = "_st" in abrasion
abrasion = abrasion.replace("_st", "")
skin_list_ = await BuffSkin.random_skin(
len(rand_list), color, abrasion, is_stattrak, case_name
)
skin_list += [(skin, rand) for skin, rand in zip(skin_list_, rand_list)]
return skin_list
class OpenCasesLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
case_name = fields.CharField(255)
"""箱子名称"""
name = fields.CharField(255)
"""武器/手套/刀名称"""
skin_name = fields.CharField(255)
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
abrasion_value = fields.FloatField()
"""磨损数值"""
color = fields.CharField(255)
"""颜色(品质)"""
price = fields.FloatField(default=0)
"""价格"""
create_time = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
class Meta:
table = "open_cases_log"
table_description = "开箱日志表"
async def _run_script(cls):
return [
"ALTER TABLE open_cases_log RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_log ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_log ALTER COLUMN group_id TYPE character varying(255);",
]
class OpenCasesUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
total_count: int = fields.IntField(default=0)
"""总开启次数"""
blue_count: int = fields.IntField(default=0)
"""蓝色"""
blue_st_count: int = fields.IntField(default=0)
"""蓝色暗金"""
purple_count: int = fields.IntField(default=0)
"""紫色"""
purple_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
pink_count: int = fields.IntField(default=0)
"""粉色"""
pink_st_count: int = fields.IntField(default=0)
"""粉色暗金"""
red_count: int = fields.IntField(default=0)
"""紫色"""
red_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
knife_count: int = fields.IntField(default=0)
"""金色"""
knife_st_count: int = fields.IntField(default=0)
"""金色暗金"""
spend_money: float = fields.IntField(default=0)
"""花费金币"""
make_money: float = fields.FloatField(default=0)
"""赚取金币"""
today_open_total: int = fields.IntField(default=0)
"""今日开箱数量"""
open_cases_time_last: datetime = fields.DatetimeField()
"""最后开箱日期"""
knifes_name: str = fields.TextField(default="")
"""已获取金色"""
class Meta:
table = "open_cases_users"
table_description = "开箱统计数据表"
unique_together = ("user_id", "group_id")
async def _run_script(cls):
return [
"alter table open_cases_users alter COLUMN make_money type float;", # 将make_money字段改为float
"alter table open_cases_users alter COLUMN spend_money type float;", # 将spend_money字段改为float
"ALTER TABLE open_cases_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_users ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_users ALTER COLUMN group_id TYPE character varying(255);",
]
class CaseManager:
CURRENT_CASES = []
async def reload(cls):
cls.CURRENT_CASES = []
case_list = await BuffSkin.filter(color="CASE").values_list(
"case_name", flat=True
)
for case_name in (
await BuffSkin.filter(case_name__not="未知武器箱")
.annotate()
.distinct()
.values_list("case_name", flat=True)
):
for name in case_name.split(","): # type: ignore
if name not in cls.CURRENT_CASES and name in case_list:
cls.CURRENT_CASES.append(name)
The provided code snippet includes necessary dependencies for implementing the `open_case` function. Write a Python function `async def open_case( user_id: Union[int, str], group_id: Union[int, str], case_name: str ) -> Union[str, Message]` to solve the following problem:
开箱 Args: user_id (str): 用户id group_id (int): 群号 case_name (str, optional): 武器箱名称. Defaults to "狂牙大行动". Returns: Union[str, Message]: 回复消息
Here is the function:
async def open_case(
user_id: Union[int, str], group_id: Union[int, str], case_name: str
) -> Union[str, Message]:
"""开箱
Args:
user_id (str): 用户id
group_id (int): 群号
case_name (str, optional): 武器箱名称. Defaults to "狂牙大行动".
Returns:
Union[str, Message]: 回复消息
"""
user_id = str(user_id)
group_id = str(group_id)
if not CaseManager.CURRENT_CASES:
return "未收录任何武器箱"
if not case_name:
case_name = random.choice(CaseManager.CURRENT_CASES) # type: ignore
if case_name not in CaseManager.CURRENT_CASES:
return "武器箱未收录, 当前可用武器箱:\n" + ", ".join(CaseManager.CURRENT_CASES) # type: ignore
logger.debug(f"尝试开启武器箱: {case_name}", "开箱", user_id, group_id)
case = cn2py(case_name)
user = await OpenCasesUser.get_or_none(user_id=user_id, group_id=group_id)
if not user:
user = await OpenCasesUser.create(
user_id=user_id, group_id=group_id, open_cases_time_last=datetime.now()
)
max_count = await get_user_max_count(user_id, group_id)
# 一天次数上限
if user.today_open_total >= max_count:
return _handle_is_MAX_COUNT()
skin_list = await random_skin(1, case_name)
if not skin_list:
return "未抽取到任何皮肤..."
skin, rand = skin_list[0]
rand = str(rand)[:11]
case_price = 0
if case_skin := await BuffSkin.get_or_none(case_name=case_name, color="CASE"):
case_price = case_skin.sell_min_price
user.today_open_total += 1
user.total_count += 1
user.open_cases_time_last = datetime.now()
await user.save(
update_fields=["today_open_total", "total_count", "open_cases_time_last"]
)
add_count(user, skin, case_price)
ridicule_result = random.choice(RESULT_MESSAGE[skin.color])
price_result = skin.sell_min_price
name = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
img_path = IMAGE_PATH / "csgo_cases" / case / f"{cn2py(name)}.jpg"
logger.info(
f"开启{case_name}武器箱获得 {skin.name}{'(StatTrak™)' if skin.is_stattrak else ''} | {skin.skin_name} ({skin.abrasion}) 磨损: [{rand}] 价格: {skin.sell_min_price}",
"开箱",
user_id,
group_id,
)
await user.save()
await OpenCasesLog.create(
user_id=user_id,
group_id=group_id,
case_name=case_name,
name=skin.name,
skin_name=skin.skin_name,
is_stattrak=skin.is_stattrak,
abrasion=skin.abrasion,
color=skin.color,
price=skin.sell_min_price,
abrasion_value=rand,
create_time=datetime.now(),
)
logger.debug(f"添加 1 条开箱日志", "开箱", user_id, group_id)
over_count = max_count - user.today_open_total
img = await draw_card(skin, rand)
return (
f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n"
+ image(img)
+ f"\n箱子单价:{case_price}\n花费:{17 + case_price:.2f}\n:{ridicule_result}"
) | 开箱 Args: user_id (str): 用户id group_id (int): 群号 case_name (str, optional): 武器箱名称. Defaults to "狂牙大行动". Returns: Union[str, Message]: 回复消息 |
188,175 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
: "蓝", "PURPLE": "紫", "PINK": "粉", "RED": "红", "KNIFE": "金"}
def add_count(user: OpenCasesUser, skin: BuffSkin, case_price: float):
if skin.color == "BLUE":
if skin.is_stattrak:
user.blue_st_count += 1
else:
user.blue_count += 1
elif skin.color == "PURPLE":
if skin.is_stattrak:
user.purple_st_count += 1
else:
user.purple_count += 1
elif skin.color == "PINK":
if skin.is_stattrak:
user.pink_st_count += 1
else:
user.pink_count += 1
elif skin.color == "RED":
if skin.is_stattrak:
user.red_st_count += 1
else:
user.red_count += 1
elif skin.color == "KNIFE":
if skin.is_stattrak:
user.knife_st_count += 1
else:
user.knife_count += 1
user.make_money += skin.sell_min_price
user.spend_money += 17 + case_price
async def get_user_max_count(
user_id: Union[int, str], group_id: Union[str, int]
) -> int:
"""获取用户每日最大开箱次数
Args:
user_id (str): 用户id
group_id (int): 群号
Returns:
int: 最大开箱次数
"""
user, _ = await SignGroupUser.get_or_create(
user_id=str(user_id), group_id=str(group_id)
)
impression = int(user.impression)
initial_open_case_count = Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
each_impression_add_count = Config.get_config(
"open_cases", "EACH_IMPRESSION_ADD_COUNT"
)
return int(initial_open_case_count + impression / each_impression_add_count) # type: ignore
def _handle_is_MAX_COUNT() -> str:
return f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)"
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def cn2py(word: str) -> str:
"""
说明:
将字符串转化为拼音
参数:
:param word: 文本
"""
temp = ""
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
temp += "".join(i)
return temp
async def draw_card(skin: BuffSkin, rand: str) -> BuildImage:
"""构造抽取图片
Args:
skin (BuffSkin): BuffSkin
rand (str): 磨损
Returns:
BuildImage: BuildImage
"""
name = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
file_path = BASE_PATH / cn2py(skin.case_name.split(",")[0]) / f"{cn2py(name)}.jpg"
if not file_path.exists():
logger.warning(f"皮肤图片: {name} 不存在", "开箱")
skin_bk = BuildImage(
460, 200, color=(25, 25, 25, 100), font_size=25, font="CJGaoDeGuo.otf"
)
if file_path.exists():
skin_image = BuildImage(205, 153, background=file_path)
await skin_bk.apaste(skin_image, (10, 30), alpha=True)
await skin_bk.aline((220, 10, 220, 180))
await skin_bk.atext((10, 10), skin.name, (255, 255, 255))
name_icon = BuildImage(20, 20, background=ICON_PATH / "name_white.png")
await skin_bk.apaste(name_icon, (240, 13), True)
await skin_bk.atext((265, 15), f"名称:", (255, 255, 255), font_size=20)
await skin_bk.atext(
(300, 9),
f"{skin.skin_name + ('(St)' if skin.is_stattrak else '')}",
(255, 255, 255),
)
tone_icon = BuildImage(20, 20, background=ICON_PATH / "tone_white.png")
await skin_bk.apaste(tone_icon, (240, 45), True)
await skin_bk.atext((265, 45), "品质:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 40), COLOR2NAME[skin.color][:2], COLOR2COLOR[skin.color])
type_icon = BuildImage(20, 20, background=ICON_PATH / "type_white.png")
await skin_bk.apaste(type_icon, (240, 73), True)
await skin_bk.atext((265, 75), "类型:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 70), skin.weapon_type, (255, 255, 255))
price_icon = BuildImage(20, 20, background=ICON_PATH / "price_white.png")
await skin_bk.apaste(price_icon, (240, 103), True)
await skin_bk.atext((265, 105), "价格:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 102), str(skin.sell_min_price), (0, 255, 98))
abrasion_icon = BuildImage(20, 20, background=ICON_PATH / "abrasion_white.png")
await skin_bk.apaste(abrasion_icon, (240, 133), True)
await skin_bk.atext((265, 135), "磨损:", (255, 255, 255), font_size=20)
await skin_bk.atext((300, 130), skin.abrasion, (255, 255, 255))
await skin_bk.atext((228, 165), f"({rand})", (255, 255, 255))
return skin_bk
import random
async def random_skin(num: int, case_name: str) -> List[Tuple[BuffSkin, float]]:
"""
随机抽取皮肤
"""
case_name = case_name.replace("武器箱", "").replace(" ", "")
color_map = {}
for _ in range(num):
rand = random.random()
# 尝试降低磨损
if rand > MINIMAL_WEAR_E:
for _ in range(2):
if random.random() < 0.5:
logger.debug(f"[START]开箱随机磨损触发降低磨损条件: {rand}")
if random.random() < 0.2:
rand /= 3
else:
rand /= 2
logger.debug(f"[END]开箱随机磨损触发降低磨损条件: {rand}")
break
abrasion = get_wear(rand)
logger.debug(f"开箱随机磨损: {rand} | {abrasion}")
color, is_stattrak = random_color_and_st(rand)
if not color_map.get(color):
color_map[color] = {}
if is_stattrak:
if not color_map[color].get(f"{abrasion}_st"):
color_map[color][f"{abrasion}_st"] = []
color_map[color][f"{abrasion}_st"].append(rand)
else:
if not color_map[color].get(abrasion):
color_map[color][f"{abrasion}"] = []
color_map[color][f"{abrasion}"].append(rand)
skin_list = []
for color in color_map:
for abrasion in color_map[color]:
rand_list = color_map[color][abrasion]
is_stattrak = "_st" in abrasion
abrasion = abrasion.replace("_st", "")
skin_list_ = await BuffSkin.random_skin(
len(rand_list), color, abrasion, is_stattrak, case_name
)
skin_list += [(skin, rand) for skin, rand in zip(skin_list_, rand_list)]
return skin_list
class OpenCasesLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
case_name = fields.CharField(255)
"""箱子名称"""
name = fields.CharField(255)
"""武器/手套/刀名称"""
skin_name = fields.CharField(255)
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
abrasion_value = fields.FloatField()
"""磨损数值"""
color = fields.CharField(255)
"""颜色(品质)"""
price = fields.FloatField(default=0)
"""价格"""
create_time = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
class Meta:
table = "open_cases_log"
table_description = "开箱日志表"
async def _run_script(cls):
return [
"ALTER TABLE open_cases_log RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_log ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_log ALTER COLUMN group_id TYPE character varying(255);",
]
class OpenCasesUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
total_count: int = fields.IntField(default=0)
"""总开启次数"""
blue_count: int = fields.IntField(default=0)
"""蓝色"""
blue_st_count: int = fields.IntField(default=0)
"""蓝色暗金"""
purple_count: int = fields.IntField(default=0)
"""紫色"""
purple_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
pink_count: int = fields.IntField(default=0)
"""粉色"""
pink_st_count: int = fields.IntField(default=0)
"""粉色暗金"""
red_count: int = fields.IntField(default=0)
"""紫色"""
red_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
knife_count: int = fields.IntField(default=0)
"""金色"""
knife_st_count: int = fields.IntField(default=0)
"""金色暗金"""
spend_money: float = fields.IntField(default=0)
"""花费金币"""
make_money: float = fields.FloatField(default=0)
"""赚取金币"""
today_open_total: int = fields.IntField(default=0)
"""今日开箱数量"""
open_cases_time_last: datetime = fields.DatetimeField()
"""最后开箱日期"""
knifes_name: str = fields.TextField(default="")
"""已获取金色"""
class Meta:
table = "open_cases_users"
table_description = "开箱统计数据表"
unique_together = ("user_id", "group_id")
async def _run_script(cls):
return [
"alter table open_cases_users alter COLUMN make_money type float;", # 将make_money字段改为float
"alter table open_cases_users alter COLUMN spend_money type float;", # 将spend_money字段改为float
"ALTER TABLE open_cases_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_users ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_users ALTER COLUMN group_id TYPE character varying(255);",
]
class CaseManager:
CURRENT_CASES = []
async def reload(cls):
cls.CURRENT_CASES = []
case_list = await BuffSkin.filter(color="CASE").values_list(
"case_name", flat=True
)
for case_name in (
await BuffSkin.filter(case_name__not="未知武器箱")
.annotate()
.distinct()
.values_list("case_name", flat=True)
):
for name in case_name.split(","): # type: ignore
if name not in cls.CURRENT_CASES and name in case_list:
cls.CURRENT_CASES.append(name)
The provided code snippet includes necessary dependencies for implementing the `open_multiple_case` function. Write a Python function `async def open_multiple_case( user_id: Union[int, str], group_id: Union[str, int], case_name: str, num: int = 10 )` to solve the following problem:
多连开箱 Args: user_id (int): 用户id group_id (int): 群号 case_name (str): 箱子名称 num (int, optional): 数量. Defaults to 10. Returns: _type_: _description_
Here is the function:
async def open_multiple_case(
user_id: Union[int, str], group_id: Union[str, int], case_name: str, num: int = 10
):
"""多连开箱
Args:
user_id (int): 用户id
group_id (int): 群号
case_name (str): 箱子名称
num (int, optional): 数量. Defaults to 10.
Returns:
_type_: _description_
"""
user_id = str(user_id)
group_id = str(group_id)
if not CaseManager.CURRENT_CASES:
return "未收录任何武器箱"
if not case_name:
case_name = random.choice(CaseManager.CURRENT_CASES) # type: ignore
if case_name not in CaseManager.CURRENT_CASES:
return "武器箱未收录, 当前可用武器箱:\n" + ", ".join(CaseManager.CURRENT_CASES) # type: ignore
user, _ = await OpenCasesUser.get_or_create(
user_id=user_id,
group_id=group_id,
defaults={"open_cases_time_last": datetime.now()},
)
max_count = await get_user_max_count(user_id, group_id)
if user.today_open_total >= max_count:
return _handle_is_MAX_COUNT()
if max_count - user.today_open_total < num:
return (
f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)"
f"\n剩余开箱次数:{max_count - user.today_open_total}"
)
logger.debug(f"尝试开启武器箱: {case_name}", "开箱", user_id, group_id)
case = cn2py(case_name)
skin_count = {}
img_list = []
skin_list = await random_skin(num, case_name)
if not skin_list:
return "未抽取到任何皮肤..."
total_price = 0
log_list = []
now = datetime.now()
user.today_open_total += num
user.total_count += num
user.open_cases_time_last = datetime.now()
await user.save(
update_fields=["today_open_total", "total_count", "open_cases_time_last"]
)
case_price = 0
if case_skin := await BuffSkin.get_or_none(case_name=case_name, color="CASE"):
case_price = case_skin.sell_min_price
img_w, img_h = 0, 0
for skin, rand in skin_list:
img = await draw_card(skin, str(rand)[:11])
img_w, img_h = img.size
total_price += skin.sell_min_price
color_name = COLOR2CN[skin.color]
if not skin_count.get(color_name):
skin_count[color_name] = 0
skin_count[color_name] += 1
add_count(user, skin, case_price)
img_list.append(img)
logger.info(
f"开启{case_name}武器箱获得 {skin.name}{'(StatTrak™)' if skin.is_stattrak else ''} | {skin.skin_name} ({skin.abrasion}) 磨损: [{rand:.11f}] 价格: {skin.sell_min_price}",
"开箱",
user_id,
group_id,
)
log_list.append(
OpenCasesLog(
user_id=user_id,
group_id=group_id,
case_name=case_name,
name=skin.name,
skin_name=skin.skin_name,
is_stattrak=skin.is_stattrak,
abrasion=skin.abrasion,
color=skin.color,
price=skin.sell_min_price,
abrasion_value=rand,
create_time=now,
)
)
await user.save()
if log_list:
await OpenCasesLog.bulk_create(log_list, 10)
logger.debug(f"添加 {len(log_list)} 条开箱日志", "开箱", user_id, group_id)
img_w += 10
img_h += 10
w = img_w * 5
if num < 5:
h = img_h - 10
w = img_w * num
elif not num % 5:
h = img_h * int(num / 5)
else:
h = img_h * int(num / 5) + img_h
markImg = BuildImage(
w - 10, h - 10, img_w - 10, img_h - 10, 10, color=(255, 255, 255)
)
for img in img_list:
markImg.paste(img, alpha=True)
over_count = max_count - user.today_open_total
result = ""
for color_name in skin_count:
result += f"[{color_name}:{skin_count[color_name]}] "
return (
f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n"
+ image(markImg)
+ "\n"
+ result[:-1]
+ f"\n箱子单价:{case_price}\n总获取金额:{total_price:.2f}\n总花费:{(17 + case_price) * num:.2f}"
) | 多连开箱 Args: user_id (int): 用户id group_id (int): 群号 case_name (str): 箱子名称 num (int, optional): 数量. Defaults to 10. Returns: _type_: _description_ |
188,176 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
class OpenCasesUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
total_count: int = fields.IntField(default=0)
"""总开启次数"""
blue_count: int = fields.IntField(default=0)
"""蓝色"""
blue_st_count: int = fields.IntField(default=0)
"""蓝色暗金"""
purple_count: int = fields.IntField(default=0)
"""紫色"""
purple_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
pink_count: int = fields.IntField(default=0)
"""粉色"""
pink_st_count: int = fields.IntField(default=0)
"""粉色暗金"""
red_count: int = fields.IntField(default=0)
"""紫色"""
red_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
knife_count: int = fields.IntField(default=0)
"""金色"""
knife_st_count: int = fields.IntField(default=0)
"""金色暗金"""
spend_money: float = fields.IntField(default=0)
"""花费金币"""
make_money: float = fields.FloatField(default=0)
"""赚取金币"""
today_open_total: int = fields.IntField(default=0)
"""今日开箱数量"""
open_cases_time_last: datetime = fields.DatetimeField()
"""最后开箱日期"""
knifes_name: str = fields.TextField(default="")
"""已获取金色"""
class Meta:
table = "open_cases_users"
table_description = "开箱统计数据表"
unique_together = ("user_id", "group_id")
async def _run_script(cls):
return [
"alter table open_cases_users alter COLUMN make_money type float;", # 将make_money字段改为float
"alter table open_cases_users alter COLUMN spend_money type float;", # 将spend_money字段改为float
"ALTER TABLE open_cases_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_users ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_users ALTER COLUMN group_id TYPE character varying(255);",
]
async def total_open_statistics(
user_id: Union[str, int], group_id: Union[str, int]
) -> str:
user, _ = await OpenCasesUser.get_or_create(
user_id=str(user_id), group_id=str(group_id)
)
return (
f"开箱总数:{user.total_count}\n"
f"今日开箱:{user.today_open_total}\n"
f"蓝色军规:{user.blue_count}\n"
f"蓝色暗金:{user.blue_st_count}\n"
f"紫色受限:{user.purple_count}\n"
f"紫色暗金:{user.purple_st_count}\n"
f"粉色保密:{user.pink_count}\n"
f"粉色暗金:{user.pink_st_count}\n"
f"红色隐秘:{user.red_count}\n"
f"红色暗金:{user.red_st_count}\n"
f"金色罕见:{user.knife_count}\n"
f"金色暗金:{user.knife_st_count}\n"
f"花费金额:{user.spend_money}\n"
f"获取金额:{user.make_money:.2f}\n"
f"最后开箱日期:{user.open_cases_time_last.date()}"
) | null |
188,177 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
class OpenCasesUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
total_count: int = fields.IntField(default=0)
"""总开启次数"""
blue_count: int = fields.IntField(default=0)
"""蓝色"""
blue_st_count: int = fields.IntField(default=0)
"""蓝色暗金"""
purple_count: int = fields.IntField(default=0)
"""紫色"""
purple_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
pink_count: int = fields.IntField(default=0)
"""粉色"""
pink_st_count: int = fields.IntField(default=0)
"""粉色暗金"""
red_count: int = fields.IntField(default=0)
"""紫色"""
red_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
knife_count: int = fields.IntField(default=0)
"""金色"""
knife_st_count: int = fields.IntField(default=0)
"""金色暗金"""
spend_money: float = fields.IntField(default=0)
"""花费金币"""
make_money: float = fields.FloatField(default=0)
"""赚取金币"""
today_open_total: int = fields.IntField(default=0)
"""今日开箱数量"""
open_cases_time_last: datetime = fields.DatetimeField()
"""最后开箱日期"""
knifes_name: str = fields.TextField(default="")
"""已获取金色"""
class Meta:
table = "open_cases_users"
table_description = "开箱统计数据表"
unique_together = ("user_id", "group_id")
async def _run_script(cls):
return [
"alter table open_cases_users alter COLUMN make_money type float;", # 将make_money字段改为float
"alter table open_cases_users alter COLUMN spend_money type float;", # 将spend_money字段改为float
"ALTER TABLE open_cases_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_users ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_users ALTER COLUMN group_id TYPE character varying(255);",
]
async def group_statistics(group_id: Union[int, str]):
user_list = await OpenCasesUser.filter(group_id=str(group_id)).all()
# lan zi fen hong jin pricei
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0, 0]
for user in user_list:
uplist[0] += user.blue_count
uplist[1] += user.blue_st_count
uplist[2] += user.purple_count
uplist[3] += user.purple_st_count
uplist[4] += user.pink_count
uplist[5] += user.pink_st_count
uplist[6] += user.red_count
uplist[7] += user.red_st_count
uplist[8] += user.knife_count
uplist[9] += user.knife_st_count
uplist[10] += user.make_money
uplist[11] += user.total_count
uplist[12] += user.today_open_total
return (
f"群开箱总数:{uplist[11]}\n"
f"群今日开箱:{uplist[12]}\n"
f"蓝色军规:{uplist[0]}\n"
f"蓝色暗金:{uplist[1]}\n"
f"紫色受限:{uplist[2]}\n"
f"紫色暗金:{uplist[3]}\n"
f"粉色保密:{uplist[4]}\n"
f"粉色暗金:{uplist[5]}\n"
f"红色隐秘:{uplist[6]}\n"
f"红色暗金:{uplist[7]}\n"
f"金色罕见:{uplist[8]}\n"
f"金色暗金:{uplist[9]}\n"
f"花费金额:{uplist[11] * 17}\n"
f"获取金额:{uplist[10]:.2f}"
) | null |
188,178 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
async def get_old_knife(user_id: str, group_id: str) -> List[OpenCasesLog]:
"""获取旧数据字段
Args:
user_id (str): 用户id
group_id (str): 群号
Returns:
List[OpenCasesLog]: 旧数据兼容
"""
user, _ = await OpenCasesUser.get_or_create(user_id=user_id, group_id=group_id)
knifes_name = user.knifes_name
data_list = []
if knifes_name:
knifes_list = knifes_name[:-1].split(",")
for knife in knifes_list:
try:
if r := re.search(
"(.*)\|\|(.*) \| (.*)\((.*)\) 磨损:(.*), 价格:(.*)", knife
):
case_name_py = r.group(1)
name = r.group(2)
skin_name = r.group(3)
abrasion = r.group(4)
abrasion_value = r.group(5)
price = r.group(6)
name = name.replace("(StatTrak™)", "")
data_list.append(
OpenCasesLog(
user_id=user_id,
group_id=group_id,
name=name.strip(),
case_name=case_name_py.strip(),
skin_name=skin_name.strip(),
abrasion=abrasion.strip(),
abrasion_value=abrasion_value,
price=price,
)
)
except Exception as e:
logger.error(f"获取兼容旧数据错误: {knife}", "我的金色", user_id, group_id, e=e)
return data_list
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def cn2py(word: str) -> str:
"""
说明:
将字符串转化为拼音
参数:
:param word: 文本
"""
temp = ""
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
temp += "".join(i)
return temp
class OpenCasesLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
case_name = fields.CharField(255)
"""箱子名称"""
name = fields.CharField(255)
"""武器/手套/刀名称"""
skin_name = fields.CharField(255)
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
abrasion_value = fields.FloatField()
"""磨损数值"""
color = fields.CharField(255)
"""颜色(品质)"""
price = fields.FloatField(default=0)
"""价格"""
create_time = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
class Meta:
table = "open_cases_log"
table_description = "开箱日志表"
async def _run_script(cls):
return [
"ALTER TABLE open_cases_log RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_log ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_log ALTER COLUMN group_id TYPE character varying(255);",
]
The provided code snippet includes necessary dependencies for implementing the `get_my_knifes` function. Write a Python function `async def get_my_knifes( user_id: Union[str, int], group_id: Union[str, int] ) -> Union[str, MessageSegment]` to solve the following problem:
获取我的金色 Args: user_id (str): 用户id group_id (str): 群号 Returns: Union[str, MessageSegment]: 回复消息或图片
Here is the function:
async def get_my_knifes(
user_id: Union[str, int], group_id: Union[str, int]
) -> Union[str, MessageSegment]:
"""获取我的金色
Args:
user_id (str): 用户id
group_id (str): 群号
Returns:
Union[str, MessageSegment]: 回复消息或图片
"""
data_list = await get_old_knife(str(user_id), str(group_id))
data_list += await OpenCasesLog.filter(
user_id=user_id, group_id=group_id, color="KNIFE"
).all()
if not data_list:
return "您木有开出金色级别的皮肤喔"
length = len(data_list)
if length < 5:
h = 600
w = length * 540
elif length % 5 == 0:
h = 600 * int(length / 5)
w = 540 * 5
else:
h = 600 * int(length / 5) + 600
w = 540 * 5
A = BuildImage(w, h, 540, 600)
for skin in data_list:
name = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
img_path = (
IMAGE_PATH / "csgo_cases" / cn2py(skin.case_name) / f"{cn2py(name)}.jpg"
)
knife_img = BuildImage(470, 600, 470, 470, font_size=20)
await knife_img.apaste(
BuildImage(470, 470, background=img_path if img_path.exists() else None),
(0, 0),
True,
)
await knife_img.atext(
(5, 500), f"\t{skin.name}|{skin.skin_name}({skin.abrasion})"
)
await knife_img.atext((5, 530), f"\t磨损:{skin.abrasion_value}")
await knife_img.atext((5, 560), f"\t价格:{skin.price}")
await A.apaste(knife_img)
return image(A) | 获取我的金色 Args: user_id (str): 用户id group_id (str): 群号 Returns: Union[str, MessageSegment]: 回复消息或图片 |
188,179 | import asyncio
import random
import re
from datetime import datetime
from typing import Union
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import cn2py
from .build_image import draw_card
from .config import *
from .models.open_cases_log import OpenCasesLog
from .models.open_cases_user import OpenCasesUser
from .utils import CaseManager, update_skin_data
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
import random
async def update_skin_data(name: str, is_update_case_name: bool = False) -> str:
"""更新箱子内皮肤数据
Args:
name (str): 箱子名称
is_update_case_name (bool): 是否必定更新所属箱子
Returns:
_type_: _description_
"""
type_ = None
if name in CASE2ID:
type_ = UpdateType.CASE
if name in KNIFE2ID:
type_ = UpdateType.WEAPON_TYPE
if not type_:
return "未在指定武器箱或指定武器类型内"
session = Config.get_config("open_cases", "COOKIE")
if not session:
return "BUFF COOKIE为空捏!"
weapon2case = {}
if type_ == UpdateType.WEAPON_TYPE:
db_data = await BuffSkin.filter(name__contains=name).all()
weapon2case = {
item.name + item.skin_name: item.case_name
for item in db_data
if item.case_name != "未知武器箱"
}
data_list, total = await search_skin_page(name, 1, type_)
if isinstance(data_list, str):
return data_list
for page in range(2, total + 1):
rand_time = random.randint(20, 50)
logger.debug(f"访问随机等待时间: {rand_time}", "开箱更新")
await asyncio.sleep(rand_time)
data_list_, total = await search_skin_page(name, page, type_)
if isinstance(data_list_, list):
data_list += data_list_
create_list: List[BuffSkin] = []
update_list: List[BuffSkin] = []
log_list = []
now = datetime.now()
exists_id_list = []
new_weapon2case = {}
for skin in data_list:
if skin.skin_id in exists_id_list:
continue
if skin.case_name:
skin.case_name = (
skin.case_name.replace("”", "")
.replace("“", "")
.replace("武器箱", "")
.replace(" ", "")
)
skin.name = skin.name.replace("(★ StatTrak™)", "").replace("(★)", "")
exists_id_list.append(skin.skin_id)
key = skin.name + skin.skin_name
name_ = skin.name + skin.skin_name + skin.abrasion
skin.create_time = now
skin.update_time = now
if UpdateType.WEAPON_TYPE and not skin.case_name:
if is_update_case_name:
case_name = new_weapon2case.get(key)
else:
case_name = weapon2case.get(key)
if not case_name:
if case_list := await get_skin_case(skin.skin_id):
case_name = ",".join(case_list)
rand = random.randint(10, 20)
logger.debug(
f"获取 {skin.name} | {skin.skin_name} 皮肤所属武器箱: {case_name}, 访问随机等待时间: {rand}",
"开箱更新",
)
await asyncio.sleep(rand)
if not case_name:
case_name = "未知武器箱"
else:
weapon2case[key] = case_name
new_weapon2case[key] = case_name
if skin.case_name == "反恐精英20周年":
skin.case_name = "CS20"
skin.case_name = case_name
if await BuffSkin.exists(skin_id=skin.skin_id):
update_list.append(skin)
else:
create_list.append(skin)
log_list.append(
BuffSkinLog(
name=skin.name,
case_name=skin.case_name,
skin_name=skin.skin_name,
is_stattrak=skin.is_stattrak,
abrasion=skin.abrasion,
color=skin.color,
steam_price=skin.steam_price,
weapon_type=skin.weapon_type,
buy_max_price=skin.buy_max_price,
buy_num=skin.buy_num,
sell_min_price=skin.sell_min_price,
sell_num=skin.sell_num,
sell_reference_price=skin.sell_reference_price,
create_time=now,
)
)
name_ = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
for c_name_ in skin.case_name.split(","):
file_path = BASE_PATH / cn2py(c_name_) / f"{cn2py(name_)}.jpg"
if not file_path.exists():
logger.debug(f"下载皮肤 {name} 图片: {skin.img_url}...", "开箱更新")
await AsyncHttpx.download_file(skin.img_url, file_path)
rand_time = random.randint(1, 10)
await asyncio.sleep(rand_time)
logger.debug(f"图片下载随机等待时间: {rand_time}", "开箱更新")
else:
logger.debug(f"皮肤 {name_} 图片已存在...", "开箱更新")
if create_list:
logger.debug(f"更新武器箱/皮肤: [<u><e>{name}</e></u>], 创建 {len(create_list)} 个皮肤!")
await BuffSkin.bulk_create(set(create_list), 10)
if update_list:
abrasion_list = []
name_list = []
skin_name_list = []
for skin in update_list:
if skin.abrasion not in abrasion_list:
abrasion_list.append(skin.abrasion)
if skin.name not in name_list:
name_list.append(skin.name)
if skin.skin_name not in skin_name_list:
skin_name_list.append(skin.skin_name)
db_data = await BuffSkin.filter(
case_name__contains=name,
skin_name__in=skin_name_list,
name__in=name_list,
abrasion__in=abrasion_list,
).all()
_update_list = []
for data in db_data:
for skin in update_list:
if (
data.name == skin.name
and data.skin_name == skin.skin_name
and data.abrasion == skin.abrasion
):
data.steam_price = skin.steam_price
data.buy_max_price = skin.buy_max_price
data.buy_num = skin.buy_num
data.sell_min_price = skin.sell_min_price
data.sell_num = skin.sell_num
data.sell_reference_price = skin.sell_reference_price
data.update_time = skin.update_time
_update_list.append(data)
logger.debug(f"更新武器箱/皮肤: [<u><c>{name}</c></u>], 更新 {len(create_list)} 个皮肤!")
await BuffSkin.bulk_update(
_update_list,
[
"steam_price",
"buy_max_price",
"buy_num",
"sell_min_price",
"sell_num",
"sell_reference_price",
"update_time",
],
10,
)
if log_list:
logger.debug(f"更新武器箱/皮肤: [<u><e>{name}</e></u>], 新增 {len(log_list)} 条皮肤日志!")
await BuffSkinLog.bulk_create(log_list)
if name not in CaseManager.CURRENT_CASES:
CaseManager.CURRENT_CASES.append(name) # type: ignore
return f"更新武器箱/皮肤: [{name}] 成功, 共更新 {len(update_list)} 个皮肤, 新创建 {len(create_list)} 个皮肤!"
The provided code snippet includes necessary dependencies for implementing the `auto_update` function. Write a Python function `async def auto_update()` to solve the following problem:
自动更新武器箱
Here is the function:
async def auto_update():
"""自动更新武器箱"""
if case_list := Config.get_config("open_cases", "DAILY_UPDATE"):
logger.debug("尝试自动更新武器箱", "更新武器箱")
if "ALL" in case_list:
case_list = CASE2ID.keys()
logger.debug(f"预计自动更新武器箱 {len(case_list)} 个", "更新武器箱")
for case_name in case_list:
logger.debug(f"开始自动更新武器箱: {case_name}", "更新武器箱")
try:
await update_skin_data(case_name)
rand = random.randint(300, 500)
logger.info(f"成功自动更新武器箱: {case_name}, 将在 {rand} 秒后再次更新下一武器箱", "更新武器箱")
await asyncio.sleep(rand)
except Exception as e:
logger.error(f"自动更新武器箱: {case_name}", e=e) | 自动更新武器箱 |
188,180 | import asyncio
import os
import random
import re
import time
from datetime import datetime, timedelta
from typing import List, Optional, Tuple, Union
import nonebot
from tortoise.functions import Count
from configs.config import Config
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, BuildMat
from utils.utils import broadcast_group, cn2py
from .build_image import generate_skin
from .config import (
CASE2ID,
CASE_BACKGROUND,
COLOR2NAME,
KNIFE2ID,
NAME2COLOR,
UpdateType,
)
from .models.buff_skin import BuffSkin
from .models.buff_skin_log import BuffSkinLog
from .models.open_cases_user import OpenCasesUser
def get_bk_image_size(
total_size: int,
base_size: Tuple[int, int],
img_size: Tuple[int, int],
extra_height: int = 0,
):
"""获取所需背景大小且不改变图片长宽比
Args:
total_size (int): 总面积
base_size (Tuple[int, int]): 初始背景大小
img_size (Tuple[int, int]): 贴图大小
Returns:
_type_: 满足所有贴图大小
"""
bk_w, bk_h = base_size
img_w, img_h = img_size
is_add_title_size = False
left_dis = 0
right_dis = 0
old_size = (0, 0)
new_size = (0, 0)
ratio = 1.1
while 1:
w_ = int(ratio * bk_w)
h_ = int(ratio * bk_h)
size = w_ * h_
if size < total_size:
left_dis = size
else:
right_dis = size
r = w_ / (img_w + 25)
if right_dis and r - int(r) < 0.1:
if not is_add_title_size and extra_height:
total_size = int(total_size + w_ * extra_height)
is_add_title_size = True
right_dis = 0
continue
if total_size - left_dis > right_dis - total_size:
new_size = (w_, h_)
else:
new_size = old_size
break
old_size = (w_, h_)
ratio += 0.1
return new_size
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
async def generate_skin(skin: BuffSkin, update_count: int) -> Optional[BuildImage]:
"""构造皮肤图片
Args:
skin (BuffSkin): BuffSkin
Returns:
Optional[BuildImage]: 图片
"""
name = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
file_path = BASE_PATH / cn2py(skin.case_name.split(",")[0]) / f"{cn2py(name)}.jpg"
if not file_path.exists():
logger.warning(f"皮肤图片: {name} 不存在", "查看武器箱")
if skin.color == "CASE":
case_bk = BuildImage(
700, 200, color=(25, 25, 25, 100), font_size=25, font="CJGaoDeGuo.otf"
)
if file_path.exists():
skin_img = BuildImage(200, 200, background=file_path)
await case_bk.apaste(skin_img, (10, 10), True)
await case_bk.aline((250, 10, 250, 190))
await case_bk.aline((280, 160, 660, 160))
name_icon = BuildImage(30, 30, background=ICON_PATH / "box_white.png")
await case_bk.apaste(name_icon, (260, 25), True)
await case_bk.atext((295, 30), "名称:", (255, 255, 255))
await case_bk.atext((345, 25), skin.case_name, (255, 0, 38), font_size=30)
type_icon = BuildImage(30, 30, background=ICON_PATH / "type_white.png")
await case_bk.apaste(type_icon, (260, 70), True)
await case_bk.atext((295, 75), "类型:", (255, 255, 255))
await case_bk.atext((345, 72), "武器箱", (0, 157, 255), font_size=30)
price_icon = BuildImage(30, 30, background=ICON_PATH / "price_white.png")
await case_bk.apaste(price_icon, (260, 114), True)
await case_bk.atext((295, 120), "单价:", (255, 255, 255))
await case_bk.atext(
(340, 116), str(skin.sell_min_price), (0, 255, 98), font_size=30
)
update_count_icon = BuildImage(
40, 40, background=ICON_PATH / "reload_white.png"
)
await case_bk.apaste(update_count_icon, (575, 10), True)
await case_bk.atext((625, 12), str(update_count), (255, 255, 255), font_size=45)
num_icon = BuildImage(30, 30, background=ICON_PATH / "num_white.png")
await case_bk.apaste(num_icon, (455, 70), True)
await case_bk.atext((490, 75), "在售:", (255, 255, 255))
await case_bk.atext((535, 72), str(skin.sell_num), (144, 0, 255), font_size=30)
want_buy_icon = BuildImage(30, 30, background=ICON_PATH / "want_buy_white.png")
await case_bk.apaste(want_buy_icon, (455, 114), True)
await case_bk.atext((490, 120), "求购:", (255, 255, 255))
await case_bk.atext((535, 116), str(skin.buy_num), (144, 0, 255), font_size=30)
await case_bk.atext((275, 165), "更新时间", (255, 255, 255), font_size=22)
date = str(
skin.update_time.replace(microsecond=0).astimezone(
timezone(timedelta(hours=8))
)
).split("+")[0]
await case_bk.atext(
(344, 170),
date,
(255, 255, 255),
font_size=30,
)
return case_bk
else:
skin_bk = BuildImage(
235, 250, color=(25, 25, 25, 100), font_size=25, font="CJGaoDeGuo.otf"
)
if file_path.exists():
skin_image = BuildImage(205, 153, background=file_path)
await skin_bk.apaste(skin_image, (10, 30), alpha=True)
update_count_icon = BuildImage(
35, 35, background=ICON_PATH / "reload_white.png"
)
await skin_bk.aline((10, 180, 220, 180))
await skin_bk.atext((10, 10), skin.name, (255, 255, 255))
await skin_bk.apaste(update_count_icon, (140, 10), True)
await skin_bk.atext((175, 15), str(update_count), (255, 255, 255))
await skin_bk.atext((10, 185), f"{skin.skin_name}", (255, 255, 255), "by_width")
await skin_bk.atext((10, 218), "品质:", (255, 255, 255))
await skin_bk.atext(
(55, 218), COLOR2NAME[skin.color][:2], COLOR2COLOR[skin.color]
)
await skin_bk.atext((100, 218), "类型:", (255, 255, 255))
await skin_bk.atext((145, 218), skin.weapon_type, (255, 255, 255))
return skin_bk
COLOR2NAME = {
"WHITE": "消费级",
"LIGHTBLUE": "工业级",
"BLUE": "军规级",
"PURPLE": "受限",
"PINK": "保密",
"RED": "隐秘",
"KNIFE": "非凡",
}
ases" / "_background" / "shu"
class BuffSkin(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
case_name: str = fields.CharField(255) # type: ignore
"""箱子名称"""
name: str = fields.CharField(255) # type: ignore
"""武器/手套/刀名称"""
skin_name: str = fields.CharField(255) # type: ignore
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
color = fields.CharField(255)
"""颜色(品质)"""
skin_id = fields.CharField(255, null=True, unique=True)
"""皮肤id"""
img_url = fields.CharField(255)
"""图片url"""
steam_price: float = fields.FloatField(default=0)
"""steam价格"""
weapon_type = fields.CharField(255)
"""枪械类型"""
buy_max_price: float = fields.FloatField(default=0)
"""最大求购价格"""
buy_num: int = fields.IntField(default=0)
"""求购数量"""
sell_min_price: float = fields.FloatField(default=0)
"""售卖最低价格"""
sell_num: int = fields.IntField(default=0)
"""出售个数"""
sell_reference_price: float = fields.FloatField(default=0)
"""参考价格"""
create_time: datetime = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
update_time: datetime = fields.DatetimeField(auto_add=True)
"""更新日期"""
class Meta:
table = "buff_skin"
table_description = "Buff皮肤数据表"
# unique_together = ("case_name", "name", "skin_name", "abrasion", "is_stattrak")
def __eq__(self, other: "BuffSkin"):
return self.skin_id == other.skin_id
def __hash__(self):
return hash(self.case_name + self.name + self.skin_name + str(self.is_stattrak))
async def random_skin(
cls,
num: int,
color: str,
abrasion: str,
is_stattrak: bool = False,
case_name: Optional[str] = None,
) -> List["BuffSkin"]: # type: ignore
query = cls
if case_name:
query = query.filter(case_name__contains=case_name)
query = query.filter(abrasion=abrasion, is_stattrak=is_stattrak, color=color)
skin_list = await query.annotate(rand=Random()).limit(num) # type:ignore
num_ = num
cnt = 0
while len(skin_list) < num:
cnt += 1
num_ = num - len(skin_list)
skin_list += await query.annotate(rand=Random()).limit(num_)
if cnt > 10:
break
return skin_list # type: ignore
async def _run_script(cls):
return [
"ALTER TABLE buff_skin ADD img_url varchar(255);", # 新增img_url
"ALTER TABLE buff_skin ADD skin_id varchar(255);", # 新增skin_id
"ALTER TABLE buff_skin ADD steam_price float DEFAULT 0;", # 新增steam_price
"ALTER TABLE buff_skin ADD weapon_type varchar(255);", # 新增type
"ALTER TABLE buff_skin ADD buy_max_price float DEFAULT 0;", # 新增buy_max_price
"ALTER TABLE buff_skin ADD buy_num Integer DEFAULT 0;", # 新增buy_max_price
"ALTER TABLE buff_skin ADD sell_min_price float DEFAULT 0;", # 新增sell_min_price
"ALTER TABLE buff_skin ADD sell_num Integer DEFAULT 0;", # 新增sell_num
"ALTER TABLE buff_skin ADD sell_reference_price float DEFAULT 0;", # 新增sell_reference_price
"ALTER TABLE buff_skin DROP COLUMN skin_price;", # 删除skin_price
"alter table buff_skin drop constraint if EXISTS uid_buff_skin_case_na_c35c93;", # 删除唯一约束
"UPDATE buff_skin set case_name='手套' where case_name='手套武器箱'",
"UPDATE buff_skin set case_name='左轮' where case_name='左轮武器箱'",
]
class BuffSkinLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
case_name = fields.CharField(255)
"""箱子名称"""
name = fields.CharField(255)
"""武器/手套/刀名称"""
skin_name = fields.CharField(255)
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
color = fields.CharField(255)
"""颜色(品质)"""
steam_price = fields.FloatField(default=0)
"""steam价格"""
weapon_type = fields.CharField(255)
"""枪械类型"""
buy_max_price = fields.FloatField(default=0)
"""最大求购价格"""
buy_num = fields.IntField(default=0)
"""求购数量"""
sell_min_price = fields.FloatField(default=0)
"""售卖最低价格"""
sell_num = fields.IntField(default=0)
"""出售个数"""
sell_reference_price = fields.FloatField(default=0)
"""参考价格"""
create_time = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
class Meta:
table = "buff_skin_log"
table_description = "Buff皮肤更新日志表"
async def _run_script(cls):
return [
"UPDATE buff_skin_log set case_name='手套' where case_name='手套武器箱'",
"UPDATE buff_skin_log set case_name='左轮' where case_name='左轮武器箱'",
]
The provided code snippet includes necessary dependencies for implementing the `build_case_image` function. Write a Python function `async def build_case_image(case_name: str) -> Union[BuildImage, str]` to solve the following problem:
构造武器箱图片 Args: case_name (str): 名称 Returns: Union[BuildImage, str]: 图片
Here is the function:
async def build_case_image(case_name: str) -> Union[BuildImage, str]:
"""构造武器箱图片
Args:
case_name (str): 名称
Returns:
Union[BuildImage, str]: 图片
"""
background = random.choice(os.listdir(CASE_BACKGROUND))
background_img = BuildImage(0, 0, background=CASE_BACKGROUND / background)
if case_name:
log_list = (
await BuffSkinLog.filter(case_name__contains=case_name)
.annotate(count=Count("id"))
.group_by("skin_name")
.values_list("skin_name", "count")
)
skin_list_ = await BuffSkin.filter(case_name__contains=case_name).all()
skin2count = {item[0]: item[1] for item in log_list}
case = None
skin_list: List[BuffSkin] = []
exists_name = []
for skin in skin_list_:
if skin.color == "CASE":
case = skin
else:
name = skin.name + skin.skin_name
if name not in exists_name:
skin_list.append(skin)
exists_name.append(name)
generate_img = {}
for skin in skin_list:
skin_img = await generate_skin(skin, skin2count.get(skin.skin_name, 0))
if skin_img:
if not generate_img.get(skin.color):
generate_img[skin.color] = []
generate_img[skin.color].append(skin_img)
skin_image_list = []
for color in COLOR2NAME:
if generate_img.get(color):
skin_image_list = skin_image_list + generate_img[color]
img = skin_image_list[0]
img_w, img_h = img.size
total_size = (img_w + 25) * (img_h + 10) * len(skin_image_list) # 总面积
new_size = get_bk_image_size(total_size, background_img.size, img.size, 250)
A = BuildImage(
new_size[0] + 50, new_size[1], background=CASE_BACKGROUND / background
)
await A.afilter("GaussianBlur", 2)
if case:
case_img = await generate_skin(case, skin2count.get(f"{case_name}武器箱", 0))
if case_img:
A.paste(case_img, (25, 25), True)
w = 25
h = 230
skin_image_list.reverse()
for image in skin_image_list:
A.paste(image, (w, h), True)
w += image.w + 20
if w + image.w - 25 > A.w:
h += image.h + 10
w = 25
if h + img_h + 100 < A.h:
await A.acrop((0, 0, A.w, h + img_h + 100))
return A
else:
log_list = (
await BuffSkinLog.filter(color="CASE")
.annotate(count=Count("id"))
.group_by("case_name")
.values_list("case_name", "count")
)
name2count = {item[0]: item[1] for item in log_list}
skin_list = await BuffSkin.filter(color="CASE").all()
image_list: List[BuildImage] = []
for skin in skin_list:
if img := await generate_skin(skin, name2count[skin.case_name]):
image_list.append(img)
if not image_list:
return "未收录武器箱"
w = 25
h = 150
img = image_list[0]
img_w, img_h = img.size
total_size = (img_w + 25) * (img_h + 10) * len(image_list) # 总面积
new_size = get_bk_image_size(total_size, background_img.size, img.size, 155)
A = BuildImage(
new_size[0] + 50, new_size[1], background=CASE_BACKGROUND / background
)
await A.afilter("GaussianBlur", 2)
bk_img = BuildImage(
img_w, 120, color=(25, 25, 25, 100), font_size=60, font="CJGaoDeGuo.otf"
)
await bk_img.atext(
(0, 0), f"已收录 {len(image_list)} 个武器箱", (255, 255, 255), center_type="center"
)
await A.apaste(bk_img, (10, 10), True, "by_width")
for image in image_list:
A.paste(image, (w, h), True)
w += image.w + 20
if w + image.w - 25 > A.w:
h += image.h + 10
w = 25
if h + img_h + 100 < A.h:
await A.acrop((0, 0, A.w, h + img_h + 100))
return A | 构造武器箱图片 Args: case_name (str): 名称 Returns: Union[BuildImage, str]: 图片 |
188,181 | import asyncio
import os
import random
import re
import time
from datetime import datetime, timedelta
from typing import List, Optional, Tuple, Union
import nonebot
from tortoise.functions import Count
from configs.config import Config
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, BuildMat
from utils.utils import broadcast_group, cn2py
from .build_image import generate_skin
from .config import (
CASE2ID,
CASE_BACKGROUND,
COLOR2NAME,
KNIFE2ID,
NAME2COLOR,
UpdateType,
)
from .models.buff_skin import BuffSkin
from .models.buff_skin_log import BuffSkinLog
from .models.open_cases_user import OpenCasesUser
class BuildMat:
"""
针对 折线图/柱状图,基于 BuildImage 编写的 非常难用的 自定义画图工具
目前仅支持 正整数
"""
def __init__(
self,
y: List[int],
mat_type: str = "line",
*,
x_name: Optional[str] = None,
y_name: Optional[str] = None,
x_index: List[Union[str, int, float]] = None,
y_index: List[Union[str, int, float]] = None,
x_min_spacing: Optional[int] = None,
x_rotate: int = 0,
title: Optional[str] = None,
size: Tuple[int, int] = (1000, 1000),
font: str = "msyh.ttf",
font_size: Optional[int] = None,
display_num: bool = False,
is_grid: bool = False,
background: Optional[List[str]] = None,
background_filler_type: Optional[str] = "center",
bar_color: Optional[List[Union[str, Tuple[int, int, int]]]] = None,
):
"""
说明:
初始化 BuildMat
参数:
:param y: 坐标值
:param mat_type: 图像类型 可能的值:[line]: 折线图,[bar]: 柱状图,[barh]: 横向柱状图
:param x_name: 横坐标名称
:param y_name: 纵坐标名称
:param x_index: 横坐标值
:param y_index: 纵坐标值
:param x_min_spacing: x轴最小间距
:param x_rotate: 横坐标旋转角度
:param title: 标题
:param size: 图像大小,建议默认
:param font: 字体
:param font_size: 字体大小,建议默认
:param display_num: 是否显示数值
:param is_grid: 是否添加栅格
:param background: 背景图片
:param background_filler_type: 图像填充类型
:param bar_color: 柱状图颜色,位 ['*'] 时替换位彩虹随机色
"""
self.mat_type = mat_type
self.markImg = None
self._check_value(y, y_index)
self.w = size[0]
self.h = size[1]
self.y = y
self.x_name = x_name
self.y_name = y_name
self.x_index = x_index
self.y_index = y_index
self.x_min_spacing = x_min_spacing
self.x_rotate = x_rotate
self.title = title
self.font = font
self.display_num = display_num
self.is_grid = is_grid
self.background = background
self.background_filler_type = background_filler_type
self.bar_color = bar_color if bar_color else [(0, 0, 0)]
self.size = size
self.padding_w = 120
self.padding_h = 120
self.line_length = 760
self._deviation = 0.905
self._color = {}
if not font_size:
self.font_size = int(25 * (1 - len(x_index) / 100))
else:
self.font_size = font_size
if self.bar_color == ["*"]:
self.bar_color = [
"#FF0000",
"#FF7F00",
"#FFFF00",
"#00FF00",
"#00FFFF",
"#0000FF",
"#8B00FF",
]
if not x_index:
raise ValueError("缺少 x_index [横坐标值]...")
if x_min_spacing:
self._x_interval = x_min_spacing
else:
self._x_interval = int((self.line_length - 70) / len(x_index))
self._bar_width = int(30 * (1 - (len(x_index) + 10) / 100))
# 没有 y_index 时自动生成
if not y_index:
_y_index = []
_max_value = int(max(y))
_max_value = ceil(
_max_value / eval("1" + "0" * (len(str(_max_value)) - 1))
) * eval("1" + "0" * (len(str(_max_value)) - 1))
_max_value = _max_value if _max_value >= 10 else 100
_step = int(_max_value / 10)
for i in range(_step, _max_value + _step, _step):
_y_index.append(i)
self.y_index = _y_index
self._p = self.line_length / max(self.y_index)
self._y_interval = int((self.line_length - 70) / len(self.y_index))
def gen_graph(self):
"""
说明:
生成图像
"""
self.markImg = self._init_graph(
x_name=self.x_name,
y_name=self.y_name,
x_index=self.x_index,
y_index=self.y_index,
font_size=self.font_size,
is_grid=self.is_grid,
)
if self.mat_type == "line":
self._gen_line_graph(y=self.y, display_num=self.display_num)
elif self.mat_type == "bar":
self._gen_bar_graph(y=self.y, display_num=self.display_num)
elif self.mat_type == "barh":
self._gen_bar_graph(y=self.y, display_num=self.display_num, is_barh=True)
def set_y(self, y: List[int]):
"""
说明:
给坐标点设置新值
参数:
:param y: 坐标点
"""
self._check_value(y, self.y_index)
self.y = y
def set_y_index(self, y_index: List[Union[str, int, float]]):
"""
说明:
设置y轴坐标值
参数:
:param y_index: y轴坐标值
"""
self._check_value(self.y, y_index)
self.y_index = y_index
def set_title(self, title: str, color: Optional[Union[str, Tuple[int, int, int]]]):
"""
说明:
设置标题
参数:
:param title: 标题
:param color: 字体颜色
"""
self.title = title
if color:
self._color["title"] = color
def set_background(
self, background: Optional[List[str]], type_: Optional[str] = None
):
"""
说明:
设置背景图片
参数:
:param background: 图片路径列表
:param type_: 填充类型
"""
self.background = background
self.background_filler_type = type_ if type_ else self.background_filler_type
def show(self):
"""
说明:
展示图像
"""
self.markImg.show()
def pic2bs4(self) -> str:
"""
说明:
转base64
"""
return self.markImg.pic2bs4()
def resize(self, ratio: float = 0.9):
"""
说明:
调整图像大小
参数:
:param ratio: 比例
"""
self.markImg.resize(ratio)
def save(self, path: Union[str, Path]):
"""
说明:
保存图片
参数:
:param path: 路径
"""
self.markImg.save(path)
def _check_value(
self,
y: List[int],
y_index: List[Union[str, int, float]] = None,
x_index: List[Union[str, int, float]] = None,
):
"""
说明:
检查值合法性
参数:
:param y: 坐标值
:param y_index: y轴坐标值
:param x_index: x轴坐标值
"""
if y_index:
_value = x_index if self.mat_type == "barh" else y_index
if max(y) > max(y_index):
raise ValueError("坐标点的值必须小于y轴坐标的最大值...")
i = -9999999999
for y in y_index:
if y > i:
i = y
else:
raise ValueError("y轴坐标值必须有序...")
def _gen_line_graph(
self,
y: List[Union[int, float]],
display_num: bool = False,
):
"""
说明:
生成折线图
参数:
:param y: 坐标点
:param display_num: 显示该点的值
"""
_black_point = BuildImage(11, 11, color=random.choice(self.bar_color))
_black_point.circle()
x_interval = self._x_interval
current_w = self.padding_w + x_interval
current_h = self.padding_h + self.line_length
for i in range(len(y)):
if display_num:
w = int(self.markImg.getsize(str(y[i]))[0] / 2)
self.markImg.text(
(
current_w - w,
current_h - int(y[i] * self._p * self._deviation) - 25 - 5,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
if i != len(y) - 1:
self.markImg.line(
(
current_w,
current_h - int(y[i] * self._p * self._deviation),
current_w + x_interval,
current_h - int(y[i + 1] * self._p * self._deviation),
),
fill=(0, 0, 0),
width=2,
)
self.markImg.paste(
_black_point,
(
current_w - 3,
current_h - int(y[i] * self._p * self._deviation) - 3,
),
True,
)
current_w += x_interval
def _gen_bar_graph(
self,
y: List[Union[int, float]],
display_num: bool = False,
is_barh: bool = False,
):
"""
说明:
生成柱状图
参数:
:param y: 坐标值
:param display_num: 是否显示数值
:param is_barh: 横柱状图
"""
_interval = self._x_interval
if is_barh:
current_h = self.padding_h + self.line_length - _interval
current_w = self.padding_w
else:
current_w = self.padding_w + _interval
current_h = self.padding_h + self.line_length
for i in range(len(y)):
# 画出显示数字
if display_num:
# 横柱状图
if is_barh:
font_h = self.markImg.getsize(str(y[i]))[1]
self.markImg.text(
(
self.padding_w
+ int(y[i] * self._p * self._deviation)
+ 2
+ 5,
current_h - int(font_h / 2) - 1,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
else:
w = int(self.markImg.getsize(str(y[i]))[0] / 2)
self.markImg.text(
(
current_w - w,
current_h - int(y[i] * self._p * self._deviation) - 25,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
if i != len(y):
bar_color = random.choice(self.bar_color)
if is_barh:
A = BuildImage(
int(y[i] * self._p * self._deviation),
self._bar_width,
color=bar_color,
)
self.markImg.paste(
A,
(
current_w + 2,
current_h - int(self._bar_width / 2),
),
)
else:
A = BuildImage(
self._bar_width,
int(y[i] * self._p * self._deviation),
color=bar_color,
)
self.markImg.paste(
A,
(
current_w - int(self._bar_width / 2),
current_h - int(y[i] * self._p * self._deviation),
),
)
if is_barh:
current_h -= _interval
else:
current_w += _interval
def _init_graph(
self,
x_name: Optional[str] = None,
y_name: Optional[str] = None,
x_index: List[Union[str, int, float]] = None,
y_index: List[Union[str, int, float]] = None,
font_size: Optional[int] = None,
is_grid: bool = False,
) -> BuildImage:
"""
说明:
初始化图像,生成xy轴
参数:
:param x_name: x轴名称
:param y_name: y轴名称
:param x_index: x轴坐标值
:param y_index: y轴坐标值
:param is_grid: 添加栅格
"""
padding_w = self.padding_w
padding_h = self.padding_h
line_length = self.line_length
background = random.choice(self.background) if self.background else None
if self.x_min_spacing:
length = (len(self.x_index) + 1) * self.x_min_spacing
if 2 * padding_w + length > self.w:
self.w = 2 * padding_w + length
background = None
A = BuildImage(
self.w, self.h, font_size=font_size, font=self.font, background=background
)
if background:
_tmp = BuildImage(self.w, self.h)
_tmp.transparent(2)
A.paste(_tmp, alpha=True)
if self.title:
title = BuildImage(
0,
0,
plain_text=self.title,
color=(255, 255, 255, 0),
font_size=35,
font_color=self._color.get("title"),
font=self.font,
)
A.paste(title, (0, 25), True, "by_width")
A.line(
(
padding_w,
padding_h + line_length,
self.w - padding_w,
padding_h + line_length,
),
(0, 0, 0),
2,
)
A.line(
(
padding_w,
padding_h,
padding_w,
padding_h + line_length,
),
(0, 0, 0),
2,
)
_interval = self._x_interval
if self.mat_type == "barh":
tmp = x_index
x_index = y_index
y_index = tmp
_interval = self._y_interval
current_w = padding_w + _interval
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
_grid = self.line_length if is_grid else 10
x_rotate_height = 0
for _x in x_index:
_p = BuildImage(1, _grid, color="#a9a9a9")
A.paste(_p, (current_w, padding_h + line_length - _grid))
w = int(_text_font.getsize(f"{_x}")[0] / 2)
text = BuildImage(
0,
0,
plain_text=f"{_x}",
font_size=self.font_size,
color=(255, 255, 255, 0),
font=self.font,
)
text.rotate(self.x_rotate, True)
A.paste(text, (current_w - w, padding_h + line_length + 10), alpha=True)
current_w += _interval
x_rotate_height = text.h
_interval = self._x_interval if self.mat_type == "barh" else self._y_interval
current_h = padding_h + line_length - _interval
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
for _y in y_index:
_p = BuildImage(_grid, 1, color="#a9a9a9")
A.paste(_p, (padding_w + 2, current_h))
w, h = _text_font.getsize(f"{_y}")
h = int(h / 2)
text = BuildImage(
0,
0,
plain_text=f"{_y}",
font_size=self.font_size,
color=(255, 255, 255, 0),
font=self.font,
)
idx = 0
while text.size[0] > self.padding_w - 10 and idx < 3:
text = BuildImage(
0,
0,
plain_text=f"{_y}",
font_size=int(self.font_size * 0.75),
color=(255, 255, 255, 0),
font=self.font,
)
w, _ = text.getsize(f"{_y}")
idx += 1
A.paste(text, (padding_w - w - 10, current_h - h), alpha=True)
current_h -= _interval
if x_name:
A.text((int(padding_w / 2), int(padding_w / 2)), x_name)
if y_name:
A.text(
(
int(padding_w + line_length + 50 - A.getsize(y_name)[0]),
int(padding_h + line_length + 50 + x_rotate_height),
),
y_name,
)
return A
class BuffSkinLog(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
case_name = fields.CharField(255)
"""箱子名称"""
name = fields.CharField(255)
"""武器/手套/刀名称"""
skin_name = fields.CharField(255)
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
color = fields.CharField(255)
"""颜色(品质)"""
steam_price = fields.FloatField(default=0)
"""steam价格"""
weapon_type = fields.CharField(255)
"""枪械类型"""
buy_max_price = fields.FloatField(default=0)
"""最大求购价格"""
buy_num = fields.IntField(default=0)
"""求购数量"""
sell_min_price = fields.FloatField(default=0)
"""售卖最低价格"""
sell_num = fields.IntField(default=0)
"""出售个数"""
sell_reference_price = fields.FloatField(default=0)
"""参考价格"""
create_time = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
class Meta:
table = "buff_skin_log"
table_description = "Buff皮肤更新日志表"
async def _run_script(cls):
return [
"UPDATE buff_skin_log set case_name='手套' where case_name='手套武器箱'",
"UPDATE buff_skin_log set case_name='左轮' where case_name='左轮武器箱'",
]
async def init_skin_trends(
name: str, skin: str, abrasion: str, day: int = 7
) -> Optional[BuildMat]:
date = datetime.now() - timedelta(days=day)
log_list = (
await BuffSkinLog.filter(
name__contains=name.upper(),
skin_name=skin,
abrasion__contains=abrasion,
create_time__gt=date,
is_stattrak=False,
)
.order_by("create_time")
.limit(day * 5)
.all()
)
if not log_list:
return None
date_list = []
price_list = []
for log in log_list:
date = str(log.create_time.date())
if date not in date_list:
date_list.append(date)
price_list.append(log.sell_min_price)
bar_graph = BuildMat(
y=price_list,
mat_type="line",
title=f"{name}({skin})价格趋势({day})",
x_index=date_list,
x_min_spacing=90,
display_num=True,
x_rotate=30,
background=[
f"{IMAGE_PATH}/background/create_mat/{x}"
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
],
bar_color=["*"],
)
await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph)
return bar_graph | null |
188,182 | import asyncio
import os
import random
import re
import time
from datetime import datetime, timedelta
from typing import List, Optional, Tuple, Union
import nonebot
from tortoise.functions import Count
from configs.config import Config
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, BuildMat
from utils.utils import broadcast_group, cn2py
from .build_image import generate_skin
from .config import (
CASE2ID,
CASE_BACKGROUND,
COLOR2NAME,
KNIFE2ID,
NAME2COLOR,
UpdateType,
)
from .models.buff_skin import BuffSkin
from .models.buff_skin_log import BuffSkinLog
from .models.open_cases_user import OpenCasesUser
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
async def broadcast_group(
message: Union[str, Message, MessageSegment],
bot: Optional[Union[Bot, List[Bot]]] = None,
bot_id: Optional[Union[str, Set[str]]] = None,
ignore_group: Optional[Set[int]] = None,
check_func: Optional[Callable[[int], bool]] = None,
log_cmd: Optional[str] = None,
):
"""获取所有Bot或指定Bot对象广播群聊
Args:
message (Any): 广播消息内容
bot (Optional[Bot], optional): 指定bot对象. Defaults to None.
bot_id (Optional[str], optional): 指定bot id. Defaults to None.
ignore_group (Optional[List[int]], optional): 忽略群聊列表. Defaults to None.
check_func (Optional[Callable[[int], bool]], optional): 发送前对群聊检测方法,判断是否发送. Defaults to None.
log_cmd (Optional[str], optional): 日志标记. Defaults to None.
"""
if not message:
raise ValueError("群聊广播消息不能为空")
bot_dict = nonebot.get_bots()
bot_list: List[Bot] = []
if bot:
if isinstance(bot, list):
bot_list = bot
else:
bot_list.append(bot)
elif bot_id:
_bot_id_list = bot_id
if isinstance(bot_id, str):
_bot_id_list = [bot_id]
for id_ in _bot_id_list:
if bot_id in bot_dict:
bot_list.append(bot_dict[bot_id])
else:
logger.warning(f"Bot:{id_} 对象未连接或不存在")
else:
bot_list = list(bot_dict.values())
_used_group = []
for _bot in bot_list:
try:
if _group_list := await _bot.get_group_list():
group_id_list = [g["group_id"] for g in _group_list]
for group_id in set(group_id_list):
try:
if (
ignore_group and group_id in ignore_group
) or group_id in _used_group:
continue
if check_func and not check_func(group_id):
continue
_used_group.append(group_id)
await _bot.send_group_msg(group_id=group_id, message=message)
except Exception as e:
logger.error(
f"广播群发消息失败: {message}",
command=log_cmd,
group_id=group_id,
e=e,
)
except Exception as e:
logger.error(f"Bot: {_bot.self_id} 获取群聊列表失败", command=log_cmd, e=e)
class OpenCasesUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
total_count: int = fields.IntField(default=0)
"""总开启次数"""
blue_count: int = fields.IntField(default=0)
"""蓝色"""
blue_st_count: int = fields.IntField(default=0)
"""蓝色暗金"""
purple_count: int = fields.IntField(default=0)
"""紫色"""
purple_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
pink_count: int = fields.IntField(default=0)
"""粉色"""
pink_st_count: int = fields.IntField(default=0)
"""粉色暗金"""
red_count: int = fields.IntField(default=0)
"""紫色"""
red_st_count: int = fields.IntField(default=0)
"""紫色暗金"""
knife_count: int = fields.IntField(default=0)
"""金色"""
knife_st_count: int = fields.IntField(default=0)
"""金色暗金"""
spend_money: float = fields.IntField(default=0)
"""花费金币"""
make_money: float = fields.FloatField(default=0)
"""赚取金币"""
today_open_total: int = fields.IntField(default=0)
"""今日开箱数量"""
open_cases_time_last: datetime = fields.DatetimeField()
"""最后开箱日期"""
knifes_name: str = fields.TextField(default="")
"""已获取金色"""
class Meta:
table = "open_cases_users"
table_description = "开箱统计数据表"
unique_together = ("user_id", "group_id")
async def _run_script(cls):
return [
"alter table open_cases_users alter COLUMN make_money type float;", # 将make_money字段改为float
"alter table open_cases_users alter COLUMN spend_money type float;", # 将spend_money字段改为float
"ALTER TABLE open_cases_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE open_cases_users ALTER COLUMN user_id TYPE character varying(255);",
"ALTER TABLE open_cases_users ALTER COLUMN group_id TYPE character varying(255);",
]
The provided code snippet includes necessary dependencies for implementing the `reset_count_daily` function. Write a Python function `async def reset_count_daily()` to solve the following problem:
重置每日开箱
Here is the function:
async def reset_count_daily():
"""
重置每日开箱
"""
try:
await OpenCasesUser.all().update(today_open_total=0)
await broadcast_group(
"[[_task|open_case_reset_remind]]今日开箱次数重置成功", log_cmd="开箱重置提醒"
)
except Exception as e:
logger.error(f"开箱重置错误", e=e) | 重置每日开箱 |
188,183 | import asyncio
import os
import random
import re
import time
from datetime import datetime, timedelta
from typing import List, Optional, Tuple, Union
import nonebot
from tortoise.functions import Count
from configs.config import Config
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, BuildMat
from utils.utils import broadcast_group, cn2py
from .build_image import generate_skin
from .config import (
CASE2ID,
CASE_BACKGROUND,
COLOR2NAME,
KNIFE2ID,
NAME2COLOR,
UpdateType,
)
from .models.buff_skin import BuffSkin
from .models.buff_skin_log import BuffSkinLog
from .models.open_cases_user import OpenCasesUser
BASE_PATH = IMAGE_PATH / "csgo_cases"
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def cn2py(word: str) -> str:
"""
说明:
将字符串转化为拼音
参数:
:param word: 文本
"""
temp = ""
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
temp += "".join(i)
return temp
class BuffSkin(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
case_name: str = fields.CharField(255) # type: ignore
"""箱子名称"""
name: str = fields.CharField(255) # type: ignore
"""武器/手套/刀名称"""
skin_name: str = fields.CharField(255) # type: ignore
"""皮肤名称"""
is_stattrak = fields.BooleanField(default=False)
"""是否暗金(计数)"""
abrasion = fields.CharField(255)
"""磨损度"""
color = fields.CharField(255)
"""颜色(品质)"""
skin_id = fields.CharField(255, null=True, unique=True)
"""皮肤id"""
img_url = fields.CharField(255)
"""图片url"""
steam_price: float = fields.FloatField(default=0)
"""steam价格"""
weapon_type = fields.CharField(255)
"""枪械类型"""
buy_max_price: float = fields.FloatField(default=0)
"""最大求购价格"""
buy_num: int = fields.IntField(default=0)
"""求购数量"""
sell_min_price: float = fields.FloatField(default=0)
"""售卖最低价格"""
sell_num: int = fields.IntField(default=0)
"""出售个数"""
sell_reference_price: float = fields.FloatField(default=0)
"""参考价格"""
create_time: datetime = fields.DatetimeField(auto_add_now=True)
"""创建日期"""
update_time: datetime = fields.DatetimeField(auto_add=True)
"""更新日期"""
class Meta:
table = "buff_skin"
table_description = "Buff皮肤数据表"
# unique_together = ("case_name", "name", "skin_name", "abrasion", "is_stattrak")
def __eq__(self, other: "BuffSkin"):
return self.skin_id == other.skin_id
def __hash__(self):
return hash(self.case_name + self.name + self.skin_name + str(self.is_stattrak))
async def random_skin(
cls,
num: int,
color: str,
abrasion: str,
is_stattrak: bool = False,
case_name: Optional[str] = None,
) -> List["BuffSkin"]: # type: ignore
query = cls
if case_name:
query = query.filter(case_name__contains=case_name)
query = query.filter(abrasion=abrasion, is_stattrak=is_stattrak, color=color)
skin_list = await query.annotate(rand=Random()).limit(num) # type:ignore
num_ = num
cnt = 0
while len(skin_list) < num:
cnt += 1
num_ = num - len(skin_list)
skin_list += await query.annotate(rand=Random()).limit(num_)
if cnt > 10:
break
return skin_list # type: ignore
async def _run_script(cls):
return [
"ALTER TABLE buff_skin ADD img_url varchar(255);", # 新增img_url
"ALTER TABLE buff_skin ADD skin_id varchar(255);", # 新增skin_id
"ALTER TABLE buff_skin ADD steam_price float DEFAULT 0;", # 新增steam_price
"ALTER TABLE buff_skin ADD weapon_type varchar(255);", # 新增type
"ALTER TABLE buff_skin ADD buy_max_price float DEFAULT 0;", # 新增buy_max_price
"ALTER TABLE buff_skin ADD buy_num Integer DEFAULT 0;", # 新增buy_max_price
"ALTER TABLE buff_skin ADD sell_min_price float DEFAULT 0;", # 新增sell_min_price
"ALTER TABLE buff_skin ADD sell_num Integer DEFAULT 0;", # 新增sell_num
"ALTER TABLE buff_skin ADD sell_reference_price float DEFAULT 0;", # 新增sell_reference_price
"ALTER TABLE buff_skin DROP COLUMN skin_price;", # 删除skin_price
"alter table buff_skin drop constraint if EXISTS uid_buff_skin_case_na_c35c93;", # 删除唯一约束
"UPDATE buff_skin set case_name='手套' where case_name='手套武器箱'",
"UPDATE buff_skin set case_name='左轮' where case_name='左轮武器箱'",
]
The provided code snippet includes necessary dependencies for implementing the `download_image` function. Write a Python function `async def download_image(case_name: Optional[str] = None)` to solve the following problem:
下载皮肤图片 参数: case_name: 箱子名称.
Here is the function:
async def download_image(case_name: Optional[str] = None):
"""下载皮肤图片
参数:
case_name: 箱子名称.
"""
skin_list = (
await BuffSkin.filter(case_name=case_name).all()
if case_name
else await BuffSkin.all()
)
for skin in skin_list:
name_ = skin.name + "-" + skin.skin_name + "-" + skin.abrasion
for c_name_ in skin.case_name.split(","):
try:
file_path = BASE_PATH / cn2py(c_name_) / f"{cn2py(name_)}.jpg"
if not file_path.exists():
logger.debug(
f"下载皮肤 {c_name_}/{skin.name} 图片: {skin.img_url}...",
"开箱图片更新",
)
await AsyncHttpx.download_file(skin.img_url, file_path)
rand_time = random.randint(1, 5)
await asyncio.sleep(rand_time)
logger.debug(f"图片下载随机等待时间: {rand_time}", "开箱图片更新")
else:
logger.debug(f"皮肤 {c_name_}/{skin.name} 图片已存在...", "开箱图片更新")
except Exception as e:
logger.error(
f"下载皮肤 {c_name_}/{skin.name} 图片: {skin.img_url}",
"开箱图片更新",
e=e,
) | 下载皮肤图片 参数: case_name: 箱子名称. |
188,184 | from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot import on_command
from nonebot.params import CommandArg
from utils.utils import get_message_img, is_chinese
from utils.message_builder import image
from configs.path_config import TEMP_PATH
from utils.image_utils import BuildImage
from services.log import logger
from utils.http_utils import AsyncHttpxn_usage__ = """
usage:
将图片黑白化并配上中文与日语
指令:
黑白图 [文本] [图片]
""".strip()
w2b_img = on_command("黑白草图", aliases={"黑白图"}, priority=5, block=True)
def centered_text(img: BuildImage, text: str, add_h: int):
async def get_translate(msg: str) -> str:
def formalization_msg(msg: str) -> str:
def init_h_font_size(h):
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_message_img(data: Union[str, Message]) -> List[str]:
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
class BuildImage:
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
def getsize(self, msg: Any) -> Tuple[int, int]:
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
async def asave(self, path: Optional[Union[str, Path]] = None):
def save(self, path: Optional[Union[str, Path]] = None):
def show(self):
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
async def acrop(self, box: Tuple[int, int, int, int]):
def crop(self, box: Tuple[int, int, int, int]):
def check_font_size(self, word: str) -> bool:
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
def transparent(self, alpha_ratio: float = 1, n: int = 0):
def pic2bs4(self) -> str:
def convert(self, type_: ModeType):
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
async def acircle(self):
def circle(self):
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
async def arotate(self, angle: int, expand: bool = False):
def rotate(self, angle: int, expand: bool = False):
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
async def afilter(self, filter_: str, aud: Optional[int] = None):
def filter(self, filter_: str, aud: Optional[int] = None):
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
def getchannel(self, type_):
class logger:
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
class AsyncHttpx:
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
async def _(event: MessageEvent, arg: Message = CommandArg()):
# try:
img = get_message_img(event.json())
msg = arg.extract_plain_text().strip()
if not img or not msg:
await w2b_img.finish(f"格式错误:\n" + __plugin_usage__)
img = img[0]
if not await AsyncHttpx.download_file(
img, TEMP_PATH / f"{event.user_id}_w2b.png"
):
await w2b_img.finish("下载图片失败...请稍后再试...")
msg = await get_translate(msg)
w2b = BuildImage(0, 0, background=TEMP_PATH / f"{event.user_id}_w2b.png")
w2b.convert("L")
msg_sp = msg.split("<|>")
w, h = w2b.size
add_h, font_size = init_h_font_size(h)
bg = BuildImage(w, h + add_h, color="black", font_size=int(font_size))
bg.paste(w2b)
chinese_msg = formalization_msg(msg)
if not bg.check_font_size(chinese_msg):
if len(msg_sp) == 1:
centered_text(bg, chinese_msg, add_h)
else:
centered_text(bg, chinese_msg + "<|>" + msg_sp[1], add_h)
elif not bg.check_font_size(msg_sp[0]):
centered_text(bg, msg, add_h)
else:
ratio = (bg.getsize(msg_sp[0])[0] + 20) / bg.w
add_h = add_h * ratio
bg.resize(ratio)
centered_text(bg, msg, add_h)
await w2b_img.send(image(b64=bg.pic2bs4()))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 制作黑白草图 {msg}"
) | null |
188,185 | import asyncio
import os
import random
from datetime import datetime
from io import BytesIO
from pathlib import Path
from typing import List, Optional
import nonebot
from nonebot import Driver
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME, Config
from configs.path_config import IMAGE_PATH
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from utils.image_utils import BuildImage
from utils.message_builder import image
from utils.utils import get_user_avatar
from .config import (
SIGN_BACKGROUND_PATH,
SIGN_BORDER_PATH,
SIGN_RESOURCE_PATH,
SIGN_TODAY_CARD_PATH,
level2attitude,
lik2level,
lik2relation,
)
def generate_progress_bar_pic():
def clear_sign_data_pic():
class GroupInfoUser(Model):
async def get_group_member_id_list(cls, group_id: Union[int, str]) -> Set[int]:
async def set_user_nickname(cls, user_id: Union[int, str], group_id: Union[int, str], nickname: str):
async def get_user_all_group(cls, user_id: Union[int, str]) -> List[int]:
async def get_user_nickname(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
async def get_group_member_uid(cls, user_id: Union[int, str], group_id: Union[int, str]) -> Optional[int]:
async def _run_script(cls):
SIGN_RESOURCE_PATH = IMAGE_PATH / 'sign' / 'sign_res'
SIGN_TODAY_CARD_PATH = IMAGE_PATH / 'sign' / 'today_card'
async def init_image():
SIGN_RESOURCE_PATH.mkdir(parents=True, exist_ok=True)
SIGN_TODAY_CARD_PATH.mkdir(exist_ok=True, parents=True)
if not await GroupInfoUser.get_or_none(user_id="114514"):
await GroupInfoUser.create(
user_id="114514",
group_id="114514",
user_name="",
uid=0,
)
generate_progress_bar_pic()
clear_sign_data_pic() | null |
188,186 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
async def _handle_check_in(
nickname: str, user_id: str, group: str, present: datetime
) -> MessageSegment:
user, _ = await SignGroupUser.get_or_create(user_id=user_id, group_id=group)
impression_added = (secrets.randbelow(99) + 1) / 100
critx2 = random.random()
add_probability = float(user.add_probability)
specify_probability = user.specify_probability
if critx2 + add_probability > 0.97:
impression_added *= 2
elif critx2 < specify_probability:
impression_added *= 2
await SignGroupUser.sign(user, impression_added)
gold = random.randint(1, 100)
gift, gift_type = random_event(float(user.impression))
if gift_type == "gold":
await BagUser.add_gold(user_id, group, gold + gift)
gift = f"额外金币 + {gift}"
else:
await BagUser.add_gold(user_id, group, gold)
await BagUser.add_property(user_id, group, gift)
gift += " + 1"
logger.info(
f"(USER {user.user_id}, GROUP {user.group_id})"
f" CHECKED IN successfully. score: {user.impression:.2f} "
f"(+{impression_added:.2f}).获取金币:{gold + gift if gift == 'gold' else gold}"
)
if critx2 + add_probability > 0.97 or critx2 < specify_probability:
return await get_card(user, nickname, impression_added, gold, gift, True)
else:
return await get_card(user, nickname, impression_added, gold, gift)
class BagUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
gold = fields.IntField(default=100)
"""金币数量"""
spend_total_gold = fields.IntField(default=0)
"""花费金币总数"""
get_total_gold = fields.IntField(default=0)
"""获取金币总数"""
get_today_gold = fields.IntField(default=0)
"""今日获取金币"""
spend_today_gold = fields.IntField(default=0)
"""今日获取金币"""
property: Dict[str, int] = fields.JSONField(default={})
"""道具"""
class Meta:
table = "bag_users"
table_description = "用户道具数据表"
unique_together = ("user_id", "group_id")
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取金币概况
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取当前金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return user.gold
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
"""
说明:
获取当前道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param only_active: 仅仅获取主动使用的道具
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
if only_active and user.property:
data = {}
name_list = [
x.goods_name
for x in await GoodsInfo.get_all_goods()
if not x.is_passive
]
for key in [x for x in user.property if x in name_list]:
data[key] = user.property[key]
return data
return user.property
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
增加金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold + num
user.get_total_gold = user.get_total_gold + num
user.get_today_gold = user.get_today_gold + num
await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"])
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
花费金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold - num
user.spend_total_gold = user.spend_total_gold + num
user.spend_today_gold = user.spend_today_gold + num
await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"])
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
"""
说明:
增加道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 道具数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if property_.get(name) is None:
property_[name] = 0
property_[name] += num
user.property = property_
await user.save(update_fields=["property"])
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
"""
说明:
使用/删除 道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 使用个数
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if name in property_:
if (n := property_.get(name, 0)) < num:
return False
if n == num:
del property_[name]
else:
property_[name] -= num
await user.save(update_fields=["property"])
return True
return False
async def _run_script(cls):
return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段
"ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);"
]
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def get_card(
user: SignGroupUser,
nickname: str,
add_impression: Optional[float],
gold: Optional[int],
gift: str,
is_double: bool = False,
is_card_view: bool = False,
) -> MessageSegment:
user_id = user.user_id
date = datetime.now().date()
_type = "view" if is_card_view else "sign"
card_file = (
Path(SIGN_TODAY_CARD_PATH) / f"{user_id}_{user.group_id}_{_type}_{date}.png"
)
if card_file.exists():
return image(
IMAGE_PATH
/ "sign"
/ "today_card"
/ f"{user_id}_{user.group_id}_{_type}_{date}.png"
)
else:
if add_impression == -1:
card_file = (
Path(SIGN_TODAY_CARD_PATH)
/ f"{user_id}_{user.group_id}_view_{date}.png"
)
if card_file.exists():
return image(
IMAGE_PATH
/ "sign"
/ "today_card"
/ f"{user_id}_{user.group_id}_view_{date}.png"
)
is_card_view = True
ava = BytesIO(await get_user_avatar(user_id))
uid = await GroupInfoUser.get_group_member_uid(user.user_id, user.group_id)
impression_list = None
if is_card_view:
_, impression_list, _ = await SignGroupUser.get_all_impression(
user.group_id
)
return await asyncio.get_event_loop().run_in_executor(
None,
_generate_card,
user,
nickname,
user_id,
add_impression,
gold,
gift,
uid,
ava,
impression_list,
is_double,
is_card_view,
)
The provided code snippet includes necessary dependencies for implementing the `group_user_check_in` function. Write a Python function `async def group_user_check_in( nickname: str, user_id: int, group: int ) -> MessageSegment` to solve the following problem:
Returns string describing the result of checking in
Here is the function:
async def group_user_check_in(
nickname: str, user_id: int, group: int
) -> MessageSegment:
"Returns string describing the result of checking in"
present = datetime.now()
# 取得相应用户
user, is_create = await SignGroupUser.get_or_create(
user_id=str(user_id), group_id=str(group)
)
# 如果同一天签到过,特殊处理
if not is_create and (
user.checkin_time_last.date() >= present.date()
or f"{user}_{group}_sign_{datetime.now().date()}"
in os.listdir(SIGN_TODAY_CARD_PATH)
):
gold = await BagUser.get_gold(user_id, group)
return await get_card(user, nickname, -1, gold, "")
return await _handle_check_in(nickname, user_id, group, present) # ok | Returns string describing the result of checking in |
188,187 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
async def _handle_check_in(
nickname: str, user_id: str, group: str, present: datetime
) -> MessageSegment:
user, _ = await SignGroupUser.get_or_create(user_id=user_id, group_id=group)
impression_added = (secrets.randbelow(99) + 1) / 100
critx2 = random.random()
add_probability = float(user.add_probability)
specify_probability = user.specify_probability
if critx2 + add_probability > 0.97:
impression_added *= 2
elif critx2 < specify_probability:
impression_added *= 2
await SignGroupUser.sign(user, impression_added)
gold = random.randint(1, 100)
gift, gift_type = random_event(float(user.impression))
if gift_type == "gold":
await BagUser.add_gold(user_id, group, gold + gift)
gift = f"额外金币 + {gift}"
else:
await BagUser.add_gold(user_id, group, gold)
await BagUser.add_property(user_id, group, gift)
gift += " + 1"
logger.info(
f"(USER {user.user_id}, GROUP {user.group_id})"
f" CHECKED IN successfully. score: {user.impression:.2f} "
f"(+{impression_added:.2f}).获取金币:{gold + gift if gift == 'gold' else gold}"
)
if critx2 + add_probability > 0.97 or critx2 < specify_probability:
return await get_card(user, nickname, impression_added, gold, gift, True)
else:
return await get_card(user, nickname, impression_added, gold, gift)
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
The provided code snippet includes necessary dependencies for implementing the `check_in_all` function. Write a Python function `async def check_in_all(nickname: str, user_id: str)` to solve the following problem:
说明: 签到所有群 参数: :param nickname: 昵称 :param user_id: 用户id
Here is the function:
async def check_in_all(nickname: str, user_id: str):
"""
说明:
签到所有群
参数:
:param nickname: 昵称
:param user_id: 用户id
"""
present = datetime.now()
for u in await SignGroupUser.filter(user_id=user_id).all():
group = u.group_id
if not (
u.checkin_time_last.date() >= present.date()
or f"{u}_{group}_sign_{datetime.now().date()}"
in os.listdir(SIGN_TODAY_CARD_PATH)
):
await _handle_check_in(nickname, user_id, group, present) | 说明: 签到所有群 参数: :param nickname: 昵称 :param user_id: 用户id |
188,188 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
class BagUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
gold = fields.IntField(default=100)
"""金币数量"""
spend_total_gold = fields.IntField(default=0)
"""花费金币总数"""
get_total_gold = fields.IntField(default=0)
"""获取金币总数"""
get_today_gold = fields.IntField(default=0)
"""今日获取金币"""
spend_today_gold = fields.IntField(default=0)
"""今日获取金币"""
property: Dict[str, int] = fields.JSONField(default={})
"""道具"""
class Meta:
table = "bag_users"
table_description = "用户道具数据表"
unique_together = ("user_id", "group_id")
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取金币概况
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取当前金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return user.gold
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
"""
说明:
获取当前道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param only_active: 仅仅获取主动使用的道具
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
if only_active and user.property:
data = {}
name_list = [
x.goods_name
for x in await GoodsInfo.get_all_goods()
if not x.is_passive
]
for key in [x for x in user.property if x in name_list]:
data[key] = user.property[key]
return data
return user.property
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
增加金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold + num
user.get_total_gold = user.get_total_gold + num
user.get_today_gold = user.get_today_gold + num
await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"])
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
花费金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold - num
user.spend_total_gold = user.spend_total_gold + num
user.spend_today_gold = user.spend_today_gold + num
await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"])
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
"""
说明:
增加道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 道具数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if property_.get(name) is None:
property_[name] = 0
property_[name] += num
user.property = property_
await user.save(update_fields=["property"])
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
"""
说明:
使用/删除 道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 使用个数
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if name in property_:
if (n := property_.get(name, 0)) < num:
return False
if n == num:
del property_[name]
else:
property_[name] -= num
await user.save(update_fields=["property"])
return True
return False
async def _run_script(cls):
return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段
"ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);"
]
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def get_card(
user: SignGroupUser,
nickname: str,
add_impression: Optional[float],
gold: Optional[int],
gift: str,
is_double: bool = False,
is_card_view: bool = False,
) -> MessageSegment:
user_id = user.user_id
date = datetime.now().date()
_type = "view" if is_card_view else "sign"
card_file = (
Path(SIGN_TODAY_CARD_PATH) / f"{user_id}_{user.group_id}_{_type}_{date}.png"
)
if card_file.exists():
return image(
IMAGE_PATH
/ "sign"
/ "today_card"
/ f"{user_id}_{user.group_id}_{_type}_{date}.png"
)
else:
if add_impression == -1:
card_file = (
Path(SIGN_TODAY_CARD_PATH)
/ f"{user_id}_{user.group_id}_view_{date}.png"
)
if card_file.exists():
return image(
IMAGE_PATH
/ "sign"
/ "today_card"
/ f"{user_id}_{user.group_id}_view_{date}.png"
)
is_card_view = True
ava = BytesIO(await get_user_avatar(user_id))
uid = await GroupInfoUser.get_group_member_uid(user.user_id, user.group_id)
impression_list = None
if is_card_view:
_, impression_list, _ = await SignGroupUser.get_all_impression(
user.group_id
)
return await asyncio.get_event_loop().run_in_executor(
None,
_generate_card,
user,
nickname,
user_id,
add_impression,
gold,
gift,
uid,
ava,
impression_list,
is_double,
is_card_view,
)
async def group_user_check(nickname: str, user_id: str, group: str) -> MessageSegment:
# heuristic: if users find they have never checked in they are probable to check in
user, _ = await SignGroupUser.get_or_create(
user_id=str(user_id), group_id=str(group)
)
gold = await BagUser.get_gold(user_id, group)
return await get_card(user, nickname, None, gold, "", is_card_view=True) | null |
188,189 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
user_qq_list, impression_list, group_list = await SignGroupUser.get_all_impression(
group_id
)
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def init_rank(
title: str,
all_user_id: List[str],
all_user_data: List[Union[int, float]],
group_id: int,
total_count: int = 10,
) -> BuildMat:
"""
说明:
初始化通用的数据排行榜
参数:
:param title: 排行榜标题
:param all_user_id: 所有用户的qq号
:param all_user_data: 所有用户需要排行的对应数据
:param group_id: 群号,用于从数据库中获取该用户在此群的昵称
:param total_count: 获取人数总数
"""
_uname_lst = []
_num_lst = []
for i in range(min(len(all_user_id), total_count)):
_max = max(all_user_data)
max_user_id = all_user_id[all_user_data.index(_max)]
all_user_id.remove(max_user_id)
all_user_data.remove(_max)
if user := await GroupInfoUser.get_or_none(
user_id=str(max_user_id), group_id=str(group_id)
):
user_name = user.user_name
else:
user_name = f"{max_user_id}"
_uname_lst.append(user_name)
_num_lst.append(_max)
_uname_lst.reverse()
_num_lst.reverse()
return await asyncio.get_event_loop().run_in_executor(
None, _init_rank_graph, title, _uname_lst, _num_lst
)
class BuildMat:
"""
针对 折线图/柱状图,基于 BuildImage 编写的 非常难用的 自定义画图工具
目前仅支持 正整数
"""
def __init__(
self,
y: List[int],
mat_type: str = "line",
*,
x_name: Optional[str] = None,
y_name: Optional[str] = None,
x_index: List[Union[str, int, float]] = None,
y_index: List[Union[str, int, float]] = None,
x_min_spacing: Optional[int] = None,
x_rotate: int = 0,
title: Optional[str] = None,
size: Tuple[int, int] = (1000, 1000),
font: str = "msyh.ttf",
font_size: Optional[int] = None,
display_num: bool = False,
is_grid: bool = False,
background: Optional[List[str]] = None,
background_filler_type: Optional[str] = "center",
bar_color: Optional[List[Union[str, Tuple[int, int, int]]]] = None,
):
"""
说明:
初始化 BuildMat
参数:
:param y: 坐标值
:param mat_type: 图像类型 可能的值:[line]: 折线图,[bar]: 柱状图,[barh]: 横向柱状图
:param x_name: 横坐标名称
:param y_name: 纵坐标名称
:param x_index: 横坐标值
:param y_index: 纵坐标值
:param x_min_spacing: x轴最小间距
:param x_rotate: 横坐标旋转角度
:param title: 标题
:param size: 图像大小,建议默认
:param font: 字体
:param font_size: 字体大小,建议默认
:param display_num: 是否显示数值
:param is_grid: 是否添加栅格
:param background: 背景图片
:param background_filler_type: 图像填充类型
:param bar_color: 柱状图颜色,位 ['*'] 时替换位彩虹随机色
"""
self.mat_type = mat_type
self.markImg = None
self._check_value(y, y_index)
self.w = size[0]
self.h = size[1]
self.y = y
self.x_name = x_name
self.y_name = y_name
self.x_index = x_index
self.y_index = y_index
self.x_min_spacing = x_min_spacing
self.x_rotate = x_rotate
self.title = title
self.font = font
self.display_num = display_num
self.is_grid = is_grid
self.background = background
self.background_filler_type = background_filler_type
self.bar_color = bar_color if bar_color else [(0, 0, 0)]
self.size = size
self.padding_w = 120
self.padding_h = 120
self.line_length = 760
self._deviation = 0.905
self._color = {}
if not font_size:
self.font_size = int(25 * (1 - len(x_index) / 100))
else:
self.font_size = font_size
if self.bar_color == ["*"]:
self.bar_color = [
"#FF0000",
"#FF7F00",
"#FFFF00",
"#00FF00",
"#00FFFF",
"#0000FF",
"#8B00FF",
]
if not x_index:
raise ValueError("缺少 x_index [横坐标值]...")
if x_min_spacing:
self._x_interval = x_min_spacing
else:
self._x_interval = int((self.line_length - 70) / len(x_index))
self._bar_width = int(30 * (1 - (len(x_index) + 10) / 100))
# 没有 y_index 时自动生成
if not y_index:
_y_index = []
_max_value = int(max(y))
_max_value = ceil(
_max_value / eval("1" + "0" * (len(str(_max_value)) - 1))
) * eval("1" + "0" * (len(str(_max_value)) - 1))
_max_value = _max_value if _max_value >= 10 else 100
_step = int(_max_value / 10)
for i in range(_step, _max_value + _step, _step):
_y_index.append(i)
self.y_index = _y_index
self._p = self.line_length / max(self.y_index)
self._y_interval = int((self.line_length - 70) / len(self.y_index))
def gen_graph(self):
"""
说明:
生成图像
"""
self.markImg = self._init_graph(
x_name=self.x_name,
y_name=self.y_name,
x_index=self.x_index,
y_index=self.y_index,
font_size=self.font_size,
is_grid=self.is_grid,
)
if self.mat_type == "line":
self._gen_line_graph(y=self.y, display_num=self.display_num)
elif self.mat_type == "bar":
self._gen_bar_graph(y=self.y, display_num=self.display_num)
elif self.mat_type == "barh":
self._gen_bar_graph(y=self.y, display_num=self.display_num, is_barh=True)
def set_y(self, y: List[int]):
"""
说明:
给坐标点设置新值
参数:
:param y: 坐标点
"""
self._check_value(y, self.y_index)
self.y = y
def set_y_index(self, y_index: List[Union[str, int, float]]):
"""
说明:
设置y轴坐标值
参数:
:param y_index: y轴坐标值
"""
self._check_value(self.y, y_index)
self.y_index = y_index
def set_title(self, title: str, color: Optional[Union[str, Tuple[int, int, int]]]):
"""
说明:
设置标题
参数:
:param title: 标题
:param color: 字体颜色
"""
self.title = title
if color:
self._color["title"] = color
def set_background(
self, background: Optional[List[str]], type_: Optional[str] = None
):
"""
说明:
设置背景图片
参数:
:param background: 图片路径列表
:param type_: 填充类型
"""
self.background = background
self.background_filler_type = type_ if type_ else self.background_filler_type
def show(self):
"""
说明:
展示图像
"""
self.markImg.show()
def pic2bs4(self) -> str:
"""
说明:
转base64
"""
return self.markImg.pic2bs4()
def resize(self, ratio: float = 0.9):
"""
说明:
调整图像大小
参数:
:param ratio: 比例
"""
self.markImg.resize(ratio)
def save(self, path: Union[str, Path]):
"""
说明:
保存图片
参数:
:param path: 路径
"""
self.markImg.save(path)
def _check_value(
self,
y: List[int],
y_index: List[Union[str, int, float]] = None,
x_index: List[Union[str, int, float]] = None,
):
"""
说明:
检查值合法性
参数:
:param y: 坐标值
:param y_index: y轴坐标值
:param x_index: x轴坐标值
"""
if y_index:
_value = x_index if self.mat_type == "barh" else y_index
if max(y) > max(y_index):
raise ValueError("坐标点的值必须小于y轴坐标的最大值...")
i = -9999999999
for y in y_index:
if y > i:
i = y
else:
raise ValueError("y轴坐标值必须有序...")
def _gen_line_graph(
self,
y: List[Union[int, float]],
display_num: bool = False,
):
"""
说明:
生成折线图
参数:
:param y: 坐标点
:param display_num: 显示该点的值
"""
_black_point = BuildImage(11, 11, color=random.choice(self.bar_color))
_black_point.circle()
x_interval = self._x_interval
current_w = self.padding_w + x_interval
current_h = self.padding_h + self.line_length
for i in range(len(y)):
if display_num:
w = int(self.markImg.getsize(str(y[i]))[0] / 2)
self.markImg.text(
(
current_w - w,
current_h - int(y[i] * self._p * self._deviation) - 25 - 5,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
if i != len(y) - 1:
self.markImg.line(
(
current_w,
current_h - int(y[i] * self._p * self._deviation),
current_w + x_interval,
current_h - int(y[i + 1] * self._p * self._deviation),
),
fill=(0, 0, 0),
width=2,
)
self.markImg.paste(
_black_point,
(
current_w - 3,
current_h - int(y[i] * self._p * self._deviation) - 3,
),
True,
)
current_w += x_interval
def _gen_bar_graph(
self,
y: List[Union[int, float]],
display_num: bool = False,
is_barh: bool = False,
):
"""
说明:
生成柱状图
参数:
:param y: 坐标值
:param display_num: 是否显示数值
:param is_barh: 横柱状图
"""
_interval = self._x_interval
if is_barh:
current_h = self.padding_h + self.line_length - _interval
current_w = self.padding_w
else:
current_w = self.padding_w + _interval
current_h = self.padding_h + self.line_length
for i in range(len(y)):
# 画出显示数字
if display_num:
# 横柱状图
if is_barh:
font_h = self.markImg.getsize(str(y[i]))[1]
self.markImg.text(
(
self.padding_w
+ int(y[i] * self._p * self._deviation)
+ 2
+ 5,
current_h - int(font_h / 2) - 1,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
else:
w = int(self.markImg.getsize(str(y[i]))[0] / 2)
self.markImg.text(
(
current_w - w,
current_h - int(y[i] * self._p * self._deviation) - 25,
),
f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}",
)
if i != len(y):
bar_color = random.choice(self.bar_color)
if is_barh:
A = BuildImage(
int(y[i] * self._p * self._deviation),
self._bar_width,
color=bar_color,
)
self.markImg.paste(
A,
(
current_w + 2,
current_h - int(self._bar_width / 2),
),
)
else:
A = BuildImage(
self._bar_width,
int(y[i] * self._p * self._deviation),
color=bar_color,
)
self.markImg.paste(
A,
(
current_w - int(self._bar_width / 2),
current_h - int(y[i] * self._p * self._deviation),
),
)
if is_barh:
current_h -= _interval
else:
current_w += _interval
def _init_graph(
self,
x_name: Optional[str] = None,
y_name: Optional[str] = None,
x_index: List[Union[str, int, float]] = None,
y_index: List[Union[str, int, float]] = None,
font_size: Optional[int] = None,
is_grid: bool = False,
) -> BuildImage:
"""
说明:
初始化图像,生成xy轴
参数:
:param x_name: x轴名称
:param y_name: y轴名称
:param x_index: x轴坐标值
:param y_index: y轴坐标值
:param is_grid: 添加栅格
"""
padding_w = self.padding_w
padding_h = self.padding_h
line_length = self.line_length
background = random.choice(self.background) if self.background else None
if self.x_min_spacing:
length = (len(self.x_index) + 1) * self.x_min_spacing
if 2 * padding_w + length > self.w:
self.w = 2 * padding_w + length
background = None
A = BuildImage(
self.w, self.h, font_size=font_size, font=self.font, background=background
)
if background:
_tmp = BuildImage(self.w, self.h)
_tmp.transparent(2)
A.paste(_tmp, alpha=True)
if self.title:
title = BuildImage(
0,
0,
plain_text=self.title,
color=(255, 255, 255, 0),
font_size=35,
font_color=self._color.get("title"),
font=self.font,
)
A.paste(title, (0, 25), True, "by_width")
A.line(
(
padding_w,
padding_h + line_length,
self.w - padding_w,
padding_h + line_length,
),
(0, 0, 0),
2,
)
A.line(
(
padding_w,
padding_h,
padding_w,
padding_h + line_length,
),
(0, 0, 0),
2,
)
_interval = self._x_interval
if self.mat_type == "barh":
tmp = x_index
x_index = y_index
y_index = tmp
_interval = self._y_interval
current_w = padding_w + _interval
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
_grid = self.line_length if is_grid else 10
x_rotate_height = 0
for _x in x_index:
_p = BuildImage(1, _grid, color="#a9a9a9")
A.paste(_p, (current_w, padding_h + line_length - _grid))
w = int(_text_font.getsize(f"{_x}")[0] / 2)
text = BuildImage(
0,
0,
plain_text=f"{_x}",
font_size=self.font_size,
color=(255, 255, 255, 0),
font=self.font,
)
text.rotate(self.x_rotate, True)
A.paste(text, (current_w - w, padding_h + line_length + 10), alpha=True)
current_w += _interval
x_rotate_height = text.h
_interval = self._x_interval if self.mat_type == "barh" else self._y_interval
current_h = padding_h + line_length - _interval
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
for _y in y_index:
_p = BuildImage(_grid, 1, color="#a9a9a9")
A.paste(_p, (padding_w + 2, current_h))
w, h = _text_font.getsize(f"{_y}")
h = int(h / 2)
text = BuildImage(
0,
0,
plain_text=f"{_y}",
font_size=self.font_size,
color=(255, 255, 255, 0),
font=self.font,
)
idx = 0
while text.size[0] > self.padding_w - 10 and idx < 3:
text = BuildImage(
0,
0,
plain_text=f"{_y}",
font_size=int(self.font_size * 0.75),
color=(255, 255, 255, 0),
font=self.font,
)
w, _ = text.getsize(f"{_y}")
idx += 1
A.paste(text, (padding_w - w - 10, current_h - h), alpha=True)
current_h -= _interval
if x_name:
A.text((int(padding_w / 2), int(padding_w / 2)), x_name)
if y_name:
A.text(
(
int(padding_w + line_length + 50 - A.getsize(y_name)[0]),
int(padding_h + line_length + 50 + x_rotate_height),
),
y_name,
)
return A
async def group_impression_rank(group: int, num: int) -> Optional[BuildMat]:
user_qq_list, impression_list, _ = await SignGroupUser.get_all_impression(group)
return await init_rank("好感度排行榜", user_qq_list, impression_list, group, num) | null |
188,190 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
class BagUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
gold = fields.IntField(default=100)
"""金币数量"""
spend_total_gold = fields.IntField(default=0)
"""花费金币总数"""
get_total_gold = fields.IntField(default=0)
"""获取金币总数"""
get_today_gold = fields.IntField(default=0)
"""今日获取金币"""
spend_today_gold = fields.IntField(default=0)
"""今日获取金币"""
property: Dict[str, int] = fields.JSONField(default={})
"""道具"""
class Meta:
table = "bag_users"
table_description = "用户道具数据表"
unique_together = ("user_id", "group_id")
async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str:
"""
说明:
获取金币概况
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int:
"""
说明:
获取当前金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
return user.gold
async def get_property(
cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False
) -> Dict[str, int]:
"""
说明:
获取当前道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param only_active: 仅仅获取主动使用的道具
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
if only_active and user.property:
data = {}
name_list = [
x.goods_name
for x in await GoodsInfo.get_all_goods()
if not x.is_passive
]
for key in [x for x in user.property if x in name_list]:
data[key] = user.property[key]
return data
return user.property
async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
增加金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold + num
user.get_total_gold = user.get_total_gold + num
user.get_today_gold = user.get_today_gold + num
await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"])
async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int):
"""
说明:
花费金币
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param num: 金币数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.gold = user.gold - num
user.spend_total_gold = user.spend_total_gold + num
user.spend_today_gold = user.spend_today_gold + num
await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"])
async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1):
"""
说明:
增加道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 道具数量
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if property_.get(name) is None:
property_[name] = 0
property_[name] += num
user.property = property_
await user.save(update_fields=["property"])
async def delete_property(
cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1
) -> bool:
"""
说明:
使用/删除 道具
参数:
:param user_id: 用户id
:param group_id: 所在群组id
:param name: 道具名称
:param num: 使用个数
"""
user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id))
property_ = user.property
if name in property_:
if (n := property_.get(name, 0)) < num:
return False
if n == num:
del property_[name]
else:
property_[name] -= num
await user.save(update_fields=["property"])
return True
return False
async def _run_script(cls):
return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段
"ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id
"ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def random_gold(user_id, group_id, impression):
if impression < 1:
impression = 1
gold = random.randint(1, 100) + random.randint(1, int(impression))
if await BagUser.add_gold(user_id, group_id, gold):
return gold
else:
return 0 | null |
188,191 | import asyncio
import math
import os
import random
import secrets
from datetime import datetime, timedelta
from io import BytesIO
from typing import Optional
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import NICKNAME
from models.bag_user import BagUser
from models.group_member_info import GroupInfoUser
from models.sign_group_user import SignGroupUser
from services.log import logger
from utils.data_utils import init_rank
from utils.image_utils import BuildImage, BuildMat
from utils.utils import get_user_avatar
from .random_event import random_event
from .utils import SIGN_TODAY_CARD_PATH, get_card
user_qq_list, impression_list, group_list = await SignGroupUser.get_all_impression(
group_id
)
users, impressions, groups = [], [], []
num = 0
for i in range(105 if len(user_qq_list) > 105 else len(user_qq_list)):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
if user not in data["0"]:
users.append(user)
impressions.append(impression)
groups.append(group)
else:
num += 1
for i in range(num):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
users.append(user)
impressions.append(impression)
groups.append(group)
return (await asyncio.gather(*[_pst(users, impressions, groups)]))[0 def _pst(users: list, impressions: list, groups: list):
lens = len(users)
count = math.ceil(lens / 33)
width = 10
idx = 0
A = BuildImage(1740, 3300, color="#FFE4C4")
for _ in range(count):
col_img = BuildImage(550, 3300, 550, 100, color="#FFE4C4")
for _ in range(33 if int(lens / 33) >= 1 else lens % 33 - 1):
idx += 1
if idx > 100:
break
impression = max(impressions)
index = impressions.index(impression)
user = users[index]
group = groups[index]
impressions.pop(index)
users.pop(index)
groups.pop(index)
if user_ := await GroupInfoUser.get_or_none(
user_id=str(user), group_id=str(group)
):
user_name = user_.user_name
else:
user_name = f"我名字呢?"
user_name = user_name if len(user_name) < 11 else user_name[:10] + "..."
ava = await get_user_avatar(user)
if ava:
ava = BuildImage(50, 50, background=BytesIO(ava))
else:
ava = BuildImage(50, 50, color="white")
ava.circle()
bk = BuildImage(550, 100, color="#FFE4C4", font_size=30)
font_w, font_h = bk.getsize(f"{idx}")
bk.text((5, int((100 - font_h) / 2)), f"{idx}.")
bk.paste(ava, (55, int((100 - 50) / 2)), True)
bk.text((120, int((100 - font_h) / 2)), f"{user_name}")
bk.text((460, int((100 - font_h) / 2)), f"[{impression:.2f}]")
col_img.paste(bk)
A.paste(col_img, (width, 0))
lens -= 33
width += 580
W = BuildImage(1740, 3700, color="#FFE4C4", font_size=130)
W.paste(A, (0, 260))
font_w, font_h = W.getsize(f"{NICKNAME}的好感度总榜")
W.text((int((1740 - font_w) / 2), int((260 - font_h) / 2)), f"{NICKNAME}的好感度总榜")
return W.pic2bs4()
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
async def impression_rank(group_id: int, data: dict):
user_qq_list, impression_list, group_list = await SignGroupUser.get_all_impression(
group_id
)
users, impressions, groups = [], [], []
num = 0
for i in range(105 if len(user_qq_list) > 105 else len(user_qq_list)):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
if user not in data["0"]:
users.append(user)
impressions.append(impression)
groups.append(group)
else:
num += 1
for i in range(num):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
users.append(user)
impressions.append(impression)
groups.append(group)
return (await asyncio.gather(*[_pst(users, impressions, groups)]))[0] | null |
188,192 | import nonebot
from nonebot import Driver
from configs.config import Config
from models.sign_group_user import SignGroupUser
from utils.decorator.shop import NotMeetUseConditionsException, shop_register
class SignGroupUser(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
user_id = fields.CharField(255)
"""用户id"""
group_id = fields.CharField(255)
"""群聊id"""
checkin_count = fields.IntField(default=0)
"""签到次数"""
checkin_time_last = fields.DatetimeField(default=datetime.min)
"""最后签到时间"""
impression = fields.DecimalField(10, 3, default=0)
"""好感度"""
add_probability = fields.DecimalField(10, 3, default=0)
"""双倍签到增加概率"""
specify_probability = fields.DecimalField(10, 3, default=0)
"""使用指定双倍概率"""
# specify_probability = fields.DecimalField(10, 3, default=0)
class Meta:
table = "sign_group_users"
table_description = "群员签到数据表"
unique_together = ("user_id", "group_id")
async def sign(cls, user: "SignGroupUser", impression: float):
"""
说明:
签到
说明:
:param user: 用户
:param impression: 增加的好感度
"""
user.checkin_time_last = datetime.now()
user.checkin_count = user.checkin_count + 1
user.add_probability = 0
user.specify_probability = 0
user.impression = float(user.impression) + impression
await user.save()
async def get_all_impression(
cls, group_id: Union[int, str]
) -> Tuple[List[str], List[float], List[str]]:
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param group_id: 群号
"""
if group_id:
query = cls.filter(group_id=str(group_id))
else:
query = cls
value_list = await query.all().values_list("user_id", "group_id", "impression") # type: ignore
user_list = []
group_list = []
impression_list = []
for value in value_list:
user_list.append(value[0])
group_list.append(value[1])
impression_list.append(float(value[2]))
return user_list, impression_list, group_list
async def _run_script(cls):
return ["ALTER TABLE sign_group_users RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id
"ALTER TABLE sign_group_users ALTER COLUMN user_id TYPE character varying(255);",
# 将user_id字段类型改为character varying(255)
"ALTER TABLE sign_group_users ALTER COLUMN group_id TYPE character varying(255);"
]
class NotMeetUseConditionsException(Exception):
"""
不满足条件异常类
"""
def __init__(self, info: Optional[Union[str, MessageSegment, Message]]):
super().__init__(self)
self._info = info
def get_info(self):
return self._info
shop_register = ShopRegister()
The provided code snippet includes necessary dependencies for implementing the `_` function. Write a Python function `async def _()` to solve the following problem:
导入内置的三个商品
Here is the function:
async def _():
"""
导入内置的三个商品
"""
@shop_register(
name=("好感度双倍加持卡Ⅰ", "好感度双倍加持卡Ⅱ", "好感度双倍加持卡Ⅲ"),
price=(30, 150, 250),
des=(
"下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)",
"下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)",
"下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)",
),
load_status=bool(Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS")),
icon=(
"favorability_card_1.png",
"favorability_card_2.png",
"favorability_card_3.png",
),
**{"好感度双倍加持卡Ⅰ_prob": 0.1, "好感度双倍加持卡Ⅱ_prob": 0.2, "好感度双倍加持卡Ⅲ_prob": 0.3},
)
async def sign_card(user_id: int, group_id: int, prob: float):
user, _ = await SignGroupUser.get_or_create(user_id=str(user_id), group_id=str(group_id))
user.add_probability = prob
await user.save(update_fields=["add_probability"])
@shop_register(
name="测试道具A",
price=99,
des="随便侧而出",
load_status=False,
icon="sword.png",
)
async def _(user_id: int, group_id: int):
print(user_id, group_id, "使用测试道具")
@shop_register.before_handle(name="测试道具A", load_status=False)
async def _(user_id: int, group_id: int):
print(user_id, group_id, "第一个使用前函数(before handle)")
@shop_register.before_handle(name="测试道具A", load_status=False)
async def _(user_id: int, group_id: int):
print(user_id, group_id, "第二个使用前函数(before handle)222")
raise NotMeetUseConditionsException("太笨了!") # 抛出异常,阻断使用,并返回信息
@shop_register.after_handle(name="测试道具A", load_status=False)
async def _(user_id: int, group_id: int):
print(user_id, group_id, "第一个使用后函数(after handle)") | 导入内置的三个商品 |
188,193 | from typing import List
from fastapi import APIRouter, WebSocket
from loguru import logger
from nonebot.utils import escape_tag
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from .log_manager import LOG_STORAGE
LOG_STORAGE: LogStorage[str] = LogStorage[str]()
The provided code snippet includes necessary dependencies for implementing the `system_logs_history` function. Write a Python function `async def system_logs_history(reverse: bool = False)` to solve the following problem:
历史日志 参数: reverse: 反转顺序.
Here is the function:
async def system_logs_history(reverse: bool = False):
"""历史日志
参数:
reverse: 反转顺序.
"""
return LOG_STORAGE.list(reverse=reverse) # type: ignore | 历史日志 参数: reverse: 反转顺序. |
188,194 | from typing import List
from fastapi import APIRouter, WebSocket
from loguru import logger
from nonebot.utils import escape_tag
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from .log_manager import LOG_STORAGE
LOG_STORAGE: LogStorage[str] = LogStorage[str]()
async def system_logs_realtime(websocket: WebSocket):
await websocket.accept()
async def log_listener(log: str):
await websocket.send_text(log)
LOG_STORAGE.listeners.add(log_listener)
try:
while websocket.client_state == WebSocketState.CONNECTED:
recv = await websocket.receive()
logger.trace(
f"{system_logs_realtime.__name__!r} received "
f"<e>{escape_tag(repr(recv))}</e>"
)
except WebSocketDisconnect:
pass
finally:
LOG_STORAGE.listeners.remove(log_listener)
return | null |
188,195 | import time
from typing import Optional
import nonebot
from nonebot import Driver
from nonebot.adapters.onebot.v11 import Bot
bot_live = BotLive()
async def _(bot: Bot):
bot_live.add(bot.self_id) | null |
188,196 | import time
from typing import Optional
import nonebot
from nonebot import Driver
from nonebot.adapters.onebot.v11 import Bot
bot_live = BotLive()
async def _(bot: Bot):
bot_live.remove(bot.self_id) | null |
188,197 | import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import psutil
import ujson as json
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from nonebot.utils import run_sync
from configs.config import Config
from configs.path_config import (
DATA_PATH,
FONT_PATH,
IMAGE_PATH,
LOG_PATH,
RECORD_PATH,
TEMP_PATH,
TEXT_PATH,
)
from .base_model import SystemFolderSize, SystemStatus, User
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
class User(BaseModel):
username: str
password: str
The provided code snippet includes necessary dependencies for implementing the `create_token` function. Write a Python function `def create_token(user: User, expires_delta: Optional[timedelta] = None)` to solve the following problem:
创建token 参数: user: 用户信息 expires_delta: 过期时间.
Here is the function:
def create_token(user: User, expires_delta: Optional[timedelta] = None):
"""创建token
参数:
user: 用户信息
expires_delta: 过期时间.
"""
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
return jwt.encode(
claims={"sub": user.username, "exp": expire},
key=SECRET_KEY,
algorithm=ALGORITHM,
) | 创建token 参数: user: 用户信息 expires_delta: 过期时间. |
188,198 | import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import psutil
import ujson as json
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from nonebot.utils import run_sync
from configs.config import Config
from configs.path_config import (
DATA_PATH,
FONT_PATH,
IMAGE_PATH,
LOG_PATH,
RECORD_PATH,
TEMP_PATH,
TEXT_PATH,
)
from .base_model import SystemFolderSize, SystemStatus, User
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/login")
def get_user(uname: str) -> Optional[User]:
"""获取账号密码
参数:
uname: uname
返回:
Optional[User]: 用户信息
"""
username = Config.get_config("web-ui", "username")
password = Config.get_config("web-ui", "password")
if username and password and uname == username:
return User(username=username, password=password)
The provided code snippet includes necessary dependencies for implementing the `authentication` function. Write a Python function `def authentication()` to solve the following problem:
权限验证 异常: JWTError: JWTError HTTPException: HTTPException
Here is the function:
def authentication():
"""权限验证
异常:
JWTError: JWTError
HTTPException: HTTPException
"""
# if token not in token_data["token"]:
def inner(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username, expire = payload.get("sub"), payload.get("exp")
user = get_user(username) # type: ignore
if user is None:
raise JWTError
except JWTError:
raise HTTPException(status_code=400, detail="登录验证失败或已失效, 踢出房间!")
return Depends(inner) | 权限验证 异常: JWTError: JWTError HTTPException: HTTPException |
188,199 | import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import psutil
import ujson as json
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from nonebot.utils import run_sync
from configs.config import Config
from configs.path_config import (
DATA_PATH,
FONT_PATH,
IMAGE_PATH,
LOG_PATH,
RECORD_PATH,
TEMP_PATH,
TEXT_PATH,
)
from .base_model import SystemFolderSize, SystemStatus, User
lass SystemStatus(BaseModel):
"""
系统状态
"""
cpu: float
memory: float
disk: float
check_time: datetime
The provided code snippet includes necessary dependencies for implementing the `get_system_status` function. Write a Python function `def get_system_status() -> SystemStatus` to solve the following problem:
说明: 获取系统信息等
Here is the function:
def get_system_status() -> SystemStatus:
"""
说明:
获取系统信息等
"""
cpu = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
disk = psutil.disk_usage("/").percent
return SystemStatus(
cpu=cpu,
memory=memory,
disk=disk,
check_time=datetime.now().replace(microsecond=0),
) | 说明: 获取系统信息等 |
188,200 | import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import psutil
import ujson as json
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from nonebot.utils import run_sync
from configs.config import Config
from configs.path_config import (
DATA_PATH,
FONT_PATH,
IMAGE_PATH,
LOG_PATH,
RECORD_PATH,
TEMP_PATH,
TEXT_PATH,
)
from .base_model import SystemFolderSize, SystemStatus, User
def _get_dir_size(dir_path: Path) -> float:
"""
说明:
获取文件夹大小
参数:
:param dir_path: 文件夹路径
"""
size = 0
for root, dirs, files in os.walk(dir_path):
size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
return size
class SystemFolderSize(BaseModel):
"""
资源文件占比
"""
name: str
"""名称"""
size: float
"""大小"""
full_path: Optional[str]
"""完整路径"""
is_dir: bool
"""是否为文件夹"""
The provided code snippet includes necessary dependencies for implementing the `get_system_disk` function. Write a Python function `def get_system_disk( full_path: Optional[str], ) -> List[SystemFolderSize]` to solve the following problem:
说明: 获取资源文件大小等
Here is the function:
def get_system_disk(
full_path: Optional[str],
) -> List[SystemFolderSize]:
"""
说明:
获取资源文件大小等
"""
base_path = Path(full_path) if full_path else Path()
other_size = 0
data_list = []
for file in os.listdir(base_path):
f = base_path / file
if f.is_dir():
size = _get_dir_size(f) / 1024 / 1024
data_list.append(SystemFolderSize(name=file, size=size, full_path=str(f), is_dir=True))
else:
other_size += f.stat().st_size / 1024 / 1024
if other_size:
data_list.append(SystemFolderSize(name='other_file', size=other_size, full_path=full_path, is_dir=False))
return data_list
# else:
# if type_ == "image":
# dir_path = IMAGE_PATH
# elif type_ == "font":
# dir_path = FONT_PATH
# elif type_ == "text":
# dir_path = TEXT_PATH
# elif type_ == "record":
# dir_path = RECORD_PATH
# elif type_ == "data":
# dir_path = DATA_PATH
# elif type_ == "temp":
# dir_path = TEMP_PATH
# else:
# dir_path = LOG_PATH
# dir_map = {}
# other_file_size = 0
# for file in os.listdir(dir_path):
# file = Path(dir_path / file)
# if file.is_dir():
# dir_map[file.name] = _get_dir_size(file) / 1024 / 1024
# else:
# other_file_size += os.path.getsize(file) / 1024 / 1024
# dir_map["其他文件"] = other_file_size
# dir_map["check_time"] = datetime.now().replace(microsecond=0)
# return dir_map | 说明: 获取资源文件大小等 |
188,201 | from utils.http_utils import AsyncHttpx
import json
async def search_song(song_name: str):
"""
搜索歌曲
:param song_name: 歌名
"""
r = await AsyncHttpx.post(
f"http://music.163.com/api/search/get/",
data={"s": song_name, "limit": 1, "type": 1, "offset": 0},
)
if r.status_code != 200:
return None
return json.loads(r.text)
async def get_song_id(song_name: str) -> int:
""" """
r = await search_song(song_name)
try:
return r["result"]["songs"][0]["id"]
except KeyError:
return 0 | null |
188,202 | from utils.http_utils import AsyncHttpx
import json
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
The provided code snippet includes necessary dependencies for implementing the `get_song_info` function. Write a Python function `async def get_song_info(songId: int)` to solve the following problem:
获取歌曲信息
Here is the function:
async def get_song_info(songId: int):
"""
获取歌曲信息
"""
r = await AsyncHttpx.post(
f"http://music.163.com/api/song/detail/?id={songId}&ids=%5B{songId}%5D",
)
if r.status_code != 200:
return None
return json.loads(r.text) | 获取歌曲信息 |
188,203 | import asyncio
import time
import aiohttp
import ujson as json
from bilireq import video
from nonebot import on_message
from nonebot.adapters.onebot.v11 import ActionFailed, GroupMessageEvent
from nonebot.adapters.onebot.v11.permission import GROUP
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.browser import get_browser
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage
from utils.manager import group_manager
from utils.message_builder import image
from utils.user_agent import get_user_agent
from utils.utils import get_local_proxy, get_message_json, get_message_text, is_number
async def plugin_on_checker(event: GroupMessageEvent) -> bool:
return group_manager.get_plugin_status("parse_bilibili_json", event.group_id) | null |
188,204 | import asyncio
import time
import aiohttp
import ujson as json
from bilireq import video
from nonebot import on_message
from nonebot.adapters.onebot.v11 import ActionFailed, GroupMessageEvent
from nonebot.adapters.onebot.v11.permission import GROUP
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.browser import get_browser
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage
from utils.manager import group_manager
from utils.message_builder import image
from utils.user_agent import get_user_agent
from utils.utils import get_local_proxy, get_message_json, get_message_text, is_number
parse_bilibili_json = on_message(
priority=1, permission=GROUP, block=False, rule=plugin_on_checker
)
_tmp = {}
def resize(path: str):
A = BuildImage(0, 0, background=path, ratio=0.5)
A.save(path)
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
def get_browser() -> Browser:
if not _browser:
raise RuntimeError("playwright is not initalized")
return _browser
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
def get_user_agent():
return {"User-Agent": random.choice(user_agent)}
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def get_message_text(data: Union[str, Message]) -> str:
"""
说明:
获取消息中 纯文本 的信息
参数:
:param data: event.json()
"""
result = ""
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
if isinstance(message, str):
return message.strip()
for msg in message:
if msg["type"] == "text":
result += msg["data"]["text"].strip() + " "
return result.strip()
else:
for seg in data["text"]:
result += seg.data["text"] + " "
return result.strip()
def get_message_json(data: str) -> List[dict]:
"""
说明:
获取消息中所有 json
参数:
:param data: event.json()
"""
try:
json_list = []
event = json.loads(data)
if data and (message := event.get("message")):
for msg in message:
if msg["type"] == "json":
json_list.append(msg["data"])
return json_list
except KeyError:
return []
async def _(event: GroupMessageEvent):
vd_info = None
url = None
if get_message_json(event.json()):
try:
data = json.loads(get_message_json(event.json())[0]["data"])
except (IndexError, KeyError):
data = None
if data:
# 转发视频
if data.get("desc") == "哔哩哔哩" or "哔哩哔哩" in data.get("prompt"):
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(
data["meta"]["detail_1"]["qqdocurl"],
timeout=7,
) as response:
url = str(response.url).split("?")[0]
if url[-1] == "/":
url = url[:-1]
bvid = url.split("/")[-1]
vd_info = await video.get_video_base_info(bvid)
# 转发专栏
if (
data.get("meta")
and data["meta"].get("news")
and data["meta"]["news"].get("desc") == "哔哩哔哩专栏"
):
url = data["meta"]["news"]["jumpUrl"]
page = None
try:
browser = await get_browser()
if not browser:
return
page = await browser.new_page(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/93.0.4530.0 Safari/537.36"
)
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
await page.click("#app > div")
div = await page.query_selector("#app > div")
await div.screenshot(
path=f"{IMAGE_PATH}/temp/cv_{event.user_id}.png",
timeout=100000,
)
await asyncio.get_event_loop().run_in_executor(
None, resize, TEMP_PATH / f"cv_{event.user_id}.png"
)
await parse_bilibili_json.send(
"[[_task|bilibili_parse]]"
+ image(TEMP_PATH / f"cv_{event.user_id}.png")
)
await page.close()
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
)
except Exception as e:
logger.error(f"尝试解析bilibili专栏 {url} 失败 {type(e)}:{e}")
if page:
await page.close()
return
# BV
if msg := get_message_text(event.json()):
if "BV" in msg:
index = msg.find("BV")
if len(msg[index + 2 :]) >= 10:
msg = msg[index : index + 12]
url = f"https://www.bilibili.com/video/{msg}"
vd_info = await video.get_video_base_info(msg)
elif "av" in msg:
index = msg.find("av")
if len(msg[index + 2 :]) >= 1:
msg = msg[index + 2 : index + 11]
if is_number(msg):
url = f"https://www.bilibili.com/video/av{msg}"
vd_info = await video.get_video_base_info("av" + msg)
elif "https://b23.tv" in msg:
url = "https://" + msg[msg.find("b23.tv") : msg.find("b23.tv") + 14]
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(
url,
timeout=7,
) as response:
url = (str(response.url).split("?")[0]).strip("/")
bvid = url.split("/")[-1]
vd_info = await video.get_video_base_info(bvid)
if vd_info:
if (
url in _tmp.keys() and time.time() - _tmp[url] > 30
) or url not in _tmp.keys():
_tmp[url] = time.time()
aid = vd_info["aid"]
title = vd_info["title"]
author = vd_info["owner"]["name"]
reply = vd_info["stat"]["reply"] # 回复
favorite = vd_info["stat"]["favorite"] # 收藏
coin = vd_info["stat"]["coin"] # 投币
# like = vd_info['stat']['like'] # 点赞
# danmu = vd_info['stat']['danmaku'] # 弹幕
date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
try:
await parse_bilibili_json.send(
"[[_task|bilibili_parse]]"
+ image(vd_info["pic"])
+ f"\nav{aid}\n标题:{title}\n"
f"UP:{author}\n"
f"上传日期:{date}\n"
f"回复:{reply},收藏:{favorite},投币:{coin}\n"
f"{url}"
)
except ActionFailed:
logger.warning(f"{event.group_id} 发送bilibili解析失败")
else:
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
) | null |
188,205 | from utils.utils import get_bot
from bs4 import BeautifulSoup
from utils.http_utils import AsyncHttpx
import asyncio
import platform
import os
url = "https://github.com/Mrs4s/go-cqhttp/releases"
class AsyncHttpx:
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
async def download_gocq_lasted(path: str):
text = (await AsyncHttpx.get(url)).text
soup = BeautifulSoup(text, "lxml")
a = soup.find("div", {"class": "release-header"}).find("a")
title = a.text
_url = a.get("href")
for file in os.listdir(path):
if file.endswith(".zip"):
if (
file == title + "-windows-amd64.zip"
or file == title + "_windows_amd64.zip"
):
return "gocqhttp没有更新!"
for file in os.listdir(path):
os.remove(path + file)
text = (await AsyncHttpx.get("https://github.com" + _url)).text
update_info = ""
soup = BeautifulSoup(text, "lxml")
info_div = soup.find("div", {"class": "markdown-body"})
for p in info_div.find_all("p"):
update_info += p.text.replace("<br>", "\n") + "\n"
div_all = soup.select(
"div.d-flex.flex-justify-between.flex-items-center.py-1.py-md-2.Box-body.px-2"
)
for div in div_all:
if (
div.find("a").find("span").text == title + "-windows-amd64.zip"
or div.find("a").find("span").text == title + "-linux-arm64.tar.gz"
or div.find("a").find("span").text == "go-cqhttp_windows_amd64.zip"
or div.find("a").find("span").text == "go-cqhttp_linux_arm64.tar.gz"
):
file_url = div.find("a").get("href")
if div.find("a").find("span").text.find("windows") == -1:
tag = "-linux-arm64.tar.gz"
else:
tag = "-windows-amd64.zip"
await AsyncHttpx.download_file(
"https://github.com" + file_url, path + title + tag
)
return update_info | null |
188,206 | from utils.utils import get_bot
from bs4 import BeautifulSoup
from utils.http_utils import AsyncHttpx
import asyncio
import platform
import os
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_bot(id_: Optional[str] = None) -> Optional[Bot]:
"""
说明:
获取 bot 对象
"""
try:
return nonebot.get_bot(id_)
except ValueError:
return None
async def upload_gocq_lasted(path, name, group_id):
bot = get_bot()
folder_id = 0
for folder in (await bot.get_group_root_files(group_id=group_id))["folders"]:
if folder["folder_name"] == "gocq":
folder_id = folder["folder_id"]
if not folder_id:
await bot.send_group_msg(group_id=group_id, message=f"请创建gocq文件夹后重试!")
for file in os.listdir(path):
os.remove(path + file)
else:
await bot.upload_group_file(
group_id=group_id, folder=folder_id, file=path + name, name=name
) | null |
188,207 | import platform
from asyncio.exceptions import TimeoutError
from pathlib import Path
from typing import Optional
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.message_builder import image
from utils.utils import change_img_md5
async def parser_data(
url: str, num: int, params: dict, type_: str, r18: int = 0
) -> "list, int":
"""
解析数据
:param url: hibiapi搜索url
:param num: 数量
:param params: 参数
:param type_: 类型,rank或search
:param r18: 是否r18
"""
info_list = []
for _ in range(3):
try:
response = await AsyncHttpx.get(
url,
params=params,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
)
if response.status_code == 200:
data = response.json()
if data.get("illusts"):
data = data["illusts"]
break
except TimeoutError:
pass
except Exception as e:
logger.error(f"P站排行/搜图解析数据发生错误 {type(e)}:{e}")
return ["发生了一些些错误..."], 995
else:
return ["网络不太好?没有该页数?也许过一会就好了..."], 998
num = num if num < 30 else 30
_data = []
for x in data:
if x["page_count"] < Config.get_config("pixiv_rank_search", "MAX_PAGE_LIMIT"):
_data.append(x)
if len(_data) == num:
break
for x in _data:
if type_ == "search" and r18 == 1:
if "R-18" in str(x["tags"]):
continue
title = x["title"]
author = x["user"]["name"]
urls = []
if x["page_count"] == 1:
urls.append(x["image_urls"]["large"])
else:
for j in x["meta_pages"]:
urls.append(j["image_urls"]["large"])
info_list.append((title, author, urls))
return info_list, 200
The provided code snippet includes necessary dependencies for implementing the `get_pixiv_urls` function. Write a Python function `async def get_pixiv_urls( mode: str, num: int = 10, page: int = 1, date: Optional[str] = None ) -> "list, int"` to solve the following problem:
拿到pixiv rank图片url :param mode: 模式 :param num: 数量 :param page: 页数 :param date: 日期
Here is the function:
async def get_pixiv_urls(
mode: str, num: int = 10, page: int = 1, date: Optional[str] = None
) -> "list, int":
"""
拿到pixiv rank图片url
:param mode: 模式
:param num: 数量
:param page: 页数
:param date: 日期
"""
params = {"mode": mode, "page": page}
if date:
params["date"] = date
hibiapi = Config.get_config("hibiapi", "HIBIAPI")
hibiapi = hibiapi[:-1] if hibiapi[-1] == "/" else hibiapi
rank_url = f"{hibiapi}/api/pixiv/rank"
return await parser_data(rank_url, num, params, "rank") | 拿到pixiv rank图片url :param mode: 模式 :param num: 数量 :param page: 页数 :param date: 日期 |
188,208 | import platform
from asyncio.exceptions import TimeoutError
from pathlib import Path
from typing import Optional
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.message_builder import image
from utils.utils import change_img_md5
async def parser_data(
url: str, num: int, params: dict, type_: str, r18: int = 0
) -> "list, int":
"""
解析数据
:param url: hibiapi搜索url
:param num: 数量
:param params: 参数
:param type_: 类型,rank或search
:param r18: 是否r18
"""
info_list = []
for _ in range(3):
try:
response = await AsyncHttpx.get(
url,
params=params,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
)
if response.status_code == 200:
data = response.json()
if data.get("illusts"):
data = data["illusts"]
break
except TimeoutError:
pass
except Exception as e:
logger.error(f"P站排行/搜图解析数据发生错误 {type(e)}:{e}")
return ["发生了一些些错误..."], 995
else:
return ["网络不太好?没有该页数?也许过一会就好了..."], 998
num = num if num < 30 else 30
_data = []
for x in data:
if x["page_count"] < Config.get_config("pixiv_rank_search", "MAX_PAGE_LIMIT"):
_data.append(x)
if len(_data) == num:
break
for x in _data:
if type_ == "search" and r18 == 1:
if "R-18" in str(x["tags"]):
continue
title = x["title"]
author = x["user"]["name"]
urls = []
if x["page_count"] == 1:
urls.append(x["image_urls"]["large"])
else:
for j in x["meta_pages"]:
urls.append(j["image_urls"]["large"])
info_list.append((title, author, urls))
return info_list, 200
The provided code snippet includes necessary dependencies for implementing the `search_pixiv_urls` function. Write a Python function `async def search_pixiv_urls( keyword: str, num: int, page: int, r18: int ) -> "list, list"` to solve the following problem:
搜图图片的url :param keyword: 关键词 :param num: 数量 :param page: 页数 :param r18: 是否r18
Here is the function:
async def search_pixiv_urls(
keyword: str, num: int, page: int, r18: int
) -> "list, list":
"""
搜图图片的url
:param keyword: 关键词
:param num: 数量
:param page: 页数
:param r18: 是否r18
"""
params = {"word": keyword, "page": page}
hibiapi = Config.get_config("hibiapi", "HIBIAPI")
hibiapi = hibiapi[:-1] if hibiapi[-1] == "/" else hibiapi
search_url = f"{hibiapi}/api/pixiv/search"
return await parser_data(search_url, num, params, "search", r18) | 搜图图片的url :param keyword: 关键词 :param num: 数量 :param page: 页数 :param r18: 是否r18 |
188,209 | import platform
from asyncio.exceptions import TimeoutError
from pathlib import Path
from typing import Optional
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.message_builder import image
from utils.utils import change_img_md5
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def change_img_md5(path_file: Union[str, Path]) -> bool:
"""
说明:
改变图片MD5
参数:
:param path_file: 图片路径
"""
try:
with open(path_file, "a") as f:
f.write(str(int(time.time() * 1000)))
return True
except Exception as e:
logger.warning(f"改变图片MD5错误 Path:{path_file}", e=e)
return False
The provided code snippet includes necessary dependencies for implementing the `download_pixiv_imgs` function. Write a Python function `async def download_pixiv_imgs( urls: list, user_id: int, forward_msg_index: int = None ) -> str` to solve the following problem:
下载图片 :param urls: 图片链接 :param user_id: 用户id :param forward_msg_index: 转发消息中的图片排序
Here is the function:
async def download_pixiv_imgs(
urls: list, user_id: int, forward_msg_index: int = None
) -> str:
"""
下载图片
:param urls: 图片链接
:param user_id: 用户id
:param forward_msg_index: 转发消息中的图片排序
"""
result = ""
index = 0
for url in urls:
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url = (
url.replace("i.pximg.net", ws_url)
.replace("i.pixiv.cat", ws_url)
.replace("_webp", "")
)
try:
file = (
TEMP_PATH / f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg"
if forward_msg_index is not None
else TEMP_PATH / f"{user_id}_{index}_pixiv.jpg"
)
file = Path(file)
try:
if await AsyncHttpx.download_file(
url,
file,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
):
change_img_md5(file)
if forward_msg_index is not None:
result += image(
TEMP_PATH
/ f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg",
)
else:
result += image(TEMP_PATH / f"{user_id}_{index}_pixiv.jpg")
index += 1
except OSError:
if file.exists():
file.unlink()
except Exception as e:
logger.error(f"P站排行/搜图下载图片错误 {type(e)}:{e}")
return result | 下载图片 :param urls: 图片链接 :param user_id: 用户id :param forward_msg_index: 转发消息中的图片排序 |
188,210 | import time
from io import BytesIO
from typing import Any, Dict, Tuple
import imagehash
from nonebot import on_command, on_message
from nonebot.adapters.onebot.v11 import ActionFailed, Bot, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import Command, CommandArg
from PIL import Image
from configs.config import NICKNAME, Config
from configs.path_config import DATA_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import get_img_hash
from utils.utils import get_message_img, get_message_text, is_number
def get_data() -> Dict[Any, Any]:
try:
with open(DATA_PATH / "group_mute_data.json", "r", encoding="utf8") as f:
data = json.load(f)
except (ValueError, FileNotFoundError):
data = {}
return data | null |
188,211 | import time
from io import BytesIO
from typing import Any, Dict, Tuple
import imagehash
from nonebot import on_command, on_message
from nonebot.adapters.onebot.v11 import ActionFailed, Bot, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import Command, CommandArg
from PIL import Image
from configs.config import NICKNAME, Config
from configs.path_config import DATA_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import get_img_hash
from utils.utils import get_message_img, get_message_text, is_number
mute = on_message(priority=1, block=False)
async def download_img_and_hash(url) -> str:
mute_dict = {}
mute_data = get_data()
class logger:
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_message_img(data: Union[str, Message]) -> List[str]:
def get_message_text(data: Union[str, Message]) -> str:
async def _(bot: Bot, event: GroupMessageEvent):
group_id = str(event.group_id)
msg = get_message_text(event.json())
img_list = get_message_img(event.json())
img_hash = ""
for img in img_list:
img_hash += await download_img_and_hash(img)
msg += img_hash
if not mute_data.get(group_id):
mute_data[group_id] = {
"count": Config.get_config("mute", "MUTE_DEFAULT_COUNT"),
"time": Config.get_config("mute", "MUTE_DEFAULT_TIME"),
"duration": Config.get_config("mute", "MUTE_DEFAULT_DURATION"),
}
if not mute_dict.get(event.user_id):
mute_dict[event.user_id] = {"time": time.time(), "count": 1, "msg": msg}
else:
if msg and msg.find(mute_dict[event.user_id]["msg"]) != -1:
mute_dict[event.user_id]["count"] += 1
else:
mute_dict[event.user_id]["time"] = time.time()
mute_dict[event.user_id]["count"] = 1
mute_dict[event.user_id]["msg"] = msg
if time.time() - mute_dict[event.user_id]["time"] > mute_data[group_id]["time"]:
mute_dict[event.user_id]["time"] = time.time()
mute_dict[event.user_id]["count"] = 1
if (
mute_dict[event.user_id]["count"] > mute_data[group_id]["count"]
and time.time() - mute_dict[event.user_id]["time"]
< mute_data[group_id]["time"]
):
try:
if mute_data[group_id]["duration"] != 0:
await bot.set_group_ban(
group_id=event.group_id,
user_id=event.user_id,
duration=mute_data[group_id]["duration"] * 60,
)
await mute.send(f"检测到恶意刷屏,{NICKNAME}要把你关进小黑屋!", at_sender=True)
mute_dict[event.user_id]["count"] = 0
logger.info(
f"USER {event.user_id} GROUP {event.group_id} "
f'检测刷屏 被禁言 {mute_data[group_id]["duration"] / 60} 分钟'
)
except ActionFailed:
pass | null |
188,212 | import time
from io import BytesIO
from typing import Any, Dict, Tuple
import imagehash
from nonebot import on_command, on_message
from nonebot.adapters.onebot.v11 import ActionFailed, Bot, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.params import Command, CommandArg
from PIL import Image
from configs.config import NICKNAME, Config
from configs.path_config import DATA_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import get_img_hash
from utils.utils import get_message_img, get_message_text, is_number
mute = on_message(priority=1, block=False)
mute_setting = on_command(
"mute_setting",
aliases={"设置刷屏检测时间", "设置刷屏检测次数", "设置刷屏禁言时长", "刷屏检测设置"},
permission=GROUP,
block=True,
priority=5,
)
def save_data():
global mute_data
with open(DATA_PATH / "group_mute_data.json", "w", encoding="utf8") as f:
json.dump(mute_data, f, indent=4)
mute_data = get_data()
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
async def _(
event: GroupMessageEvent,
cmd: Tuple[str, ...] = Command(),
arg: Message = CommandArg(),
):
global mute_data
group_id = str(event.group_id)
if not mute_data.get(group_id):
mute_data[group_id] = {
"count": Config.get_config("mute", "MUTE_DEFAULT_COUNT"),
"time": Config.get_config("mute", "MUTE_DEFAULT_TIME"),
"duration": Config.get_config("mute", "MUTE_DEFAULT_DURATION"),
}
msg = arg.extract_plain_text().strip()
if cmd[0] == "刷屏检测设置":
await mute_setting.finish(
f'最大次数:{mute_data[group_id]["count"]} 次\n'
f'规定时间:{mute_data[group_id]["time"]} 秒\n'
f'禁言时长:{mute_data[group_id]["duration"]:.2f} 分钟\n'
f"【在规定时间内发送相同消息超过最大次数则禁言\n当禁言时长为0时关闭此功能】"
)
if not is_number(msg):
await mute.finish("设置的参数必须是数字啊!", at_sender=True)
if cmd[0] == "设置刷屏检测时间":
mute_data[group_id]["time"] = int(msg)
msg += "秒"
if cmd[0] == "设置刷屏检测次数":
mute_data[group_id]["count"] = int(msg)
msg += " 次"
if cmd[0] == "设置刷屏禁言时长":
mute_data[group_id]["duration"] = int(msg)
msg += " 分钟"
await mute_setting.send(f"刷屏检测:{cmd[0]}为 {msg}")
logger.info(f"USER {event.user_id} GROUP {group_id} {cmd[0]}:{msg}")
save_data() | null |
188,213 | from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg
from services.log import logger
from configs.config import NICKNAME
import random
import asyncio
roll = on_command("roll", priority=5, block=True)
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip().split()
if not msg:
await roll.finish(f"roll: {random.randint(0, 100)}", at_sender=True)
user_name = event.sender.card or event.sender.nickname
await roll.send(
random.choice(
[
"转动命运的齿轮,拨开眼前迷雾...",
f"启动吧,命运的水晶球,为{user_name}指引方向!",
"嗯哼,在此刻转动吧!命运!",
f"在此祈愿,请为{user_name}降下指引...",
]
)
)
await asyncio.sleep(1)
x = random.choice(msg)
await roll.send(
random.choice(
[
f"让{NICKNAME}看看是什么结果!答案是:‘{x}’",
f"根据命运的指引,接下来{user_name} ‘{x}’ 会比较好",
f"祈愿被回应了!是 ‘{x}’!",
f"结束了,{user_name},命运之轮停在了 ‘{x}’!",
]
)
)
logger.info(
f"(USER {event.user_id}, "
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 发送roll:{msg}"
) | null |
188,214 | import time
from hashlib import md5
from typing import Any, Tuple
from nonebot.internal.matcher import Matcher
from nonebot.internal.params import Depends
from nonebot.params import RegexGroup
from nonebot.typing import T_State
from configs.config import Config
from utils.http_utils import AsyncHttpx
language = {
"自动": "auto",
"粤语": "yue",
"韩语": "kor",
"泰语": "th",
"葡萄牙语": "pt",
"希腊语": "el",
"保加利亚语": "bul",
"芬兰语": "fin",
"斯洛文尼亚语": "slo",
"繁体中文": "cht",
"中文": "zh",
"文言文": "wyw",
"法语": "fra",
"阿拉伯语": "ara",
"德语": "de",
"荷兰语": "nl",
"爱沙尼亚语": "est",
"捷克语": "cs",
"瑞典语": "swe",
"越南语": "vie",
"英语": "en",
"日语": "jp",
"西班牙语": "spa",
"俄语": "ru",
"意大利语": "it",
"波兰语": "pl",
"丹麦语": "dan",
"罗马尼亚语": "rom",
"匈牙利语": "hu",
}
The provided code snippet includes necessary dependencies for implementing the `CheckParam` function. Write a Python function `def CheckParam()` to solve the following problem:
检查翻译内容是否在language中
Here is the function:
def CheckParam():
"""
检查翻译内容是否在language中
"""
async def dependency(
matcher: Matcher,
state: T_State,
reg_group: Tuple[Any, ...] = RegexGroup(),
):
form, to, _ = reg_group
values = language.values()
if form:
form = form.split(":")[-1]
if form not in language and form not in values:
await matcher.finish("FORM选择的语种不存在")
state["form"] = form
else:
state["form"] = "auto"
if to:
to = to.split(":")[-1]
if to not in language and to not in values:
await matcher.finish("TO选择的语种不存在")
state["to"] = to
else:
state["to"] = "auto"
return Depends(dependency) | 检查翻译内容是否在language中 |
188,215 | import time
from hashlib import md5
from typing import Any, Tuple
from nonebot.internal.matcher import Matcher
from nonebot.internal.params import Depends
from nonebot.params import RegexGroup
from nonebot.typing import T_State
from configs.config import Config
from utils.http_utils import AsyncHttpx
URL = "http://api.fanyi.baidu.com/api/trans/vip/translate"
language = {
"自动": "auto",
"粤语": "yue",
"韩语": "kor",
"泰语": "th",
"葡萄牙语": "pt",
"希腊语": "el",
"保加利亚语": "bul",
"芬兰语": "fin",
"斯洛文尼亚语": "slo",
"繁体中文": "cht",
"中文": "zh",
"文言文": "wyw",
"法语": "fra",
"阿拉伯语": "ara",
"德语": "de",
"荷兰语": "nl",
"爱沙尼亚语": "est",
"捷克语": "cs",
"瑞典语": "swe",
"越南语": "vie",
"英语": "en",
"日语": "jp",
"西班牙语": "spa",
"俄语": "ru",
"意大利语": "it",
"波兰语": "pl",
"丹麦语": "dan",
"罗马尼亚语": "rom",
"匈牙利语": "hu",
}
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
The provided code snippet includes necessary dependencies for implementing the `translate_msg` function. Write a Python function `async def translate_msg(word: str, form: str, to: str) -> str` to solve the following problem:
翻译 Args: word (str): 翻译文字 form (str): 源语言 to (str): 目标语言 Returns: str: 翻译后的文字
Here is the function:
async def translate_msg(word: str, form: str, to: str) -> str:
"""翻译
Args:
word (str): 翻译文字
form (str): 源语言
to (str): 目标语言
Returns:
str: 翻译后的文字
"""
if form in language:
form = language[form]
if to in language:
to = language[to]
salt = str(time.time())
app_id = Config.get_config("translate", "APPID")
secret_key = Config.get_config("translate", "SECRET_KEY")
sign = app_id + word + salt + secret_key # type: ignore
md5_ = md5()
md5_.update(sign.encode("utf-8"))
sign = md5_.hexdigest()
params = {
"q": word,
"from": form,
"to": to,
"appid": app_id,
"salt": salt,
"sign": sign,
}
url = URL + "?"
for key, value in params.items():
url += f"{key}={value}&"
url = url[:-1]
resp = await AsyncHttpx.get(url)
data = resp.json()
if data.get("error_code"):
return data.get("error_msg")
if trans_result := data.get("trans_result"):
return trans_result[0]["dst"]
return "没有找到翻译捏" | 翻译 Args: word (str): 翻译文字 form (str): 源语言 to (str): 目标语言 Returns: str: 翻译后的文字 |
188,216 | from lxml import etree
import feedparser
from urllib import parse
from services.log import logger
from utils.http_utils import AsyncHttpx
from typing import List, Union
import time
async def get_repass(url: str, max_: int) -> List[str]:
put_line = []
text = (await AsyncHttpx.get(url)).text
d = feedparser.parse(text)
max_ = max_ if max_ < len([e.link for e in d.entries]) else len([e.link for e in d.entries])
url_list = [e.link for e in d.entries][:max_]
for u in url_list:
try:
text = (await AsyncHttpx.get(u)).text
html = etree.HTML(text)
magent = html.xpath('.//a[@id="a_magnet"]/text()')[0]
title = html.xpath(".//h3/text()")[0]
item = html.xpath(
'//div[@class="info resource-info right"]/ul/li'
)
class_a = (
item[0]
.xpath("string(.)")[5:]
.strip()
.replace("\xa0", "")
.replace("\t", "")
)
size = item[3].xpath("string(.)")[5:].strip()
put_line.append(
"【{}】| {}\n【{}】| {}".format(class_a, title, size, magent)
)
except Exception as e:
logger.error(f"搜番发生错误 {type(e)}:{e}")
return put_line
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
async def from_anime_get_info(key_word: str, max_: int) -> Union[str, List[str]]:
s_time = time.time()
url = "https://share.dmhy.org/topics/rss/rss.xml?keyword=" + parse.quote(key_word)
try:
repass = await get_repass(url, max_)
except Exception as e:
logger.error(f"发生了一些错误 {type(e)}:{e}")
return "发生了一些错误!"
repass.insert(0, f"搜索 {key_word} 结果(耗时 {int(time.time() - s_time)} 秒):\n")
return repass | null |
188,217 | from typing import Union
import cv2
import numpy as np
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message, MessageEvent
from nonebot.params import Arg, ArgStr, CommandArg, Depends
from nonebot.rule import to_me
from nonebot.typing import T_State
from PIL import Image, ImageFilter
from configs.config import NICKNAME
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, pic2b64
from utils.message_builder import image
from utils.utils import get_message_img, is_number
update_img = on_command(
"修改图片", aliases={"操作图片", "改图"}, priority=5, rule=to_me(), block=True
)
method_str = ""
method_oper = []
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def get_message_img(data: Union[str, Message]) -> List[str]:
"""
说明:
获取消息中所有的 图片 的链接
参数:
:param data: event.json()
"""
img_list = []
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
for msg in message:
if msg["type"] == "image":
img_list.append(msg["data"]["url"])
else:
for seg in data["image"]:
img_list.append(seg.data["url"])
return img_list
def parse_key(key: str):
async def _key_parser(state: T_State, inp: Union[Message, str] = Arg(key)):
if key != "img_list" and isinstance(inp, Message):
inp = inp.extract_plain_text().strip()
if inp in ["取消", "算了"]:
await update_img.finish("已取消操作..")
if key == "method":
if inp not in method_oper:
await update_img.reject_arg("method", f"操作不正确,请重新输入!{method_str}")
elif key == "x":
method = state["method"]
if method in ["1", "修改尺寸"]:
if not is_number(inp) or int(inp) < 1:
await update_img.reject_arg("x", "宽度不正确!请重新输入数字...")
elif method in ["2", "等比压缩", "3", "旋转图片"]:
if not is_number(inp):
await update_img.reject_arg("x", "比率不正确!请重新输入数字...")
elif method in ["10", "底色替换"]:
if inp not in ["红色", "蓝色", "红", "蓝"]:
await update_img.reject_arg("x", "请输入支持的被替换的底色:\n红色 蓝色")
elif key == "y":
method = state["method"]
if method in ["1", "修改尺寸"]:
if not is_number(inp) or int(inp) < 1:
await update_img.reject_arg("y", "长度不正确!请重新输入数字...")
elif method in ["10", "底色替换"]:
if inp not in [
"红色",
"白色",
"蓝色",
"绿色",
"黄色",
"红",
"白",
"蓝",
"绿",
"黄",
]:
await update_img.reject_arg("y", "请输入支持的替换的底色:\n红色 蓝色 白色 绿色")
elif key == "img_list":
if not get_message_img(inp):
await update_img.reject_arg("img_list", "没图?没图?没图?来图速来!")
state[key] = inp
return _key_parser | null |
188,218 | from typing import Union
import cv2
import numpy as np
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message, MessageEvent
from nonebot.params import Arg, ArgStr, CommandArg, Depends
from nonebot.rule import to_me
from nonebot.typing import T_State
from PIL import Image, ImageFilter
from configs.config import NICKNAME
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, pic2b64
from utils.message_builder import image
from utils.utils import get_message_img, is_number
update_img = on_command(
"修改图片", aliases={"操作图片", "改图"}, priority=5, rule=to_me(), block=True
)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def get_message_img(data: Union[str, Message]) -> List[str]:
"""
说明:
获取消息中所有的 图片 的链接
参数:
:param data: event.json()
"""
img_list = []
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
for msg in message:
if msg["type"] == "image":
img_list.append(msg["data"]["url"])
else:
for seg in data["image"]:
img_list.append(seg.data["url"])
return img_list
async def _(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
if str(event.get_message()) in ["帮助"]:
await update_img.finish(image("update_img_help.png"))
raw_arg = arg.extract_plain_text().strip()
img_list = get_message_img(event.json())
if raw_arg:
args = raw_arg.split("[")[0].split()
state["method"] = args[0]
if len(args) == 2:
if args[0] in ["等比压缩", "旋转图片"]:
if is_number(args[1]):
state["x"] = args[1]
state["y"] = ""
elif len(args) > 2:
if args[0] in ["修改尺寸"]:
if is_number(args[1]):
state["x"] = args[1]
if is_number(args[2]):
state["y"] = args[2]
if args[0] in ["底色替换"]:
if args[1] in ["红色", "蓝色", "蓝", "红"]:
state["x"] = args[1]
if args[2] in ["红色", "白色", "蓝色", "绿色", "黄色", "红", "白", "蓝", "绿", "黄"]:
state["y"] = args[2]
if args[0] in ["水平翻转", "铅笔滤镜", "模糊效果", "锐化效果", "高斯模糊", "边缘检测"]:
state["x"] = ""
state["y"] = ""
if img_list:
state["img_list"] = event.message | null |
188,219 | from typing import Union
import cv2
import numpy as np
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message, MessageEvent
from nonebot.params import Arg, ArgStr, CommandArg, Depends
from nonebot.rule import to_me
from nonebot.typing import T_State
from PIL import Image, ImageFilter
from configs.config import NICKNAME
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage, pic2b64
from utils.message_builder import image
from utils.utils import get_message_img, is_number
update_img = on_command(
"修改图片", aliases={"操作图片", "改图"}, priority=5, rule=to_me(), block=True
)
method_list = [
"修改尺寸",
"等比压缩",
"旋转图片",
"水平翻转",
"铅笔滤镜",
"模糊效果",
"锐化效果",
"高斯模糊",
"边缘检测",
"底色替换",
]
for i in range(len(method_list)):
method_str += f"\n{i + 1}.{method_list[i]}"
method_oper.append(method_list[i])
method_oper.append(str(i + 1))
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
def pic2b64(pic: Image) -> str:
"""
说明:
PIL图片转base64
参数:
:param pic: 通过PIL打开的图片文件
"""
buf = BytesIO()
pic.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def get_message_img(data: Union[str, Message]) -> List[str]:
"""
说明:
获取消息中所有的 图片 的链接
参数:
:param data: event.json()
"""
img_list = []
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
for msg in message:
if msg["type"] == "image":
img_list.append(msg["data"]["url"])
else:
for seg in data["image"]:
img_list.append(seg.data["url"])
return img_list
async def _(
event: MessageEvent,
state: T_State,
method: str = ArgStr("method"),
x: str = ArgStr("x"),
y: str = ArgStr("y"),
img_list: Message = Arg("img_list"),
):
x = x or ""
y = y or ""
img_list = get_message_img(img_list)
if is_number(x):
x = float(x)
if is_number(y):
y = int(y)
index = 0
result = ""
for img_url in img_list:
if await AsyncHttpx.download_file(
img_url, TEMP_PATH / f"{event.user_id}_{index}_update.png"
):
index += 1
else:
await update_img.finish("获取图片超时了...", at_sender=True)
if index == 0:
return
if method in ["修改尺寸", "1"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png")
img = img.convert("RGB")
img = img.resize((int(x), int(y)), Image.ANTIALIAS)
result += image(b64=pic2b64(img))
await update_img.finish(result, at_sender=True)
if method in ["等比压缩", "2"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png")
width, height = img.size
img = img.convert("RGB")
if width * x < 8000 and height * x < 8000:
img = img.resize((int(x * width), int(x * height)))
result += image(b64=pic2b64(img))
else:
await update_img.finish(f"{NICKNAME}不支持图片压缩后宽或高大于8000的存在!!")
if method in ["旋转图片", "3"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png")
img = img.rotate(x)
result += image(b64=pic2b64(img))
if method in ["水平翻转", "4"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png")
img = img.transpose(Image.FLIP_LEFT_RIGHT)
result += image(b64=pic2b64(img))
if method in ["铅笔滤镜", "5"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.CONTOUR
)
result += image(b64=pic2b64(img))
if method in ["模糊效果", "6"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.BLUR
)
result += image(b64=pic2b64(img))
if method in ["锐化效果", "7"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.EDGE_ENHANCE
)
result += image(b64=pic2b64(img))
if method in ["高斯模糊", "8"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.GaussianBlur
)
result += image(b64=pic2b64(img))
if method in ["边缘检测", "9"]:
for i in range(index):
img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.FIND_EDGES
)
result += image(b64=pic2b64(img))
if method in ["底色替换", "10"]:
if x in ["蓝色", "蓝"]:
lower = np.array([90, 70, 70])
upper = np.array([110, 255, 255])
if x in ["红色", "红"]:
lower = np.array([0, 135, 135])
upper = np.array([180, 245, 230])
if y in ["蓝色", "蓝"]:
color = (255, 0, 0)
if y in ["红色", "红"]:
color = (0, 0, 255)
if y in ["白色", "白"]:
color = (255, 255, 255)
if y in ["绿色", "绿"]:
color = (0, 255, 0)
if y in ["黄色", "黄"]:
color = (0, 255, 255)
for k in range(index):
img = cv2.imread(TEMP_PATH / f"{event.user_id}_{k}_update.png")
img = cv2.resize(img, None, fx=0.3, fy=0.3)
rows, cols, channels = img.shape
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
# erode = cv2.erode(mask, None, iterations=1)
dilate = cv2.dilate(mask, None, iterations=1)
for i in range(rows):
for j in range(cols):
if dilate[i, j] == 255:
img[i, j] = color
cv2.imwrite(TEMP_PATH / f"{event.user_id}_{k}_ok_update.png", img)
for i in range(index):
result += image(TEMP_PATH / f"{event.user_id}_{i}_ok_update.png")
if is_number(method):
method = method_list[int(method) - 1]
logger.info(
f"(USER {event.user_id}, GROUP"
f" {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 使用{method}"
)
await update_img.finish(result, at_sender=True) | null |
188,220 | from asyncio.exceptions import TimeoutError
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent
from nonebot.params import Arg, CommandArg
from nonebot.typing import T_State
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.manager import withdraw_message_manager
from utils.message_builder import image
from utils.utils import change_pixiv_image_links, is_number
async def _h(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
pid = arg.extract_plain_text().strip()
if pid:
state["pid"] = pid | null |
188,221 | from asyncio.exceptions import TimeoutError
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent
from nonebot.params import Arg, CommandArg
from nonebot.typing import T_State
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.manager import withdraw_message_manager
from utils.message_builder import image
from utils.utils import change_pixiv_image_links, is_number
pid_search = on_command("p搜", aliases={"pixiv搜", "P搜"}, priority=5, block=True)
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class AsyncHttpx:
proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()}
async def get(
cls,
url: str,
*,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Get
参数:
:param url: url
:param params: params
:param headers: 请求头
:param cookies: cookies
:param verify: verify
:param use_proxy: 使用默认代理
:param proxy: 指定代理
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def post(
cls,
url: str,
*,
data: Optional[Dict[str, str]] = None,
content: Any = None,
files: Any = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
json: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> Response:
"""
说明:
Post
参数:
:param url: url
:param data: data
:param content: content
:param files: files
:param use_proxy: 是否默认代理
:param proxy: 指定代理
:param json: json
:param params: params
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client:
return await client.post(
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
)
async def download_file(
cls,
url: str,
path: Union[str, Path],
*,
params: Optional[Dict[str, str]] = None,
verify: bool = True,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
stream: bool = False,
**kwargs,
) -> bool:
"""
说明:
下载文件
参数:
:param url: url
:param path: 存储路径
:param params: params
:param verify: verify
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
:param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件)
"""
if isinstance(path, str):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
for _ in range(3):
if not stream:
try:
content = (
await cls.get(
url,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
proxy=proxy,
timeout=timeout,
**kwargs,
)
).content
async with aiofiles.open(path, "wb") as wf:
await wf.write(content)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
if not headers:
headers = get_user_agent()
proxy_ = proxy if proxy else cls.proxy if use_proxy else None
try:
async with httpx.AsyncClient(
proxies=proxy_, verify=verify
) as client:
async with client.stream(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
**kwargs,
) as response:
logger.info(
f"开始下载 {path.name}.. Path: {path.absolute()}"
)
async with aiofiles.open(path, "wb") as wf:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
rich.progress.TextColumn(path.name),
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task(
"Download", total=total
)
async for chunk in response.aiter_bytes():
await wf.write(chunk)
await wf.flush()
progress.update(
download_task,
completed=response.num_bytes_downloaded,
)
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
return True
except (TimeoutError, ConnectTimeout):
pass
else:
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
except Exception as e:
logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e)
return False
async def gather_download_file(
cls,
url_list: List[str],
path_list: List[Union[str, Path]],
*,
limit_async_number: Optional[int] = None,
params: Optional[Dict[str, str]] = None,
use_proxy: bool = True,
proxy: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
timeout: Optional[int] = 30,
**kwargs,
) -> List[bool]:
"""
说明:
分组同时下载文件
参数:
:param url_list: url列表
:param path_list: 存储路径列表
:param limit_async_number: 限制同时请求数量
:param params: params
:param use_proxy: 使用代理
:param proxy: 指定代理
:param headers: 请求头
:param cookies: cookies
:param timeout: 超时时间
"""
if n := len(url_list) != len(path_list):
raise UrlPathNumberNotEqual(
f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}"
)
if limit_async_number and n > limit_async_number:
m = float(n) / limit_async_number
x = 0
j = limit_async_number
_split_url_list = []
_split_path_list = []
for _ in range(int(m)):
_split_url_list.append(url_list[x:j])
_split_path_list.append(path_list[x:j])
x += limit_async_number
j += limit_async_number
if int(m) < m:
_split_url_list.append(url_list[j:])
_split_path_list.append(path_list[j:])
else:
_split_url_list = [url_list]
_split_path_list = [path_list]
tasks = []
result_ = []
for x, y in zip(_split_url_list, _split_path_list):
for url, path in zip(x, y):
tasks.append(
asyncio.create_task(
cls.download_file(
url,
path,
params=params,
headers=headers,
cookies=cookies,
use_proxy=use_proxy,
timeout=timeout,
proxy=proxy,
**kwargs,
)
)
)
_x = await asyncio.gather(*tasks)
result_ = result_ + list(_x)
tasks.clear()
return result_
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def is_number(s: Union[int, str]) -> bool:
"""
说明:
检测 s 是否为数字
参数:
:param s: 文本
"""
if isinstance(s, int):
return True
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def change_pixiv_image_links(
url: str, size: Optional[str] = None, nginx_url: Optional[str] = None
):
"""
说明:
根据配置改变图片大小和反代链接
参数:
:param url: 图片原图链接
:param size: 模式
:param nginx_url: 反代
"""
if size == "master":
img_sp = url.rsplit(".", maxsplit=1)
url = img_sp[0]
img_type = img_sp[1]
url = url.replace("original", "master") + f"_master1200.{img_type}"
if not nginx_url:
nginx_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if nginx_url:
url = (
url.replace("i.pximg.net", nginx_url)
.replace("i.pixiv.cat", nginx_url)
.replace("_webp", "")
)
return url
async def _g(event: MessageEvent, state: T_State, pid: str = Arg("pid")):
url = Config.get_config("hibiapi", "HIBIAPI") + "/api/pixiv/illust"
if pid in ["取消", "算了"]:
await pid_search.finish("已取消操作...")
if not is_number(pid):
await pid_search.reject_arg("pid", "笨蛋,重新输入数!字!")
for _ in range(3):
try:
data = (
await AsyncHttpx.get(
url,
params={"id": pid},
timeout=5,
)
).json()
except TimeoutError:
pass
except Exception as e:
await pid_search.finish(f"发生了一些错误..{type(e)}:{e}")
else:
if data.get("error"):
await pid_search.finish(data["error"]["user_message"], at_sender=True)
data = data["illust"]
if not data["width"] and not data["height"]:
await pid_search.finish(f"没有搜索到 PID:{pid} 的图片", at_sender=True)
pid = data["id"]
title = data["title"]
author = data["user"]["name"]
author_id = data["user"]["id"]
image_list = []
try:
image_list.append(data["meta_single_page"]["original_image_url"])
except KeyError:
for image_url in data["meta_pages"]:
image_list.append(image_url["image_urls"]["original"])
for i, img_url in enumerate(image_list):
img_url = change_pixiv_image_links(img_url)
if not await AsyncHttpx.download_file(
img_url,
TEMP_PATH / f"pid_search_{event.user_id}_{i}.png",
headers=headers,
):
await pid_search.send("图片下载失败了....", at_sender=True)
tmp = ""
if isinstance(event, GroupMessageEvent):
tmp = "\n【注】将在30后撤回......"
msg_id = await pid_search.send(
Message(
f"title:{title}\n"
f"pid:{pid}\n"
f"author:{author}\n"
f"author_id:{author_id}\n"
f'{image(TEMP_PATH / f"pid_search_{event.user_id}_{i}.png")}'
f"{tmp}"
)
)
logger.info(
f"(USER {event.user_id}, "
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询图片 PID:{pid}"
)
if isinstance(event, GroupMessageEvent):
withdraw_message_manager.append((msg_id, 30))
break
else:
await pid_search.finish("图片下载失败了....", at_sender=True) | null |
188,222 | import random
from nonebot import on_message
from nonebot.adapters.onebot.v11 import GroupMessageEvent
from nonebot.adapters.onebot.v11.permission import GROUP
from configs.config import NICKNAME, Config
from configs.path_config import TEMP_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.image_utils import get_img_hash
from utils.message_builder import image
from utils.utils import get_message_img, get_message_text
Config.add_plugin_config(
"_task", "DEFAULT_FUDU", True, help_="被动 复读 进群默认开关状态", default_value=True, type=bool
)
_fudu_list = Fudu()
fudu = on_message(permission=GROUP, priority=999)
async def get_fudu_img_hash(url, group_id):
try:
if await AsyncHttpx.download_file(
url, TEMP_PATH / f"compare_{group_id}_img.jpg"
):
img_hash = get_img_hash(TEMP_PATH / f"compare_{group_id}_img.jpg")
return str(img_hash)
else:
logger.warning(f"复读下载图片失败...")
except Exception as e:
logger.warning(f"复读读取图片Hash出错 {type(e)}:{e}")
return ""
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
{
"run_sql": [], # 需要启动前运行的sql语句
"_shop_before_handle": {}, # 商品使用前函数
"_shop_after_handle": {}, # 商品使用后函数
}
def get_message_img(data: Union[str, Message]) -> List[str]:
"""
说明:
获取消息中所有的 图片 的链接
参数:
:param data: event.json()
"""
img_list = []
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
for msg in message:
if msg["type"] == "image":
img_list.append(msg["data"]["url"])
else:
for seg in data["image"]:
img_list.append(seg.data["url"])
return img_list
def get_message_text(data: Union[str, Message]) -> str:
"""
说明:
获取消息中 纯文本 的信息
参数:
:param data: event.json()
"""
result = ""
if isinstance(data, str):
event = json.loads(data)
if data and (message := event.get("message")):
if isinstance(message, str):
return message.strip()
for msg in message:
if msg["type"] == "text":
result += msg["data"]["text"].strip() + " "
return result.strip()
else:
for seg in data["text"]:
result += seg.data["text"] + " "
return result.strip()
async def _(event: GroupMessageEvent):
if event.is_tome():
return
if msg := get_message_text(event.json()):
if msg.startswith(f"@可爱的{NICKNAME}"):
await fudu.finish("复制粘贴的虚空艾特?", at_sender=True)
img = get_message_img(event.json())
msg = get_message_text(event.json())
if not img and not msg:
return
if img:
img_hash = await get_fudu_img_hash(img[0], event.group_id)
else:
img_hash = ""
add_msg = msg + "|-|" + img_hash
if _fudu_list.size(event.group_id) == 0:
_fudu_list.append(event.group_id, add_msg)
elif _fudu_list.check(event.group_id, add_msg):
_fudu_list.append(event.group_id, add_msg)
else:
_fudu_list.clear(event.group_id)
_fudu_list.append(event.group_id, add_msg)
if _fudu_list.size(event.group_id) > 2:
if random.random() < Config.get_config(
"fudu", "FUDU_PROBABILITY"
) and not _fudu_list.is_repeater(event.group_id):
if random.random() < 0.2:
if msg.endswith("打断施法!"):
await fudu.finish("[[_task|fudu]]打断" + msg)
else:
await fudu.finish("[[_task|fudu]]打断施法!")
_fudu_list.set_repeater(event.group_id)
if img and msg:
rst = msg + image(TEMP_PATH / f"compare_{event.group_id}_img.jpg")
elif img:
rst = image(TEMP_PATH / f"compare_{event.group_id}_img.jpg")
elif msg:
rst = msg
else:
rst = ""
if rst:
await fudu.finish("[[_task|fudu]]" + rst) | null |
188,223 | import os
import random
import re
from configs.config import NICKNAME, Config
from configs.path_config import DATA_PATH, IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.message_builder import face, image
from .utils import ai_message_manager
index = 0
anime_data = json.load(open(DATA_PATH / "anime.json", "r", encoding="utf8"))
global index
def xie_ai(text: str) -> str:
"""
获取青云客回复
:param text: 问题
:return: 青云可回复
"""
res = await AsyncHttpx.get(
f"http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}"
)
content = ""
try:
data = json.loads(res.text)
if data["result"] == 0:
content = data["content"]
if "菲菲" in content:
content = content.replace("菲菲", NICKNAME)
if "艳儿" in content:
content = content.replace("艳儿", NICKNAME)
if "公众号" in content:
content = ""
if "{br}" in content:
content = content.replace("{br}", "\n")
if "提示" in content:
content = content[: content.find("提示")]
if "淘宝" in content or "taobao.com" in content:
return ""
while True:
r = re.search("{face:(.*)}", content)
if r:
id_ = r.group(1)
content = content.replace(
"{" + f"face:{id_}" + "}", str(face(int(id_)))
)
else:
break
return (
content
if not content and not Config.get_config("ai", "ALAPI_AI_CHECK")
else await check_text(content)
)
except Exception as e:
logger.error(f"Ai xie_ai 发生错误 {type(e)}:{e}")
return ""
return random.choice(
[
"你在说啥子?",
f"纯洁的{NICKNAME}没听懂",
"下次再告诉你(下次一定)",
"你觉得我听懂了吗?嗯?",
"我!不!知!道!",
]
) + image(
IMAGE_PATH / "noresult" / random.choice(os.listdir(IMAGE_PATH / "noresult"))
)
ai_message_manager = AiMessageManager()
The provided code snippet includes necessary dependencies for implementing the `get_chat_result` function. Write a Python function `async def get_chat_result(text: str, img_url: str, user_id: int, nickname: str) -> str` to solve the following problem:
获取 AI 返回值,顺序: 特殊回复 -> 图灵 -> 青云客 :param text: 问题 :param img_url: 图片链接 :param user_id: 用户id :param nickname: 用户昵称 :return: 回答
Here is the function:
async def get_chat_result(text: str, img_url: str, user_id: int, nickname: str) -> str:
"""
获取 AI 返回值,顺序: 特殊回复 -> 图灵 -> 青云客
:param text: 问题
:param img_url: 图片链接
:param user_id: 用户id
:param nickname: 用户昵称
:return: 回答
"""
global index
ai_message_manager.add_message(user_id, text)
special_rst = await ai_message_manager.get_result(user_id, nickname)
if special_rst:
ai_message_manager.add_result(user_id, special_rst)
return special_rst
if index == 5:
index = 0
if len(text) < 6 and random.random() < 0.6:
keys = anime_data.keys()
for key in keys:
if text.find(key) != -1:
return random.choice(anime_data[key]).replace("你", nickname)
rst = await tu_ling(text, img_url, user_id)
if not rst:
rst = await xie_ai(text)
if not rst:
return no_result()
if nickname:
if len(nickname) < 5:
if random.random() < 0.5:
nickname = "~".join(nickname) + "~"
if random.random() < 0.2:
if nickname.find("大人") == -1:
nickname += "大~人~"
rst = str(rst).replace("小主人", nickname).replace("小朋友", nickname)
ai_message_manager.add_result(user_id, rst)
return rst | 获取 AI 返回值,顺序: 特殊回复 -> 图灵 -> 青云客 :param text: 问题 :param img_url: 图片链接 :param user_id: 用户id :param nickname: 用户昵称 :return: 回答 |
188,224 | import os
import random
import re
from configs.config import NICKNAME, Config
from configs.path_config import DATA_PATH, IMAGE_PATH
from services.log import logger
from utils.http_utils import AsyncHttpx
from utils.message_builder import face, image
from .utils import ai_message_manager
return random.choice(
[
"你在说啥子?",
f"纯洁的{NICKNAME}没听懂",
"下次再告诉你(下次一定)",
"你觉得我听懂了吗?嗯?",
"我!不!知!道!",
]
) + image(
IMAGE_PATH / "noresult" / random.choice(os.listdir(IMAGE_PATH / "noresult"))
)
def image(
file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None,
b64: Optional[str] = None,
) -> MessageSegment:
"""
说明:
生成一个 MessageSegment.image 消息
生成顺序:绝对路径(abspath) > base64(b64) > img_name
参数:
:param file: 图片文件
:param b64: 图片base64(兼容旧方法)
"""
if b64:
file = b64 if b64.startswith("base64://") else ("base64://" + b64)
if isinstance(file, str):
if file.startswith(("http", "base64://")):
return MessageSegment.image(file)
else:
if (IMAGE_PATH / file).exists():
return MessageSegment.image(IMAGE_PATH / file)
logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...")
return ""
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
if isinstance(file, (bytes, io.BytesIO)):
return MessageSegment.image(file)
if isinstance(file, (BuildImage, BuildMat)):
return MessageSegment.image(file.pic2bs4())
return MessageSegment.image("")
The provided code snippet includes necessary dependencies for implementing the `hello` function. Write a Python function `def hello() -> str` to solve the following problem:
一些打招呼的内容
Here is the function:
def hello() -> str:
"""
一些打招呼的内容
"""
result = random.choice(
(
"哦豁?!",
"你好!Ov<",
f"库库库,呼唤{NICKNAME}做什么呢",
"我在呢!",
"呼呼,叫俺干嘛",
)
)
img = random.choice(os.listdir(IMAGE_PATH / "zai"))
if img[-4:] == ".gif":
result += image(IMAGE_PATH / "zai" / img)
else:
result += image(IMAGE_PATH / "zai" / img)
return result | 一些打招呼的内容 |
188,225 | from io import BytesIO
from bilireq.user import get_user_info
from httpx import AsyncClient
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncHttpx, get_user_agent
from utils.image_utils import BuildImage
async def get_pic(url: str) -> bytes:
"""
获取图像
:param url: 图像链接
:return: 图像二进制
"""
return (await AsyncHttpx.get(url, timeout=10)).content
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
The provided code snippet includes necessary dependencies for implementing the `create_live_des_image` function. Write a Python function `async def create_live_des_image(uid: int, title: str, cover: str, tags: str, des: str)` to solve the following problem:
生成主播简介图片 :param uid: 主播 uid :param title: 直播间标题 :param cover: 直播封面 :param tags: 直播标签 :param des: 直播简介 :return:
Here is the function:
async def create_live_des_image(uid: int, title: str, cover: str, tags: str, des: str):
"""
生成主播简介图片
:param uid: 主播 uid
:param title: 直播间标题
:param cover: 直播封面
:param tags: 直播标签
:param des: 直播简介
:return:
"""
user_info = await get_user_info(uid)
name = user_info["name"]
sex = user_info["sex"]
face = user_info["face"]
sign = user_info["sign"]
ava = BuildImage(100, 100, background=BytesIO(await get_pic(face)))
ava.circle()
cover = BuildImage(470, 265, background=BytesIO(await get_pic(cover))) | 生成主播简介图片 :param uid: 主播 uid :param title: 直播间标题 :param cover: 直播封面 :param tags: 直播标签 :param des: 直播简介 :return: |
188,226 | from io import BytesIO
from bilireq.user import get_user_info
from httpx import AsyncClient
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncHttpx, get_user_agent
from utils.image_utils import BuildImage
BORDER_PATH = IMAGE_PATH / "border"
BORDER_PATH.mkdir(parents=True, exist_ok=True)
class BuildImage:
"""
快捷生成图片与操作图片的工具类
"""
def __init__(
self,
w: int,
h: int,
paste_image_width: int = 0,
paste_image_height: int = 0,
paste_space: int = 0,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None,
image_mode: ModeType = "RGBA",
font_size: int = 10,
background: Union[Optional[str], BytesIO, Path] = None,
font: str = "yz.ttf",
ratio: float = 1,
is_alpha: bool = False,
plain_text: Optional[str] = None,
font_color: Optional[Union[str, Tuple[int, int, int]]] = None,
**kwargs,
):
"""
参数:
:param w: 自定义图片的宽度,w=0时为图片原本宽度
:param h: 自定义图片的高度,h=0时为图片原本高度
:param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行
:param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行
:param paste_space: 自动贴图间隔
:param color: 生成图片的颜色
:param image_mode: 图片的类型
:param font_size: 文字大小
:param background: 打开图片的路径
:param font: 字体,默认在 resource/ttf/ 路径下
:param ratio: 倍率压缩
:param is_alpha: 是否背景透明
:param plain_text: 纯文字文本
"""
self.w = int(w)
self.h = int(h)
self.paste_image_width = int(paste_image_width)
self.paste_image_height = int(paste_image_height)
self.paste_space = int(paste_space)
self._current_w = 0
self._current_h = 0
self.uid = uuid.uuid1()
self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color:
color = (255, 255, 255)
self.background = background
if not background:
if plain_text:
if not color:
color = (255, 255, 255, 0)
ttf_w, ttf_h = self.getsize(str(plain_text))
self.w = self.w if self.w > ttf_w else ttf_w
self.h = self.h if self.h > ttf_h else ttf_h
self.markImg = Image.new(image_mode, (self.w, self.h), color)
self.markImg.convert(image_mode)
else:
if not w and not h:
self.markImg = Image.open(background)
w, h = self.markImg.size
if ratio and ratio > 0 and ratio != 1:
self.w = int(ratio * w)
self.h = int(ratio * h)
self.markImg = self.markImg.resize(
(self.w, self.h), Image.ANTIALIAS
)
else:
self.w = w
self.h = h
else:
self.markImg = Image.open(background).resize(
(self.w, self.h), Image.ANTIALIAS
)
if is_alpha:
try:
if array := self.markImg.load():
for i in range(w):
for j in range(h):
pos = array[i, j]
is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3
if is_edit:
array[i, j] = (255, 255, 255, 0)
except Exception as e:
logger.warning(f"背景透明化发生错误..{type(e)}:{e}")
self.draw = ImageDraw.Draw(self.markImg)
self.size = self.w, self.h
if plain_text:
fill = font_color if font_color else (0, 0, 0)
self.text((0, 0), str(plain_text), fill)
try:
self.loop = asyncio.get_event_loop()
except RuntimeError:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
self.loop = asyncio.get_event_loop()
def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont:
"""
说明:
加载字体
参数:
:param font: 字体名称
:param font_size: 字体大小
"""
return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size)
async def apaste(
self,
img: "BuildImage" or Image,
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
异步 贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
await self.loop.run_in_executor(
None, self.paste, img, pos, alpha, center_type, allow_negative
)
def paste(
self,
img: "BuildImage",
pos: Optional[Tuple[int, int]] = None,
alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
allow_negative: bool = False,
):
"""
说明:
贴图
参数:
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
:param pos: 贴图位置(左上角)
:param alpha: 图片背景是否为透明
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
width, height = 0, 0
if not pos:
pos = (0, 0)
if center_type == "center":
width = int((self.w - img.w) / 2)
height = int((self.h - img.h) / 2)
elif center_type == "by_width":
width = int((self.w - img.w) / 2)
height = pos[1]
elif center_type == "by_height":
width = pos[0]
height = int((self.h - img.h) / 2)
pos = (width, height)
if pos and allow_negative:
if pos[0] < 0:
pos = (self.w + pos[0], pos[1])
if pos[1] < 0:
pos = (pos[0], self.h + pos[1])
if isinstance(img, BuildImage):
img = img.markImg
if self._current_w >= self.w:
self._current_w = 0
self._current_h += self.paste_image_height + self.paste_space
if not pos:
pos = (self._current_w, self._current_h)
if alpha:
try:
self.markImg.paste(img, pos, img)
except ValueError:
img = img.convert("RGBA")
self.markImg.paste(img, pos, img)
else:
self.markImg.paste(img, pos)
self._current_w += self.paste_image_width + self.paste_space
def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
:param font: 字体
:param font_size: 字体大小
"""
font_ = cls.load_font(font, font_size)
return font_.getsize(msg) # type: ignore
def getsize(self, msg: Any) -> Tuple[int, int]:
"""
说明:
获取文字在该图片 font_size 下所需要的空间
参数:
:param msg: 文字内容
"""
return self.font.getsize(str(msg)) # type: ignore
async def apoint(
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
):
"""
说明:
异步 绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
await self.loop.run_in_executor(None, self.point, pos, fill)
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
"""
说明:
绘制多个或单独的像素
参数:
:param pos: 坐标
:param fill: 填错颜色
"""
self.draw.point(pos, fill=fill)
async def aellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
异步 绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
def ellipse(
self,
pos: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[Tuple[int, int, int]] = None,
width: int = 1,
):
"""
说明:
绘制圆
参数:
:param pos: 坐标范围
:param fill: 填充颜色
:param outline: 描线颜色
:param width: 描线宽度
"""
self.draw.ellipse(pos, fill, outline, width)
async def atext(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
异步 在图片上添加文字
参数:
:param pos: 文字位置
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
await self.loop.run_in_executor(
None, self.text, pos, text, fill, center_type, font, font_size, **kwargs
)
def text(
self,
pos: Union[Tuple[int, int], Tuple[float, float]],
text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
font: Optional[Union[FreeTypeFont, str]] = None,
font_size: Optional[int] = None,
**kwargs,
):
"""
说明:
在图片上添加文字
参数:
:param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效)
:param text: 文字内容
:param fill: 文字颜色
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
:param font: 字体
:param font_size: 字体大小
"""
if center_type:
if center_type not in ["center", "by_height", "by_width"]:
raise ValueError(
"center_type must be 'center', 'by_width' or 'by_height'"
)
w, h = self.w, self.h
longgest_text = ""
sentence = text.split("\n")
for x in sentence:
longgest_text = x if len(x) > len(longgest_text) else longgest_text
ttf_w, ttf_h = self.getsize(longgest_text)
ttf_h = ttf_h * len(sentence)
if center_type == "center":
w = int((w - ttf_w) / 2)
h = int((h - ttf_h) / 2)
elif center_type == "by_width":
w = int((w - ttf_w) / 2)
h = pos[1]
elif center_type == "by_height":
h = int((h - ttf_h) / 2)
w = pos[0]
pos = (w, h)
if font:
if isinstance(font, str):
font = self.load_font(font, font_size)
elif font_size:
font = self.load_font(self.font_name, font_size)
self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs)
async def asave(self, path: Optional[Union[str, Path]] = None):
"""
说明:
异步 保存图片
参数:
:param path: 图片路径
"""
await self.loop.run_in_executor(None, self.save, path)
def save(self, path: Optional[Union[str, Path]] = None):
"""
说明:
保存图片
参数:
:param path: 图片路径
"""
self.markImg.save(path or self.background) # type: ignore
def show(self):
"""
说明:
显示图片
"""
self.markImg.show()
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
异步 压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
"""
说明:
压缩图片
参数:
:param ratio: 压缩倍率
:param w: 压缩图片宽度至 w
:param h: 压缩图片高度至 h
"""
if not w and not h and not ratio:
raise Exception("缺少参数...")
if not w and not h and ratio:
w = int(self.w * ratio)
h = int(self.h * ratio)
self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
async def acrop(self, box: Tuple[int, int, int, int]):
"""
说明:
异步 裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
await self.loop.run_in_executor(None, self.crop, box)
def crop(self, box: Tuple[int, int, int, int]):
"""
说明:
裁剪图片
参数:
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
"""
self.markImg = self.markImg.crop(box)
self.w, self.h = self.markImg.size
self.size = self.w, self.h
self.draw = ImageDraw.Draw(self.markImg)
def check_font_size(self, word: str) -> bool:
"""
说明:
检查文本所需宽度是否大于图片宽度
参数:
:param word: 文本内容
"""
return self.font.getsize(word)[0] > self.w
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
异步 图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
def transparent(self, alpha_ratio: float = 1, n: int = 0):
"""
说明:
图片透明化
参数:
:param alpha_ratio: 透明化程度
:param n: 透明化大小内边距
"""
self.markImg = self.markImg.convert("RGBA")
x, y = self.markImg.size
for i in range(n, x - n):
for k in range(n, y - n):
color = self.markImg.getpixel((i, k))
color = color[:-1] + (int(100 * alpha_ratio),)
self.markImg.putpixel((i, k), color)
self.draw = ImageDraw.Draw(self.markImg)
def pic2bs4(self) -> str:
"""
说明:
BuildImage 转 base64
"""
buf = BytesIO()
self.markImg.save(buf, format="PNG")
base64_str = base64.b64encode(buf.getvalue()).decode()
return "base64://" + base64_str
def convert(self, type_: ModeType):
"""
说明:
修改图片类型
参数:
:param type_: 类型
"""
self.markImg = self.markImg.convert(type_)
async def arectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
异步 画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
def rectangle(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None,
outline: Optional[str] = None,
width: int = 1,
):
"""
说明:
画框
参数:
:param xy: 坐标
:param fill: 填充颜色
:param outline: 轮廓颜色
:param width: 线宽
"""
self.draw.rectangle(xy, fill, outline, width)
async def apolygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
异步 画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
def polygon(
self,
xy: List[Tuple[int, int]],
fill: Tuple[int, int, int] = (0, 0, 0),
outline: int = 1,
):
"""
说明:
画多边形
参数:
:param xy: 坐标
:param fill: 颜色
:param outline: 线宽
"""
self.draw.polygon(xy, fill, outline)
async def aline(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[str, Tuple[int, int, int]]] = None,
width: int = 1,
):
"""
说明:
异步 画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
await self.loop.run_in_executor(None, self.line, xy, fill, width)
def line(
self,
xy: Tuple[int, int, int, int],
fill: Optional[Union[Tuple[int, int, int], str]] = None,
width: int = 1,
):
"""
说明:
画线
参数:
:param xy: 坐标
:param fill: 填充
:param width: 线宽
"""
self.draw.line(xy, fill, width)
async def acircle(self):
"""
说明:
异步 将 BuildImage 图片变为圆形
"""
await self.loop.run_in_executor(None, self.circle)
def circle(self):
"""
说明:
使图像变圆
"""
self.markImg.convert("RGBA")
size = self.markImg.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS)
width = 1
antialias = 4
ellipse_box = [0, 0, r2 - 2, r2 - 2]
mask = Image.new(
size=[int(dim * antialias) for dim in self.markImg.size],
mode="L",
color="black",
)
draw = ImageDraw.Draw(mask)
for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"):
left, top = [(value + offset) * antialias for value in ellipse_box[:2]]
right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)
mask = mask.resize(self.markImg.size, Image.LANCZOS)
try:
self.markImg.putalpha(mask)
except ValueError:
pass
async def acircle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
异步 矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
await self.loop.run_in_executor(None, self.circle_corner, radii, point_list)
def circle_corner(
self,
radii: int = 30,
point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"],
):
"""
说明:
矩形四角变圆
参数:
:param radii: 半径
:param point_list: 需要变化的角
"""
# 画圆(用于分离4个角)
img = self.markImg.convert("RGBA")
alpha = img.split()[-1]
circle = Image.new("L", (radii * 2, radii * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形
w, h = img.size
if "lt" in point_list:
alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0))
if "rt" in point_list:
alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0))
if "lb" in point_list:
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
if "rb" in point_list:
alpha.paste(
circle.crop((radii, radii, radii * 2, radii * 2)),
(w - radii, h - radii),
)
img.putalpha(alpha)
self.markImg = img
self.draw = ImageDraw.Draw(self.markImg)
async def arotate(self, angle: int, expand: bool = False):
"""
说明:
异步 旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
await self.loop.run_in_executor(None, self.rotate, angle, expand)
def rotate(self, angle: int, expand: bool = False):
"""
说明:
旋转图片
参数:
:param angle: 角度
:param expand: 放大图片适应角度
"""
self.markImg = self.markImg.rotate(angle, expand=expand)
async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
异步 旋转图片(包括边框)
参数:
:param angle: 角度
"""
await self.loop.run_in_executor(None, self.transpose, angle)
def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]):
"""
说明:
旋转图片(包括边框)
参数:
:param angle: 角度
"""
self.markImg.transpose(angle)
async def afilter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
异步 图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
await self.loop.run_in_executor(None, self.filter, filter_, aud)
def filter(self, filter_: str, aud: Optional[int] = None):
"""
说明:
图片变化
参数:
:param filter_: 变化效果
:param aud: 利率
"""
_x = None
if filter_ == "GaussianBlur": # 高斯模糊
_x = ImageFilter.GaussianBlur
elif filter_ == "EDGE_ENHANCE": # 锐化效果
_x = ImageFilter.EDGE_ENHANCE
elif filter_ == "BLUR": # 模糊效果
_x = ImageFilter.BLUR
elif filter_ == "CONTOUR": # 铅笔滤镜
_x = ImageFilter.CONTOUR
elif filter_ == "FIND_EDGES": # 边缘检测
_x = ImageFilter.FIND_EDGES
if _x:
if aud:
self.markImg = self.markImg.filter(_x(aud))
else:
self.markImg = self.markImg.filter(_x)
self.draw = ImageDraw.Draw(self.markImg)
async def areplace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
异步 颜色替换
参数:
:param src_color: 目标颜色,或者使用列表,设置阈值
:param replace_color: 替换颜色
"""
self.loop.run_in_executor(
None, self.replace_color_tran, src_color, replace_color
)
def replace_color_tran(
self,
src_color: Union[
Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]]
],
replace_color: Tuple[int, int, int],
):
"""
说明:
颜色替换
参数:
:param src_color: 目标颜色,或者使用元祖,设置阈值
:param replace_color: 替换颜色
"""
if isinstance(src_color, tuple):
start_ = src_color[0]
end_ = src_color[1]
else:
start_ = src_color
end_ = None
for i in range(self.w):
for j in range(self.h):
r, g, b = self.markImg.getpixel((i, j))
if not end_:
if r == start_[0] and g == start_[1] and b == start_[2]:
self.markImg.putpixel((i, j), replace_color)
else:
if (
start_[0] <= r <= end_[0]
and start_[1] <= g <= end_[1]
and start_[2] <= b <= end_[2]
):
self.markImg.putpixel((i, j), replace_color)
#
def getchannel(self, type_):
self.markImg = self.markImg.getchannel(type_)
The provided code snippet includes necessary dependencies for implementing the `_create_live_des_image` function. Write a Python function `def _create_live_des_image( title: str, cover: BuildImage, tags: str, des: str, user_name: str, sex: str, sign: str, ava: BuildImage, )` to solve the following problem:
生成主播简介图片 :param title: 直播间标题 :param cover: 直播封面 :param tags: 直播标签 :param des: 直播简介 :param user_name: 主播名称 :param sex: 主播性别 :param sign: 主播签名 :param ava: 主播头像 :return:
Here is the function:
def _create_live_des_image(
title: str,
cover: BuildImage,
tags: str,
des: str,
user_name: str,
sex: str,
sign: str,
ava: BuildImage,
):
"""
生成主播简介图片
:param title: 直播间标题
:param cover: 直播封面
:param tags: 直播标签
:param des: 直播简介
:param user_name: 主播名称
:param sex: 主播性别
:param sign: 主播签名
:param ava: 主播头像
:return:
"""
border = BORDER_PATH / "0.png"
border_img = None
if border.exists():
border_img = BuildImage(1772, 2657, background=border)
bk = BuildImage(1772, 2657, font_size=30)
bk.paste(cover, (0, 100), center_type="by_width") | 生成主播简介图片 :param title: 直播间标题 :param cover: 直播封面 :param tags: 直播标签 :param des: 直播简介 :param user_name: 主播名称 :param sex: 主播性别 :param sign: 主播签名 :param ava: 主播头像 :return: |
188,227 | from io import BytesIO
from bilireq.user import get_user_info
from httpx import AsyncClient
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncHttpx, get_user_agent
from utils.image_utils import BuildImage
BASE_URL = "https://api.bilibili.com"
The provided code snippet includes necessary dependencies for implementing the `get_videos` function. Write a Python function `async def get_videos( uid: int, tid: int = 0, pn: int = 1, keyword: str = "", order: str = "pubdate" )` to solve the following problem:
获取用户投该视频信息 作为bilibili_api和bilireq的替代品。 如果bilireq.user更新了,可以转为调用bilireq.user的get_videos方法,两者完全一致。 :param uid: 用户 UID :param tid: 分区 ID :param pn: 页码 :param keyword: 搜索关键词 :param order: 排序方式,可以为 “pubdate(上传日期从新到旧), stow(收藏从多到少), click(播放量从多到少)”
Here is the function:
async def get_videos(
uid: int, tid: int = 0, pn: int = 1, keyword: str = "", order: str = "pubdate"
):
"""
获取用户投该视频信息
作为bilibili_api和bilireq的替代品。
如果bilireq.user更新了,可以转为调用bilireq.user的get_videos方法,两者完全一致。
:param uid: 用户 UID
:param tid: 分区 ID
:param pn: 页码
:param keyword: 搜索关键词
:param order: 排序方式,可以为 “pubdate(上传日期从新到旧), stow(收藏从多到少), click(播放量从多到少)”
"""
from bilireq.utils import ResponseCodeError
url = f"{BASE_URL}/x/space/arc/search"
headers = get_user_agent()
headers["Referer"] = f"https://space.bilibili.com/{uid}/video"
async with AsyncClient() as client:
r = await client.head(
"https://space.bilibili.com",
headers=headers,
)
params = {
"mid": uid,
"ps": 30,
"tid": tid,
"pn": pn,
"keyword": keyword,
"order": order,
}
raw_json = (
await client.get(url, params=params, headers=headers, cookies=r.cookies)
).json()
if raw_json["code"] != 0:
raise ResponseCodeError(
code=raw_json["code"],
msg=raw_json["message"],
data=raw_json.get("data", None),
)
return raw_json["data"] | 获取用户投该视频信息 作为bilibili_api和bilireq的替代品。 如果bilireq.user更新了,可以转为调用bilireq.user的get_videos方法,两者完全一致。 :param uid: 用户 UID :param tid: 分区 ID :param pn: 页码 :param keyword: 搜索关键词 :param order: 排序方式,可以为 “pubdate(上传日期从新到旧), stow(收藏从多到少), click(播放量从多到少)” |
188,228 | import random
from asyncio.exceptions import TimeoutError
from datetime import datetime
from typing import Optional, Tuple, Union
from bilireq import dynamic
from bilireq.exceptions import ResponseCodeError
from bilireq.grpc.dynamic import grpc_get_user_dynamics
from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType
from bilireq.live import get_room_info_by_id
from bilireq.user import get_videos
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.browser import get_browser
from utils.http_utils import AsyncHttpx, AsyncPlaywright
from utils.manager import resources_manager
from utils.message_builder import image
from utils.utils import get_bot, get_local_proxy
from .model import BilibiliSub
from .utils import get_meta, get_user_card
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class BilibiliSub(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
sub_id = fields.CharField(255)
"""订阅id"""
sub_type = fields.CharField(255)
"""订阅类型"""
sub_users = fields.TextField()
"""订阅用户"""
live_short_id = fields.CharField(255, null=True)
"""直播短id"""
live_status = fields.IntField(null=True)
"""直播状态 0: 停播 1: 直播"""
uid = fields.CharField(255, null=True)
"""主播/UP UID"""
uname = fields.CharField(255, null=True)
"""主播/UP 名称"""
latest_video_created = fields.BigIntField(null=True)
"""最后视频上传时间"""
dynamic_upload_time = fields.BigIntField(null=True, default=0)
"""动态发布时间"""
season_name = fields.CharField(255, null=True)
"""番剧名称"""
season_id = fields.IntField(null=True)
"""番剧id"""
season_current_episode = fields.CharField(255, null=True)
"""番剧最新集数"""
season_update_time = fields.DateField(null=True)
"""番剧更新日期"""
class Meta:
table = "bilibili_sub"
table_description = "B站订阅数据表"
unique_together = ("sub_id", "sub_type")
async def sub_handle(
cls,
sub_id: str,
sub_type: Optional[str] = None,
sub_user: str = "",
*,
live_short_id: Optional[str] = None,
live_status: Optional[int] = None,
dynamic_upload_time: int = 0,
uid: Optional[str] = None,
uname: Optional[str] = None,
latest_video_created: Optional[int] = None,
season_name: Optional[str] = None,
season_id: Optional[int] = None,
season_current_episode: Optional[str] = None,
season_update_time: Optional[datetime] = None,
) -> bool:
"""
说明:
添加订阅
参数:
:param sub_id: 订阅名称,房间号,番剧号等
:param sub_type: 订阅类型
:param sub_user: 订阅此条目的用户
:param live_short_id: 直接短 id
:param live_status: 主播开播状态
:param dynamic_upload_time: 主播/UP最新动态时间
:param uid: 主播/UP uid
:param uname: 用户名称
:param latest_video_created: 最新视频上传时间
:param season_name: 番剧名称
:param season_id: 番剧 season_id
:param season_current_episode: 番剧最新集数
:param season_update_time: 番剧更新时间
"""
sub_id = str(sub_id)
try:
data = {
"sub_type": sub_type,
"sub_user": sub_user,
"live_short_id": live_short_id,
"live_status": live_status,
"dynamic_upload_time": dynamic_upload_time,
"uid": uid,
"uname": uname,
"latest_video_created": latest_video_created,
"season_name": season_name,
"season_id": season_id,
"season_current_episode": season_current_episode,
"season_update_time": season_update_time,
}
if sub_user:
sub_user = sub_user if sub_user[-1] == "," else f"{sub_user},"
sub = None
if sub_type:
sub = await cls.get_or_none(sub_id=sub_id, sub_type=sub_type)
else:
sub = await cls.get_or_none(sub_id=sub_id)
if sub:
sub_users = sub.sub_users + sub_user
data["sub_type"] = sub_type or sub.sub_type
data["sub_users"] = sub_users
data["live_short_id"] = live_short_id or sub.live_short_id
data["live_status"] = (
live_status if live_status is not None else sub.live_status
)
data["dynamic_upload_time"] = (
dynamic_upload_time or sub.dynamic_upload_time
)
data["uid"] = uid or sub.uid
data["uname"] = uname or sub.uname
data["latest_video_created"] = (
latest_video_created or sub.latest_video_created
)
data["season_name"] = season_name or sub.season_name
data["season_id"] = season_id or sub.season_id
data["season_current_episode"] = (
season_current_episode or sub.season_current_episode
)
data["season_update_time"] = (
season_update_time or sub.season_update_time
)
else:
await cls.create(sub_id=sub_id, sub_type=sub_type, sub_users=sub_user)
await cls.update_or_create(sub_id=sub_id, defaults=data)
return True
except Exception as e:
logger.error(f"添加订阅 Id: {sub_id} 错误", e=e)
return False
async def delete_bilibili_sub(
cls, sub_id: str, sub_user: str, sub_type: Optional[str] = None
) -> bool:
"""
说明:
删除订阅
参数:
:param sub_id: 订阅名称
:param sub_user: 删除此条目的用户
"""
try:
group_id = None
contains_str = sub_user
if ":" in sub_user:
group_id = sub_user.split(":")[1]
contains_str = f":{group_id}"
if sub_type:
sub = await cls.get_or_none(
sub_id=sub_id, sub_type=sub_type, sub_users__contains=contains_str
)
else:
sub = await cls.get_or_none(
sub_id=sub_id, sub_users__contains=contains_str
)
if not sub:
return False
if group_id:
sub.sub_users = ",".join(
[s for s in sub.sub_users.split(",") if f":{group_id}" not in s]
)
else:
sub.sub_users = sub.sub_users.replace(f"{sub_user},", "")
if sub.sub_users.strip():
await sub.save(update_fields=["sub_users"])
else:
await sub.delete()
return True
except Exception as e:
logger.error(f"bilibili_sub 删除订阅错误", target=sub_id, e=e)
return False
async def get_all_sub_data(
cls,
) -> Tuple[List["BilibiliSub"], List["BilibiliSub"], List["BilibiliSub"]]:
"""
说明:
分类获取所有数据
"""
live_data = []
up_data = []
season_data = []
query = await cls.all()
for x in query:
if x.sub_type == "live":
live_data.append(x)
if x.sub_type == "up":
up_data.append(x)
if x.sub_type == "season":
season_data.append(x)
return live_data, up_data, season_data
def _run_script(cls):
return [
"ALTER TABLE bilibili_sub ALTER COLUMN season_update_time TYPE timestamp with time zone USING season_update_time::timestamp with time zone;",
"alter table bilibili_sub alter COLUMN sub_id type varchar(255);", # 将sub_id字段改为字符串
"alter table bilibili_sub alter COLUMN live_short_id type varchar(255);", # 将live_short_id字段改为字符串
"alter table bilibili_sub alter COLUMN uid type varchar(255);", # 将live_short_id字段改为字符串
]
async def get_user_card(
mid: str, photo: bool = False, auth=None, reqtype="both", **kwargs
):
from bilireq.utils import get
url = f"{BASE_URL}/x/web-interface/card"
return (
await get(
url,
params={"mid": mid, "photo": photo},
auth=auth,
reqtype=reqtype,
**kwargs,
)
)["card"]
The provided code snippet includes necessary dependencies for implementing the `add_live_sub` function. Write a Python function `async def add_live_sub(live_id: str, sub_user: str) -> str` to solve the following problem:
添加直播订阅 :param live_id: 直播房间号 :param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group) :return:
Here is the function:
async def add_live_sub(live_id: str, sub_user: str) -> str:
"""
添加直播订阅
:param live_id: 直播房间号
:param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group)
:return:
"""
try:
if await BilibiliSub.exists(
sub_type="live", sub_id=live_id, sub_users__contains=sub_user + ","
):
return "该订阅Id已存在..."
try:
"""bilibili_api.live库的LiveRoom类中get_room_info改为bilireq.live库的get_room_info_by_id方法"""
live_info = await get_room_info_by_id(live_id)
except ResponseCodeError:
return f"未找到房间号Id:{live_id} 的信息,请检查Id是否正确"
uid = str(live_info["uid"])
room_id = live_info["room_id"]
short_id = live_info["short_id"]
title = live_info["title"]
live_status = live_info["live_status"]
try:
user_info = await get_user_card(uid)
except ResponseCodeError:
return f"未找到UpId:{uid} 的信息,请检查Id是否正确"
uname = user_info["name"]
dynamic_info = await dynamic.get_user_dynamics(int(uid))
dynamic_upload_time = 0
if dynamic_info.get("cards"):
dynamic_upload_time = dynamic_info["cards"][0]["desc"]["dynamic_id"]
if await BilibiliSub.sub_handle(
room_id,
"live",
sub_user,
uid=uid,
live_short_id=short_id,
live_status=live_status,
uname=uname,
dynamic_upload_time=dynamic_upload_time,
):
if data := await BilibiliSub.get_or_none(sub_id=room_id):
uname = data.uname
return (
"已成功订阅主播:\n"
f"\ttitle:{title}\n"
f"\tname: {uname}\n"
f"\tlive_id:{room_id}\n"
f"\tuid:{uid}"
)
return "添加订阅失败..."
except Exception as e:
logger.error(f"订阅主播live_id: {live_id} 错误", e=e)
return "添加订阅失败..." | 添加直播订阅 :param live_id: 直播房间号 :param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group) :return: |
188,229 | import random
from asyncio.exceptions import TimeoutError
from datetime import datetime
from typing import Optional, Tuple, Union
from bilireq import dynamic
from bilireq.exceptions import ResponseCodeError
from bilireq.grpc.dynamic import grpc_get_user_dynamics
from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType
from bilireq.live import get_room_info_by_id
from bilireq.user import get_videos
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.browser import get_browser
from utils.http_utils import AsyncHttpx, AsyncPlaywright
from utils.manager import resources_manager
from utils.message_builder import image
from utils.utils import get_bot, get_local_proxy
from .model import BilibiliSub
from .utils import get_meta, get_user_card
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class BilibiliSub(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
sub_id = fields.CharField(255)
"""订阅id"""
sub_type = fields.CharField(255)
"""订阅类型"""
sub_users = fields.TextField()
"""订阅用户"""
live_short_id = fields.CharField(255, null=True)
"""直播短id"""
live_status = fields.IntField(null=True)
"""直播状态 0: 停播 1: 直播"""
uid = fields.CharField(255, null=True)
"""主播/UP UID"""
uname = fields.CharField(255, null=True)
"""主播/UP 名称"""
latest_video_created = fields.BigIntField(null=True)
"""最后视频上传时间"""
dynamic_upload_time = fields.BigIntField(null=True, default=0)
"""动态发布时间"""
season_name = fields.CharField(255, null=True)
"""番剧名称"""
season_id = fields.IntField(null=True)
"""番剧id"""
season_current_episode = fields.CharField(255, null=True)
"""番剧最新集数"""
season_update_time = fields.DateField(null=True)
"""番剧更新日期"""
class Meta:
table = "bilibili_sub"
table_description = "B站订阅数据表"
unique_together = ("sub_id", "sub_type")
async def sub_handle(
cls,
sub_id: str,
sub_type: Optional[str] = None,
sub_user: str = "",
*,
live_short_id: Optional[str] = None,
live_status: Optional[int] = None,
dynamic_upload_time: int = 0,
uid: Optional[str] = None,
uname: Optional[str] = None,
latest_video_created: Optional[int] = None,
season_name: Optional[str] = None,
season_id: Optional[int] = None,
season_current_episode: Optional[str] = None,
season_update_time: Optional[datetime] = None,
) -> bool:
"""
说明:
添加订阅
参数:
:param sub_id: 订阅名称,房间号,番剧号等
:param sub_type: 订阅类型
:param sub_user: 订阅此条目的用户
:param live_short_id: 直接短 id
:param live_status: 主播开播状态
:param dynamic_upload_time: 主播/UP最新动态时间
:param uid: 主播/UP uid
:param uname: 用户名称
:param latest_video_created: 最新视频上传时间
:param season_name: 番剧名称
:param season_id: 番剧 season_id
:param season_current_episode: 番剧最新集数
:param season_update_time: 番剧更新时间
"""
sub_id = str(sub_id)
try:
data = {
"sub_type": sub_type,
"sub_user": sub_user,
"live_short_id": live_short_id,
"live_status": live_status,
"dynamic_upload_time": dynamic_upload_time,
"uid": uid,
"uname": uname,
"latest_video_created": latest_video_created,
"season_name": season_name,
"season_id": season_id,
"season_current_episode": season_current_episode,
"season_update_time": season_update_time,
}
if sub_user:
sub_user = sub_user if sub_user[-1] == "," else f"{sub_user},"
sub = None
if sub_type:
sub = await cls.get_or_none(sub_id=sub_id, sub_type=sub_type)
else:
sub = await cls.get_or_none(sub_id=sub_id)
if sub:
sub_users = sub.sub_users + sub_user
data["sub_type"] = sub_type or sub.sub_type
data["sub_users"] = sub_users
data["live_short_id"] = live_short_id or sub.live_short_id
data["live_status"] = (
live_status if live_status is not None else sub.live_status
)
data["dynamic_upload_time"] = (
dynamic_upload_time or sub.dynamic_upload_time
)
data["uid"] = uid or sub.uid
data["uname"] = uname or sub.uname
data["latest_video_created"] = (
latest_video_created or sub.latest_video_created
)
data["season_name"] = season_name or sub.season_name
data["season_id"] = season_id or sub.season_id
data["season_current_episode"] = (
season_current_episode or sub.season_current_episode
)
data["season_update_time"] = (
season_update_time or sub.season_update_time
)
else:
await cls.create(sub_id=sub_id, sub_type=sub_type, sub_users=sub_user)
await cls.update_or_create(sub_id=sub_id, defaults=data)
return True
except Exception as e:
logger.error(f"添加订阅 Id: {sub_id} 错误", e=e)
return False
async def delete_bilibili_sub(
cls, sub_id: str, sub_user: str, sub_type: Optional[str] = None
) -> bool:
"""
说明:
删除订阅
参数:
:param sub_id: 订阅名称
:param sub_user: 删除此条目的用户
"""
try:
group_id = None
contains_str = sub_user
if ":" in sub_user:
group_id = sub_user.split(":")[1]
contains_str = f":{group_id}"
if sub_type:
sub = await cls.get_or_none(
sub_id=sub_id, sub_type=sub_type, sub_users__contains=contains_str
)
else:
sub = await cls.get_or_none(
sub_id=sub_id, sub_users__contains=contains_str
)
if not sub:
return False
if group_id:
sub.sub_users = ",".join(
[s for s in sub.sub_users.split(",") if f":{group_id}" not in s]
)
else:
sub.sub_users = sub.sub_users.replace(f"{sub_user},", "")
if sub.sub_users.strip():
await sub.save(update_fields=["sub_users"])
else:
await sub.delete()
return True
except Exception as e:
logger.error(f"bilibili_sub 删除订阅错误", target=sub_id, e=e)
return False
async def get_all_sub_data(
cls,
) -> Tuple[List["BilibiliSub"], List["BilibiliSub"], List["BilibiliSub"]]:
"""
说明:
分类获取所有数据
"""
live_data = []
up_data = []
season_data = []
query = await cls.all()
for x in query:
if x.sub_type == "live":
live_data.append(x)
if x.sub_type == "up":
up_data.append(x)
if x.sub_type == "season":
season_data.append(x)
return live_data, up_data, season_data
def _run_script(cls):
return [
"ALTER TABLE bilibili_sub ALTER COLUMN season_update_time TYPE timestamp with time zone USING season_update_time::timestamp with time zone;",
"alter table bilibili_sub alter COLUMN sub_id type varchar(255);", # 将sub_id字段改为字符串
"alter table bilibili_sub alter COLUMN live_short_id type varchar(255);", # 将live_short_id字段改为字符串
"alter table bilibili_sub alter COLUMN uid type varchar(255);", # 将live_short_id字段改为字符串
]
async def get_user_card(
mid: str, photo: bool = False, auth=None, reqtype="both", **kwargs
):
from bilireq.utils import get
url = f"{BASE_URL}/x/web-interface/card"
return (
await get(
url,
params={"mid": mid, "photo": photo},
auth=auth,
reqtype=reqtype,
**kwargs,
)
)["card"]
The provided code snippet includes necessary dependencies for implementing the `add_up_sub` function. Write a Python function `async def add_up_sub(uid: str, sub_user: str) -> str` to solve the following problem:
添加订阅 UP :param uid: UP uid :param sub_user: 订阅用户
Here is the function:
async def add_up_sub(uid: str, sub_user: str) -> str:
"""
添加订阅 UP
:param uid: UP uid
:param sub_user: 订阅用户
"""
uname = uid
dynamic_upload_time = 0
latest_video_created = 0
try:
if await BilibiliSub.exists(
sub_type="up", sub_id=uid, sub_users__contains=sub_user + ","
):
return "该订阅Id已存在..."
try:
"""bilibili_api.user库中User类的get_user_info改为bilireq.user库的get_user_info方法"""
user_info = await get_user_card(uid)
except ResponseCodeError:
return f"未找到UpId:{uid} 的信息,请检查Id是否正确"
uname = user_info["name"]
"""bilibili_api.user库中User类的get_dynamics改为bilireq.dynamic库的get_user_dynamics方法"""
dynamic_info = await dynamic.get_user_dynamics(int(uid))
if dynamic_info.get("cards"):
dynamic_upload_time = dynamic_info["cards"][0]["desc"]["dynamic_id"]
except Exception as e:
logger.error(f"订阅Up uid: {uid} 错误", e=e)
if await BilibiliSub.sub_handle(
uid,
"up",
sub_user,
uid=uid,
uname=uname,
dynamic_upload_time=dynamic_upload_time,
latest_video_created=latest_video_created,
):
return "已成功订阅UP:\n" f"\tname: {uname}\n" f"\tuid:{uid}"
else:
return "添加订阅失败..." | 添加订阅 UP :param uid: UP uid :param sub_user: 订阅用户 |
188,230 | import random
from asyncio.exceptions import TimeoutError
from datetime import datetime
from typing import Optional, Tuple, Union
from bilireq import dynamic
from bilireq.exceptions import ResponseCodeError
from bilireq.grpc.dynamic import grpc_get_user_dynamics
from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType
from bilireq.live import get_room_info_by_id
from bilireq.user import get_videos
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from configs.config import Config
from configs.path_config import IMAGE_PATH, TEMP_PATH
from services.log import logger
from utils.browser import get_browser
from utils.http_utils import AsyncHttpx, AsyncPlaywright
from utils.manager import resources_manager
from utils.message_builder import image
from utils.utils import get_bot, get_local_proxy
from .model import BilibiliSub
from .utils import get_meta, get_user_card
class logger:
TEMPLATE_A = "{}"
TEMPLATE_B = "[<u><c>{}</c></u>]: {}"
TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
TEMPLATE_USER = "用户[<u><e>{}</e></u>] "
TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] "
TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] "
TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) "
SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]"
WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}"
ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}"
def info(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
logger_.opt(colors=True).info(template)
def success(
cls,
info: str,
command: str,
param: Optional[Dict[str, Any]] = None,
result: Optional[str] = "",
):
param_str = ""
if param:
param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()])
logger_.opt(colors=True).success(
cls.SUCCESS_TEMPLATE.format(command, info, param_str, result)
)
def warning(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误<r>{type(e)}: {e}</r>"
logger_.opt(colors=True).warning(template)
def error(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).error(template)
def debug(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
e: Optional[Exception] = None,
):
template = cls.__parser_template(info, command, user_id, group_id, target)
if e:
template += f" || 错误 <r>{type(e)}: {e}</r>"
logger_.opt(colors=True).debug(template)
def __parser_template(
cls,
info: str,
command: Optional[str] = None,
user_id: Optional[Union[int, str]] = None,
group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None,
) -> str:
arg_list = []
template = ""
if group_id is not None:
template += cls.TEMPLATE_GROUP
arg_list.append(group_id)
if user_id is not None:
template += cls.TEMPLATE_USER
arg_list.append(user_id)
if command is not None:
template += cls.TEMPLATE_COMMAND
arg_list.append(command)
if target is not None:
template += cls.TEMPLATE_TARGET
arg_list.append(target)
arg_list.append(info)
template += "{}"
return template.format(*arg_list)
class BilibiliSub(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
"""自增id"""
sub_id = fields.CharField(255)
"""订阅id"""
sub_type = fields.CharField(255)
"""订阅类型"""
sub_users = fields.TextField()
"""订阅用户"""
live_short_id = fields.CharField(255, null=True)
"""直播短id"""
live_status = fields.IntField(null=True)
"""直播状态 0: 停播 1: 直播"""
uid = fields.CharField(255, null=True)
"""主播/UP UID"""
uname = fields.CharField(255, null=True)
"""主播/UP 名称"""
latest_video_created = fields.BigIntField(null=True)
"""最后视频上传时间"""
dynamic_upload_time = fields.BigIntField(null=True, default=0)
"""动态发布时间"""
season_name = fields.CharField(255, null=True)
"""番剧名称"""
season_id = fields.IntField(null=True)
"""番剧id"""
season_current_episode = fields.CharField(255, null=True)
"""番剧最新集数"""
season_update_time = fields.DateField(null=True)
"""番剧更新日期"""
class Meta:
table = "bilibili_sub"
table_description = "B站订阅数据表"
unique_together = ("sub_id", "sub_type")
async def sub_handle(
cls,
sub_id: str,
sub_type: Optional[str] = None,
sub_user: str = "",
*,
live_short_id: Optional[str] = None,
live_status: Optional[int] = None,
dynamic_upload_time: int = 0,
uid: Optional[str] = None,
uname: Optional[str] = None,
latest_video_created: Optional[int] = None,
season_name: Optional[str] = None,
season_id: Optional[int] = None,
season_current_episode: Optional[str] = None,
season_update_time: Optional[datetime] = None,
) -> bool:
"""
说明:
添加订阅
参数:
:param sub_id: 订阅名称,房间号,番剧号等
:param sub_type: 订阅类型
:param sub_user: 订阅此条目的用户
:param live_short_id: 直接短 id
:param live_status: 主播开播状态
:param dynamic_upload_time: 主播/UP最新动态时间
:param uid: 主播/UP uid
:param uname: 用户名称
:param latest_video_created: 最新视频上传时间
:param season_name: 番剧名称
:param season_id: 番剧 season_id
:param season_current_episode: 番剧最新集数
:param season_update_time: 番剧更新时间
"""
sub_id = str(sub_id)
try:
data = {
"sub_type": sub_type,
"sub_user": sub_user,
"live_short_id": live_short_id,
"live_status": live_status,
"dynamic_upload_time": dynamic_upload_time,
"uid": uid,
"uname": uname,
"latest_video_created": latest_video_created,
"season_name": season_name,
"season_id": season_id,
"season_current_episode": season_current_episode,
"season_update_time": season_update_time,
}
if sub_user:
sub_user = sub_user if sub_user[-1] == "," else f"{sub_user},"
sub = None
if sub_type:
sub = await cls.get_or_none(sub_id=sub_id, sub_type=sub_type)
else:
sub = await cls.get_or_none(sub_id=sub_id)
if sub:
sub_users = sub.sub_users + sub_user
data["sub_type"] = sub_type or sub.sub_type
data["sub_users"] = sub_users
data["live_short_id"] = live_short_id or sub.live_short_id
data["live_status"] = (
live_status if live_status is not None else sub.live_status
)
data["dynamic_upload_time"] = (
dynamic_upload_time or sub.dynamic_upload_time
)
data["uid"] = uid or sub.uid
data["uname"] = uname or sub.uname
data["latest_video_created"] = (
latest_video_created or sub.latest_video_created
)
data["season_name"] = season_name or sub.season_name
data["season_id"] = season_id or sub.season_id
data["season_current_episode"] = (
season_current_episode or sub.season_current_episode
)
data["season_update_time"] = (
season_update_time or sub.season_update_time
)
else:
await cls.create(sub_id=sub_id, sub_type=sub_type, sub_users=sub_user)
await cls.update_or_create(sub_id=sub_id, defaults=data)
return True
except Exception as e:
logger.error(f"添加订阅 Id: {sub_id} 错误", e=e)
return False
async def delete_bilibili_sub(
cls, sub_id: str, sub_user: str, sub_type: Optional[str] = None
) -> bool:
"""
说明:
删除订阅
参数:
:param sub_id: 订阅名称
:param sub_user: 删除此条目的用户
"""
try:
group_id = None
contains_str = sub_user
if ":" in sub_user:
group_id = sub_user.split(":")[1]
contains_str = f":{group_id}"
if sub_type:
sub = await cls.get_or_none(
sub_id=sub_id, sub_type=sub_type, sub_users__contains=contains_str
)
else:
sub = await cls.get_or_none(
sub_id=sub_id, sub_users__contains=contains_str
)
if not sub:
return False
if group_id:
sub.sub_users = ",".join(
[s for s in sub.sub_users.split(",") if f":{group_id}" not in s]
)
else:
sub.sub_users = sub.sub_users.replace(f"{sub_user},", "")
if sub.sub_users.strip():
await sub.save(update_fields=["sub_users"])
else:
await sub.delete()
return True
except Exception as e:
logger.error(f"bilibili_sub 删除订阅错误", target=sub_id, e=e)
return False
async def get_all_sub_data(
cls,
) -> Tuple[List["BilibiliSub"], List["BilibiliSub"], List["BilibiliSub"]]:
"""
说明:
分类获取所有数据
"""
live_data = []
up_data = []
season_data = []
query = await cls.all()
for x in query:
if x.sub_type == "live":
live_data.append(x)
if x.sub_type == "up":
up_data.append(x)
if x.sub_type == "season":
season_data.append(x)
return live_data, up_data, season_data
def _run_script(cls):
return [
"ALTER TABLE bilibili_sub ALTER COLUMN season_update_time TYPE timestamp with time zone USING season_update_time::timestamp with time zone;",
"alter table bilibili_sub alter COLUMN sub_id type varchar(255);", # 将sub_id字段改为字符串
"alter table bilibili_sub alter COLUMN live_short_id type varchar(255);", # 将live_short_id字段改为字符串
"alter table bilibili_sub alter COLUMN uid type varchar(255);", # 将live_short_id字段改为字符串
]
async def get_meta(media_id: str, auth=None, reqtype="both", **kwargs):
"""
根据番剧 ID 获取番剧元数据信息,
作为bilibili_api和bilireq的替代品。
如果bilireq.bangumi更新了,可以转为调用bilireq.bangumi的get_meta方法,两者完全一致。
"""
from bilireq.utils import get
url = f"{BASE_URL}/pgc/review/user"
params = {"media_id": media_id}
raw_json = await get(
url, raw=True, params=params, auth=auth, reqtype=reqtype, **kwargs
)
return raw_json["result"]
The provided code snippet includes necessary dependencies for implementing the `add_season_sub` function. Write a Python function `async def add_season_sub(media_id: str, sub_user: str) -> str` to solve the following problem:
添加订阅 UP :param media_id: 番剧 media_id :param sub_user: 订阅用户
Here is the function:
async def add_season_sub(media_id: str, sub_user: str) -> str:
"""
添加订阅 UP
:param media_id: 番剧 media_id
:param sub_user: 订阅用户
"""
try:
if await BilibiliSub.exists(
sub_type="season", sub_id=media_id, sub_users__contains=sub_user + ","
):
return "该订阅Id已存在..."
try:
"""bilibili_api.bangumi库中get_meta改为bilireq.bangumi库的get_meta方法"""
season_info = await get_meta(media_id)
except ResponseCodeError:
return f"未找到media_id:{media_id} 的信息,请检查Id是否正确"
season_id = season_info["media"]["season_id"]
season_current_episode = season_info["media"]["new_ep"]["index"]
season_name = season_info["media"]["title"]
if await BilibiliSub.sub_handle(
media_id,
"season",
sub_user,
season_name=season_name,
season_id=season_id,
season_current_episode=season_current_episode,
):
return (
"已成功订阅番剧:\n"
f"\ttitle: {season_name}\n"
f"\tcurrent_episode: {season_current_episode}"
)
else:
return "添加订阅失败..."
except Exception as e:
logger.error(f"订阅番剧 media_id: {media_id} 错误", e=e)
return "添加订阅失败..." | 添加订阅 UP :param media_id: 番剧 media_id :param sub_user: 订阅用户 |