From c247637d3093bf017cce8e86d9b08ead3cc7fbae Mon Sep 17 00:00:00 2001 From: fehknt Date: Fri, 10 Nov 2023 02:27:39 +0000 Subject: [PATCH 1/5] Add logging with variable log levels --- hamalert.py | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/hamalert.py b/hamalert.py index 938305b..d2df5cb 100644 --- a/hamalert.py +++ b/hamalert.py @@ -1,6 +1,8 @@ +import argparse import telnetlib import json import requests +import logging # Replace with your HamAlert username and password HAMALERT_USERNAME = "USERNAME" @@ -14,9 +16,9 @@ def send_discord_webhook(content): headers = {"Content-Type": "application/json"} response = requests.post(DISCORD_WEBHOOK_URL, json=data, headers=headers) if response.status_code == 204: - print("Discord webhook sent successfully.") + logging.info("Discord webhook sent successfully.") else: - print("Failed to send Discord webhook. Status code:", response.status_code) + logging.error("Failed to send Discord webhook. Status code:", response.status_code) def telnet_listener(host, port, username, password): try: @@ -28,7 +30,7 @@ def telnet_listener(host, port, username, password): while True: data = tn.read_until(b"\n").decode("utf-8").strip() - print("Received data:", data) + logging.info("Received data:", data) # Split the received data into separate pieces pieces = data.split() @@ -46,20 +48,32 @@ def telnet_listener(host, port, username, password): send_discord_webhook(message) else: - print("Received data is not in the expected format. Skipping.") - print("Number of pieces:", len(pieces)) - print("Received data:", pieces) + logging.warning("Received data is not in the expected format. Skipping.") + logging.warning("Number of pieces:", len(pieces)) + logging.info("Received data:", pieces) except ConnectionRefusedError: - print("Telnet connection refused. Make sure the server is running and reachable.") + logging.error("Telnet connection refused. Make sure the server is running and reachable.") except Exception as e: - print("An error occurred:", e) + logging.error("An error occurred:", e) +def setup_args(): + # Create an argument parser + parser = argparse.ArgumentParser() + # Add an argument for the logging level + parser.add_argument('-l', '--log-level', help='The logging level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']) + + # Parse the arguments + args = parser.parse_args() + + # Set the logging level + logging.basicConfig(level=args.log_level) if __name__ == "__main__": # HAM ALERT TELNET INFORMATION HOST = "hamalert.org" PORT = 7300 + setup_args() telnet_listener(HOST, PORT, HAMALERT_USERNAME, HAMALERT_PASSWORD) From 4dc347ecbfb139d2cfcdd9e3f5c619c71fc5a396 Mon Sep 17 00:00:00 2001 From: fehknt Date: Fri, 10 Nov 2023 02:34:58 +0000 Subject: [PATCH 2/5] Update to JSON format --- hamalert.py | 75 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 53 insertions(+), 22 deletions(-) diff --git a/hamalert.py b/hamalert.py index d2df5cb..fbeadd1 100644 --- a/hamalert.py +++ b/hamalert.py @@ -1,5 +1,6 @@ import argparse import telnetlib +import time import json import requests import logging @@ -27,30 +28,60 @@ def telnet_listener(host, port, username, password): tn.write(username.encode("utf-8") + b"\n") tn.read_until(b"password: ") tn.write(password.encode("utf-8") + b"\n") + initialized = False while True: - data = tn.read_until(b"\n").decode("utf-8").strip() - logging.info("Received data:", data) - - # Split the received data into separate pieces - pieces = data.split() - - # Ensure that the data has enough pieces to extract relevant information - if len(pieces) >= 5 and pieces[1] == "de": - source_call = pieces[2].strip(':') - destination_call = pieces[3] - frequency = pieces[4] - timestamp = pieces[-1] - - # Construct the message for Discord webhook - message = f"DX de {source_call} @ {timestamp}\n" - message += f"{frequency} on {destination_call}" - - send_discord_webhook(message) - else: - logging.warning("Received data is not in the expected format. Skipping.") - logging.warning("Number of pieces:", len(pieces)) - logging.info("Received data:", pieces) + data = tn.read_until(b"\n", timeout=30).decode("utf-8").strip() + if data != "": + logging.info("Received data:", data) + + if data == f"Hello {username}, this is HamAlert": + continue + if data == f"{username} de HamAlert >": + logging.info("Telnet connected, attempting to set JSON mode.") + time.sleep(1) + tn.write(b"set/json\n") + continue + if data == "Operation successful": + logging.info("Successfully set JSON mode") + initialized = True + continue + if not initialized: + # Dont try to parse incoming data until finished setting up JSON mode. + # It's possible a spot comes in right when we first connect which can't be parsed. + continue + + if data == "": + # We must have hit the timeout case in the read. + # Just send a keepalive command and try another read. + logging.debug(f"10s timeout hit, sending no-op") + tn.sock.sendall(telnetlib.IAC + telnetlib.NOP) + continue + + # Split the received data into json object + try: + data_dict = json.loads(data) + + required_fields = {'fullCallsign', 'callsign', 'frequency', 'mode', 'spotter', 'time', 'source'} + # Ensure that the data has enough pieces to extract relevant information + if all(key in data_dict for key in required_fields): + # Construct the message for Discord webhook + message = f"SPOT: {data_dict['callsign']} seen by {data_dict['spotter']} on {data_dict['frequency']} MHz ({data_dict['mode']}) at {data_dict['time']} UTC" + sota_fields = {'summitName', 'summitRef', 'summitPoints', 'summitHeight'} + if all(key in data_dict for key in sota_fields): + message = "SOTA " + message + message += f"\nSummit: {data_dict['summitName']} -- {data_dict['summitRef']} -- a {data_dict['summitPoints']} point summit at {data_dict['summitHeight']}m elevation!" + + else: + logging.warning("Received data is not in the expected format. Skipping.") + logging.warning(f"Parsed data: {data_dict}") + + except json.JSONDecodeError as e: + resetJson = True + message = data + + logging.info(f"sending message to discord: {message}") + send_discord_webhook(message) except ConnectionRefusedError: logging.error("Telnet connection refused. Make sure the server is running and reachable.") From a8949ff136177d5c50d64bf436049d61ccfdf5bf Mon Sep 17 00:00:00 2001 From: fehknt Date: Fri, 10 Nov 2023 02:44:47 +0000 Subject: [PATCH 3/5] fix logging message to formatstring --- hamalert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hamalert.py b/hamalert.py index fbeadd1..a937db5 100644 --- a/hamalert.py +++ b/hamalert.py @@ -33,7 +33,7 @@ def telnet_listener(host, port, username, password): while True: data = tn.read_until(b"\n", timeout=30).decode("utf-8").strip() if data != "": - logging.info("Received data:", data) + logging.info(f"Received data: {data}") if data == f"Hello {username}, this is HamAlert": continue From 4dc522454743f5229489ddc36dee4379515d6b6f Mon Sep 17 00:00:00 2001 From: Matthew Date: Thu, 9 Nov 2023 23:04:09 -0500 Subject: [PATCH 4/5] Update README.md --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1b7c4d0..b1e02ab 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ HamAlerts to Discord Webook Using an Ubuntu Linux Machine follow the below steps: ---------------------------------------------------------------------------------------------------- -To Set up Telnet and Discord Connections: +To Set up Telnet and Discord Connections: [!!!! TO BE UPDATED WITH NEW INSTRUCTIONS !!!!] 1. Create trigger on https://hamalert.org and have it action "Telnet" 2. Create a linux machine and install python3 sudo apt install python3-pip @@ -29,3 +29,10 @@ To create a discord webhook follow the below instructions: Created by W2ORT Matthew O. https://w2ort.com + +Updated and heavily corrected by: +Dylon N6MX +Devin KN6PHZ + +Special Thanks to: +Mark KD7DTS and the W6TRW Club! From f44abd2d2194e0fdd1df44377151b4704ffc0d05 Mon Sep 17 00:00:00 2001 From: Matthew Date: Thu, 9 Nov 2023 23:37:00 -0500 Subject: [PATCH 5/5] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b1e02ab..754cdcf 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,15 @@ HamAlerts to Discord Webook Using an Ubuntu Linux Machine follow the below steps: ---------------------------------------------------------------------------------------------------- -To Set up Telnet and Discord Connections: [!!!! TO BE UPDATED WITH NEW INSTRUCTIONS !!!!] +To Set up HamAlert and Discord Connections: 1. Create trigger on https://hamalert.org and have it action "Telnet" 2. Create a linux machine and install python3 sudo apt install python3-pip pip install requests 3. Create your python file and copy the information from hamalert.py 4. Edit HAMALERT USERNAME, PASSWORD, and DISCORD WEBHOOK to be your information -5. Run Command: "nohup python3 hamalert.py &" (Use this command so the script stays running after you close your CLI session) +5. Follow the following guide to run python as a service in your operating system. This works for Ubuntu as well! +https://gist.github.com/emxsys/a507f3cad928e66f6410e7ac28e2990f 6. Enjoy! ----------------------------------------------------------------------------------------------------