Skip to content

Commit

Permalink
Merge pull request #167 from Desiders/use-linters
Browse files Browse the repository at this point in the history
Apply `isort` and `ruff` to the whole code. Remove `black`
  • Loading branch information
bomzheg authored Feb 21, 2024
2 parents 58deec2 + 72ece67 commit 3af5ba6
Show file tree
Hide file tree
Showing 61 changed files with 346 additions and 377 deletions.
11 changes: 3 additions & 8 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,11 @@ jobs:
id: ruff
if: steps.changed-python-files.outputs.all_changed_files != '' && !cancelled()
run: |
ruff check --config=pyproject.toml --show-fixes --output-format=github ${{ steps.changed-python-files.outputs.all_changed_files }}
- name: Black
id: black
if: steps.changed-python-files.outputs.all_changed_files != '' && !cancelled()
run: |
black --config=pyproject.toml --check --diff --verbose ${{ steps.changed-python-files.outputs.all_changed_files }}
ruff check --config=pyproject.toml .
ruff format --check --config=pyproject.toml .
- name: Isort
id: isort
if: steps.changed-python-files.outputs.all_changed_files != '' && !cancelled()
run: |
isort --check --diff --profile=black ${{ steps.changed-python-files.outputs.all_changed_files }}
isort --check --diff --profile=black .
11 changes: 7 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ repos:
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 23.12.1
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
Expand All @@ -17,4 +13,11 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.9
hooks:
# Run the linter
- id: ruff
name: ruff (rust)
args: ["--config", "pyproject.toml", "--fix"]
# Run the formatter
- id: ruff-format
name: ruff-format (rust)
args: ["--config", "pyproject.toml"]
10 changes: 5 additions & 5 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
__version__ = '1.4'
__application_name__ = 'KarmaBot'
__author__ = __maintainer__ = 'Yuriy Chebyshev'
__copyright__ = 'Copyleft 2019-2021'
__version__ = "1.4"
__application_name__ = "KarmaBot"
__author__ = __maintainer__ = "Yuriy Chebyshev"
__copyright__ = "Copyleft 2019-2021"
__license__ = "WTFPL"
__email__ = '[email protected]'
__email__ = "[email protected]"
19 changes: 15 additions & 4 deletions app/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,23 @@
"""

from .karmic_triggers import (
MINUS,
MINUS_EMOJI,
MINUS_TRIGGERS,
PLUS,
PLUS_TRIGGERS,
PLUS_EMOJI,
PLUS_TRIGGERS,
PLUS_WORDS,
MINUS,
MINUS_TRIGGERS,
MINUS_EMOJI,
)
from .main import load_config

__all__ = [
"MINUS",
"MINUS_EMOJI",
"MINUS_TRIGGERS",
"PLUS",
"PLUS_EMOJI",
"PLUS_TRIGGERS",
"PLUS_WORDS",
"load_config",
]
8 changes: 4 additions & 4 deletions app/config/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@

def load_db_config(app_dir: Path):
db_config = DBConfig()
db_config.db_type = os.getenv("DB_TYPE", default='sqlite')
db_config.db_type = os.getenv("DB_TYPE", default="sqlite")
db_config.login = os.getenv("DB_LOGIN")
db_config.password = os.getenv("DB_PASSWORD")
db_config.db_name = os.getenv("DB_NAME")
db_config.db_host = os.getenv("DB_HOST", default='localhost')
db_config.db_host = os.getenv("DB_HOST", default="localhost")
port = os.getenv("DB_PORT")
if port is None:
if db_config.db_type == 'mysql':
if db_config.db_type == "mysql":
db_config.db_port = 3306
elif db_config.db_type == 'postgres':
elif db_config.db_type == "postgres":
db_config.db_port = 5432
else:
db_config.db_port = int(port)
Expand Down
14 changes: 8 additions & 6 deletions app/config/karmic_restriction.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@

from app.models.common import TypeRestriction
from app.models.config import AutoRestrictionConfig

from .moderation import FOREVER_RESTRICT_DURATION
from .restriction_plan import RestrictionPlan, RestrictionPlanElem


NEGATIVE_KARMA_TO_RESTRICT = -100
KARMA_AFTER_RESTRICT = -80
RESTRICTIONS_PLAN = RestrictionPlan([
RestrictionPlanElem(timedelta(days=7), TypeRestriction.karmic_ro),
RestrictionPlanElem(timedelta(days=30), TypeRestriction.karmic_ro),
RestrictionPlanElem(FOREVER_RESTRICT_DURATION, TypeRestriction.karmic_ban),
])
RESTRICTIONS_PLAN = RestrictionPlan(
[
RestrictionPlanElem(timedelta(days=7), TypeRestriction.karmic_ro),
RestrictionPlanElem(timedelta(days=30), TypeRestriction.karmic_ro),
RestrictionPlanElem(FOREVER_RESTRICT_DURATION, TypeRestriction.karmic_ban),
]
)


def load_karmic_restriction_config() -> AutoRestrictionConfig:
Expand Down
64 changes: 39 additions & 25 deletions app/config/karmic_triggers.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,42 @@
PLUS = "+"
PLUS_WORDS = frozenset({
"спасибо",
"спс",
"спасибочки",
"спасибки",
"благодарю",
"пасиба",
"пасеба",
"посеба",
"благодарочка",
"thx",
"мерси",
"выручил",
"сяп",
"сяб",
"сенк",
"сенкс",
"сяпки",
"сябки",
"сенью",
"благодарствую",
})
PLUS_WORDS = frozenset(
{
"спасибо",
"спс",
"спасибочки",
"спасибки",
"благодарю",
"пасиба",
"пасеба",
"посеба",
"благодарочка",
"thx",
"мерси",
"выручил",
"сяп",
"сяб",
"сенк",
"сенкс",
"сяпки",
"сябки",
"сенью",
"благодарствую",
}
)
PLUS_TRIGGERS = frozenset({PLUS, *PLUS_WORDS})
PLUS_EMOJI = frozenset({"👍", })
PLUS_EMOJI = frozenset(
{
"👍",
}
)
MINUS = "-"
MINUS_TRIGGERS = frozenset({MINUS, })
MINUS_EMOJI = frozenset({'👎', })
MINUS_TRIGGERS = frozenset(
{
MINUS,
}
)
MINUS_EMOJI = frozenset(
{
"👎",
}
)
3 changes: 1 addition & 2 deletions app/config/logging_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from app.models.config import LogConfig
from app.utils.log import Logger


logger = Logger(__name__)


Expand All @@ -17,6 +16,6 @@ def logging_setup(config_path: Path, log_config: LogConfig):
with (config_path / "logging.yaml").open("r") as f:
logging_config = yaml.safe_load(f)
with suppress(KeyError):
logging_config['handlers']['file']['filename'] = log_dir / "app.log"
logging_config["handlers"]["file"]["filename"] = log_dir / "app.log"
logging.config.dictConfig(logging_config)
logger.info("Logging configured successfully")
8 changes: 2 additions & 6 deletions app/config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ def load_config(config_dir: Path = None) -> Config:
with (config_dir / "bot-config.yaml").open("r", encoding="utf-8") as f:
config_file_data = yaml.load(f, Loader=yaml.FullLoader)

log_config = load_log_config(
app_dir=app_dir, log_chat_id=config_file_data["log_chat_id"]
)
log_config = load_log_config(app_dir=app_dir, log_chat_id=config_file_data["log_chat_id"])
logging_setup(config_dir, log_config)

load_dotenv(str(config_dir / ".env"))
Expand All @@ -44,9 +42,7 @@ def load_config(config_dir: Path = None) -> Config:
config_file_data["tg_client_config"] | {"bot_token": _bot_token}
),
storage=load_storage(config_file_data["storage"]),
report_award_cleanup_delay=config_file_data.get(
"report_award_cleanup_delay", 3600
),
report_award_cleanup_delay=config_file_data.get("report_award_cleanup_delay", 3600),
callback_query_answer_cache_time=config_file_data.get(
"callback_query_answer_cache_time", 3600
),
Expand Down
1 change: 0 additions & 1 deletion app/config/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

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, permissions=ChatPermissions(can_send_messages=False))
Expand Down
2 changes: 1 addition & 1 deletion app/config/storage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any

from app.models.config.storage import StorageConfig, StorageType, RedisConfig
from app.models.config.storage import RedisConfig, StorageConfig, StorageType


def load_storage(dct: dict[str, Any]) -> StorageConfig:
Expand Down
4 changes: 2 additions & 2 deletions app/config/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def load_webhook_config() -> WebhookConfig:
return WebhookConfig(
host=os.getenv("WEBHOOK_HOST"),
port=os.getenv("WEBHOOK_PORT", default=443),
path=os.getenv("WEBHOOK_PATH", default='/karmabot/'),
listen_host=os.getenv("LISTEN_IP", default='localhost'),
path=os.getenv("WEBHOOK_PATH", default="/karmabot/"),
listen_host=os.getenv("LISTEN_IP", default="localhost"),
listen_port=int(os.getenv("LISTEN_PORT", default=3000)),
)
11 changes: 9 additions & 2 deletions app/filters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

from .has_target import HasTargetFilter
from .karma_change import KarmaFilter
from .tg_permissions import (BotHasPermissions, HasPermissions,
TargetHasPermissions)
from .tg_permissions import BotHasPermissions, HasPermissions, TargetHasPermissions

logger = Logger(__name__)

__all__ = [
"HasTargetFilter",
"KarmaFilter",
"BotHasPermissions",
"HasPermissions",
"TargetHasPermissions",
]
4 changes: 1 addition & 3 deletions app/filters/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
class HasResolvedReport(BaseFilter):
"""Check if reported message already resolved report"""

async def __call__(
self, message: types.Message, chat: Chat, report_repo: ReportRepo
) -> bool:
async def __call__(self, message: types.Message, chat: Chat, report_repo: ReportRepo) -> bool:
if not message.reply_to_message:
return False
return await report_repo.has_resolved_report(
Expand Down
24 changes: 6 additions & 18 deletions app/filters/tg_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,10 @@ def __post_init__(self):
arg: True for arg in self.ARGUMENTS.values() if getattr(self, arg)
}

def _get_cached_value(
self, user: types.User, chat: Chat
) -> types.ChatMember | None:
def _get_cached_value(self, user: types.User, chat: Chat) -> types.ChatMember | None:
return None # TODO

def _set_cached_value(
self, user: types.User, chat: Chat, _member: types.ChatMember
):
def _set_cached_value(self, user: types.User, chat: Chat, _member: types.ChatMember):
return None # TODO

async def _get_chat_member(
Expand All @@ -66,9 +62,7 @@ async def _get_chat_member(
if target_user_id is None:
return False
try:
chat_member = next(
filter(lambda member: member.user.id == target_user_id, admins)
)
chat_member = next(filter(lambda member: member.user.id == target_user_id, admins))
except StopIteration:
return False
self._set_cached_value(user, chat, chat_member)
Expand All @@ -92,9 +86,7 @@ async def __call__(

return {self.PAYLOAD_ARGUMENT_NAME: chat_member}

def get_target_id(
self, update: types.TelegramObject, user: types.User, bot: Bot
) -> int | None:
def get_target_id(self, update: types.TelegramObject, user: types.User, bot: Bot) -> int | None:
return user.id


Expand All @@ -107,9 +99,7 @@ class TargetHasPermissions(HasPermissions):
can_be_same: bool = False
can_be_bot: bool = False

def get_target_id(
self, message: types.Message, user: types.User, bot: Bot
) -> int | None:
def get_target_id(self, message: types.Message, user: types.User, bot: Bot) -> int | None:
target_user = get_target_user(message, self.can_be_same, self.can_be_bot)
if target_user is None:
return None
Expand All @@ -133,7 +123,5 @@ class BotHasPermissions(HasPermissions):
}
PAYLOAD_ARGUMENT_NAME = "bot_member"

def get_target_id(
self, message: types.Message, user: types.User, bot: Bot
) -> int | None:
def get_target_id(self, message: types.Message, user: types.User, bot: Bot) -> int | None:
return bot.id
19 changes: 11 additions & 8 deletions app/handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from aiogram import Dispatcher, Bot
from aiogram import Bot, Dispatcher

from . import base, chat_rules
from . import change_karma
from . import errors
from . import karma
from . import moderator
from . import settings
from . import superuser
from ..models.config import Config
from . import (
base,
change_karma,
chat_rules,
errors,
karma,
moderator,
settings,
superuser,
)


def setup(dp: Dispatcher, bot: Bot, config: Config):
Expand Down
5 changes: 1 addition & 4 deletions app/handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,7 @@ async def cmd_about(message: types.Message):

@router.message(Command("idchat", prefix="!"))
async def get_idchat(message: types.Message):
text = (
f"id этого чата: {hpre(message.chat.id)}\n"
f"Ваш id: {hpre(message.from_user.id)}"
)
text = f"id этого чата: {hpre(message.chat.id)}\nВаш id: {hpre(message.from_user.id)}"
if message.reply_to_message:
text += (
f"\nid {hbold(message.reply_to_message.from_user.full_name)}: "
Expand Down
4 changes: 1 addition & 3 deletions app/handlers/change_karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ async def cancel_karma(
return await callback_query.answer("Эта кнопка не для Вас", cache_time=3600)
rollback_karma = float(callback_data.rollback_karma)
moderator_event_id = (
None
if callback_data.moderator_event_id == "null"
else callback_data.moderator_event_id
None if callback_data.moderator_event_id == "null" else callback_data.moderator_event_id
)
await cancel_karma_change(
callback_data.karma_event_id, rollback_karma, moderator_event_id, bot, user_repo
Expand Down
Loading

0 comments on commit 3af5ba6

Please sign in to comment.