This commit is contained in:
felinae98 2022-03-24 19:36:54 +08:00
parent c6dfc9818e
commit df23648b0f
No known key found for this signature in database
GPG Key ID: 00C8B010587FF610
3 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,58 @@
import json
from typing import Optional
from nonebot_bison.types import Category, Tag, Target
from nonebot_plugin_datastore.db import create_session
from sqlalchemy.sql.expression import select
from .db_model import Subscribe as MSubscribe
from .db_model import Target as MTarget
from .db_model import User
class DBConfig:
def __init__(self):
self.session = create_session()
async def add_subscribe(
self,
user: int,
user_type: str,
target: Target,
target_name: str,
platform_name: str,
cats: list[Category],
tags: list[Tag],
):
db_user_stmt = (
select(User).where(User.uid == user).where(User.type == user_type)
)
db_user: Optional[User] = (await self.session.scalars(db_user_stmt)).first()
if not db_user:
db_user = User(uid=user, type=user_type)
self.session.add(db_user)
db_target_stmt = (
select(MTarget)
.where(MTarget.platform_name == platform_name)
.where(MTarget.target == target)
)
db_target: Optional[MTarget] = (
await self.session.scalars(db_target_stmt)
).first()
if not db_target:
db_target = MTarget(
target=target, platform_name=platform_name, target_name=target_name
)
else:
db_target.target_name = target_name # type: ignore
subscribe = MSubscribe(
categories=json.dumps(cats),
tags=json.dumps(tags),
user=db_user,
target=db_target,
)
self.session.add(subscribe)
await self.session.commit()
config = DBConfig()

View File

@ -0,0 +1,6 @@
class NoSuchUserException(Exception):
pass
class NoSuchSubscribeException(Exception):
pass

View File

@ -0,0 +1,17 @@
from nonebug.app import App
async def test_add_subscrib(app: App):
from nonebot_bison.config.db_config import config
from nonebot_bison.types import Target
await config.add_subscribe(
user=123,
user_type="group",
target=Target("weibo_id"),
target_name="weibo_name",
platform_name="weibo",
cats=[],
tags=[],
)