Skip to content

Commit

Permalink
Help (#7)
Browse files Browse the repository at this point in the history
* .

* matcher container

* .

* .

* -

* -
  • Loading branch information
shpaker authored Mar 5, 2022
1 parent 7140448 commit 19d2739
Show file tree
Hide file tree
Showing 12 changed files with 317 additions and 157 deletions.
73 changes: 73 additions & 0 deletions chatushka/bot/libs/mute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from datetime import datetime, timedelta, timezone
from enum import Enum
from random import choice

from chatushka.bot.settings import get_settings
from chatushka.core.matchers import CommandsMatcher
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,
can_send_media_messages=False,
can_send_polls=False,
can_send_other_messages=False,
)
settings = get_settings()
mute_matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)


class MuteMessages(Enum):
ACCIDENT = (
'🧐 <a href="tg://user?id={user}">{name}</a> споткнулся, упал и попал в больницу на {time} минут.',
'🧐 <a href="tg://user?id={user}">{name}</a> заигрался револьвером и угодил в травмпункт на {time} минут.',
'🧐 <a href="tg://user?id={user}">{name}</a> переводил бабушку через дорогу и теперь отдыхает {time} минут.',
'🧐 <a href="tg://user?id={user}">{name}</a> решил подумать о жизни {time} минут.',
)
LOOSER = (
'🧐 <a href="tg://user?id={looser_id}">{looser_name}</a> хотел убить '
'<a href="tg://user?id={victim_id}">{victim_name}</a>, но что-то пошло не так и он '
"вынужден провести в тюрьме {time} минут",
'🧐 У <a href="tg://user?id={looser_id}">{looser_name}</a> лапки коротковаты '
'чтоб убить <a href="tg://user?id={victim_id}">{victim_name}</a>',
)


