🎉 Init

This commit is contained in:
CMHopeSunshine 2023-03-01 23:51:11 +08:00
commit 49ea404eb8
12 changed files with 3410 additions and 0 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
ENVIRONMENT=dev
DRIVER=~fastapi

7
.env.prod Normal file
View File

@ -0,0 +1,7 @@
HOST=0.0.0.0
PORT=13579
LOG_LEVEL=INFO
SUPERUSERS=["123456"]
NICKNAME=["派蒙"]
COMMAND_START=[""]
COMMAND_SEP=[""]

142
.gitignore vendored Normal file
View File

@ -0,0 +1,142 @@
# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
doc/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
.idea
# End of https://www.toptal.com/developers/gitignore/api/python

30
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,30 @@
ci:
autofix_commit_msg: ":rotating_light: auto fix by pre-commit hooks"
autofix_prs: true
autoupdate_branch: dev
autoupdate_schedule: monthly
autoupdate_commit_msg: ":arrow_up: auto update by pre-commit hooks"
repos:
- repo: https://github.com/psf/black
rev: 23.1a1
hooks:
- id: black
args: [-S, --verbose]
verbose: true
- repo: https://github.com/python-poetry/poetry
rev: 1.3.1
hooks:
- id: poetry-check
- id: poetry-export
args:
[
"-f",
"requirements.txt",
"--without-hashes",
"--output",
"requirements.txt",
]
verbose: true

19
LittlePaimon/__init__.py Normal file
View File

@ -0,0 +1,19 @@
from pathlib import Path
from typing import Union
import nonebot
from .log import init_logger
from nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11Adapter
def run(*args, **kwargs):
init_logger()
nonebot.init()
app = nonebot.get_asgi()
driver = nonebot.get_driver()
driver.register_adapter(ONEBOT_V11Adapter)
nonebot.run(app=app, *args, **kwargs)
def load_plugin(name: Union[str, Path]):
nonebot.load_plugin(name)

85
LittlePaimon/hook.py Normal file
View File

@ -0,0 +1,85 @@
import asyncio
import inspect
from nonebot import get_driver, get_bot
from nonebot.adapters import Bot
from nonebot.utils import is_coroutine_callable, run_sync
from typing import Callable
_start_up_func = []
_start_up_func_after_db = []
_shutdown_func = []
_shutdown_func_before_db = []
driver = get_driver()
@driver.on_startup
async def _run_start_up():
await asyncio.gather(*_start_up_func)
...
await asyncio.gather(*_start_up_func_after_db)
@driver.on_shutdown
async def _run_shutdown():
await asyncio.gather(*_shutdown_func)
...
await asyncio.gather(*_shutdown_func_before_db)
def on_startup(database: bool = False) -> Callable:
"""
包裹一个函数使其在bot启动完成时运行如果该函数有数据库相关处理参数database需为True
:param database: 是否有数据库相关处理
"""
def return_func(func: Callable) -> Callable:
if database:
_start_up_func_after_db.append(func)
else:
_start_up_func.append(func)
return func
return return_func
def on_shutdown(database: bool = False) -> Callable:
"""
包裹一个函数使其在bot停止前运行如果该函数有数据库相关处理参数database需为True
:param database: 是否有数据库相关处理
"""
def return_func(func: Callable) -> Callable:
if database:
_shutdown_func_before_db.append(func)
else:
_shutdown_func.append(func)
return func
return return_func
async def handle_func_params(func: Callable):
"""
处理函数依赖注入已支持的注入参数有
- bot: nonebot.adapters.Bot及其子类默认值可为bot_id来指定bot例如bot: Bot = 123456789
:param func:
:return:
"""
func = func if is_coroutine_callable(func) else run_sync(func)
param = inspect.signature(func).parameters
if 'bot' in param and issubclass(param['bot'].annotation, Bot):
default = param['bot'].default
if default == inspect.Parameter.empty:
await func(bot=get_bot())
elif isinstance(default, (int, str)):
await func(bot=get_bot(default))
else:
await func()
else:
await func()

192
LittlePaimon/log.py Normal file
View File

