Skip to content

Commit

Permalink
customized messages && errors; updated readme.md (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
bralbral committed Sep 23, 2023
1 parent 179ddb2 commit d56f2bc
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 15 deletions.
2 changes: 2 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Admin can answer to message by reply. The answer will be sent to the person who

If the transfer is successful, the administrator will be notified.

You can [customize the bot's responses](./deploy/example.config.yaml#12), or use default values.

## Deploy

### Install from source
Expand Down
28 changes: 27 additions & 1 deletion deploy/example.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,30 @@ bot:
token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# chat id for redirect messages
chat_id: -100XXXXXXXXXXXXX
chat_id: -100XXXXXXXXXXXXX

# Fill variables below as you want, or use default values.
# You can use HTML tags provided by the sulguk package.
# https://github.com/Tishka17/sulguk#readme

#messages:
# notify_user_about_success_deliver: ✅ Please wait for response.
# help_message: |
# <h1>
# 👋 Hello!
# </h1>
# <p>
# I can redirect to recipient <b>text, audios, voice messages, images, files</b> to recipient.
# </p>
#
# <p>
# Just send your message and wait for a response!
# </p>
# notify_admin_about_success_answer: ✅ Answered.
#
#errors:
# unsupported_type: ❌ Unsupported message type.<br/>Please check <b>/help</b> command.
# too_long_message_text: ❌ Too long message text.
# too_long_message_caption: ❌ Too long message caption.
# copy_message: ❌ Error during copying
# extract_user_id: ❌ Error during extract_id
7 changes: 6 additions & 1 deletion src/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@
async def main() -> None:
config: Config = load_config(config_path=os.path.join(ROOT_DIR, "config.yaml"))

dp: Dispatcher = setup_dispatcher(logger=logger, chat_id=config.chat_id)
dp: Dispatcher = setup_dispatcher(
logger=logger,
chat_id=config.chat_id,
messages=config.messages,
errors=config.errors,
)
bot: Bot = await setup_bot(config=config.bot)

await logger.ainfo("Starting bot")
Expand Down
12 changes: 8 additions & 4 deletions src/bot/handlers/admins/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,30 @@

from .utils import extract_id
from src.bot.filters import FilterByChatID
from src.config import Errors
from src.config import Messages

router = Router(name="admins")


@router.message(FilterByChatID(), F.reply_to_message) # type: ignore
async def reply_to_user(message: Message, bot: Bot, **kwargs):
async def reply_to_user(
message: Message, bot: Bot, messages: Messages, errors: Errors, **kwargs
):
try:
user_id = extract_id(message.reply_to_message)
except ValueError as ex:
await message.reply(f"❌ Error during extract_id: {str(ex)}")
await message.reply(text=f"{errors.extract_user_id} {str(ex)}")
return

try:
await bot.copy_message(
from_chat_id=message.chat.id, chat_id=user_id, message_id=message.message_id
)
await message.reply(text="✅ Answered.")
await message.reply(text=messages.notify_admin_about_success_answer)

except TelegramAPIError as ex:
await message.reply(f"❌ Error during copying: {str(ex)}")
await message.reply(text=f"{errors.copy_message} {str(ex)}")


__all__ = ["router"]
8 changes: 5 additions & 3 deletions src/bot/handlers/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from aiogram.types import Message
from sulguk import SULGUK_PARSE_MODE

from src.constants import START_MESSAGE
from src.config import Messages

logger = structlog.stdlib.get_logger()
router = Router(name="misc")
Expand All @@ -13,9 +13,11 @@
@router.message(
Command("start", "help"),
) # type: ignore
async def start_help_handler(message: Message, **kwargs) -> None:
async def start_help_handler(message: Message, messages: Messages, **kwargs) -> None:
await message.answer(
START_MESSAGE, disable_web_page_preview=True, parse_mode=SULGUK_PARSE_MODE
messages.help_message,
disable_web_page_preview=True,
parse_mode=SULGUK_PARSE_MODE,
)


Expand Down
15 changes: 12 additions & 3 deletions src/bot/handlers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from aiogram.types import Message
from sulguk import SULGUK_PARSE_MODE

from src.config import Errors
from src.config import Messages

router = Router(name="users")


Expand All @@ -14,6 +17,8 @@ async def handle_user_message(
message: Message,
bot: Bot,
chat_id: int,
messages: Messages,
errors: Errors,
**kwargs,
):
if message.content_type not in (
Expand All @@ -26,7 +31,7 @@ async def handle_user_message(
ContentType.VOICE,
):
await message.reply(
text="❌ Unsupported message type.<br/>Please check <b>/help</b> command.",
text=errors.unsupported_type,
parse_mode=SULGUK_PARSE_MODE,
)

Expand All @@ -37,7 +42,7 @@ async def handle_user_message(

if message.text:
if len(message.text) > 4000:
await message.reply("❌ Too long message text")
await message.reply(text=errors.too_long_message_text)
return

message_text = f"<br/>#id{message.from_user.id}<br/>" + message.html_text
Expand All @@ -47,6 +52,10 @@ async def handle_user_message(
)

else:
if len(message.caption) > 1000:
await message.reply(text=errors.too_long_message_caption)
return

caption = message.caption if message.caption else ""
caption += f"<br/>#id{message.from_user.id}<br/>"

Expand All @@ -58,7 +67,7 @@ async def handle_user_message(
parse_mode=SULGUK_PARSE_MODE,
)

await message.reply(text="✅ Please wait for response.")
await message.reply(text=messages.notify_user_about_success_deliver)

return

Expand Down
8 changes: 7 additions & 1 deletion src/bot/utils/setup_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@

from src.bot.handlers import register_handlers
from src.bot.middlewares import LoggerMiddleware
from src.config import Errors
from src.config import Messages


def setup_dispatcher(logger: BoundLogger, chat_id: int) -> Dispatcher:
def setup_dispatcher(
logger: BoundLogger, chat_id: int, messages: Messages, errors: Errors
) -> Dispatcher:
dp: Dispatcher = Dispatcher(
storage=MemoryStorage(),
logger=logger,
chat_id=chat_id,
messages=messages,
errors=errors,
events_isolation=SimpleEventIsolation(),
)
dp.message.middleware(LoggerMiddleware(logger=logger))
Expand Down
5 changes: 3 additions & 2 deletions src/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from .models import BotConfig
from .models import Config
from .utils import load_config
from src.config.models import Errors
from src.config.models import Messages


__all__ = ["BotConfig", "Config", "load_config"]
__all__ = ["BotConfig", "Config", "Errors", "Messages", "load_config"]
34 changes: 34 additions & 0 deletions src/config/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from pydantic import Field
from pydantic import SecretStr
from pydantic_settings import BaseSettings

Expand All @@ -10,13 +11,46 @@ class BotConfig(BaseSettings):
token: SecretStr


class Messages(BaseSettings):
notify_user_about_success_deliver: str = Field(
default="✅ Please wait for response."
)
help_message: str = Field(
default="""
<h1>
👋 Hello!
</h1>
<p>
I can redirect to recipient <b>text, audios, voice messages, images, files</b> to recipient.
</p>
<p>
Just send your message and wait for a response!
</p>
"""
)
notify_admin_about_success_answer: str = Field(default="✅ Answered.")


class Errors(BaseSettings):
unsupported_type: str = Field(
default="❌ Unsupported message type.<br/>Please check <b>/help</b> command."
)
too_long_message_text: str = Field(default="❌ Too long message text.")
too_long_message_caption: str = Field(default="❌ Too long message caption.")
copy_message: str = Field(default="❌ Error during copying")
extract_user_id: str = Field(default="❌ Error during extract_id")


class Config(BaseSettings):
"""
All in one config
"""

bot: BotConfig
chat_id: int
messages: Messages = Messages()
errors: Errors = Errors()


__all__ = ["BotConfig", "Config"]

0 comments on commit d56f2bc

Please sign in to comment.