async def send_mute_request(
api: TelegramBotApi,
message: Message,
initiator: User,
restrict_user: User,
restrict_time: timedelta,
) -> None:
text_tmpl = choice(MuteMessages.ACCIDENT.value)
is_success = await api.restrict_chat_member(
chat_id=message.chat.id,
user_id=restrict_user.id,
permissions=RESTRICT_PERMISSION,
until_date=datetime.now(tz=timezone.utc) + restrict_time,
)
if is_success:
await api.send_message(
chat_id=message.chat.id,
text=text_tmpl.format(
user=restrict_user.id,
name=restrict_user.readable_name,
time=int(restrict_time.total_seconds() // 60),
),
)
return
text_tmpl = choice(MuteMessages.LOOSER.value)
await api.send_message(
chat_id=message.chat.id,
text=text_tmpl.format(
looser_id=initiator.id,
looser_name=initiator.readable_name,
victim_id=restrict_user.id,
victim_name=restrict_user.readable_name,
),
reply_to_message_id=message.message_id,
)
19 changes: 12 additions & 7 deletions chatushka/bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
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.matchers import (
admin_matcher,
eight_ball_matcher,
helpers_matcher,
heroes_matcher,
jokes_matcher,
suicide_matcher,
)
from chatushka.bot.settings import get_settings
from chatushka.core.services.mongodb.wrapper import MongoDBWrapper

Expand All @@ -19,16 +26,14 @@ def make_bot(
instance = ChatushkaBot(token=token, debug=debug)
wrapper = MongoDBWrapper()
wrapper.add_event_handlers(instance)

instance.add_matchers(
instance.add_matcher(
admin_matcher,
jokes_matcher,
*eight_ball_matchers,
eight_ball_matcher,
helpers_matcher,
*heroes_matchers,
heroes_matcher,
suicide_matcher,
)

instance.add_matchers()
return instance


Expand Down
10 changes: 6 additions & 4 deletions chatushka/bot/matchers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from chatushka.bot.matchers.admin import admin_matcher
from chatushka.bot.matchers.bobuk_jokes import jokes_matcher
from chatushka.bot.matchers.eight_ball import eight_ball_matchers
from chatushka.bot.matchers.eight_ball import eight_ball_matcher
from chatushka.bot.matchers.helpers import helpers_matcher
from chatushka.bot.matchers.heroes import heroes_matchers
from chatushka.bot.matchers.heroes import heroes_matcher
from chatushka.bot.matchers.suicide import suicide_matcher

__all__ = (
"admin_matcher",
"jokes_matcher",
"eight_ball_matchers",
"eight_ball_matcher",
"helpers_matcher",
"heroes_matchers",
"heroes_matcher",
"suicide_matcher",
)
12 changes: 12 additions & 0 deletions chatushka/bot/matchers/admin/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from chatushka.bot.matchers.admin.mute import mute_matcher
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,
)
admin_matcher.add_matcher(mute_matcher)

__all__ = ("admin_matcher",)
8 changes: 0 additions & 8 deletions chatushka/bot/matchers/admin/_matcher.py

This file was deleted.

127 changes: 35 additions & 92 deletions chatushka/bot/matchers/admin/mute.py
Original file line number Diff line number Diff line change
@@ -1,115 +1,58 @@
from datetime import datetime, timedelta, timezone
from enum import Enum
from random import choice, randrange
from typing import Optional
from datetime import timedelta
from random import randrange

from chatushka.bot.matchers.admin._matcher import admin_matcher
from chatushka.core.transports.models import ChatPermissions, Message, User
from chatushka.bot.libs.mute import send_mute_request
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

RESTRICT_PERMISSION = ChatPermissions(
can_send_messages=False,
can_send_media_messages=False,
can_send_polls=False,
can_send_other_messages=False,
settings = get_settings()
mute_matcher = CommandsMatcher(
prefixes=settings.command_prefixes,
postfixes=settings.command_postfixes,
)


class MuteMessages(Enum):
ACCIDENT = (
'🧐 <a href="tg://user?id={user}">{name}</a> споткнулся и упал. Попал в больницу на {time} минут.',
'🧐 <a href="tg://user?id={user}">{name}</a> заигрался револьвером и угодил в травмпункт на {time} минут.',
'🧐 <a href="tg://user?id={user}">{name}</a> переводил бабушку через дорогу и теперь отдыхает {time} минут.',
)
LOOSER = (
'🧐 <a href="tg://user?id={looser_id}">{looser_name}</a> хотел убить '
'<a href="tg://user?id={victim_id}">{victim_name}</a>, но что-то пошло не так и он '
"вынужден провести в тюрьме {time} минут",
)


@admin_matcher()
@mute_matcher("mute", "shutup")
async def mute_handler(
api: TelegramBotApi,
message: Message,
args: list[str],
) -> None:
restrict_time = timedelta(minutes=randrange(10, 30))
admins = await api.get_chat_administrators(message.chat.id)

privileges = None
for admin in admins:
if admin.user.id == message.user.id:
privileges = admin
break

restrict_text = None
restrict_user: Optional[User] = None
restrict_time = None

if not privileges or not (privileges.can_restrict_members or privileges.status.CREATOR):
restrict_user = message.user
restrict_time = timedelta(minutes=randrange(10, 30))
text_tmpl = choice(MuteMessages.ACCIDENT.value)
restrict_text = text_tmpl.format(
user=restrict_user.id,
name=restrict_user.readable_name,
time=restrict_time.total_seconds() // 60,
)

if not message.reply_to_message:
restrict_user = message.user
restrict_time = timedelta(minutes=randrange(10, 30))
text_tmpl = choice(MuteMessages.LOOSER.value)
restrict_text = text_tmpl.format(
looser_id=restrict_user.id,
looser_name=restrict_user.readable_name,
victim_id=message.reply_to_message.user.id,
victim_name=message.reply_to_message.user.readable_name,
time=restrict_time.total_seconds() // 60,
if (
not message.reply_to_message
or not privileges
or not privileges.status.CREATOR
or not privileges.can_restrict_members
):
await send_mute_request(
api=api,
message=message,
initiator=message.user,
restrict_user=message.user,
restrict_time=restrict_time,
)

if not restrict_user:
restrict_user = message.reply_to_message.user
return

try:
if not restrict_time:
restrict_time = timedelta(hours=int(args[0]))
restrict_time = timedelta(hours=int(args[0]))
except (ValueError, IndexError):
restrict_time = timedelta(minutes=randrange(10, 30))
text = (
f'🧐 <a href="tg://user?id={restrict_user.id}">{restrict_user.readable_name}</a> будет молчать ровно'
f" {restrict_time.total_seconds() // 60} минут"
)
await api.send_message(
chat_id=message.chat.id,
text=text,
reply_to_message_id=message.message_id,
)

try:
is_success = await api.restrict_chat_member(
chat_id=message.chat.id,
user_id=restrict_user.id,
permissions=RESTRICT_PERMISSION,
until_date=datetime.now(tz=timezone.utc) + restrict_time,
)
except ValueError:
is_success = False

if not restrict_text:
restrict_text = (
f'Пользователь <a href="tg://user?id={restrict_user.id}">{restrict_user.readable_name}</a> '
f"принял обет молчания"
)

if is_success:
await api.send_message(
chat_id=message.chat.id,
text=restrict_text,
)
return None
await api.send_message(
chat_id=message.chat.id,
text=f"Лапки коротковаты чтоб покарать "
f'<a href="tg://user?id={restrict_user.id}">{restrict_user.readable_name}</a>',
reply_to_message_id=message.message_id,
pass

await send_mute_request(
api=api,
message=message,
initiator=message.user,
restrict_user=message.reply_to_message.user,
restrict_time=restrict_time,
)
58 changes: 58 additions & 0 deletions chatushka/bot/matchers/admin/pin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from asyncio import sleep

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

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


@pin_matcher("pin")
async def pin_handler(
api: TelegramBotApi,
message: Message,
args: list[str],
) -> None:
if not message.reply_to_message:
await api.send_message(
chat_id=message.chat.id,
text="Для закрепа необходимо написать команду реплаем",
reply_to_message_id=message.message_id,
)

try:
pin_hours = int(args[0])
except (ValueError, IndexError):
pin_hours = None

_ = await api.pin_chat_message(
chat_id=message.chat.id,
message_id=message.reply_to_message.message_id,
)
if pin_hours:
await api.send_message(
chat_id=message.chat.id,
text="Через {} часа закреп будет убран",
reply_to_message_id=message.message_id,
)
await sleep(pin_hours * 60)
await api.unpin_chat_message(
chat_id=message.chat.id,
message_id=message.reply_to_message.message_id,
)


@pin_matcher("unpin")
async def unpin_handler(
api: TelegramBotApi,
message: Message,
) -> None:
await api.unpin_chat_message(
chat_id=message.chat.id,
message_id=message.reply_to_message.message_id,
)
Loading

0 comments on commit 19d2739

Please sign in to comment.