Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
shpaker committed Aug 14, 2021
1 parent 38212d2 commit 7140448
Show file tree
Hide file tree
Showing 55 changed files with 370 additions and 349 deletions.
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

FROM python:3.9-slim as base-image
ARG POETRY_VERSION=1.1.7
WORKDIR /service
Expand Down
6 changes: 2 additions & 4 deletions chatushka/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from chatushka.bot import Chatushka
from chatushka.core.bot import ChatushkaBot

__all__ = (
"Chatushka",
)
__all__ = ("ChatushkaBot",)
78 changes: 3 additions & 75 deletions chatushka/__main__.py
Original file line number Diff line number Diff line change
@@ -1,77 +1,5 @@
from asyncio import run
from logging import DEBUG, INFO, WARNING, basicConfig, getLogger

from chatushka import Chatushka
from chatushka.matchers import CommandsMatcher, RegexMatcher
from chatushka.samples.handlers.eight_ball import eight_ball_answer_handler, eight_ball_handler
from chatushka.samples.handlers.helpers import mute_handler, suicide_handler
from chatushka.samples.handlers.id import user_id_handler
from chatushka.samples.handlers.jokes import jokes_handler
from chatushka.samples.matchers.heroes.matchers import add_heroes_matchers
from chatushka.services.mongodb.wrapper import MongoDBWrapper
from chatushka.settings import get_settings

logger = getLogger()
settings = get_settings()


def make_regex_matcher():
matcher = RegexMatcher()
matcher.add_handler(r"\?", eight_ball_answer_handler)
return matcher


def make_commands_matcher():
matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
allow_raw=True,
)
matcher.add_handler("id", user_id_handler)
matcher.add_handler("joke", jokes_handler)
matcher.add_handler(("8ball", "ball8", "b8", "8b"), eight_ball_handler)
return matcher


def make_sensitive_matcher():
matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)
matcher.add_handler(("suicide", "wtf"), suicide_handler)
return matcher


def make_privilege_matcher():
matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)
matcher.add_handler("mute", mute_handler)
return matcher


def make_bot() -> Chatushka:
instance = Chatushka(token=settings.token, debug=settings.debug)
wrapper = MongoDBWrapper()
wrapper.add_event_handlers(instance)
add_heroes_matchers(instance)
instance.add_matchers(
make_commands_matcher(),
make_sensitive_matcher(),
make_privilege_matcher(),
make_regex_matcher(),
)
return instance


def main():
basicConfig(level=DEBUG if settings.debug else INFO)
logger.debug("Debug mode is on".upper())
getLogger("httpx").setLevel(WARNING)
bot = make_bot()
run(bot.serve())

from chatushka.bot.main import cli_main

# pylint: disable=no-value-for-parameter
if __name__ == "__main__":
main()
cli_main()
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@

from pymongo.results import InsertOneResult, UpdateResult

from chatushka.samples.matchers.heroes.models import (
HeroesActivationMeta,
HeroesActivationModel,
HeroesActivationUpdatableModel,
)
from chatushka.samples.matchers.heroes.mongodb import get_activations_collection
from chatushka.transports.models import Chat, User
from chatushka.bot.models.heroes import HeroesActivationMeta, HeroesActivationModel, HeroesActivationUpdatableModel
from chatushka.bot.mongodb import get_activations_collection
from chatushka.core.transports.models import Chat, User


