Skip to content

Commit cc6a65f

Browse files
committed
Command for real time server stats
1 parent d993b66 commit cc6a65f

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed
101 Bytes
Binary file not shown.

app/core/bot.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from app.handlers.basic import register_basic_handlers
66
from app.handlers.schedule import send_report_24hr
7+
from app.handlers.server import server_stats_commands
78
from app.services.metrics import wait_for_clock
89
from app.services.clock import Clock
910

@@ -12,6 +13,7 @@ async def main():
1213
dp = Dispatcher()
1314

1415
register_basic_handlers(dp)
16+
server_stats_commands(dp)
1517

1618
clock = Clock()
1719
clock_task = asyncio.create_task(clock.day_cycle_clock())

app/database/readb.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import sqlite3
2+
import time
3+
from pathlib import Path
4+
import asyncio
5+
from concurrent.futures import ThreadPoolExecutor
6+
7+
DB_PATH = Path(__file__).resolve().parent / 'server_metrics.db'
8+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
9+
10+
_executor = ThreadPoolExecutor(max_workers=1)
11+
12+
CREATE_TABLE_SQL = '''
13+
CREATE TABLE IF NOT EXISTS Metrics (
14+
id INTEGER PRIMARY KEY AUTOINCREMENT,
15+
timestamp INTEGER NOT NULL,
16+
mem_total REAL,
17+
mem_used REAL,
18+
mem_prcnt REAL,
19+
cpu_prcnt REAL,
20+
cpu_freq REAL,
21+
cpu_temp REAL
22+
);
23+
'''
24+
25+
LATEST_ROW_SQL = '''
26+
SELECT timestamp, mem_total, mem_used, mem_prcnt, cpu_prcnt, cpu_freq, cpu_temp
27+
FROM Metrics
28+
ORDER BY timestamp DESC
29+
LIMIT 1;
30+
'''
31+
32+
def _read_latest_sync():
33+
with sqlite3.connect(DB_PATH) as connection:
34+
connection.row_factory = sqlite3.Row
35+
cursor = connection.cursor()
36+
cursor.execute(CREATE_TABLE_SQL)
37+
cursor.execute(LATEST_ROW_SQL)
38+
row = cursor.fetchone()
39+
return dict(row) if row else None
40+
41+
async def read_latest():
42+
loop = asyncio.get_event_loop()
43+
return await loop.run_in_executor(_executor, _read_latest_sync)

app/handlers/server.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from app.database.readb import read_latest
2+
from app.filters.owner import IsOwner
3+
from aiogram import types
4+
from aiogram.filters import Command
5+
6+
def server_stats_commands(dp):
7+
@dp.message(Command("now"), IsOwner())
8+
async def stats_now(message: types.Message):
9+
metrics = await read_latest()
10+
if metrics:
11+
await message.answer(
12+
f"{metrics}"
13+
)
14+
else:
15+
await message.answer("No metrics found.")

0 commit comments

Comments
 (0)