160 lines
6.8 KiB
Python
160 lines
6.8 KiB
Python
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, Bot
|
||
from telegram.ext import CommandHandler, MessageHandler, filters, CallbackContext, ContextTypes
|
||
from telegram.error import TelegramError
|
||
from utils.logger import logger
|
||
from utils.user_data import get_user_info
|
||
from utils.admin_utils import is_admin
|
||
from utils.message_sender import send_message
|
||
from utils.admin_utils import ADMINS, count_memorial_notes, has_records
|
||
from utils.database import USER_DATA, save_database
|
||
from utils.formating import format_names
|
||
from telegram.error import BadRequest
|
||
|
||
# Новая функция для админов
|
||
|
||
admin_keyboard = InlineKeyboardMarkup([
|
||
[InlineKeyboardButton("О здравии", callback_data='admin_life'),
|
||
InlineKeyboardButton("За упокой", callback_data='admin_dead')],
|
||
[InlineKeyboardButton("Статистика", callback_data='admin_stats')]
|
||
])
|
||
|
||
admin_view_keyboard = InlineKeyboardMarkup([
|
||
[InlineKeyboardButton("Прочитано", callback_data='admin_done')],
|
||
[InlineKeyboardButton("Предидущее", callback_data='admin_prev'),
|
||
InlineKeyboardButton("Следующее", callback_data='admin_next')],
|
||
[InlineKeyboardButton("Закрыть", callback_data='admin_close')]
|
||
])
|
||
|
||
async def get_chat_members(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
chat_id = update.effective_chat.id
|
||
try:
|
||
async for member in context.bot.get_chat_members(chat_id):
|
||
logger.info(f"Пользователь: {member.user.username} - {member.user.first_name} {member.user.last_name}")
|
||
except Exception as e:
|
||
logger.error(f"Ошибка при получении участников: {e}")
|
||
|
||
|
||
|
||
async def remove_notes(update: Update, context: CallbackContext)-> None:
|
||
global USER_DATA
|
||
logger.info("Функция удаления записки вызвана")
|
||
if 'typer' in context.user_data:
|
||
typer = context.user_data['typer']
|
||
logger.info("Тип записки есть")
|
||
if 'current' in context.user_data:
|
||
logger.info("Номер записки есть")
|
||
current = context.user_data['current']
|
||
idlist=list(USER_DATA)
|
||
id_list=[]
|
||
for user_id in idlist:
|
||
if typer in USER_DATA[user_id]:
|
||
id_list.append(user_id)
|
||
if not id_list:
|
||
send_message(update, context, "Нет записей")
|
||
return
|
||
id=id_list[current]
|
||
if typer in USER_DATA[id]:
|
||
message = f"✅ Ваша записка \"{typer}\" прочитана"
|
||
logger.info(message)
|
||
await send_message(update, context, message, chat_id = int(id))
|
||
del USER_DATA[id][typer]
|
||
save_database(USER_DATA)
|
||
else:
|
||
logger.info("Номер записки не задан")
|
||
else:
|
||
logger.info("Тип записки не задан")
|
||
|
||
async def get_members_count(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
chat_id = update.effective_chat.id
|
||
try:
|
||
count = await context.bot.get_chat_members_count(chat_id)
|
||
logger.info(f"Количество пользователей бота: {count}")
|
||
except Exception as e:
|
||
logger.error(f"Ошибка при получении количества участников: {e}")
|
||
|
||
async def admin_start(update: Update, context: CallbackContext) -> None: # handlers/admin_handlers.py
|
||
user_info = await get_user_info(update, context)
|
||
|
||
|
||
if is_admin(user_info["id"]):
|
||
user_name = user_info["name"]
|
||
await send_message(update, context, f"Здравствуйте, админ {user_name}!")
|
||
await send_message(update, context, "Это админ-панель")
|
||
await notify_admins(update, context)
|
||
await send_message(update, context, "Выберите действие:",reply_markup=admin_keyboard)
|
||
|
||
async def admin_view(update: Update, context: CallbackContext) -> None:
|
||
global USER_DATA
|
||
if 'typer' not in context.user_data:
|
||
logger.error("Тип чтения записки не задан!")
|
||
return
|
||
else:
|
||
typer = context.user_data['typer']
|
||
idlist=list(USER_DATA)
|
||
id_list=[]
|
||
for user_id in idlist:
|
||
if typer in USER_DATA[user_id]:
|
||
id_list.append(user_id)
|
||
if not id_list:
|
||
send_message(update, context, "Нет записей")
|
||
return
|
||
if 'current' in context.user_data:
|
||
current=context.user_data['current']
|
||
else:
|
||
current=0
|
||
logger.info(f"Len of id_list: {len(id_list)}")
|
||
if len(id_list) <= current:
|
||
current = len(id_list) -1
|
||
id=id_list[current]
|
||
logger.info(f"ID of USER:{id}")
|
||
try:
|
||
cur = await context.bot.get_chat_member(update.effective_chat.id, id)
|
||
user = cur.user.username
|
||
except BadRequest as e:
|
||
if str(e) == "Member not found":
|
||
logger.error(f"Error by get_chat_member: {e}")
|
||
user = id
|
||
message=f"Пользователь @{user}\n"
|
||
if 'Комментарий' in USER_DATA[id]:
|
||
message+=f"<u>Комментарий:</u>\n"
|
||
message+=f"{USER_DATA[id]['Комментарий']}\n"
|
||
message+=f"<u>{typer}:</u>\n"
|
||
message+=f"{format_names(USER_DATA[id][typer],numbering_type='•')}\n"
|
||
await send_message(update, context, message, reply_markup=admin_view_keyboard)
|
||
|
||
async def notify_admins(update: Update, context: CallbackContext, current_user:int = 0):
|
||
global USER_DATA
|
||
get_users_count = len(USER_DATA) # Функция получения количества непрочитанных
|
||
unread_count = count_memorial_notes(USER_DATA)
|
||
if unread_count > 0:
|
||
for admin_id in ADMINS:
|
||
try:
|
||
message=""
|
||
if current_user != 0:
|
||
try:
|
||
cur = await context.bot.get_chat_member(update.effective_chat.id, current_user)
|
||
user = cur.user.username
|
||
except BadRequest as e:
|
||
if str(e) == "Member not found":
|
||
logger.error(f"Error by get_chat_member: {e}")
|
||
user = id
|
||
message=f"@{user} добавил записки.\n"
|
||
if str(current_user) in USER_DATA:
|
||
if "Комментарий" in USER_DATA[str(current_user)]:
|
||
message+=f"<u>Комментарий пользователя:</u>\n"
|
||
message+=f"{USER_DATA[str(current_user)]['Комментарий']}\n"
|
||
message+=f"⚠️ У вас {unread_count} непрочитанных записок\n"
|
||
message+=f"От {get_users_count} пользователей\n"
|
||
logger.info(f"Message: {message}")
|
||
await send_message(update, context, message, chat_id=admin_id)
|
||
except TelegramError as e:
|
||
logger.error(f"Ошибка отправки уведомления админу {admin_id}: {e}")
|
||
|
||
|
||
|
||
|
||
def register_handlers(app):
|
||
# Здесь можно добавить функционал админ-панели
|
||
app.add_handler(CommandHandler("admin", admin_start))
|
||
|