Skip to content

Commit

Permalink
record meme generation & add label hot
Browse files Browse the repository at this point in the history
  • Loading branch information
MeetWq committed Aug 12, 2024
1 parent 5cb1d55 commit 3e552d2
Show file tree
Hide file tree
Showing 8 changed files with 755 additions and 21 deletions.
4 changes: 3 additions & 1 deletion nonebot_plugin_memes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
require("nonebot_plugin_session")
require("nonebot_plugin_userinfo")
require("nonebot_plugin_localstore")
require("nonebot_plugin_session_orm")

from . import matchers # noqa
from . import matchers, migrations # noqa
from .config import Config

__plugin_meta__ = PluginMetadata(
Expand All @@ -22,4 +23,5 @@
"nonebot_plugin_session",
"nonebot_plugin_userinfo",
),
extra={"orm_version_location": migrations},
)
2 changes: 1 addition & 1 deletion nonebot_plugin_memes/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class MemeListImageConfig(BaseModel):
text_template: str = "{keywords}"
add_category_icon: bool = True
label_new_timedelta: timedelta = timedelta(days=30)
# label_hot_frequency: int = 10
label_hot_frequency: int = 24


class Config(BaseModel):
Expand Down
9 changes: 8 additions & 1 deletion nonebot_plugin_memes/matchers/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
)
from nonebot_plugin_alconna.builtins.extensions.reply import ReplyMergeExtension
from nonebot_plugin_alconna.uniseg.tools import image_fetch
from nonebot_plugin_session import EventSession, Session
from nonebot_plugin_userinfo import ImageSource, UserInfo, get_user_info

from ..config import memes_config
from ..manager import meme_manager
from ..recorder import record_meme_generation
from ..utils import NetworkError
from .utils import UserId

Expand All @@ -42,6 +44,7 @@

