Files

258 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from aiogram import types
from aiogram.utils.keyboard import InlineKeyboardBuilder, ReplyKeyboardBuilder
# Local imports - metrics
from helper_bot.utils.metrics import track_errors, track_time
def get_reply_keyboard_for_post():
builder = InlineKeyboardBuilder()
builder.row(
types.InlineKeyboardButton(text="Опубликовать", callback_data="publish"),
types.InlineKeyboardButton(text="Отклонить", callback_data="decline"),
)
builder.row(types.InlineKeyboardButton(text="👮‍♂️ Забанить", callback_data="ban"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
async def get_reply_keyboard(db, user_id):
builder = ReplyKeyboardBuilder()
builder.row(types.KeyboardButton(text="📢Предложить свой пост"))
builder.row(types.KeyboardButton(text="📩Связаться с админами"))
builder.row(types.KeyboardButton(text=" 🎤Голосовой бот"))
builder.row(types.KeyboardButton(text="👋🏼Сказать пока!"))
if not await db.get_stickers_info(user_id):
builder.row(types.KeyboardButton(text="🤪Хочу стикеры"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def get_reply_keyboard_leave_chat():
builder = ReplyKeyboardBuilder()
builder.add(types.KeyboardButton(text="Выйти из чата"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def get_reply_keyboard_admin():
builder = ReplyKeyboardBuilder()
builder.row(
types.KeyboardButton(text="Бан (Список)"),
types.KeyboardButton(text="Бан по нику"),
types.KeyboardButton(text="Бан по ID"),
)
builder.row(
types.KeyboardButton(text="Разбан (список)"),
types.KeyboardButton(text="📊 ML Статистика"),
)
builder.row(types.KeyboardButton(text="⚙️ Авто-модерация"))
builder.row(types.KeyboardButton(text="Вернуться в бота"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def get_auto_moderation_keyboard(settings: dict) -> types.InlineKeyboardMarkup:
"""
Создает inline клавиатуру для управления авто-модерацией.
Args:
settings: Словарь с текущими настройками авто-модерации
Returns:
InlineKeyboardMarkup с кнопками управления
"""
builder = InlineKeyboardBuilder()
auto_publish = settings.get("auto_publish_enabled", False)
auto_decline = settings.get("auto_decline_enabled", False)
publish_threshold = settings.get("auto_publish_threshold", 0.8)
decline_threshold = settings.get("auto_decline_threshold", 0.4)
publish_status = "" if auto_publish else ""
decline_status = "" if auto_decline else ""
builder.row(
types.InlineKeyboardButton(
text=f"{publish_status} Авто-публикация (≥{publish_threshold})",
callback_data="auto_mod_toggle_publish",
)
)
builder.row(
types.InlineKeyboardButton(
text=f"{decline_status} Авто-отклонение (≤{decline_threshold})",
callback_data="auto_mod_toggle_decline",
)
)
builder.row(
types.InlineKeyboardButton(
text="📈 Изменить порог публикации",
callback_data="auto_mod_threshold_publish",
),
types.InlineKeyboardButton(
text="📉 Изменить порог отклонения",
callback_data="auto_mod_threshold_decline",
),
)
builder.row(
types.InlineKeyboardButton(
text="🔄 Обновить",
callback_data="auto_mod_refresh",
)
)
return builder.as_markup()
@track_time("create_keyboard_with_pagination", "keyboard_service")
@track_errors("keyboard_service", "create_keyboard_with_pagination")
def create_keyboard_with_pagination(
page: int, total_items: int, array_items: list, callback: str
):
"""
Создает клавиатуру с пагинацией для заданного набора элементов и устанавливает необходимый callback
Args:
page: Номер текущей страницы (начинается с 1).
total_items: Общее количество элементов.
array_items: Лист кортежей. Содержит в себе user_name: user_id
callback: Действие в коллбеке. Вернет callback вида ({callback}_{user_id})
Returns:
InlineKeyboardMarkup: Клавиатура с кнопками пагинации.
"""
# Проверяем валидность входных данных
if page < 1:
page = 1
if not array_items:
# Если нет элементов, возвращаем только кнопку "Назад"
keyboard = InlineKeyboardBuilder()
home_button = types.InlineKeyboardButton(
text="🏠 Назад", callback_data="return"
)
keyboard.row(home_button)
return keyboard.as_markup()
# Определяем общее количество страниц
items_per_page = 9
total_pages = (total_items + items_per_page - 1) // items_per_page
# Ограничиваем страницу максимальным значением
if page > total_pages:
page = total_pages
# Создаем билдер для клавиатуры
keyboard = InlineKeyboardBuilder()
# Вычисляем стартовый номер для текущей страницы
start_index = (page - 1) * items_per_page
# Кнопки с элементами текущей страницы
end_index = min(start_index + items_per_page, len(array_items))
current_row = []
for i in range(start_index, end_index):
current_row.append(
types.InlineKeyboardButton(
text=f"{array_items[i][0]}",
callback_data=f"{callback}_{array_items[i][1]}",
)
)
# Когда набирается 3 кнопки, добавляем ряд
if len(current_row) == 3:
keyboard.row(*current_row)
current_row = []
# Добавляем оставшиеся кнопки, если они есть
if current_row:
keyboard.row(*current_row)
# Создаем кнопки навигации только если нужно
navigation_buttons = []
# Кнопка "Предыдущая" - показываем только если не первая страница
if page > 1:
prev_button = types.InlineKeyboardButton(
text="⬅️ Предыдущая", callback_data=f"page_{page - 1}"
)
navigation_buttons.append(prev_button)
# Кнопка "Следующая" - показываем только если не последняя страница
if page < total_pages:
next_button = types.InlineKeyboardButton(
text="➡️ Следующая", callback_data=f"page_{page + 1}"
)
navigation_buttons.append(next_button)
# Добавляем кнопки навигации, если они есть
if navigation_buttons:
keyboard.row(*navigation_buttons)
# Кнопка "Назад"
home_button = types.InlineKeyboardButton(text="🏠 Назад", callback_data="return")
keyboard.row(home_button)
return keyboard.as_markup()
def create_keyboard_for_ban_reason():
builder = ReplyKeyboardBuilder()
builder.add(types.KeyboardButton(text="Спам"))
builder.add(types.KeyboardButton(text="Заебал стикерами"))
builder.row(types.KeyboardButton(text="Реклама здесь: @kerrad1 "))
builder.row(
types.KeyboardButton(
text="Тема с лагерями: https://vk.com/topic-75343895_50049913"
)
)
builder.row(types.KeyboardButton(text="Отменить"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def create_keyboard_for_ban_days():
builder = ReplyKeyboardBuilder()
builder.add(types.KeyboardButton(text="1"))
builder.add(types.KeyboardButton(text="7"))
builder.add(types.KeyboardButton(text="30"))
builder.row(types.KeyboardButton(text="Навсегда"))
builder.row(types.KeyboardButton(text="Отменить"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def create_keyboard_for_approve_ban():
builder = ReplyKeyboardBuilder()
builder.add(types.KeyboardButton(text="Подтвердить"))
builder.add(types.KeyboardButton(text="Отменить"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup
def get_main_keyboard():
builder = ReplyKeyboardBuilder()
# Первая строка: Высказаться и послушать
builder.row(
types.KeyboardButton(text="🎤Высказаться"),
types.KeyboardButton(text="🎧Послушать"),
)
# Вторая строка: сбросить прослушивания и узнать эмодзи
builder.row(
types.KeyboardButton(text="🔄Сбросить прослушивания"),
types.KeyboardButton(text="😊Узнать эмодзи"),
)
# Третья строка: Вернуться в меню
builder.row(types.KeyboardButton(text="Отменить"))
markup = builder.as_markup(resize_keyboard=True)
return markup
def get_reply_keyboard_for_voice():
builder = InlineKeyboardBuilder()
builder.row(types.InlineKeyboardButton(text="Сохранить", callback_data="save"))
builder.row(types.InlineKeyboardButton(text="Удалить", callback_data="delete"))
markup = builder.as_markup(resize_keyboard=True, one_time_keyboard=True)
return markup