Template
mirror of
https://github.com/djimboy/djimbo_template_aio3.git
synced 2026-08-24 06:07:42 +00:00
Update
This commit is contained in:
@@ -7,19 +7,19 @@ from typing import Union
|
||||
|
||||
import pytz
|
||||
from aiogram import Bot
|
||||
from aiogram.types import InlineKeyboardButton, KeyboardButton, WebAppInfo, Message, InlineKeyboardMarkup, \
|
||||
ReplyKeyboardMarkup
|
||||
from aiogram.types import (InlineKeyboardButton, KeyboardButton, WebAppInfo, Message, InlineKeyboardMarkup,
|
||||
ReplyKeyboardMarkup)
|
||||
|
||||
from tgbot.data.config import get_admins, BOT_TIMEZONE
|
||||
|
||||
|
||||
######################################## AIOGRAM ########################################
|
||||
# Генерация реплай кнопки
|
||||
#################################### AIOGRAM ###################################
|
||||
# Generate replay button
|
||||
def rkb(text: str) -> KeyboardButton:
|
||||
return KeyboardButton(text=text)
|
||||
|
||||
|
||||
# Генерация инлайн кнопки
|
||||
# Generate inline button
|
||||
def ikb(text: str, data: str = None, url: str = None, switch: str = None, web: str = None) -> InlineKeyboardButton:
|
||||
if data is not None:
|
||||
return InlineKeyboardButton(text=text, callback_data=data)
|
||||
@@ -29,9 +29,11 @@ def ikb(text: str, data: str = None, url: str = None, switch: str = None, web: s
|
||||
return InlineKeyboardButton(text=text, switch_inline_query=switch)
|
||||
elif web is not None:
|
||||
return InlineKeyboardButton(text=text, web_app=WebAppInfo(url=web))
|
||||
else:
|
||||
raise "Unknown data"
|
||||
|
||||
|
||||
# Удаление сообщения с обработкой ошибки от телеграма
|
||||
# Deleting a message with error handling from Telegram
|
||||
async def del_message(message: Message):
|
||||
try:
|
||||
await message.delete()
|
||||
@@ -39,7 +41,7 @@ async def del_message(message: Message):
|
||||
...
|
||||
|
||||
|
||||
# Умная отправка сообщений (автоотправка сообщения с фото или без)
|
||||
# Smart messaging (automatic sending of messages with or without photos)
|
||||
async def smart_message(
|
||||
bot: Bot,
|
||||
user_id: int,
|
||||
@@ -62,7 +64,7 @@ async def smart_message(
|
||||
)
|
||||
|
||||
|
||||
# Отправка сообщения всем админам
|
||||
# Send a message to all administrators
|
||||
async def send_admins(bot: Bot, text: str, markup=None, not_me=0):
|
||||
for admin in get_admins():
|
||||
try:
|
||||
@@ -77,8 +79,8 @@ async def send_admins(bot: Bot, text: str, markup=None, not_me=0):
|
||||
...
|
||||
|
||||
|
||||
######################################## ПРОЧЕЕ ########################################
|
||||
# Удаление отступов в многострочной строке ("""text""")
|
||||
##################################### MISC #####################################
|
||||
# Removing indents in a multi-line string ("""text""")
|
||||
def ded(get_text: str) -> str:
|
||||
if get_text is not None:
|
||||
split_text = get_text.split("\n")
|
||||
@@ -98,7 +100,7 @@ def ded(get_text: str) -> str:
|
||||
return get_text
|
||||
|
||||
|
||||
# Очистка текста от HTML тэгов ('<b>test</b>' -> *b*test*/b*)
|
||||
# Cleaning text of HTML tags ('<b>test</b>' -> *b*test*/b*)
|
||||
def clear_html(get_text: str) -> str:
|
||||
if get_text is not None:
|
||||
if "</" in get_text: get_text = get_text.replace("<", "*")
|
||||
@@ -110,7 +112,7 @@ def clear_html(get_text: str) -> str:
|
||||
return get_text
|
||||
|
||||
|
||||
# Очистка пробелов в списке (['', 1, ' ', 2] -> [1, 2])
|
||||
# Cleaning up gaps in the list (['', 1, ' ', 2] -> [1, 2])
|
||||
def clear_list(get_list: list) -> list:
|
||||
while "" in get_list: get_list.remove("")
|
||||
while " " in get_list: get_list.remove(" ")
|
||||
@@ -122,12 +124,12 @@ def clear_list(get_list: list) -> list:
|
||||
return get_list
|
||||
|
||||
|
||||
# Разбив списка на несколько частей ([1, 2, 3, 4] 2 -> [[1, 2], [3, 4]])
|
||||
# Split the list into several parts ([1, 2, 3, 4] 2 -> [[1, 2], [3, 4]])
|
||||
def split_list(get_list: list, count: int) -> list[list]:
|
||||
return [get_list[i:i + count] for i in range(0, len(get_list), count)]
|
||||
|
||||
|
||||
# Получение текущей даты (True - дата с временем, False - дата без времени)
|
||||
# Get the current date (True - date with time, False - date without time)
|
||||
def get_date(full: bool = True) -> str:
|
||||
if full:
|
||||
return datetime.now(pytz.timezone(BOT_TIMEZONE)).strftime("%d.%m.%Y %H:%M:%S")
|
||||
@@ -135,7 +137,7 @@ def get_date(full: bool = True) -> str:
|
||||
return datetime.now(pytz.timezone(BOT_TIMEZONE)).strftime("%d.%m.%Y")
|
||||
|
||||
|
||||
# Получение текущего unix времени (True - время в наносекундах, False - время в секундах)
|
||||
# Get the current Unix time (True - time in nanoseconds, False - time in seconds)
|
||||
def get_unix(full: bool = False) -> int:
|
||||
if full:
|
||||
return time.time_ns()
|
||||
@@ -143,7 +145,7 @@ def get_unix(full: bool = False) -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
# Конвертация unix в дату и даты в unix
|
||||
# Converting Unix to date and dates to Unix
|
||||
def convert_date(from_time, full=True, second=True) -> Union[str, int]:
|
||||
from tgbot.data.config import BOT_TIMEZONE
|
||||
|
||||
@@ -194,7 +196,7 @@ def convert_date(from_time, full=True, second=True) -> Union[str, int]:
|
||||
return to_time
|
||||
|
||||
|
||||
# Генерация уникального айди
|
||||
# Generation of a unique ID
|
||||
def gen_id(len_id: int = 16) -> int:
|
||||
mac_address = uuid.getnode()
|
||||
time_unix = int(str(time.time_ns())[:len_id])
|
||||
@@ -203,8 +205,10 @@ def gen_id(len_id: int = 16) -> int:
|
||||
return mac_address + time_unix + random_int
|
||||
|
||||
|
||||
# Генерация пароля | default, number, letter, onechar
|
||||
# Password generation | default, number, letter, onechar
|
||||
def gen_password(len_password: int = 16, type_password: str = "default") -> str:
|
||||
char_password = list("1234567890abcdefghigklmnopqrstuvyxwzABCDEFGHIGKLMNOPQRSTUVYXWZ")
|
||||
|
||||
if type_password == "default":
|
||||
char_password = list("1234567890abcdefghigklmnopqrstuvyxwzABCDEFGHIGKLMNOPQRSTUVYXWZ")
|
||||
elif type_password == "letter":
|
||||
@@ -223,7 +227,7 @@ def gen_password(len_password: int = 16, type_password: str = "default") -> str:
|
||||
return random_chars
|
||||
|
||||
|
||||
# Дополнение к числу корректного времени (1 -> 1 день, 3 -> 3 дня)
|
||||
# Addition to the correct time (1 -> 1 day, 3 -> 3 days)
|
||||
def convert_times(get_time: int, get_type: str = "day") -> str:
|
||||
get_time = int(get_time)
|
||||
if get_time < 0: get_time = 0
|
||||
@@ -251,7 +255,7 @@ def convert_times(get_time: int, get_type: str = "day") -> str:
|
||||
return f"{get_time} {get_list[count]}"
|
||||
|
||||
|
||||
# Проверка на булевый тип
|
||||
# Boolean type check
|
||||
def is_bool(value: Union[bool, str, int]) -> bool:
|
||||
value = str(value).lower()
|
||||
|
||||
@@ -263,8 +267,8 @@ def is_bool(value: Union[bool, str, int]) -> bool:
|
||||
raise ValueError(f"invalid truth value {value}")
|
||||
|
||||
|
||||
######################################## ЧИСЛА ########################################
|
||||
# Преобразование экспоненциальных чисел в читаемый вид (1e-06 -> 0.000001)
|
||||
################################### NUMBERS ####################################
|
||||
# Converting exponential numbers to a readable form (1e-06 -> 0.000001)
|
||||
def snum(amount: Union[int, float], remains: int = 2) -> str:
|
||||
format_str = "{:." + str(remains) + "f}"
|
||||
str_amount = format_str.format(float(amount))
|
||||
@@ -284,7 +288,7 @@ def snum(amount: Union[int, float], remains: int = 2) -> str:
|
||||
return str(str_amount)
|
||||
|
||||
|
||||
# Конвертация любого числа в вещественное, с удалением нулей в конце (remains - округление)
|
||||
# Convert any number to a real number, removing trailing zeros (remains - rounding)
|
||||
def to_float(get_number, remains: int = 2) -> Union[int, float]:
|
||||
if "," in str(get_number):
|
||||
get_number = str(get_number).replace(",", ".")
|
||||
@@ -313,7 +317,7 @@ def to_float(get_number, remains: int = 2) -> Union[int, float]:
|
||||
return get_number
|
||||
|
||||
|
||||
# Конвертация вещественного числа в целочисленное
|
||||
# Converting a real number to an integer
|
||||
def to_int(get_number: float) -> int:
|
||||
if "," in get_number:
|
||||
get_number = str(get_number).replace(",", ".")
|
||||
@@ -323,7 +327,7 @@ def to_int(get_number: float) -> int:
|
||||
return get_number
|
||||
|
||||
|
||||
# Проверка ввода на число
|
||||
# Data validation for numbers
|
||||
def is_number(get_number: Union[str, int, float]) -> bool:
|
||||
if str(get_number).isdigit():
|
||||
return True
|
||||
@@ -337,7 +341,7 @@ def is_number(get_number: Union[str, int, float]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Преобразование числа в читаемый вид (123456789 -> 123 456 789)
|
||||
# Converting a number to a readable form (123456789 -> 123,456,789)
|
||||
def format_rate(amount: Union[float, int], around: int = 2) -> str:
|
||||
if "," in str(amount): amount = float(str(amount).replace(",", "."))
|
||||
if " " in str(amount): amount = float(str(amount).replace(" ", ""))
|
||||
|
||||
@@ -4,22 +4,22 @@ from aiogram.types import BotCommand, BotCommandScopeChat, BotCommandScopeDefaul
|
||||
|
||||
from tgbot.data.config import get_admins
|
||||
|
||||
# Команды для юзеров
|
||||
# Commands for users
|
||||
user_commands = [
|
||||
BotCommand(command="start", description="♻️ Restart bot"),
|
||||
BotCommand(command="inline", description="🌀 Get Inline keyboard"),
|
||||
BotCommand(command="menu", description="🌀 Get keyboards"),
|
||||
]
|
||||
|
||||
# Команды для админов
|
||||
# Commands for admins
|
||||
admin_commands = [
|
||||
BotCommand(command="start", description="♻️ Restart bot"),
|
||||
BotCommand(command="inline", description="🌀 Get Inline keyboard"),
|
||||
BotCommand(command="menu", description="🌀 Get keyboards"),
|
||||
BotCommand(command="log", description="🖨 Get Logs"),
|
||||
BotCommand(command="db", description="📦 Get Database"),
|
||||
]
|
||||
|
||||
|
||||
# Установка команд
|
||||
# Set commands
|
||||
async def set_commands(bot: Bot):
|
||||
await bot.set_my_commands(user_commands, scope=BotCommandScopeDefault())
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from aiogram.types import Message
|
||||
from tgbot.data.config import get_admins
|
||||
|
||||
|
||||
# Проверка на админа
|
||||
# Filter on admin right
|
||||
class IsAdmin(BaseFilter):
|
||||
async def __call__(self, message: Message) -> bool:
|
||||
if message.from_user.id in get_admins():
|
||||
|
||||
@@ -5,24 +5,24 @@ import colorlog
|
||||
|
||||
from tgbot.data.config import PATH_LOGS
|
||||
|
||||
# Формат логгирования
|
||||
# Logging format
|
||||
log_formatter_file = bot_logger.Formatter("%(levelname)s | %(asctime)s | %(filename)s:%(lineno)d | %(message)s")
|
||||
log_formatter_console = colorlog.ColoredFormatter(
|
||||
"%(purple)s%(levelname)s %(blue)s|%(purple)s %(asctime)s %(blue)s|%(purple)s %(filename)s:%(lineno)d %(blue)s|%(purple)s %(message)s%(red)s",
|
||||
datefmt="%d-%m-%Y %H:%M:%S",
|
||||
)
|
||||
|
||||
# Логгирование в файл logs.log
|
||||
# Logging in file logs.log
|
||||
file_handler = bot_logger.FileHandler(PATH_LOGS, "w", "utf-8")
|
||||
file_handler.setFormatter(log_formatter_file)
|
||||
file_handler.setLevel(bot_logger.INFO)
|
||||
|
||||
# Логгирование в консоль
|
||||
# Logging in console
|
||||
console_handler = bot_logger.StreamHandler()
|
||||
console_handler.setFormatter(log_formatter_console)
|
||||
console_handler.setLevel(bot_logger.CRITICAL)
|
||||
|
||||
# Подключение настроек логгирования
|
||||
# Connect logging settings
|
||||
bot_logger.basicConfig(
|
||||
format="%(levelname)s | %(asctime)s | %(filename)s:%(lineno)d | %(message)s",
|
||||
handlers=[
|
||||
|
||||
@@ -6,13 +6,13 @@ from tgbot.data.config import get_admins, PATH_DATABASE, BOT_STATUS_NOTIFICATION
|
||||
from tgbot.utils.const_functions import get_date, send_admins
|
||||
|
||||
|
||||
# Выполнение функции после запуска бота (рассылка админам о запуске бота)
|
||||
# Notification after run bot (for all admins)
|
||||
async def startup_notify(bot: Bot):
|
||||
if len(get_admins()) >= 1 and BOT_STATUS_NOTIFICATION:
|
||||
await send_admins(bot, "<b>✅ Bot was started</b>")
|
||||
|
||||
|
||||
# Автоматические бэкапы БД
|
||||
# Autobackup Database
|
||||
async def autobackup_admin(bot: Bot):
|
||||
for admin in get_admins():
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user