Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add user repo #145

Merged
merged 8 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ __pycache__/
db_data/
/config/
.ruff_cache/
/app/karma_bot.session-journal
.venv/
venv/
venv/
7 changes: 5 additions & 2 deletions app/config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import yaml
from dotenv import load_dotenv

from app.models.config import Config, TgClientConfig
from app.models.config import Config

from .db import load_db_config
from .karmic_restriction import load_karmic_restriction_config
from .log import load_log_config
from .logging_config import logging_setup
from .storage import load_storage
from .tg_client import load_tg_client_config
from .webhook import load_webhook_config


Expand Down Expand Up @@ -40,7 +41,9 @@ def load_config(config_dir: Path = None) -> Config:
superusers=frozenset(config_file_data["superusers"]),
log=log_config,
dump_chat_id=config_file_data["dump_chat_id"],
tg_client=TgClientConfig(bot_token=_bot_token),
tg_client=load_tg_client_config(
config_file_data["tg_client_config"] | {"bot_token": _bot_token}
),
storage=load_storage(config_file_data["storage"]),
report_karma_award=config_file_data.get("report_karma_award", 0),
report_award_cleanup_delay=config_file_data.get(
Expand Down
8 changes: 8 additions & 0 deletions app/config/tg_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from app.models.config import TgClientConfig


def load_tg_client_config(config: dict) -> TgClientConfig:
return TgClientConfig(
bot_token=config["bot_token"],
request_interval=config["request_interval"],
)
2 changes: 1 addition & 1 deletion app/handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,5 @@ async def chat_migrate(message: types.Message, chat: Chat, chat_repo: ChatRepo):
old_id = message.chat.id
new_id = message.migrate_to_chat_id
chat.chat_id = new_id
await chat_repo.update(chat)
await chat_repo.save(chat)
logger.info(f"Migrate chat from {old_id} to {new_id}")
10 changes: 8 additions & 2 deletions app/handlers/change_karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from app.filters import HasTargetFilter, KarmaFilter
from app.infrastructure.database.models import Chat, User
from app.infrastructure.database.repo.user import UserRepo
from app.models.config import Config
from app.services.adaptive_trottle import AdaptiveThrottle
from app.services.change_karma import cancel_karma_change, change_karma
Expand Down Expand Up @@ -60,6 +61,7 @@ async def karma_change(
target: User,
config: Config,
bot: Bot,
user_repo: UserRepo,
):
try:
result_change_karma = await change_karma(
Expand All @@ -69,6 +71,7 @@ async def karma_change(
how_change=karma["karma_change"],
comment=karma["comment"],
bot=bot,
user_repo=user_repo,
)
except SubZeroKarma:
return await message.reply("У Вас слишком мало кармы для этого")
Expand Down Expand Up @@ -122,7 +125,10 @@ async def karma_change(

@router.callback_query(kb.KarmaCancelCb.filter())
async def cancel_karma(
callback_query: types.CallbackQuery, callback_data: kb.KarmaCancelCb, bot: Bot
callback_query: types.CallbackQuery,
callback_data: kb.KarmaCancelCb,
bot: Bot,
user_repo: UserRepo,
):
if callback_data.user_id != callback_query.from_user.id:
return await callback_query.answer("Эта кнопка не для Вас", cache_time=3600)
Expand All @@ -133,7 +139,7 @@ async def cancel_karma(
else callback_data.moderator_event_id
)
await cancel_karma_change(
callback_data.karma_event_id, rollback_karma, moderator_event_id, bot
callback_data.karma_event_id, rollback_karma, moderator_event_id, bot, user_repo
)
await callback_query.answer("Вы отменили изменение кармы", show_alert=True)
await callback_query.message.delete()
17 changes: 13 additions & 4 deletions app/handlers/karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from app.infrastructure.database.models import Chat, User
from app.infrastructure.database.repo.chat import ChatRepo
from app.infrastructure.database.repo.user import UserRepo
from app.models.config import Config
from app.services.karma import get_me_chat_info, get_me_info
from app.services.karma import get_top as get_karma_top
Expand All @@ -17,7 +18,9 @@


@router.message(Command("top", prefix="!"), F.chat.type == "private")
async def get_top_from_private(message: types.Message, user: User, chat_repo: ChatRepo):
async def get_top_from_private(
message: types.Message, user: User, chat_repo: ChatRepo, user_repo: UserRepo
):
parts = message.text.split(maxsplit=1)
if len(parts) > 1:
chat = await chat_repo.get_by_id(chat_id=int(parts[1]))
Expand All @@ -30,17 +33,23 @@ async def get_top_from_private(message: types.Message, user: User, chat_repo: Ch
logger.info(
"user {user} ask top karma of chat {chat}", user=user.tg_id, chat=chat.chat_id
)
text = await get_karma_top(chat, user)
text = await get_karma_top(chat, user, chat_repo=chat_repo, user_repo=user_repo)

await message.reply(text, disable_web_page_preview=True)


@router.message(Command("top", prefix="!"))
async def get_top(message: types.Message, chat: Chat, user: User):
async def get_top(
message: types.Message,
chat: Chat,
user: User,
chat_repo: ChatRepo,
user_repo: UserRepo,
):
logger.info(
"user {user} ask top karma of chat {chat}", user=user.tg_id, chat=chat.chat_id
)
text = await get_karma_top(chat, user)
text = await get_karma_top(chat, user, chat_repo=chat_repo, user_repo=user_repo)

await message.reply(text, disable_web_page_preview=True)

Expand Down
12 changes: 10 additions & 2 deletions app/handlers/moderator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from app.handlers import keyboards as kb
from app.infrastructure.database.models import Chat, ChatSettings, ReportStatus, User
from app.infrastructure.database.repo.report import ReportRepo
from app.infrastructure.database.repo.user import UserRepo
from app.models.config import Config
from app.services.moderation import (
ban_user,
Expand Down Expand Up @@ -253,10 +254,15 @@ async def get_info_about_user_private(message: types.Message):
HasTargetFilter(can_be_same=True),
)
async def get_info_about_user(
message: types.Message, chat: Chat, target: User, config: Config, bot: Bot
message: types.Message,
chat: Chat,
target: User,
config: Config,
bot: Bot,
user_repo: UserRepo,
):
info = await get_user_info(target, chat, config.date_format)
target_karma = await target.get_karma(chat)
target_karma = await user_repo.get_karma(target, chat)
if target_karma is None:
target_karma = "пока не имеет кармы"
information = f"Данные на {target.mention_link} ({target_karma}):\n" + "\n".join(
Expand Down Expand Up @@ -319,6 +325,7 @@ async def approve_report_handler(
config: Config,
chat_settings: ChatSettings,
report_repo: ReportRepo,
user_repo: UserRepo,
):
logger.info(
"Moderator {moderator} approved report {report}",
Expand All @@ -338,6 +345,7 @@ async def approve_report_handler(
chat=chat,
reward_amount=config.report_karma_award,
bot=bot,
user_repo=user_repo,
)
message = await bot.edit_message_text(
"<b>{reporter}</b> получил <b>+{reward_amount}</b> кармы "
Expand Down
81 changes: 0 additions & 81 deletions app/infrastructure/database/models/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,7 @@

from aiogram.utils.text_decorations import html_decoration as hd
from tortoise import fields
from tortoise.exceptions import DoesNotExist
from tortoise.models import Model
from tortoise.transactions import in_transaction

from app.models.db.db import karma_filters
from app.utils.exceptions import NotHaveNeighbours

SQL_PREV_NEXT = """
SELECT
prev_user_id,
next_user_id
FROM (SELECT
user_id,
LAG(user_id) OVER(ORDER BY karma) prev_user_id,
LEAD(user_id) OVER(ORDER BY karma) next_user_id
FROM user_karma
WHERE chat_id = ?)
WHERE user_id = ?
"""


class ChatType(str, Enum):
Expand All @@ -45,21 +27,6 @@ class Chat(Model):
class Meta:
table = "chats"

@classmethod
async def create_from_tg_chat(cls, chat):
chat = await cls.create(
chat_id=chat.id, type_=chat.type, title=chat.title, username=chat.username
)
return chat

@classmethod
async def get_or_create_from_tg_chat(cls, chat):
try:
chat = await cls.get(chat_id=chat.id)
except DoesNotExist:
chat = await cls.create_from_tg_chat(chat=chat)
return chat

@property
def mention(self):
return (
Expand All @@ -80,51 +47,3 @@ def __str__(self):

def __repr__(self):
return str(self)

# noinspection PyUnresolvedReferences
async def get_top_karma_list(self, limit: int = 15):
await self.fetch_related("user_karma")
users_karmas = (
await self.user_karma.order_by(*karma_filters)
.limit(limit)
.prefetch_related("user")
.all()
)
rez = []
for user_karma in users_karmas:
user = user_karma.user
karma = user_karma.karma_round
rez.append((user, karma))

return rez

# noinspection PyUnresolvedReferences
async def get_neighbours(
self, user
) -> tuple["UserKarma", "UserKarma", "UserKarma"]: # noqa: F821
prev_id, next_id = await get_neighbours_id(self.chat_id, user.id)
uk = (
await self.user_karma.filter(user_id__in=(prev_id, next_id))
.prefetch_related("user")
.order_by(*karma_filters)
.all()
)

user_uk = (
await self.user_karma.filter(user=user).prefetch_related("user").first()
)
return uk[0], user_uk, uk[1]


async def get_neighbours_id(chat_id, user_id) -> typing.Tuple[int, int]:
async with in_transaction() as conn:
neighbours = await conn.execute_query(SQL_PREV_NEXT, (chat_id, user_id))
try:
rez = dict(neighbours[1][0])
except IndexError:
raise NotHaveNeighbours
try:
rez = int(rez["prev_user_id"]), int(rez["next_user_id"])
except TypeError:
raise NotHaveNeighbours
return rez
Loading