Refactor project structure and enhance Docker configuration
- Updated `.dockerignore` to exclude test and development artifacts, optimizing the Docker image size. - Refactored `main.py` to delegate execution to `duty_teller.run.main()`, simplifying the entry point. - Introduced a new `duty_teller` package to encapsulate core functionality, improving modularity and organization. - Enhanced `pyproject.toml` to define a script for running the application, streamlining the execution process. - Updated README documentation to reflect changes in project structure and usage instructions. - Improved Alembic environment configuration to utilize the new package structure for database migrations.
This commit is contained in:
17
duty_teller/handlers/__init__.py
Normal file
17
duty_teller/handlers/__init__.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""Expose a single register_handlers(app) that registers all handlers."""
|
||||
|
||||
from telegram.ext import Application
|
||||
|
||||
from . import commands, errors, group_duty_pin, import_duty_schedule
|
||||
|
||||
|
||||
def register_handlers(app: Application) -> None:
|
||||
app.add_handler(commands.start_handler)
|
||||
app.add_handler(commands.help_handler)
|
||||
app.add_handler(commands.set_phone_handler)
|
||||
app.add_handler(import_duty_schedule.import_duty_schedule_handler)
|
||||
app.add_handler(import_duty_schedule.handover_time_handler)
|
||||
app.add_handler(import_duty_schedule.duty_schedule_document_handler)
|
||||
app.add_handler(group_duty_pin.group_duty_pin_handler)
|
||||
app.add_handler(group_duty_pin.pin_duty_handler)
|
||||
app.add_error_handler(errors.error_handler)
|
||||
94
duty_teller/handlers/commands.py
Normal file
94
duty_teller/handlers/commands.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""Command handlers: /start, /help; /start registers user."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import duty_teller.config as config
|
||||
from telegram import Update
|
||||
from telegram.ext import CommandHandler, ContextTypes
|
||||
|
||||
from duty_teller.db.session import session_scope
|
||||
from duty_teller.db.repository import get_or_create_user, set_user_phone
|
||||
from duty_teller.utils.user import build_full_name
|
||||
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message:
|
||||
return
|
||||
user = update.effective_user
|
||||
if not user:
|
||||
return
|
||||
full_name = build_full_name(user.first_name, user.last_name)
|
||||
telegram_user_id = user.id
|
||||
username = user.username
|
||||
first_name = user.first_name
|
||||
last_name = user.last_name
|
||||
|
||||
def do_get_or_create() -> None:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
get_or_create_user(
|
||||
session,
|
||||
telegram_user_id=telegram_user_id,
|
||||
full_name=full_name,
|
||||
username=username,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
)
|
||||
|
||||
await asyncio.get_running_loop().run_in_executor(None, do_get_or_create)
|
||||
|
||||
text = "Привет! Я бот календаря дежурств. Используй /help для списка команд."
|
||||
await update.message.reply_text(text)
|
||||
|
||||
|
||||
async def set_phone(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message or not update.effective_user:
|
||||
return
|
||||
if update.effective_chat and update.effective_chat.type != "private":
|
||||
await update.message.reply_text("Команда /set_phone доступна только в личке.")
|
||||
return
|
||||
args = context.args or []
|
||||
phone = " ".join(args).strip() if args else None
|
||||
telegram_user_id = update.effective_user.id
|
||||
|
||||
def do_set_phone() -> str:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
full_name = build_full_name(
|
||||
update.effective_user.first_name, update.effective_user.last_name
|
||||
)
|
||||
get_or_create_user(
|
||||
session,
|
||||
telegram_user_id=telegram_user_id,
|
||||
full_name=full_name,
|
||||
username=update.effective_user.username,
|
||||
first_name=update.effective_user.first_name,
|
||||
last_name=update.effective_user.last_name,
|
||||
)
|
||||
user = set_user_phone(session, telegram_user_id, phone or None)
|
||||
if user is None:
|
||||
return "Ошибка сохранения."
|
||||
if phone:
|
||||
return f"Телефон сохранён: {phone}"
|
||||
return "Телефон очищен."
|
||||
|
||||
result = await asyncio.get_running_loop().run_in_executor(None, do_set_phone)
|
||||
await update.message.reply_text(result)
|
||||
|
||||
|
||||
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message or not update.effective_user:
|
||||
return
|
||||
lines = [
|
||||
"Доступные команды:",
|
||||
"/start — Начать",
|
||||
"/help — Показать эту справку",
|
||||
"/set_phone — Указать или очистить телефон для отображения в дежурстве",
|
||||
"/pin_duty — В группе: закрепить сообщение о дежурстве (нужны права админа у бота)",
|
||||
]
|
||||
if config.is_admin(update.effective_user.username or ""):
|
||||
lines.append("/import_duty_schedule — Импорт расписания дежурств (JSON)")
|
||||
await update.message.reply_text("\n".join(lines))
|
||||
|
||||
|
||||
start_handler = CommandHandler("start", start)
|
||||
help_handler = CommandHandler("help", help_cmd)
|
||||
set_phone_handler = CommandHandler("set_phone", set_phone)
|
||||
16
duty_teller/handlers/errors.py
Normal file
16
duty_teller/handlers/errors.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""Global error handler: log exception and notify user."""
|
||||
|
||||
import logging
|
||||
|
||||
from telegram import Update
|
||||
from telegram.ext import ContextTypes
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def error_handler(
|
||||
update: Update | None, context: ContextTypes.DEFAULT_TYPE
|
||||
) -> None:
|
||||
logger.exception("Exception while handling an update")
|
||||
if isinstance(update, Update) and update.effective_message:
|
||||
await update.effective_message.reply_text("Произошла ошибка. Попробуйте позже.")
|
||||
225
duty_teller/handlers/group_duty_pin.py
Normal file
225
duty_teller/handlers/group_duty_pin.py
Normal file
@@ -0,0 +1,225 @@
|
||||
"""Pinned duty message in groups: handle bot add/remove, schedule updates at shift end."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import duty_teller.config as config
|
||||
from telegram import Update
|
||||
from telegram.constants import ChatMemberStatus
|
||||
from telegram.error import BadRequest, Forbidden
|
||||
from telegram.ext import ChatMemberHandler, CommandHandler, ContextTypes
|
||||
|
||||
from duty_teller.db.session import session_scope
|
||||
from duty_teller.services.group_duty_pin_service import (
|
||||
get_duty_message_text,
|
||||
get_next_shift_end_utc,
|
||||
save_pin,
|
||||
delete_pin,
|
||||
get_message_id,
|
||||
get_all_pin_chat_ids,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
JOB_NAME_PREFIX = "duty_pin_"
|
||||
RETRY_WHEN_NO_DUTY_MINUTES = 15
|
||||
|
||||
|
||||
def _get_duty_message_text_sync() -> str:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
return get_duty_message_text(session, config.DUTY_DISPLAY_TZ)
|
||||
|
||||
|
||||
def _get_next_shift_end_sync():
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
return get_next_shift_end_utc(session)
|
||||
|
||||
|
||||
def _sync_save_pin(chat_id: int, message_id: int) -> None:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
save_pin(session, chat_id, message_id)
|
||||
|
||||
|
||||
def _sync_delete_pin(chat_id: int) -> None:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
delete_pin(session, chat_id)
|
||||
|
||||
|
||||
def _sync_get_message_id(chat_id: int) -> int | None:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
return get_message_id(session, chat_id)
|
||||
|
||||
|
||||
async def _schedule_next_update(
|
||||
application, chat_id: int, when_utc: datetime | None
|
||||
) -> None:
|
||||
job_queue = application.job_queue
|
||||
if job_queue is None:
|
||||
logger.warning("Job queue not available, cannot schedule pin update")
|
||||
return
|
||||
name = f"{JOB_NAME_PREFIX}{chat_id}"
|
||||
for job in job_queue.get_jobs_by_name(name):
|
||||
job.schedule_removal()
|
||||
if when_utc is not None:
|
||||
now_utc = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
delay = when_utc - now_utc
|
||||
if delay.total_seconds() < 1:
|
||||
delay = 1
|
||||
job_queue.run_once(
|
||||
update_group_pin,
|
||||
when=delay,
|
||||
data={"chat_id": chat_id},
|
||||
name=name,
|
||||
)
|
||||
logger.info("Scheduled pin update for chat_id=%s at %s", chat_id, when_utc)
|
||||
else:
|
||||
from datetime import timedelta
|
||||
|
||||
job_queue.run_once(
|
||||
update_group_pin,
|
||||
when=timedelta(minutes=RETRY_WHEN_NO_DUTY_MINUTES),
|
||||
data={"chat_id": chat_id},
|
||||
name=name,
|
||||
)
|
||||
logger.info(
|
||||
"No next shift for chat_id=%s; scheduled retry in %s min",
|
||||
chat_id,
|
||||
RETRY_WHEN_NO_DUTY_MINUTES,
|
||||
)
|
||||
|
||||
|
||||
async def update_group_pin(context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
chat_id = context.job.data.get("chat_id")
|
||||
if chat_id is None:
|
||||
return
|
||||
loop = asyncio.get_running_loop()
|
||||
message_id = await loop.run_in_executor(None, _sync_get_message_id, chat_id)
|
||||
if message_id is None:
|
||||
logger.info("No pin record for chat_id=%s, skipping update", chat_id)
|
||||
return
|
||||
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
|
||||
try:
|
||||
await context.bot.edit_message_text(
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
text=text,
|
||||
)
|
||||
except (BadRequest, Forbidden) as e:
|
||||
logger.warning("Failed to edit pinned message chat_id=%s: %s", chat_id, e)
|
||||
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
|
||||
await _schedule_next_update(context.application, chat_id, next_end)
|
||||
|
||||
|
||||
async def my_chat_member_handler(
|
||||
update: Update, context: ContextTypes.DEFAULT_TYPE
|
||||
) -> None:
|
||||
if not update.my_chat_member or not update.effective_user:
|
||||
return
|
||||
old = update.my_chat_member.old_chat_member
|
||||
new = update.my_chat_member.new_chat_member
|
||||
chat = update.effective_chat
|
||||
if not chat or chat.type not in ("group", "supergroup"):
|
||||
return
|
||||
if new.user.id != context.bot.id:
|
||||
return
|
||||
chat_id = chat.id
|
||||
|
||||
if new.status in (
|
||||
ChatMemberStatus.MEMBER,
|
||||
ChatMemberStatus.ADMINISTRATOR,
|
||||
) and old.status in (
|
||||
ChatMemberStatus.LEFT,
|
||||
ChatMemberStatus.BANNED,
|
||||
):
|
||||
loop = asyncio.get_running_loop()
|
||||
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
|
||||
try:
|
||||
msg = await context.bot.send_message(chat_id=chat_id, text=text)
|
||||
except (BadRequest, Forbidden) as e:
|
||||
logger.warning("Failed to send duty message in chat_id=%s: %s", chat_id, e)
|
||||
return
|
||||
pinned = False
|
||||
try:
|
||||
await context.bot.pin_chat_message(
|
||||
chat_id=chat_id,
|
||||
message_id=msg.message_id,
|
||||
disable_notification=True,
|
||||
)
|
||||
pinned = True
|
||||
except (BadRequest, Forbidden) as e:
|
||||
logger.warning("Failed to pin message in chat_id=%s: %s", chat_id, e)
|
||||
await loop.run_in_executor(None, _sync_save_pin, chat_id, msg.message_id)
|
||||
if not pinned:
|
||||
try:
|
||||
await context.bot.send_message(
|
||||
chat_id=chat_id,
|
||||
text="Сообщение о дежурстве отправлено, но закрепить его не удалось. "
|
||||
"Сделайте бота администратором с правом «Закреплять сообщения» (Pin messages), "
|
||||
"затем отправьте в чат команду /pin_duty — текущее сообщение будет закреплено.",
|
||||
)
|
||||
except (BadRequest, Forbidden):
|
||||
pass
|
||||
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
|
||||
await _schedule_next_update(context.application, chat_id, next_end)
|
||||
return
|
||||
|
||||
if new.status in (ChatMemberStatus.LEFT, ChatMemberStatus.BANNED):
|
||||
await asyncio.get_running_loop().run_in_executor(
|
||||
None, _sync_delete_pin, chat_id
|
||||
)
|
||||
name = f"{JOB_NAME_PREFIX}{chat_id}"
|
||||
if context.application.job_queue:
|
||||
for job in context.application.job_queue.get_jobs_by_name(name):
|
||||
job.schedule_removal()
|
||||
logger.info("Bot left chat_id=%s, removed pin record and jobs", chat_id)
|
||||
|
||||
|
||||
def _get_all_pin_chat_ids_sync() -> list[int]:
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
return get_all_pin_chat_ids(session)
|
||||
|
||||
|
||||
async def restore_group_pin_jobs(application) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
chat_ids = await loop.run_in_executor(None, _get_all_pin_chat_ids_sync)
|
||||
for chat_id in chat_ids:
|
||||
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
|
||||
await _schedule_next_update(application, chat_id, next_end)
|
||||
logger.info("Restored %s group pin jobs", len(chat_ids))
|
||||
|
||||
|
||||
async def pin_duty_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
if not update.message or not update.effective_chat:
|
||||
return
|
||||
chat = update.effective_chat
|
||||
if chat.type not in ("group", "supergroup"):
|
||||
await update.message.reply_text("Команда /pin_duty работает только в группах.")
|
||||
return
|
||||
chat_id = chat.id
|
||||
loop = asyncio.get_running_loop()
|
||||
message_id = await loop.run_in_executor(None, _sync_get_message_id, chat_id)
|
||||
if message_id is None:
|
||||
await update.message.reply_text(
|
||||
"В этом чате ещё нет сообщения о дежурстве. Добавьте бота в группу — оно создастся автоматически."
|
||||
)
|
||||
return
|
||||
try:
|
||||
await context.bot.pin_chat_message(
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
disable_notification=True,
|
||||
)
|
||||
await update.message.reply_text("Сообщение о дежурстве закреплено.")
|
||||
except (BadRequest, Forbidden) as e:
|
||||
logger.warning("pin_duty failed chat_id=%s: %s", chat_id, e)
|
||||
await update.message.reply_text(
|
||||
"Не удалось закрепить. Убедитесь, что бот — администратор с правом «Закреплять сообщения»."
|
||||
)
|
||||
|
||||
|
||||
group_duty_pin_handler = ChatMemberHandler(
|
||||
my_chat_member_handler,
|
||||
ChatMemberHandler.MY_CHAT_MEMBER,
|
||||
)
|
||||
pin_duty_handler = CommandHandler("pin_duty", pin_duty_cmd)
|
||||
119
duty_teller/handlers/import_duty_schedule.py
Normal file
119
duty_teller/handlers/import_duty_schedule.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Import duty-schedule: /import_duty_schedule (admin only). Two steps: handover time -> JSON file."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import duty_teller.config as config
|
||||
from telegram import Update
|
||||
from telegram.ext import CommandHandler, ContextTypes, MessageHandler, filters
|
||||
|
||||
from duty_teller.db.session import session_scope
|
||||
from duty_teller.importers.duty_schedule import (
|
||||
DutyScheduleParseError,
|
||||
parse_duty_schedule,
|
||||
)
|
||||
from duty_teller.services.import_service import run_import
|
||||
from duty_teller.utils.handover import parse_handover_time
|
||||
|
||||
|
||||
async def import_duty_schedule_cmd(
|
||||
update: Update, context: ContextTypes.DEFAULT_TYPE
|
||||
) -> None:
|
||||
if not update.message or not update.effective_user:
|
||||
return
|
||||
if not config.is_admin(update.effective_user.username or ""):
|
||||
await update.message.reply_text("Доступ только для администраторов.")
|
||||
return
|
||||
context.user_data["awaiting_handover_time"] = True
|
||||
await update.message.reply_text(
|
||||
"Укажите время пересменки в формате ЧЧ:ММ и часовой пояс, "
|
||||
"например 09:00 Europe/Moscow или 06:00 UTC."
|
||||
)
|
||||
|
||||
|
||||
async def handle_handover_time_text(
|
||||
update: Update, context: ContextTypes.DEFAULT_TYPE
|
||||
) -> None:
|
||||
if not update.message or not update.effective_user or not update.message.text:
|
||||
return
|
||||
if not context.user_data.get("awaiting_handover_time"):
|
||||
return
|
||||
if not config.is_admin(update.effective_user.username or ""):
|
||||
return
|
||||
text = update.message.text.strip()
|
||||
parsed = parse_handover_time(text)
|
||||
if parsed is None:
|
||||
await update.message.reply_text(
|
||||
"Не удалось разобрать время. Укажите, например: 09:00 Europe/Moscow"
|
||||
)
|
||||
return
|
||||
hour_utc, minute_utc = parsed
|
||||
context.user_data["handover_utc_time"] = (hour_utc, minute_utc)
|
||||
context.user_data["awaiting_handover_time"] = False
|
||||
context.user_data["awaiting_duty_schedule_file"] = True
|
||||
await update.message.reply_text("Отправьте файл в формате duty-schedule (JSON).")
|
||||
|
||||
|
||||
async def handle_duty_schedule_document(
|
||||
update: Update, context: ContextTypes.DEFAULT_TYPE
|
||||
) -> None:
|
||||
if not update.message or not update.message.document or not update.effective_user:
|
||||
return
|
||||
if not context.user_data.get("awaiting_duty_schedule_file"):
|
||||
return
|
||||
handover = context.user_data.get("handover_utc_time")
|
||||
if not handover or not config.is_admin(update.effective_user.username or ""):
|
||||
return
|
||||
if not (update.message.document.file_name or "").lower().endswith(".json"):
|
||||
await update.message.reply_text("Нужен файл с расширением .json")
|
||||
return
|
||||
|
||||
hour_utc, minute_utc = handover
|
||||
file_id = update.message.document.file_id
|
||||
|
||||
file = await context.bot.get_file(file_id)
|
||||
raw = bytes(await file.download_as_bytearray())
|
||||
try:
|
||||
result = parse_duty_schedule(raw)
|
||||
except DutyScheduleParseError as e:
|
||||
context.user_data.pop("awaiting_duty_schedule_file", None)
|
||||
context.user_data.pop("handover_utc_time", None)
|
||||
await update.message.reply_text(f"Ошибка разбора файла: {e}")
|
||||
return
|
||||
|
||||
def run_import_with_scope():
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
return run_import(session, result, hour_utc, minute_utc)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
num_users, num_duty, num_unavailable, num_vacation = await loop.run_in_executor(
|
||||
None, run_import_with_scope
|
||||
)
|
||||
except Exception as e:
|
||||
await update.message.reply_text(f"Ошибка импорта: {e}")
|
||||
else:
|
||||
total = num_duty + num_unavailable + num_vacation
|
||||
parts = [f"{num_users} пользователей", f"{num_duty} дежурств"]
|
||||
if num_unavailable:
|
||||
parts.append(f"{num_unavailable} недоступностей")
|
||||
if num_vacation:
|
||||
parts.append(f"{num_vacation} отпусков")
|
||||
await update.message.reply_text(
|
||||
"Импорт выполнен: " + ", ".join(parts) + f" (всего {total} событий)."
|
||||
)
|
||||
finally:
|
||||
context.user_data.pop("awaiting_duty_schedule_file", None)
|
||||
context.user_data.pop("handover_utc_time", None)
|
||||
|
||||
|
||||
import_duty_schedule_handler = CommandHandler(
|
||||
"import_duty_schedule", import_duty_schedule_cmd
|
||||
)
|
||||
handover_time_handler = MessageHandler(
|
||||
filters.TEXT & ~filters.COMMAND,
|
||||
handle_handover_time_text,
|
||||
)
|
||||
duty_schedule_document_handler = MessageHandler(
|
||||
filters.Document.FileExtension("json"),
|
||||
handle_duty_schedule_document,
|
||||
)
|
||||
Reference in New Issue
Block a user