async def create_heroes_activation(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from pymongo.results import InsertOneResult, UpdateResult

from chatushka.samples.matchers.heroes.models import CalendarMonthModel, CalendarTypes
from chatushka.samples.matchers.heroes.mongodb import get_calendar_collection
from chatushka.bot.models.heroes import CalendarMonthModel, CalendarTypes
from chatushka.bot.mongodb import get_calendar_collection


async def create_month() -> CalendarMonthModel:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from pymongo.results import InsertOneResult, UpdateResult

from chatushka.samples.matchers.heroes.models import CalendarTypes, CalendarWeekModel
from chatushka.samples.matchers.heroes.mongodb import get_calendar_collection
from chatushka.bot.models.heroes import CalendarTypes, CalendarWeekModel
from chatushka.bot.mongodb import get_calendar_collection


async def create_week() -> CalendarWeekModel:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
REGULAR_WEEK_TEMPLATE = "Астрологи объявляют неделю <b>{beast}</b>.\n Население всех жилищ возросло."
from random import choice, randrange
from typing import Optional

REGULAR_WEEK_TEMPLATE = "Астрологи объявляют неделю <b>{beast}</b>.\nНаселение всех жилищ возросло."
SPECIAL_WEEK_TEMPLATE = (
"Астрологи объявляют, что этой неделе покровительствует сила <b>{beasts}</b>.\n"
"Популяция <b>{beasts}</b> +5.\n"
"Население всех жилищ возросло."
)
PLAGUE_MONTH_MESSAGE = "Астрологи объявляют месяц ЧУМЫ!\nНаселение всех жилищ уменьшилось вдвое."
REGULAR_MONTH_MESSAGE = "Астрологи объявляют месяц <b>{unit}</b>.\n Население всех жилищ возросло."
REGULAR_MONTH_MESSAGE = "Астрологи объявляют месяц <b>{unit}</b>.\nНаселение всех жилищ возросло."
SPECIAL_MONTH_MESSAGE = (
"Астрологи объявляют, что этому месяцу покровительствует сила <b>{unit}</b>.\n"
"Популяция <b>{unit}</b> удваивается!\n"
Expand Down Expand Up @@ -57,3 +60,51 @@
"шершня",
"жука",
)

BOOL_TRUE_VALUES = ("+", "y", "yes", "true", "on")
BOOL_FALSE_VALUES = ("-", "n", "no", "false", "off")


def extract_state(
args: list[str],
) -> Optional[bool]:
if args and args[0] in BOOL_FALSE_VALUES:
return False
if args and args[0] in BOOL_TRUE_VALUES:
return True
return None


def _get_regular_week() -> str:
beast = choice(REGULAR_WEEK_UNIT)
return REGULAR_WEEK_TEMPLATE.format(beast=beast)


def _get_monster_week() -> str:
unit = choice(PLAYABLE_UNITS)
return SPECIAL_WEEK_TEMPLATE.format(beasts=unit)


def get_week_message() -> str:
is_regular_week = randrange(4) != 0
message = _get_regular_week() if is_regular_week else _get_monster_week()
return message


def _get_regular_month() -> str:
unit = choice(REGULAR_MONTH_UNIT)
return REGULAR_MONTH_MESSAGE.format(unit=unit)


def _get_unit_month() -> str:
unit = choice(REGULAR_MONTH_UNIT)
return SPECIAL_MONTH_MESSAGE.format(unit=unit)


def get_month_message():
random_int = randrange(10)
if random_int < 5:
return _get_regular_month()
if random_int == 5:
return PLAGUE_MONTH_MESSAGE
return _get_unit_month()
53 changes: 53 additions & 0 deletions chatushka/bot/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from asyncio import run
from logging import DEBUG, INFO, WARNING, basicConfig, getLogger

from click import command, option

from chatushka import ChatushkaBot
from chatushka.bot.matchers import eight_ball_matchers, helpers_matcher, heroes_matchers, jokes_matcher, suicide_matcher
from chatushka.bot.settings import get_settings
from chatushka.core.services.mongodb.wrapper import MongoDBWrapper

logger = getLogger()
settings = get_settings()


def make_bot(
token: str,
debug: bool,
) -> ChatushkaBot:
instance = ChatushkaBot(token=token, debug=debug)
wrapper = MongoDBWrapper()
wrapper.add_event_handlers(instance)

instance.add_matchers(
jokes_matcher,
*eight_ball_matchers,
helpers_matcher,
*heroes_matchers,
suicide_matcher,
)

instance.add_matchers()
return instance


@command()
@option(
"--token",
"-t",
required=True,
)
@option(
"--debug/--no-debug",
is_flag=True,
)
def cli_main(
token: str,
debug: bool,
) -> None:
basicConfig(level=DEBUG if debug else INFO)
getLogger("httpx").setLevel(WARNING)
logger.debug("Debug mode is on".upper())
bot = make_bot(token, debug)
run(bot.serve())
13 changes: 13 additions & 0 deletions chatushka/bot/matchers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from chatushka.bot.matchers.bobuk_jokes import jokes_matcher
from chatushka.bot.matchers.eight_ball import eight_ball_matchers
from chatushka.bot.matchers.helpers import helpers_matcher
from chatushka.bot.matchers.heroes import heroes_matchers
from chatushka.bot.matchers.suicide import suicide_matcher

__all__ = (
"jokes_matcher",
"eight_ball_matchers",
"helpers_matcher",
"heroes_matchers",
"suicide_matcher",
)
File renamed without changes.
8 changes: 8 additions & 0 deletions chatushka/bot/matchers/admin/_matcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from chatushka.bot.settings import get_settings
from chatushka.core.matchers import CommandsMatcher

settings = get_settings()
admin_matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from random import choice, randrange
from typing import Optional

from chatushka.transports.models import ChatPermissions, Message, User
from chatushka.transports.telegram_bot_api import TelegramBotApi
from chatushka.bot.matchers.admin._matcher import admin_matcher
from chatushka.core.transports.models import ChatPermissions, Message, User
from chatushka.core.transports.telegram_bot_api import TelegramBotApi

RESTRICT_PERMISSION = ChatPermissions(
can_send_messages=False,
Expand All @@ -14,38 +15,6 @@
)


async def suicide_handler(
api: TelegramBotApi,
message: Message,
) -> None:
restrict_time = timedelta(minutes=randrange(1, 4 * 60))
try:
is_success = await api.restrict_chat_member(
chat_id=message.chat.id,
user_id=message.user.id,
permissions=ChatPermissions(
can_send_messages=False,
can_send_media_messages=False,
can_send_polls=False,
can_send_other_messages=False,
),
until_date=datetime.now(tz=timezone.utc) + restrict_time,
)
except ValueError:
is_success = False
if is_success:
await api.send_message(
chat_id=message.chat.id,
text=f"Пользователь {message.user.readable_name} самовыпилился на {restrict_time}",
)
return None
await api.send_message(
chat_id=message.chat.id,
text=f"Лапки коротковаты чтоб убить {message.user.readable_name}",
reply_to_message_id=message.message_id,
)


class MuteMessages(Enum):
ACCIDENT = (
'🧐 <a href="tg://user?id={user}">{name}</a> споткнулся и упал. Попал в больницу на {time} минут.',
Expand All @@ -59,6 +28,7 @@ class MuteMessages(Enum):
)


@admin_matcher()
async def mute_handler(
api: TelegramBotApi,
message: Message,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
from httpx import AsyncClient

from chatushka.transports.models import Message
from chatushka.transports.telegram_bot_api import TelegramBotApi
from chatushka.bot.settings import get_settings
from chatushka.core.matchers import CommandsMatcher
from chatushka.core.transports.models import Message
from chatushka.core.transports.telegram_bot_api import TelegramBotApi

JOKES_URL = "https://jokesrv.rubedo.cloud/"

settings = get_settings()
jokes_matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)


@jokes_matcher("jokes", "joke")
async def jokes_handler(
api: TelegramBotApi,
message: Message,
Expand Down
Loading

0 comments on commit 7140448

Please sign in to comment.