mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-12 23:40:03 +08:00
init🎉: 首次提交
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
from .db_context import *
|
||||
from .log import *
|
||||
@@ -0,0 +1,90 @@
|
||||
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 zhenxun.configs.config import (
|
||||
address,
|
||||
bind,
|
||||
database,
|
||||
password,
|
||||
port,
|
||||
sql_name,
|
||||
user,
|
||||
)
|
||||
|
||||
from .log import logger
|
||||
|
||||
MODELS: List[str] = []
|
||||
|
||||
SCRIPT_METHOD = []
|
||||
|
||||
|
||||
class Model(Model_):
|
||||
"""
|
||||
自动添加模块
|
||||
|
||||
Args:
|
||||
Model_ (_type_): _description_
|
||||
"""
|
||||
|
||||
def __init_subclass__(cls, **kwargs):
|
||||
MODELS.append(cls.__module__)
|
||||
|
||||
if func := getattr(cls, "_run_script", None):
|
||||
SCRIPT_METHOD.append((cls.__module__, func))
|
||||
|
||||
|
||||
class TestSQL(Model):
|
||||
id = fields.IntField(pk=True, generated=True, auto_increment=True)
|
||||
"""自增id"""
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
table = "test_sql"
|
||||
table_description = "执行SQL命令,不记录任何数据"
|
||||
|
||||
|
||||
async def init():
|
||||
if not bind and not any([user, password, address, port, database]):
|
||||
raise ValueError("\n数据库配置未填写.......")
|
||||
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)
|
||||
|
||||
|
||||
async def disconnect():
|
||||
await connections.close_all()
|
||||
@@ -0,0 +1,307 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, overload
|
||||
|
||||
from nonebot import require
|
||||
|
||||
require("nonebot_plugin_session")
|
||||
from loguru import logger as logger_
|
||||
from nonebot.log import default_filter, default_format
|
||||
from nonebot_plugin_session import Session
|
||||
|
||||
from zhenxun.configs.path_config import LOG_PATH
|
||||
|
||||
logger_.add(
|
||||
LOG_PATH / f"{datetime.now().date()}.log",
|
||||
level="INFO",
|
||||
rotation="00:00",
|
||||
format=default_format,
|
||||
filter=default_filter,
|
||||
retention=timedelta(days=30),
|
||||
)
|
||||
|
||||
logger_.add(
|
||||
LOG_PATH / f"error_{datetime.now().date()}.log",
|
||||
level="ERROR",
|
||||
rotation="00:00",
|
||||
format=default_format,
|
||||
filter=default_filter,
|
||||
retention=timedelta(days=30),
|
||||
)
|
||||
|
||||
|
||||
class logger:
|
||||
TEMPLATE_A = "Adapter[{}] {}"
|
||||
TEMPLATE_B = "Adapter[{}] [<u><c>{}</c></u>]: {}"
|
||||
TEMPLATE_C = "Adapter[{}] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
|
||||
TEMPLATE_D = "Adapter[{}] 群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}"
|
||||
TEMPLATE_E = "Adapter[{}] 群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}"
|
||||
|
||||
TEMPLATE_ADAPTER = "Adapter[<m>{}</m>] "
|
||||
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>]: {}"
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def info(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
):
|
||||
...
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def info(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
target: Any = None,
|
||||
):
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def info(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | Session | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
):
|
||||
user_id: str | None = session # type: ignore
|
||||
group_id = None
|
||||
if type(session) == Session:
|
||||
user_id = session.id1
|
||||
adapter = session.bot_type
|
||||
if session.id3 or session.id2:
|
||||
group_id = f"{session.id3}:{session.id2}"
|
||||
template = cls.__parser_template(
|
||||
info, command, user_id, group_id, adapter, target
|
||||
)
|
||||
logger_.opt(colors=True).info(template)
|
||||
|
||||
@classmethod
|
||||
def success(
|
||||
cls,
|
||||
info: str,
|
||||
command: str,
|
||||
param: Dict[str, Any] | None = None,
|
||||
result: 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)
|
||||
)
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def warning(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def warning(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def warning(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | Session | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
user_id: str | None = session # type: ignore
|
||||
group_id = None
|
||||
if type(session) == Session:
|
||||
user_id = session.id1
|
||||
adapter = session.bot_type
|
||||
if session.id3 or session.id2:
|
||||
group_id = f"{session.id3}:{session.id2}"
|
||||
template = cls.__parser_template(
|
||||
info, command, user_id, group_id, adapter, target
|
||||
)
|
||||
if e:
|
||||
template += f" || 错误<r>{type(e)}: {e}</r>"
|
||||
logger_.opt(colors=True).warning(template)
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def error(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def error(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def error(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | Session | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
user_id: str | None = session # type: ignore
|
||||
group_id = None
|
||||
if type(session) == Session:
|
||||
user_id = session.id1
|
||||
adapter = session.bot_type
|
||||
if session.id3 or session.id2:
|
||||
group_id = f"{session.id3}:{session.id2}"
|
||||
template = cls.__parser_template(
|
||||
info, command, user_id, group_id, adapter, target
|
||||
)
|
||||
if e:
|
||||
template += f" || 错误 <r>{type(e)}: {e}</r>"
|
||||
logger_.opt(colors=True).error(template)
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def debug(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@overload
|
||||
@classmethod
|
||||
def debug(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def debug(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
*,
|
||||
session: int | str | Session | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
e: Exception | None = None,
|
||||
):
|
||||
user_id: str | None = session # type: ignore
|
||||
group_id = None
|
||||
if type(session) == Session:
|
||||
user_id = session.id1
|
||||
adapter = session.bot_type
|
||||
if session.id3 or session.id2:
|
||||
group_id = f"{session.id3}:{session.id2}"
|
||||
template = cls.__parser_template(
|
||||
info, command, user_id, group_id, adapter, target
|
||||
)
|
||||
if e:
|
||||
template += f" || 错误 <r>{type(e)}: {e}</r>"
|
||||
logger_.opt(colors=True).debug(template)
|
||||
|
||||
@classmethod
|
||||
def __parser_template(
|
||||
cls,
|
||||
info: str,
|
||||
command: str | None = None,
|
||||
user_id: int | str | None = None,
|
||||
group_id: int | str | None = None,
|
||||
adapter: str | None = None,
|
||||
target: Any = None,
|
||||
) -> str:
|
||||
arg_list = []
|
||||
template = ""
|
||||
if adapter is not None:
|
||||
template += cls.TEMPLATE_ADAPTER
|
||||
arg_list.append(adapter)
|
||||
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)
|
||||
Reference in New Issue
Block a user