summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authoruser <user@node5.net>2024-04-27 17:59:16 +0200
committeruser <user@node5.net>2024-04-27 17:59:16 +0200
commit54534fd4588799efd7fe9179beb4306edc2e6504 (patch)
tree86185235224e62c77ae25b76029a106b3edde525 /src
parentd69b1d5b833322de4e888b73a99c0b7b85f71250 (diff)
split out telegram send message code to separate file
Diffstat (limited to 'src')
-rw-r--r--src/server_status.py32
-rw-r--r--src/telegram_notifier.py22
2 files changed, 32 insertions, 22 deletions
diff --git a/src/server_status.py b/src/server_status.py
index a0dc6b3..25670a9 100644
--- a/src/server_status.py
+++ b/src/server_status.py
@@ -1,5 +1,4 @@
-import telegram # Notifications
-import asyncio # Telegram library is async
+import telegram_notifier # Send notifications
import requests # Check HTTP status code
import os # Unix socket file handling
import subprocess # Ping check if host online
@@ -52,11 +51,12 @@ logging.getLogger("telegram").setLevel(logging.WARNING)
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
+notifier = telegram_notifier.TelegramNotifier(config['telegram']['token'], config['telegram']['chat_id'])
+
# Set the path for the Unix socket
# without reinitialising entire script
# Used for SystemD timer to invoke status check,
socket_path = "/tmp/server_status.sock"
-bot = telegram.Bot(config["telegram"]["token"])
hostname = socket.gethostname()
# Used to only notify on state change
# Initialise data structure based on targets in config file
@@ -69,18 +69,6 @@ for host, host_config in config["hosts"].items():
state[host]['http_status'][url] = None
-# Send message from non async function
-def send_message(text):
- logger.debug(f"Sending message: {text}")
- asyncio.run(async_send_message(text))
-
-
-async def async_send_message(text):
- async with bot:
- await bot.send_message(text=text, chat_id=config["telegram"]["chat_id"],
- parse_mode=telegram.constants.ParseMode.MARKDOWN)
-
-
def ping(host: str) -> bool:
response = subprocess.run(["ping", "-c", "1", host])
return response.returncode == 0
@@ -108,7 +96,7 @@ def check_target(host: str, host_config: dict) -> bool:
if changed_state or (first_test and not host_is_desired_state):
message = f"❌ `{host}` is {'online' if online else 'offline'}"
logger.warning(message)
- send_message(message)
+ notifier.send_message(message)
state[host]['online'] = online # Save current state
if online:
@@ -138,7 +126,7 @@ def check_target(host: str, host_config: dict) -> bool:
state[host]['http_status'][url] = http_state
if len(messages) > 0:
- send_message('❌ ' + '\n'.join(messages))
+ notifier.send_message('❌ ' + '\n'.join(messages))
return host_is_desired_state
@@ -156,7 +144,7 @@ def check_status() -> bool:
all_hosts_are_in_desired_state = False
return all_hosts_are_in_desired_state
except Exception as ex:
- send_message("Error getting status")
+ notifier.send_message("Error getting status")
raise ex
@@ -208,18 +196,18 @@ def listen():
def main():
- send_message(f"✅ Server status checker on `{hostname}` *online*")
+ notifier.send_message(f"✅ Server status checker on `{hostname}` *online*")
alles_gut = check_status()
if alles_gut == True:
# First test, notify of outcome
# If a non-desired state was caught in first check a notification would have been triggered.
- send_message("✅ All hosts are in desired state,\nand no discrepancies found") # Vægter
+ notifier.send_message("✅ All hosts are in desired state,\nand no discrepancies found") # Vægter
listen()
def service_exiting(signum, frame):
# Ship going down
- send_message(f"❌ Server status checker on `{hostname}` *going down*")
+ notifier.send_message(f"❌ Server status checker on `{hostname}` *going down*")
exit(0)
@@ -227,4 +215,4 @@ def service_exiting(signum, frame):
signal.signal(signal.SIGTERM, service_exiting)
if __name__ == "__main__":
- asyncio.run(main())
+ main()
diff --git a/src/telegram_notifier.py b/src/telegram_notifier.py
new file mode 100644
index 0000000..870bf6c
--- /dev/null
+++ b/src/telegram_notifier.py
@@ -0,0 +1,22 @@
+import asyncio # Telegram library is async
+import logging
+
+import telegram
+
+logger = logging.getLogger(__name__) # Set the logger name, to the name of the module
+
+
+class TelegramNotifier:
+ def __init__(self, token: str, chat_id: int):
+ self.chat_id: int = chat_id
+ self.bot = telegram.Bot(token)
+
+ async def async_send_message(self, text):
+ async with self.bot:
+ await self.bot.send_message(text=text, chat_id=self.chat_id,
+ parse_mode=telegram.constants.ParseMode.MARKDOWN)
+
+ # Send message from non async function
+ def send_message(self, text):
+ logger.debug(f"Sending message: {text}")
+ asyncio.run(self.async_send_message(text))