crk_telegram_bot/app/install.py

178 lines
6.4 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.

import os
import platform
import sys
python_version = (3, 12)
def clear_console():
os_name = platform.system()
if os_name == 'Windows':
os.system('cls')
else:
os.system('clear')
def run_command(command):
result = os.system(command)
if result == 0:
return True
else:
print(f"Command failed with status code {result}")
return False
def check_python_version():
current_version = sys.version_info
required_version = python_version
if current_version < required_version:
print(f"Python version {required_version[0]}.{required_version[1]} or newer is required.")
return False
return True
class configuration:
def __init__(self):
clear_console()
self.config_path = "app/settings/config.py" # Путь к файлу конфигурации
def check_config(self):
if not os.path.exists(self.config_path):
#print("[2/2] Config not found.")
return False
else:
#print("[2/2] Config exists.")
return True
def ask_to_recreate_config(self):
user_input = input("[2/2] Config already exists. Do you want to delete it and reinstall? (y/n): ").strip().lower()
if user_input == 'y':
print("[2/2] Deleting the config.py...")
self.delete_config()
if self.check_config():
self.ask_to_recreate_config() # Повторный запрос
self.create_config()
elif user_input == 'n':
print("[2/2] Skipping the recreation of config.")
else:
print("[2/2] Invalid input. Please answer with 'y' or 'n'.")
self.ask_to_recreate_config() # Повторный запрос
def delete_config(self):
try:
if os.path.exists(self.config_path):
os.remove(self.config_path)
print("[2/2] The config has been deleted.")
else:
print("[2/2] Config file not found; nothing to delete.")
except Exception as e:
print(f"[2/2] Error while deleting config: {e}")
def create_config(self):
token = input("[2/2] Enter your telegram bot token: ").strip()
channel_id = input("[2/2] Enter your channel_id: ").strip()
path = input("[2/2] Enter your path: ").strip()
try:
os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
with open(self.config_path, "w") as config_file:
#config_file.write(f'TOKEN = "{token}"\n')
config_file.write(f'DEBUG = False\nTOKEN = "{token}"\nCHANNEL_WHITELIST = "-100{channel_id}"\n')
print("----------------------------------------------------------------")
print("[2/2] Config creation succeeded")
print("----------------------------------------------------------------")
except Exception as e:
print(f"[2/2] Error while creating config: {e}")
def start(self):
if self.check_config():
self.ask_to_recreate_config()
else:
self.create_config()
class installation:
def __init__(self):
clear_console()
def check_env_folder(self):
"""Проверка наличия папки 'env'. Если её нет - предложим создать."""
if not os.path.exists("env"):
print("[1/2] installing environment...")
return False
else:
# print("[1/2] Folder 'env' exists.")
return True
def ask_to_recreate_env(self):
"""Запросить у пользователя, хочет ли он удалить старую среду и создать новую."""
user_input = input("[1/2] Folder 'env' already exists. Do you want to delete it and reinstall? (y/n): ").strip().lower()
if user_input == 'y':
print("[1/2] Deleting the 'env' folder...")
self.delete_env_folder()
if self.check_env_folder():
self.ask_to_recreate_env() # Повторный запрос
self.install_env()
elif user_input == 'n':
print("[1/2] Skipping the recreation of 'env'.")
else:
print("[1/2] Invalid input. Please answer with 'y' or 'n'.")
self.ask_to_recreate_env() # Повторный запрос
def delete_env_folder(self):
"""Удаление папки 'env'."""
if os.path.exists("env"):
try:
# Удаляем всю папку 'env' рекурсивно
import shutil
shutil.rmtree("env")
print("[1/2] The 'env' folder has been deleted.")
except Exception as e:
print(f"[1/2] Error while deleting 'env': {e}")
else:
print("[1/2] Folder 'env' does not exist. No need to delete.")
def create_env(self):
os_name = platform.system()
if os_name != 'Windows':
#
print("[!!!] CRITICAL WARNING")
print("[!!!] install for not windows not working")
print("[!!!] use user manual")
choice = input('Wait any key...')
# run_command("python3 -m venv env")
# run_command("./env/bin/pip install -r requirements.txt")
run_command("python -m venv env")
run_command(".\\env\\Scripts\\pip.exe install -r requirements.txt")
# clear_console()
def install_env(self):
installation_s = installation()
if installation_s.check_env_folder() == False:
installation_s.create_env()
clear_console()
print("----------------------------------------------------------------")
print("[1/2] Installation succeeded")
print("----------------------------------------------------------------")
choice = input('Wait any key...')
else:
installation_s.ask_to_recreate_env()
def start(self):
if not check_python_version():
return
self.install_env()
# print("[1/2] Installation completed successfully")
# choice = input('Wait any key...')
if __name__ == "__main__":
install = installation()
install.start()
config = configuration()
config.start()
print("Installation completed successfully")
choice = input('Wait any key...')