This repository has been archived on 2024-10-14. You can view files and clone it, but cannot push or open issues or pull requests.
AutoZoomDiscord/modules/functions.py

123 lines
3.9 KiB
Python
Raw Normal View History

2022-09-14 13:48:58 +03:00
# -*- coding: utf-8 -*-
"""Some set of functions needed for discord/telegram bots and other types of apps"""
2022-09-15 14:05:44 +03:00
from os import sep, stat, makedirs, kill
from os import name as osname
2022-09-14 13:48:58 +03:00
from datetime import datetime
2022-09-15 14:05:44 +03:00
from typing import Union
2022-09-14 13:48:58 +03:00
from ujson import loads, dumps
2022-09-15 01:20:38 +03:00
from shutil import copyfileobj
from gzip import open as gzipopen
2022-09-15 14:05:44 +03:00
from psutil import Process
2022-09-14 13:48:58 +03:00
2022-09-15 14:05:44 +03:00
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y") -> str:
2022-09-14 13:48:58 +03:00
"""Return current local time formatted as arg.
### Args:
* format (str, optional): Format that should be returned. Defaults to "%H:%M:%S | %d.%m.%Y".
### Returns:
* str: Local time formatted as arg.
"""
return datetime.now().strftime(format)
2022-09-15 14:05:44 +03:00
def checkSize(logs_folder=f"logs{sep}", log_size=1024) -> None:
2022-09-14 13:48:58 +03:00
"""Checks latest log file size and rotates it if needed.
### Args:
* logs_folder (str, optional): Folder where logs stored. Defaults to "logs/".
* log_size (int, optional): How many bytes should file containt to be rotated. Defaults to 1024.
"""
i = 0
while i < 2:
try:
2022-09-15 01:20:38 +03:00
log = stat(logs_folder + 'latest.log')
2022-09-14 13:48:58 +03:00
if (log.st_size / 1024) > log_size:
with open(logs_folder + 'latest.log', 'rb') as f_in:
2022-09-15 01:20:38 +03:00
with gzipopen(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out:
copyfileobj(f_in, f_out)
2022-09-14 13:48:58 +03:00
open(logs_folder + 'latest.log', 'w').close()
i = 2
except FileNotFoundError:
try:
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
try:
2022-09-15 01:20:38 +03:00
makedirs(logs_folder, exist_ok=True)
2022-09-14 13:48:58 +03:00
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
pass
i += 1
2022-09-15 14:05:44 +03:00
def logWrite(message: str, logs_folder=f"logs{sep}", level="INFO") -> None:
2022-09-14 13:48:58 +03:00
"""Append some message to latest log file.
### Args:
* message (str): Something you want to add to log
* logs_folder (str, optional): Folder where logs stored. Defaults to "logs/".
* level (str, optional): Log level (INFO, WARN, ERRO, CRIT, DEBG). Defaults to "INFO".
"""
checkSize(logs_folder=logs_folder)
try:
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
try:
2022-09-15 01:20:38 +03:00
makedirs(logs_folder, exist_ok=True)
2022-09-14 13:48:58 +03:00
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
print(f'[{nowtimeGet()}] [ERRO] Log file could not be written.', flush=True)
return
log.write(f'[{nowtimeGet()}] [{level}] {message}\n')
print(f'[{nowtimeGet()}] [{level}] {message}', flush=True)
log.close()
2022-09-15 14:05:44 +03:00
def jsonSave(filename: str, value: Union[list, dict]) -> None:
2022-09-14 13:48:58 +03:00
"""Save some list or dict as json file.
2022-09-15 14:05:44 +03:00
### Args:
2022-09-14 13:48:58 +03:00
* filename (str): File to which value will be written.
2022-09-15 14:05:44 +03:00
* value (Union[list, dict]): Some object that will be written to filename.
2022-09-14 13:48:58 +03:00
"""
with open(filename, 'w', encoding="utf-8") as f:
f.write(dumps(value, indent=4, ensure_ascii=False))
f.close()
2022-09-15 14:05:44 +03:00
def jsonLoad(filename: str) -> any:
2022-09-14 13:48:58 +03:00
"""Load json file and return python dict or list.
2022-09-15 14:05:44 +03:00
### Args:
2022-09-14 13:48:58 +03:00
* filename (str): File which should be loaded.
2022-09-15 14:05:44 +03:00
### Returns:
* any: Content of json file provided.
2022-09-14 13:48:58 +03:00
"""
with open(filename, 'r', encoding="utf-8") as f:
value = loads(f.read())
f.close()
2022-09-15 14:05:44 +03:00
return value
def killProc(pid: int) -> None:
"""Kill the process by its PID
### Args:
* pid (int): Process ID to be killed
"""
if osname == "posix":
from signal import SIGKILL
kill(pid, SIGKILL)
else:
p = Process(pid)
p.kill()