-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
149 lines (121 loc) · 4 KB
/
main.py
File metadata and controls
149 lines (121 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# Copyright NGGT.LightKeeper. All Rights Reserved.
import argparse
import threading
import subprocess
from pathlib import Path
from typing import List
import os
BASE_DIR = Path(__file__).resolve().parent
LOG_DIR = BASE_DIR / "logs" # Directory where logs are stored
LOG_FILE = LOG_DIR / "logs.txt"
LOG_DIR.mkdir(exist_ok=True)
def log_print(*args, **kwargs):
"""Print message to console and append it to the log file."""
print(*args, **kwargs)
message = " ".join(str(a) for a in args)
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(message + ("" if message.endswith("\n") else "\n"))
def run_subprocess(command: List[str]):
"""Run subprocess and log its output line by line."""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in process.stdout:
log_print(line.rstrip())
process.wait()
def runbotserver():
# Launch the Telegram bot in a subprocess
run_subprocess(["python", str(BASE_DIR / "bot.py")])
def runwebserver():
# Start the Django development server
run_subprocess(["python", str(BASE_DIR / "manage.py"), "runserver"])
def makemigrations():
# Create new database migrations
run_subprocess(["python", str(BASE_DIR / "manage.py"), "makemigrations"])
def migrate():
# Apply database migrations
run_subprocess(["python", str(BASE_DIR / "manage.py"), "migrate"])
def setup_django():
# Configure Django so management commands can run
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'telegram_bot_django.settings')
import django
django.setup()
def export_db(path: str):
"""Export the entire database to a JSON file."""
setup_django()
from django.core.management import call_command
with open(path, 'w', encoding='utf-8') as f:
call_command('dumpdata', '--indent', '2', stdout=f)
log_print(f'Database exported to {path}')
def import_db(path: str):
"""Import the entire database from a JSON file."""
setup_django()
from django.core.management import call_command
call_command('loaddata', path)
log_print(f'Database imported from {path}')
mess_help = '''
Available commands:
runserver
runbotserver
runwebserver
makemigrations
migrate
db import <file>
db export <file>
clearlogs
help
'''
mess_error = '''
Command error:
Unknown command: '{command}'
Usage command 'help' to view available commands
'''
def main():
# Parse command line arguments and run selected action
parser = argparse.ArgumentParser()
parser.add_argument('command', nargs='+')
command = parser.parse_args().command
cmds = command
cmd = cmds[0]
if cmd == 'db':
if len(cmds) < 3:
log_print("Usage: python main.py db <import|export> <path>")
return
action = cmds[1]
path = cmds[2]
log_print(f"Running command: {' '.join(cmds)}")
if action == 'export':
export_db(path)
elif action == 'import':
import_db(path)
else:
log_print(mess_error.format(command=' '.join(cmds)))
return
if cmd == 'runserver':
thread1 = threading.Thread(target=runbotserver)
thread2 = threading.Thread(target=runwebserver)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
if cmd == 'runbotserver':
thread1 = threading.Thread(target=runbotserver)
thread1.start()
thread1.join()
if cmd == 'runwebserver':
thread1 = threading.Thread(target=runwebserver)
thread1.start()
thread1.join()
elif cmd == 'makemigrations':
log_print(f"Running command: {cmd}")
makemigrations()
elif cmd == 'migrate':
log_print(f"Running command: {cmd}")
migrate()
elif cmd == 'clearlogs':
LOG_FILE.unlink(missing_ok=True)
log_print('Logs cleared')
elif cmd == 'help':
log_print(mess_help)
else:
log_print(mess_error)
if __name__ == '__main__':
main()