Skip to content

Commit

Permalink
Logging (#89)
Browse files Browse the repository at this point in the history
* migrate to logging

* reformat code after migrate

* more fixes
  • Loading branch information
bomzheg authored Apr 24, 2021
1 parent 1c50206 commit d07287c
Show file tree
Hide file tree
Showing 54 changed files with 198 additions and 97 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ jsons/
*.session
__pycache__/
db_data/
/config/
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ VOLUME /db_data
VOLUME /jsons
WORKDIR "."
EXPOSE 3000
COPY bot-config.yml bot-config.yml
COPY config config
COPY app app
ENTRYPOINT ["python3", "-m", "app", "-p"]
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ moderator commands list:
* !ro !mute [DURATION] [@mention] - restrict replied or mentioned user for DURATION.
* !ban [DURATION] [@mention] - kick replied user for DURATION
* DURATION in format [AAAy][BBBw][CCCd][DDDh][EEEm][FFFs] where:
* AAA - count of years (more that one year is permanent)
* AAA - count of years (more than one year is permanent)
* BBB - count of weeks
* CCC - count of days
* DDD - count of hours
* EEE - count of minutes
* FFF - count of seconds (less that 30 seconds will be mean 30 seconds)
* FFF - count of seconds (less than 30 seconds will be mean 30 seconds)
* you have to specify one or more duration part without spaces
* !warn, !w [@mention] - official warn user from moderator
* !info [@mention] - information about user (karma changes, restrictions, warns)
Expand Down
3 changes: 2 additions & 1 deletion app/config/karmic_restriction.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from datetime import timedelta

from app.models.common import TypeRestriction
from app.models.config import AutoRestrictionConfig
from .moderation import FOREVER_RESTRICT_DURATION
from .restriction_plan import RestrictionPlan, RestrictionPlanElem
from app.models.config import AutoRestrictionConfig


NEGATIVE_KARMA_TO_RESTRICT = -100
KARMA_AFTER_RESTRICT = -80
Expand Down
1 change: 0 additions & 1 deletion app/config/karmic_triggers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

PLUS = "+"
PLUS_WORDS = frozenset({
"спасибо",
Expand Down
6 changes: 3 additions & 3 deletions app/config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
from dotenv import load_dotenv

from app.models.config import Config, TgClientConfig
from .karmic_restriction import load_karmic_restriction_config
from .db import load_db_config
from .webhook import load_webhook_config
from .karmic_restriction import load_karmic_restriction_config
from .log import load_log_config
from .webhook import load_webhook_config


@lru_cache
Expand All @@ -18,7 +18,7 @@ def load_config() -> Config:
load_dotenv(str(app_dir / '.env'))

_bot_token = os.getenv("KARMA_BOT_TOKEN")
with (app_dir / "bot-config.yml").open('r', encoding="utf-8") as f:
with (app_dir / 'config' / "bot-config.yml").open('r', encoding="utf-8") as f:
config_file_data = yaml.load(f, Loader=yaml.FullLoader)

return Config(
Expand Down
1 change: 1 addition & 0 deletions app/config/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from app.models.common import TypeRestriction


DEFAULT_RESTRICT_DURATION = timedelta(hours=1)
FOREVER_RESTRICT_DURATION = timedelta(days=666)
RO_ACTION = partial(Bot.restrict_chat_member, can_send_messages=False)
Expand Down
5 changes: 4 additions & 1 deletion app/filters/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from functools import partialmethod

from aiogram import Dispatcher
from loguru import logger

from app.models.config import Config
from app.utils.log import Logger


logger = Logger(__name__)


def setup(dispatcher: Dispatcher, config: Config):
Expand Down
1 change: 1 addition & 0 deletions app/filters/has_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from aiogram import types
from aiogram.dispatcher.filters import BoundFilter

from app.services.find_target_user import get_target_user


Expand Down
4 changes: 2 additions & 2 deletions app/filters/tg_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __post_init__(self):

@classmethod
def validate(
cls, full_config: typing.Dict[str, typing.Any]
cls, full_config: typing.Dict[str, typing.Any]
) -> typing.Optional[typing.Dict[str, typing.Any]]:
config = {}
for alias, argument in cls.ARGUMENTS.items():
Expand Down Expand Up @@ -70,7 +70,7 @@ async def _get_chat_member(self, message: types.Message):
return chat_member

async def check(
self, message: types.Message
self, message: types.Message
) -> typing.Union[bool, typing.Dict[str, typing.Any]]:
chat_member = await self._get_chat_member(message)
if not chat_member:
Expand Down
4 changes: 2 additions & 2 deletions app/handlers/admin_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json

from aiogram import types
from loguru import logger

from app.config.main import load_config
from app.misc import bot, dp
Expand All @@ -11,9 +10,10 @@
User,
UserKarma,
)
from app.utils.log import Logger
from app.utils.send_text_file import send_log_files


logger = Logger(__name__)
config = load_config()


Expand Down
5 changes: 4 additions & 1 deletion app/handlers/base.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.utils.markdown import hpre, hbold
from loguru import logger

from app.misc import dp
from app.models.db import Chat
from app.utils.log import Logger


logger = Logger(__name__)


@dp.message_handler(commands=["start"], commands_prefix='!/')
Expand Down
26 changes: 13 additions & 13 deletions app/handlers/change_karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@
from aiogram import types
from aiogram.types import ContentType
from aiogram.utils.markdown import quote_html
from loguru import logger

from app.misc import dp
from app.config.main import load_config
from app.misc import dp
from app.models.db import Chat, User
from app.services.adaptive_trottle import AdaptiveThrottle
from app.services.change_karma import change_karma, cancel_karma_change
from app.services.remove_message import remove_kb
from app.services.settings import is_enable_karmic_restriction
from app.utils.exceptions import SubZeroKarma, CantChangeKarma, DontOffendRestricted
from app.services.remove_message import remove_kb
from app.utils.log import Logger
from . import keyboards as kb
from app.services.adaptive_trottle import AdaptiveThrottle


logger = Logger(__name__)
a_throttle = AdaptiveThrottle()
config = load_config()

Expand All @@ -35,21 +36,20 @@ async def too_fast_change_karma(message: types.Message, *_, **__):


@dp.message_handler(karma_change=True, has_target=True, content_types=[
ContentType.TEXT,
ContentType.TEXT,
ContentType.STICKER,
ContentType.STICKER,
ContentType.ANIMATION,
ContentType.AUDIO,
ContentType.DOCUMENT,
ContentType.PHOTO,
ContentType.VIDEO,
ContentType.VOICE,
ContentType.ANIMATION,
ContentType.AUDIO,
ContentType.DOCUMENT,
ContentType.PHOTO,
ContentType.VIDEO,
ContentType.VOICE,
])
@a_throttle.throttled(rate=30, on_throttled=too_fast_change_karma)
@dp.throttled(rate=1)
async def karma_change(message: types.Message, karma: dict, user: User, chat: Chat, target: User):

try:
result_change_karma = await change_karma(
target_user=target,
Expand Down
3 changes: 2 additions & 1 deletion app/handlers/errors.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from aiogram import types
from aiogram.utils.exceptions import CantParseEntities
from aiogram.utils.markdown import quote_html
from loguru import logger

from app.config.main import load_config
from app.misc import dp, bot
from app.utils.log import Logger


logger = Logger(__name__)
config = load_config()


Expand Down
4 changes: 2 additions & 2 deletions app/handlers/import_karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
UserKarma,
)
from app.services.user_getter import UserGetter
from app.utils.from_axenia import axenia_rating
from app.utils.exceptions import CantImportFromAxenia
from app.utils.from_axenia import axenia_rating


config = load_config()
Expand All @@ -40,7 +40,7 @@ async def check_chat_creator(message: types.Message) -> bool:


@dp.message_handler(check_chat_creator, commands="init_from_axenia", commands_prefix='!')
@dp.throttled(rate=24*3600)
@dp.throttled(rate=24 * 3600)
async def init_from_axenia(message: types.Message, chat: Chat):
msg = await message.reply(processing_text.format(-0.01))
chat_id = chat.chat_id
Expand Down
3 changes: 2 additions & 1 deletion app/handlers/karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from aiogram import types
from aiogram.types import ChatType
from aiogram.utils.markdown import hpre
from loguru import logger

from app.config.main import load_config
from app.misc import dp
Expand All @@ -17,8 +16,10 @@
get_me_chat_info
)
from app.services.remove_message import delete_message
from app.utils.log import Logger


logger = Logger(__name__)
config = load_config()


Expand Down
11 changes: 7 additions & 4 deletions app/handlers/moderator.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from aiogram import types
from aiogram.utils.exceptions import Unauthorized
from aiogram.utils.markdown import hide_link, quote_html
from loguru import logger

from app.misc import dp, bot
from app.utils.exceptions import TimedeltaParseError, ModerationError
from app.models.db import Chat, User
from app.services.user_info import get_user_info
from app.services.moderation import warn_user, ro_user, ban_user, get_duration
from app.services.remove_message import delete_message
from app.services.user_info import get_user_info
from app.utils.exceptions import TimedeltaParseError, ModerationError
from app.utils.log import Logger


logger = Logger(__name__)


@dp.message_handler(
Expand Down Expand Up @@ -136,7 +139,7 @@ async def get_info_about_user(message: types.Message, chat: Chat, target: User):
)
async def cmd_ro_bot_not_admin(message: types.Message):
"""бот без прав модератора"""
await message.reply("Чтобы я выполнял функции модератора, дайте мне соотвествующие права")
await message.reply("Чтобы я выполнял функции модератора, дайте мне соответствующие права")


@dp.message_handler(
Expand Down
5 changes: 4 additions & 1 deletion app/middlewares/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# partially from https://github.com/aiogram/bot
from aiogram import Dispatcher
from loguru import logger

from app.middlewares.acl import ACLMiddleware
from app.models.config import Config
from app.utils.log import Logger


logger = Logger(__name__)


def setup(dispatcher: Dispatcher, config: Config):
Expand Down
7 changes: 5 additions & 2 deletions app/middlewares/acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from loguru import logger

from app.models.db import Chat, User
from app.models.config import TgClientConfig
from app.models.db import Chat, User
from app.services.find_target_user import get_db_user_by_tg_user
from app.utils.lock_factory import LockFactory
from app.utils.log import Logger


logger = Logger(__name__)


class ACLMiddleware(BaseMiddleware):
Expand Down
4 changes: 3 additions & 1 deletion app/misc.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# partially from https://github.com/aiogram/bot
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from loguru import logger

from app.config import load_config
from app.models.config import Config
from app.utils.log import Logger


logger = Logger(__name__)
current_config = load_config()

bot = Bot(current_config.bot_token, parse_mode=types.ParseMode.HTML)
Expand Down
2 changes: 1 addition & 1 deletion app/models/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from .auto_restriction import AutoRestrictionConfig
from .db import DBConfig
from .log import LogConfig
from .webhook import WebhookConfig
from .tg_client import TgClientConfig
from .webhook import WebhookConfig


@dataclass
Expand Down
5 changes: 4 additions & 1 deletion app/models/config/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from dataclasses import dataclass

from loguru import logger
from app.utils.log import Logger


logger = Logger(__name__)


@dataclass
Expand Down
6 changes: 3 additions & 3 deletions app/models/db/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from .chat import Chat, ChatType
from .user import User
from .user_karma import UserKarma
from .chat_settings import ChatSettings
from .karma_actions import KarmaEvent
from .moderator_actions import ModeratorEvent
from .chat_settings import ChatSettings
from .user import User
from .user_karma import UserKarma

__all__ = [Chat, ChatType, User, UserKarma, KarmaEvent, ModeratorEvent, ChatSettings]
3 changes: 2 additions & 1 deletion app/models/db/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

from aiogram import Dispatcher
from aiogram.utils.executor import Executor
from loguru import logger
from tortoise import Tortoise, run_async

from app.models.config import DBConfig
from app.utils.log import Logger


logger = Logger(__name__)
__models__ = ['app.models.db']
karma_filters = ("-karma", "uc_id")

Expand Down
5 changes: 3 additions & 2 deletions app/models/db/karma_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from tortoise import fields
from tortoise.models import Model

from .user import User
from .chat import Chat
from app.config import load_config
from .chat import Chat
from .user import User


config = load_config()

Expand Down
Loading

0 comments on commit d07287c

Please sign in to comment.