@ -0,0 +1,192 @@
import sys
from typing import Union, TYPE_CHECKING
from loguru import logger as loguru_logger
from nonebot.log import logger_id, logger as nb_logger
from rich.console import Console
if TYPE_CHECKING:
from loguru import Record
def log_format(record: "Record") -> str:
# if record['message'] == 'NoneBot is initializing...':
# record['message'] = '正在初始化Nonebot...'
return ("<g>{time:MM-DD HH:mm:ss:SSS}</g> "
"[<lvl>{level}</lvl>] "
"<c><u>{name}</u></c> | "
"{message}\n")
def log_filter(record: "Record") -> bool:
"""默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。"""
# if record['message']:
# return False
log_level = record['extra'].get('nonebot_log_level', 'INFO')
level_no = nb_logger.level(log_level).no if isinstance(log_level, str) else log_level
return record['level'].no >= level_no
def init_logger():
nb_logger.remove(logger_id)
nb_logger.add(
sys.stdout,
level=0,
format=log_format,
filter=log_filter,
backtrace=False,
diagnose=True,
)
class logger:
"""
自定义格式色彩logger
"""
_logger: loguru_logger = nb_logger
_new_level = _logger.level('data', no=38, color='<yellow>', icon='📂')
_rich_console = Console()
@classmethod
def info(cls, command: str, info: str = '', **kwargs):
"""
info日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).info(f'{CommandColor(command)}{info}')
@classmethod
def success(cls, command: str, info: str = '', **kwargs):
"""
success日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).success(f'{CommandColor(command)}{info}')
@classmethod
def warning(cls, command: str, info: str = '', **kwargs):
"""
warning日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).warning(f'{CommandColor(command)}{info}')
@classmethod
def debug(cls, command: str, info: str = '', **kwargs):
"""
debug日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).debug(f'{CommandColor(command)}{info}')
@classmethod
def error(cls, command: str, info: str = '', **kwargs):
"""
error日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).error(f'{CommandColor(command)}{info}')
@classmethod
def data(cls, command: str, info: str = '', **kwargs):
"""
data日志
:param command: 命令名
:param info: 信息
"""
cls._logger.opt(colors=True, **kwargs).log('data', f'{CommandColor(command)}{info}')
@classmethod
def exception(cls, command: str, info: str = '', rich: bool = False, **kwargs):
"""
exception日志
:param command: 命令名
:param info: 信息
:param rich: 使用rich库打印异常
"""
if rich:
cls._logger.opt(colors=True, **kwargs).error(f'{CommandColor(command)}{info}')
cls._rich_console.print_exception(show_locals=True)
else:
cls._logger.opt(colors=True, **kwargs).exception(f'{CommandColor(command)}{info}')
@classmethod
def status(cls, command: str, message: str, color: str = 'green'):
"""
状态动画
:param command: 命令名
:param message: 消息
:param color: 颜色
:return:
"""
return cls._rich_console.status(
f'[bold underline yellow][{command}][/bold underline yellow][{color}]{message}[/{color}]',
spinner='earth')
# def ParamColor(**kwargs) -> str:
# """参数颜色"""
# text = ''.join(f'{key}=<m>{value}</m> ' for key, value in kwargs.items())
# return text.strip()
def CommandColor(command: Union[str, int]):
"""命令颜色"""
return f'<u><y>[{command}]</y></u>'
def Underline(text: Union[str, int]) -> str:
"""下划线"""
return f'<u>{text}</u>'
def Yellow(text: Union[str, int]) -> str:
"""黄色"""
return f'<y>{text}</y>'
def Green(text: Union[str, int]) -> str:
"""绿色"""
return f'<g>{text}</g>'
def Red(text: Union[str, int]) -> str:
"""红色"""
return f'<r>{text}</r>'
def Magenta(text: Union[str, int]) -> str:
"""品红色"""
return f'<m>{text}</m>'
def Bold(text: Union[str, int]) -> str:
"""粗体"""
return f'<b>{text}</b>'
__all__ = [
'logger',
# 'ParamColor',
'CommandColor',
'Underline',
'Yellow',
'Green',
'Red',
'Magenta',
'Bold',
'init_logger'
]

349
LittlePaimon/scheduler.py Normal file
View File

@ -0,0 +1,349 @@
import logging
from datetime import datetime, date, timedelta
from typing import Optional, Callable, Union
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from nonebot.log import LoguruHandler
from .hook import on_startup, on_shutdown
from .log import logger, Yellow
scheduler = AsyncIOScheduler()
scheduler.configure({'apscheduler.timezone': 'Asia/Shanghai'})
@on_startup()
async def _start_scheduler():
if not scheduler.running:
scheduler.start()
logger.info('定时任务', Yellow('启动定时任务'))
@on_shutdown()
async def _shutdown_scheduler():
if scheduler.running:
scheduler.shutdown()
logger.info('定时任务', Yellow('关闭定时任务'))
aps_logger = logging.getLogger('apscheduler')
aps_logger.setLevel(30)
aps_logger.handlers.clear()
aps_logger.addHandler(LoguruHandler())
def add_interval_job(
func: Callable,
job_id: Optional[str] = None,
weeks: int = 0,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: int = 0,
start_date: Union[date, datetime, str] = None,
end_date: Union[date, datetime, str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs) -> str:
"""
使指定函数每隔一段时间执行一次
:param func: 要执行的函数
:param job_id: 任务ID不设置则自动生成
:param weeks: 周数
:param days: 天数
:param hours: 小时
:param minutes: 分钟
:param seconds:
:param start_date: 允许执行的开始日期不设置则无限制
:param end_date: 允许执行的结束日期不设置则无限制
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
:return: 任务ID可以用于取消任务
"""
job = scheduler.add_job(func,
'interval',
weeks=weeks,
days=days,
hours=hours,
minutes=minutes,
seconds=seconds,
start_date=start_date,
end_date=end_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs,
id=job_id)
return job.id
def on_interval_time(job_id: Optional[str] = None,
weeks: int = 0,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: int = 0,
start_date: Union[date, datetime, str] = None,
end_date: Union[date, datetime, str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs) -> Callable:
"""
装饰器
装饰一个函数使其在指定间隔时间执行
示例:
每1分钟执行一次打印test
```
@on_interval_time(minutes=1)
async def test():
print('test')
```
:param job_id: 任务ID不设置则自动生成
:param weeks: 周数
:param days: 天数
:param hours: 小时
:param minutes: 分钟
:param seconds:
:param start_date: 允许执行的开始日期不设置则无限制
:param end_date: 允许执行的结束日期不设置则无限制
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
"""
def inner(func: Callable) -> Callable:
add_interval_job(func,
job_id=job_id,
weeks=weeks,
days=days,
hours=hours,
minutes=minutes,
seconds=seconds,
start_date=start_date,
end_date=end_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs)
return func
return inner
def add_cron_job(
func: Callable,
job_id: Optional[str] = None,
crontab: Optional[str] = None,
year: Union[int, str] = '*',
month: Union[int, str] = '*',
week: Union[int, str] = '*',
day: Union[int, str] = '*',
day_of_week: Union[int, str] = '*',
hour: Union[int, str] = '*',
minute: Union[int, str] = '*',
second: Union[int, str] = '*',
start_date: Union[date, datetime, str] = None,
end_date: Union[date, datetime, str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs) -> str:
"""
使指定函数按cron表达式来定期执行
:param func: 要执行的函数
:param job_id: 任务ID不设置则自动生成
:param crontab: crontab表达式如有则后续year等参数将忽略
:param year:
:param month:
:param week:
:param day_of_week: 周内第几天或者星期几
:param day:
:param hour: 小时
:param minute: 分钟
:param second:
:param start_date: 允许执行的开始日期不设置则无限制
:param end_date: 允许执行的结束日期不设置则无限制
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
:return: 任务ID可用于取消任务
"""
if crontab:
job = scheduler.add_job(func,
CronTrigger.from_crontab(crontab),
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs,
id=job_id)
else:
job = scheduler.add_job(func,
'cron',
year=year,
month=month,
day=day,
week=week,
day_of_week=day_of_week,
hour=hour,
minute=minute,
second=second,
start_date=start_date,
end_date=end_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs,
id=job_id)
return job.id
def on_cron_time(
job_id: Optional[str] = None,
crontab: Optional[str] = None,
year: Union[int, str] = '*',
month: Union[int, str] = '*',
week: Union[int, str] = '*',
day: Union[int, str] = '*',
day_of_week: Union[int, str] = '*',
hour: Union[int, str] = '*',
minute: Union[int, str] = '*',
second: Union[int, str] = '*',
start_date: Union[date, datetime, str] = None,
end_date: Union[date, datetime, str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs):
"""
装饰器
装饰一个函数使其按cron表达式时间执行
示例:
在6,7,8,11,12月的第3个周五的1,2,3点打印test
```
@on_cron_time(month='6-8,11-12', day='3rd fri', hour='0-3')
async def test():
print('test')
```
:param job_id: 任务ID不设置则自动生成
:param crontab: crontab表达式如有则后续year等参数将忽略
:param year:
:param month:
:param week:
:param day_of_week: 周内第几天或者星期几
:param day:
:param hour: 小时
:param minute: 分钟
:param second:
:param start_date: 允许执行的开始日期不设置则无限制
:param end_date: 允许执行的结束日期不设置则无限制
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
"""
def inner(func: Callable) -> Callable:
add_cron_job(func,
job_id=job_id,
crontab=crontab,
year=year,
month=month,
day=day,
week=week,
day_of_week=day_of_week,
hour=hour,
minute=minute,
second=second,
start_date=start_date,
end_date=end_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs)
return func
return inner
def add_date_job(
func: Callable,
run_date: Union[str, datetime],
job_id: Optional[str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs) -> str:
"""
使一个函数在指定时间执行
:param func: 要执行的函数
:param run_date: 执行时间
:param job_id: 任务ID不设置则自动生成
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
:return: 任务ID可用于取消任务
"""
job = scheduler.add_job(func,
'date',
run_date=run_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs,
id=job_id)
return job.id
def on_date_time(
run_date: Union[str, datetime],
job_id: Optional[str] = None,
misfire_grace_time: Optional[int] = None,
*args,
**kwargs):
"""
装饰器
装饰一个函数使其在指定时间执行
:param run_date: 执行时间
:param job_id: 任务ID不设置则自动生成
:param misfire_grace_time: 容错时间
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
"""
def inner(func: Callable) -> Callable:
add_date_job(func,
run_date=run_date,
misfire_grace_time=misfire_grace_time,
args=args,
kwargs=kwargs,
job_id=job_id)
return func
return inner
def add_run_after_job(seconds: int,
func: Callable,
*args,
**kwargs) -> str:
"""
使一个函数在指定秒数后执行
:param seconds: 秒数
:param func: 函数
:param args: 其它传给函数的位置参数
:param kwargs: 其它传给函数的关键字参数
:return: 任务ID可用于取消任务
"""
a = scheduler.add_job(func, 'date', run_date=datetime.now() + timedelta(seconds=seconds), args=args, kwargs=kwargs)
return a.id
__all__ = [
'add_interval_job',
'add_cron_job',
'add_date_job',
'add_run_after_job',
'on_interval_time',
'on_cron_time',
'on_date_time',
'scheduler'
]

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# LittlePaimon
Version 4 developing...

16
bot.py Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import nonebot
from nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11Adapter
from LittlePaimon.log import init_logger
init_logger()
nonebot.init()
app = nonebot.get_asgi()
driver = nonebot.get_driver()
driver.register_adapter(ONEBOT_V11Adapter)
if __name__ == '__main__':
nonebot.run(app='__mp_main__:app')

2513
poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

52
pyproject.toml Normal file
View File

@ -0,0 +1,52 @@
[tool.poetry]
name = "LittlePaimon"
version = "4.0"
description = "小派蒙原神qq群机器人基于NoneBot2的UID查询、抽卡导出分析、模拟抽卡、实时便签、札记等多功能小助手。"
authors = ["惜月 <277073121@qq.com>"]
license = "AGPL"
[[tool.poetry.source]]
name = "aliyun"
default = true
url = "https://mirrors.aliyun.com/pypi/simple/"
[tool.poetry.dependencies]
python = "^3.8.1"
nonebot2 = {extras = ["fastapi"], version = "^2.0.0-rc.2"}
nonebot-adapter-onebot = "^2.1"
beautifulsoup4 = "^4.10.0"
httpx = "^0.23.0"
lxml = "^4.8.0"
Pillow = "^9.1.0"
tortoise-orm = "^0.19.2"
"ruamel.yaml" = "^0.17.21"
ujson = "^5.4.0"
jieba = "^0.42.1"
gitpython = "^3.1.27"
python-jose = "^3.3.0"
amis-python = "^1.0.5"
psutil = "^5.9.3"
playwright = "^1.27.1"
qrcode = "^7.3.1"
rich = "^13.3.1"
apscheduler = "^3.9.1"
[tool.poetry.dev-dependencies]
pre-commit = "^3.0.2"
black = "^22.12.0"
[tool.black]
line-length = 79
target-version = ["py38", "py39", "py310"]
include = '\.pyi?$'
skip-string-normalization = true
extend-exclude = '''
'''
[tool.nonebot]
plugins = []
plugin_dirs = []
[build-system]
requires = ["poetry_core>=1.0.0"]
build-backend = "poetry.core.masonry.api"