async def process(
matcher: Matcher,
session: Session,
meme: Meme,
image_sources: list[ImageSource],
texts: list[str],
Expand Down Expand Up @@ -71,6 +74,7 @@ async def process(

try:
result = await run_sync(meme)(images=images, texts=texts, args=args)
await record_meme_generation(session, meme.key)
except TextOverLength:
await matcher.finish("文字长度过长")
except ArgMismatch:
Expand Down Expand Up @@ -185,6 +189,7 @@ async def _(
state: T_State,
matcher: Matcher,
user_id: UserId,
session: EventSession,
alc_matches: AlcMatches,
):
if not meme_manager.check(user_id, meme.key):
Expand Down Expand Up @@ -257,7 +262,7 @@ async def finish(msg: str) -> NoReturn:
)

matcher.stop_propagation()
await process(matcher, meme, image_sources, texts, user_infos, args)
await process(matcher, session, meme, image_sources, texts, user_infos, args)


def create_matchers():
Expand All @@ -284,6 +289,7 @@ async def _(
state: T_State,
matcher: Matcher,
user_id: UserId,
session: EventSession,
alc_matches: AlcMatches,
):
meme_params: list[T_MemeParams] = list(alc_matches.query(meme_params_key, ()))
Expand All @@ -310,6 +316,7 @@ async def _(
random_meme = random.choice(available_memes)
await process(
matcher,
session,
random_meme,
image_sources,
texts,
Expand Down
16 changes: 11 additions & 5 deletions nonebot_plugin_memes/matchers/help.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import hashlib
from datetime import datetime
from datetime import datetime, timedelta
from io import BytesIO
from itertools import chain

Expand All @@ -8,10 +8,12 @@
from nonebot.utils import run_sync
from nonebot_plugin_alconna import Image, Text, on_alconna
from nonebot_plugin_localstore import get_cache_dir
from nonebot_plugin_session import EventSession, SessionIdType
from pypinyin import Style, pinyin

from ..config import memes_config
from ..manager import meme_manager
from ..recorder import get_meme_generation_keys
from .utils import UserId

memes_cache_dir = get_cache_dir("nonebot_plugin_memes")
Expand All @@ -26,7 +28,7 @@


@help_matcher.handle()
async def _(user_id: UserId):
async def _(user_id: UserId, session: EventSession):
memes = meme_manager.get_memes()
list_image_config = memes_config.memes_list_image_config

Expand All @@ -48,15 +50,19 @@ async def _(user_id: UserId):
memes = sorted(memes, key=lambda meme: meme.date_modified, reverse=sort_reverse)

label_new_timedelta = list_image_config.label_new_timedelta
# label_hot_frequency = list_image_config.label_hot_frequency
label_hot_frequency = list_image_config.label_hot_frequency

meme_generation_keys = await get_meme_generation_keys(
session, SessionIdType.GROUP, timedelta(days=1)
)

meme_list: list[tuple[Meme, MemeProperties]] = []
for meme in memes:
labels = []
if datetime.now() - meme.date_created < label_new_timedelta:
labels.append("new")
# if await get_meme_frequency(meme.key) >= label_hot_frequency:
# labels.append("hot")
if meme_generation_keys.count(meme.key) >= label_hot_frequency:
labels.append("hot")
disabled = not meme_manager.check(user_id, meme.key)
meme_list.append((meme, MemeProperties(disabled=disabled, labels=labels)))

Expand Down
44 changes: 44 additions & 0 deletions nonebot_plugin_memes/migrations/a82b5f32c60f_init_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""init_db
迁移 ID: a82b5f32c60f
父迁移:
创建时间: 2024-08-12 22:16:13.840860
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "a82b5f32c60f"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = ("nonebot_plugin_memes",)
depends_on: str | Sequence[str] | None = "fff55366306e"


def upgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"nonebot_plugin_memes_memegenerationrecord",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("session_persist_id", sa.Integer(), nullable=False),
sa.Column("time", sa.DateTime(), nullable=False),
sa.Column("meme_key", sa.String(length=64), nullable=False),
sa.PrimaryKeyConstraint(
"id", name=op.f("pk_nonebot_plugin_memes_memegenerationrecord")
),
)
# ### end Alembic commands ###


def downgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("nonebot_plugin_memes_memegenerationrecord")
# ### end Alembic commands ###
53 changes: 53 additions & 0 deletions nonebot_plugin_memes/recorder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from datetime import datetime, timedelta, timezone

from nonebot_plugin_orm import Model, get_session
from nonebot_plugin_session import Session, SessionIdType
from nonebot_plugin_session_orm import SessionModel, get_session_persist_id
from sqlalchemy import String, select
from sqlalchemy.orm import Mapped, mapped_column


class MemeGenerationRecord(Model):
"""表情调用记录"""

__table_args__ = {"extend_existing": True}

id: Mapped[int] = mapped_column(primary_key=True)
session_persist_id: Mapped[int]
""" 会话持久化id """
time: Mapped[datetime]
""" 调用时间\n\n存放 UTC 时间 """
meme_key: Mapped[str] = mapped_column(String(64))
""" 表情名 """


async def record_meme_generation(session: Session, meme_key: str):
session_persist_id = await get_session_persist_id(session)

record = MemeGenerationRecord(
session_persist_id=session_persist_id,
time=datetime.now(timezone.utc),
meme_key=meme_key,
)
async with get_session() as db_session:
db_session.add(record)
await db_session.commit()


async def get_meme_generation_keys(
session: Session, id_type: SessionIdType, time_delta: timedelta
) -> list[str]:
whereclause = SessionModel.filter_statement(
session, id_type, include_bot_type=False
)
whereclause.append(
MemeGenerationRecord.time >= (datetime.now(timezone.utc) - time_delta)
)
statement = (
select(MemeGenerationRecord.meme_key)
.where(*whereclause)
.join(SessionModel, SessionModel.id == MemeGenerationRecord.session_persist_id)
)
async with get_session() as db_session:
result = (await db_session.scalars(statement)).all()
return list(result)
Loading

0 comments on commit 3e552d2

Please sign in to comment.