-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
106 lines (63 loc) · 2.04 KB
/
Copy pathmain.py
File metadata and controls
106 lines (63 loc) · 2.04 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
from __future__ import annotations
import asyncio
import logging
import signal
from contextlib import suppress
from dotenv import load_dotenv
from app.database.base import init_db, close_database
from app.core.scheduler import scheduler_service
from app.interfaces.telegram.bot import TelegramBot
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(name)s | %(levelname)s | %(message)s"
)
logger = logging.getLogger("teleops")
class TeleOpsApplication:
def __init__(self):
self.shutdown_event = asyncio.Event()
logger.info("Bootstrapping lightweight Telegram runtime...")
self.bot = TelegramBot()
async def initialize(self):
logger.info("Initializing database...")
await init_db()
logger.info("Starting scheduler...")
await scheduler_service.start()
async def start(self):
await self.initialize()
logger.info("Starting telegram bot...")
await self.bot.run()
async def shutdown(self):
logger.warning("Shutdown initiated...")
with suppress(Exception):
await scheduler_service.shutdown()
with suppress(Exception):
await self.bot.shutdown()
with suppress(Exception):
await close_database()
self.shutdown_event.set()
logger.warning("Shutdown complete")
async def main():
app = TeleOpsApplication()
loop = asyncio.get_running_loop()
def handle_shutdown():
asyncio.create_task(app.shutdown())
for sig in (signal.SIGINT, signal.SIGTERM):
with suppress(NotImplementedError):
loop.add_signal_handler(
sig,
handle_shutdown
)
try:
await app.start()
await app.shutdown_event.wait()
except asyncio.CancelledError:
pass
except Exception:
logger.exception("Fatal runtime error")
await app.shutdown()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass