Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ async def reply(
class TurboBotCommand(Command):
async def handle(self, c: Context):

raw_message_json = json.loads(c.message.raw_message)
raw_message_json = c.message.raw_message
if not isinstance(raw_message_json, dict):
raw_message_json = json.loads(raw_message_json)

# this will go away once signalbot is fixed
# Parse environment variables
Expand Down Expand Up @@ -184,9 +186,11 @@ async def handle(self, c: Context):
elif msg == "#":
print("is hash")
git_info = get_git_info()
str = f"Uptime: {(time.time() - start_time)} seconds\n"
str += git_info
await c.reply( LOGMSG + "I am here.\n" + str)
machine_info = get_machine_info()
status_message = f"Uptime: {(time.time() - start_time)} seconds\n"
status_message += git_info + "\n"
status_message += machine_info
await c.reply( LOGMSG + "I am here.\n" + status_message)
elif msg == "#turboboot":
print("is reboot")
await c.reply( LOGMSG + "turbobot rebooting...")
Expand Down
6 changes: 5 additions & 1 deletion tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ async def test_hash(self, receive_mock, send_mock):
receive_mock.define(["#"])
await self.run_bot()
self.assertEqual(send_mock.call_count, 1)
self.assertEqual( LOGMSG in send_mock.call_args_list[0].args[1] , True)
response = send_mock.call_args_list[0].args[1]
self.assertEqual( LOGMSG in response , True)
self.assertEqual( "Machine:" in response , True)
self.assertEqual( "Hostname:" in response , True)
self.assertEqual( "OS:" in response , True)

@patch("signalbot.SignalAPI.send", new_callable=SendMessagesMock)
@patch("signalbot.SignalAPI.receive", new_callable=ReceiveMessagesMock)
Expand Down
70 changes: 70 additions & 0 deletions utils/misc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import base64
import hashlib
import json
import platform
import shutil
import socket
from cryptography.fernet import Fernet
import git
from datetime import datetime
Expand Down Expand Up @@ -124,6 +127,73 @@ def parse_env_var(env_var, delimiter=";"):
else:
return [value] # Single value as a list

def _format_bytes(num_bytes):
"""Return a human-readable byte count."""
units = ["B", "KB", "MB", "GB", "TB"]
value = float(num_bytes)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{value:.1f} {unit}"
value /= 1024


def _get_memory_info():
"""Return Linux memory information from /proc/meminfo when available."""
meminfo_path = "/proc/meminfo"
if not os.path.exists(meminfo_path):
return None

meminfo = {}
with open(meminfo_path, "r") as file:
for line in file:
key, value = line.split(":", 1)
meminfo[key] = int(value.strip().split()[0]) * 1024

total = meminfo.get("MemTotal")
available = meminfo.get("MemAvailable")
if total is None or available is None:
return None

used = total - available
return f"{_format_bytes(used)} used / {_format_bytes(total)} total"


def get_machine_info():
"""
Retrieves basic information about the machine running the bot.

Returns:
str: A formatted string containing hostname, OS, Python version, CPU count,
load average, memory, and disk usage information.
"""
hostname = socket.gethostname()
os_info = platform.platform()
python_version = platform.python_version()
processor = platform.processor() or platform.machine() or "Unknown"
cpu_count = os.cpu_count() or "Unknown"
load_average = "Unavailable"
if hasattr(os, "getloadavg"):
load_average = ", ".join(f"{load:.2f}" for load in os.getloadavg())

memory_info = _get_memory_info() or "Unavailable"
disk_usage = shutil.disk_usage(os.getcwd())
disk_info = (
f"{_format_bytes(disk_usage.used)} used / "
f"{_format_bytes(disk_usage.total)} total"
)

return (
f"Machine:\n"
f"Hostname: {hostname}\n"
f"OS: {os_info}\n"
f"Python: {python_version}\n"
f"Processor: {processor}\n"
f"CPU Count: {cpu_count}\n"
f"Load Average: {load_average}\n"
f"Memory: {memory_info}\n"
f"Disk: {disk_info}"
)

def get_git_info():
"""
Retrieves the current branch name, commit ID, timestamp, and committer name
Expand Down
Loading