From 4b029e3f83084c295a1125b66b8947a9404ca321 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 05:45:43 +0000 Subject: [PATCH 01/11] cleaning up / reformatting --- discord_http.py | 22 +++++++++++ hamalertmessage.py | 24 ++++++++++++ requirements.txt | 3 +- spotbot.py | 93 ++++++++++++++++++++-------------------------- tables.py | 36 +++++++++--------- test.py | 3 ++ 6 files changed, 110 insertions(+), 71 deletions(-) create mode 100644 discord_http.py create mode 100644 hamalertmessage.py diff --git a/discord_http.py b/discord_http.py new file mode 100644 index 0000000..9773ab7 --- /dev/null +++ b/discord_http.py @@ -0,0 +1,22 @@ +import requests +import os + +class DiscordHttp: + def __init__(self): + self.session = requests.Session() + + def post_message(self, content, messageId=None): + target_url = os.getenv('TARGET_URL') + verb = "POST" + if messageId is not None: + target_url = target_url + f"/messages/{messageId}" + verb = "PATCH" + response = self.session.request(verb, url=target_url, params={"wait": "true"}, json=content) + return response.json()['id'] + + def get_message_from_id(self, messageId): + target_url = os.getenv('TARGET_URL') + verb = "GET" + target_url = target_url + f"/messages/{messageId}" + response = self.session.request(verb, url=target_url) + return response.json()['content'] \ No newline at end of file diff --git a/hamalertmessage.py b/hamalertmessage.py new file mode 100644 index 0000000..aa758c2 --- /dev/null +++ b/hamalertmessage.py @@ -0,0 +1,24 @@ +import datetime +from pytz import timezone + +class HamAlertMessage: + def __init__(self, req_body): + self.callsign = req_body.get('callsign', 'Unknown') + self.source = req_body.get('source', 'Unknown') + self.frequency = req_body.get('frequency', 'Unknown') + self.mode = req_body.get('mode', 'Unknown') + self.summitRef = req_body.get('summitRef', '') + self.wwffRef = req_body.get('wwffRef', '') + self.received_time_pt = datetime.datetime.now(timezone('US/Pacific')) + + def spot_deeplink(self): + match self.source: + case "sotawatch": + return f"[{self.source}](https://sotl.as/activators/{self.callsign})" + case "pota": + return f"[{self.source}](https://api.pota.app/spot/comments/{self.callsign}/{self.wwffRef})" + case _: + return "" + + def __str__(self): + return f"{self.received_time_pt.strftime("%H:%M")} | {self.callsign} | {self.spot_deeplink} | freq: {self.frequency} | mode: {self.mode} | loc: {self.summitRef}{self.wwffRef}" \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 92739e6..80288fb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ azure-functions azure-data-tables requests -pytz \ No newline at end of file +pytz +requests-mock \ No newline at end of file diff --git a/spotbot.py b/spotbot.py index 41c7b02..c27b157 100644 --- a/spotbot.py +++ b/spotbot.py @@ -2,8 +2,47 @@ import os import datetime from pytz import timezone -import requests import tables +from hamalertmessage import HamAlertMessage +from tables import HamAlertTable +from discord_http import DiscordHttp + +class SpotBot: + def __init__(self, http_req): + self.http_req = http_req + self.ham = HamAlertMessage(http_req.get_json()) + self.table = HamAlertTable() + self.discord_http = DiscordHttp() + + def process(self): + logging.info('Processing HamAlert message') + + previous_message, message_id = self.get_last_message() + previous_message = self.strikethrough_mesage(previous_message) + content = self.combine_messages(previous_message, self.ham) + self.discord_http.post_message(content, message_id) + + def strikethrough_mesage(self, message): + return f"~~{message}~~" + + def combine_messages(self, m1, m2): + return f"{m1}\n{m2}" + + def get_last_message(self): + last_message_entity = self.table.query_for_entity(self.callsign) + if self.is_entity_recent(last_message_entity): + messageId = last_message_entity['MessageId'] + existing_message = self.discord_http.get_message_from_id(messageId) + return existing_message.replace("~", ""), messageId + return "", None + + def is_entity_recent(self, entity): + if entity is None: + return False + ent_time = entity.metadata['timestamp'] + cur_time = datetime.datetime.now(datetime.timezone.utc) + lookback_seconds = int(os.getenv('LOOKBACK_SECONDS', 7200)) + return (cur_time - ent_time).total_seconds() < lookback_seconds def run(req): @@ -31,54 +70,4 @@ def run(req): content_payload = {"content":content, "flags": 4} messageId = post_message(content_payload, messageId) - tables.upsert_entity(table, callsign, messageId) - -def create_content(req_body, dd): - callsign = req_body.get('callsign', 'Unknown') - source = req_body.get('source', 'Unknown') - frequency = req_body.get('frequency', 'Unknown') - mode = req_body.get('mode', 'Unknown') - summitRef = req_body.get('summitRef', '') - wwffRef = req_body.get('wwffRef', '') - - spot_deeplink = create_spot_deeplink(source, callsign, wwffRef) - formatted_time = dd.strftime("%H:%M") - - content = f"{formatted_time} | {callsign} | {spot_deeplink} | freq: {frequency} | mode: {mode} | loc: {summitRef}{wwffRef}" - return content - -def create_spot_deeplink(source, callsign, wwffRef): - match source: - case "sotawatch": - return f"[{source}](https://sotl.as/activators/{callsign})" - case "pota": - return f"[{source}](https://api.pota.app/spot/comments/{callsign}/{wwffRef})" - case _: - return "" - -def is_entity_recent(entity): - if entity is None: - return False - ent_time = entity.metadata['timestamp'] - cur_time = datetime.datetime.now(datetime.timezone.utc) - lookback_seconds = int(os.getenv('LOOKBACK_SECONDS', 7200)) - return (cur_time - ent_time).total_seconds() < lookback_seconds - -def post_message(content, messageId=None): - target_url = os.getenv('TARGET_URL') - verb = "POST" - if messageId is not None: - target_url = target_url + f"/messages/{messageId}" - verb = "PATCH" - response = requests.request(verb, url=target_url, params={"wait": "true"}, json=content) - return extract_message_id(response) - -def get_previous_message(messageId): - target_url = os.getenv('TARGET_URL') - verb = "GET" - target_url = target_url + f"/messages/{messageId}" - response = requests.request(verb, url=target_url) - return response.json()['content'] - -def extract_message_id(response): - return response.json()['id'] \ No newline at end of file + tables.upsert_entity(table, callsign, messageId) \ No newline at end of file diff --git a/tables.py b/tables.py index c03cf94..d30db98 100644 --- a/tables.py +++ b/tables.py @@ -3,23 +3,23 @@ from azure.data.tables import TableServiceClient from azure.data.tables import UpdateMode -def get_table(): - connection_string = os.getenv('AzureWebJobsStorage') - table_name = os.getenv('TABLE_NAME') - table_service_client = TableServiceClient.from_connection_string(conn_str=connection_string) - table_client = table_service_client.get_table_client(table_name=table_name) - return table_client +class HamAlertTable: + def __init__(self): + connection_string = os.getenv('AzureWebJobsStorage') + table_name = os.getenv('TABLE_NAME') + table_service_client = TableServiceClient.from_connection_string(conn_str=connection_string) + self.table_client = table_service_client.get_table_client(table_name=table_name) -def query_for_entity(table_client, callsign): - entities = [ent for ent in table_client.query_entities(f"PartitionKey eq '{callsign}' and RowKey eq '{callsign}'")] - if len(entities) > 0: - logging.info(f"Entity already exists for {callsign}") - return entities[0] if len(entities) > 0 else None + def query_for_entity(self, callsign): + entities = [ent for ent in self.table_client.query_entities(f"PartitionKey eq '{callsign}' and RowKey eq '{callsign}'")] + if len(entities) > 0: + logging.info(f"Entity already exists for {callsign}") + return entities[0] if len(entities) > 0 else None -def upsert_entity(table_client, callsign, messageId): - entity = { - u'PartitionKey': callsign, - u'RowKey': callsign, - u'MessageId': messageId - } - table_client.upsert_entity(mode=UpdateMode.REPLACE, entity=entity) \ No newline at end of file + def upsert_entity(self, callsign, messageId): + entity = { + u'PartitionKey': callsign, + u'RowKey': callsign, + u'MessageId': messageId + } + self.table_client.upsert_entity(mode=UpdateMode.REPLACE, entity=entity) \ No newline at end of file diff --git a/test.py b/test.py index 51348e1..7acb3cd 100644 --- a/test.py +++ b/test.py @@ -3,6 +3,9 @@ from datetime import datetime from pytz import timezone +import requests +import requests_mock + class TestSpotBot(unittest.TestCase): def test_function_app_basic(self): From 1a90297c31690143d677768c21e91d57380a4923 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 05:48:47 +0000 Subject: [PATCH 02/11] upsert and use json payload --- discord_http.py | 3 ++- spotbot.py | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/discord_http.py b/discord_http.py index 9773ab7..2646b79 100644 --- a/discord_http.py +++ b/discord_http.py @@ -6,12 +6,13 @@ def __init__(self): self.session = requests.Session() def post_message(self, content, messageId=None): + content_payload = {"content": content, "flags": 4} target_url = os.getenv('TARGET_URL') verb = "POST" if messageId is not None: target_url = target_url + f"/messages/{messageId}" verb = "PATCH" - response = self.session.request(verb, url=target_url, params={"wait": "true"}, json=content) + response = self.session.request(verb, url=target_url, params={"wait": "true"}, json=content_payload) return response.json()['id'] def get_message_from_id(self, messageId): diff --git a/spotbot.py b/spotbot.py index c27b157..e85fb1c 100644 --- a/spotbot.py +++ b/spotbot.py @@ -21,6 +21,7 @@ def process(self): previous_message = self.strikethrough_mesage(previous_message) content = self.combine_messages(previous_message, self.ham) self.discord_http.post_message(content, message_id) + self.table.upsert_entity(self.ham.callsign, message_id) def strikethrough_mesage(self, message): return f"~~{message}~~" From 081a264c47e2d5bf4d078f599430903176525e8f Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:05:00 +0000 Subject: [PATCH 03/11] little cleanup: --- discord_http.py | 1 + function_app.py | 2 +- requirements.txt | 3 +-- spotbot.py | 33 +-------------------------------- 4 files changed, 4 insertions(+), 35 deletions(-) diff --git a/discord_http.py b/discord_http.py index 2646b79..5768af6 100644 --- a/discord_http.py +++ b/discord_http.py @@ -6,6 +6,7 @@ def __init__(self): self.session = requests.Session() def post_message(self, content, messageId=None): + # flags = 4 means it will suppress embeds: https://discord.com/developers/docs/resources/message#message-object-message-flags content_payload = {"content": content, "flags": 4} target_url = os.getenv('TARGET_URL') verb = "POST" diff --git a/function_app.py b/function_app.py index 41d743c..0f40f96 100644 --- a/function_app.py +++ b/function_app.py @@ -8,7 +8,7 @@ @app.route(route="spotbot", methods=[func.HttpMethod.POST]) def spotbot(req: func.HttpRequest) -> func.HttpResponse: try: - sb.run(req) + sb.SpotBot(req).process() except Exception as _excpt: logging.error(f"Exception occurred: {_excpt}") return func.HttpResponse(body=f"Exception occurred: {_excpt}", status_code=500) diff --git a/requirements.txt b/requirements.txt index 80288fb..92739e6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,4 @@ azure-functions azure-data-tables requests -pytz -requests-mock \ No newline at end of file +pytz \ No newline at end of file diff --git a/spotbot.py b/spotbot.py index e85fb1c..c0bd5d9 100644 --- a/spotbot.py +++ b/spotbot.py @@ -1,8 +1,6 @@ import logging import os import datetime -from pytz import timezone -import tables from hamalertmessage import HamAlertMessage from tables import HamAlertTable from discord_http import DiscordHttp @@ -16,7 +14,6 @@ def __init__(self, http_req): def process(self): logging.info('Processing HamAlert message') - previous_message, message_id = self.get_last_message() previous_message = self.strikethrough_mesage(previous_message) content = self.combine_messages(previous_message, self.ham) @@ -43,32 +40,4 @@ def is_entity_recent(self, entity): ent_time = entity.metadata['timestamp'] cur_time = datetime.datetime.now(datetime.timezone.utc) lookback_seconds = int(os.getenv('LOOKBACK_SECONDS', 7200)) - return (cur_time - ent_time).total_seconds() < lookback_seconds - - -def run(req): - logging.info('Python HTTP trigger function processed a request.') - dd = datetime.datetime.now(timezone('US/Pacific')) - - req_body = req.get_json() - logging.info(f"Received JSON: {req_body}") - - callsign = req_body.get('callsign') - - content = create_content(req_body, dd) - - table = tables.get_table() - entity = tables.query_for_entity(table, callsign) - messageId = None - existingMessage = None - - if is_entity_recent(entity): - messageId = entity['MessageId'] - existingMessage = get_previous_message(messageId).replace("~", "") - content = "~~" + existingMessage + "~~\n" + content - - # flags = 4 means it will suppress embeds: https://discord.com/developers/docs/resources/message#message-object-message-flags - content_payload = {"content":content, "flags": 4} - - messageId = post_message(content_payload, messageId) - tables.upsert_entity(table, callsign, messageId) \ No newline at end of file + return (cur_time - ent_time).total_seconds() < lookback_seconds \ No newline at end of file From 21bc9745d48fa9a5202f1bc230ee4da93e5b2af4 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:07:27 +0000 Subject: [PATCH 04/11] temporarily disabling tests --- test.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test.py b/test.py index 7acb3cd..bc447ef 100644 --- a/test.py +++ b/test.py @@ -3,11 +3,9 @@ from datetime import datetime from pytz import timezone -import requests -import requests_mock - class TestSpotBot(unittest.TestCase): + ''' def test_function_app_basic(self): dd = datetime.strptime("2024-10-13T01:05:03", "%Y-%m-%dT%H:%M:%S") req_body = {"callsign":"KI7HSG", "source": "pota", "frequency": "14.074", "mode": "FT8", "wwffRef":"US-0052"} @@ -21,6 +19,7 @@ def test_function_app(self): content = spotbot.create_content(req_body, dd) expected = '01:05 | KI7HSG | [sotawatch](https://sotl.as/activators/KI7HSG) | freq: 14.074 | mode: FT8 | loc: ABCD' self.assertEqual(content, expected) - + ''' + if __name__ == '__main__': unittest.main() From 406d8f36edfb34b4af2d5b87a7c78b1c5638169d Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:14:23 +0000 Subject: [PATCH 05/11] single quotes: --- hamalertmessage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hamalertmessage.py b/hamalertmessage.py index aa758c2..eec5cfd 100644 --- a/hamalertmessage.py +++ b/hamalertmessage.py @@ -21,4 +21,4 @@ def spot_deeplink(self): return "" def __str__(self): - return f"{self.received_time_pt.strftime("%H:%M")} | {self.callsign} | {self.spot_deeplink} | freq: {self.frequency} | mode: {self.mode} | loc: {self.summitRef}{self.wwffRef}" \ No newline at end of file + return f'{self.received_time_pt.strftime("%H:%M")} | {self.callsign} | {self.spot_deeplink} | freq: {self.frequency} | mode: {self.mode} | loc: {self.summitRef}{self.wwffRef}' \ No newline at end of file From 58c63c06c4dc2c84b865b6cbe2bc3a09bd11a3cc Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:18:22 +0000 Subject: [PATCH 06/11] typo --- spotbot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spotbot.py b/spotbot.py index c0bd5d9..8961e0b 100644 --- a/spotbot.py +++ b/spotbot.py @@ -27,7 +27,7 @@ def combine_messages(self, m1, m2): return f"{m1}\n{m2}" def get_last_message(self): - last_message_entity = self.table.query_for_entity(self.callsign) + last_message_entity = self.table.query_for_entity(self.ham.callsign) if self.is_entity_recent(last_message_entity): messageId = last_message_entity['MessageId'] existing_message = self.discord_http.get_message_from_id(messageId) From 7877944fc827e7409f49cd136840b1cb2a17ea9a Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:22:40 +0000 Subject: [PATCH 07/11] typo with method --- hamalertmessage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hamalertmessage.py b/hamalertmessage.py index eec5cfd..235bcf8 100644 --- a/hamalertmessage.py +++ b/hamalertmessage.py @@ -21,4 +21,4 @@ def spot_deeplink(self): return "" def __str__(self): - return f'{self.received_time_pt.strftime("%H:%M")} | {self.callsign} | {self.spot_deeplink} | freq: {self.frequency} | mode: {self.mode} | loc: {self.summitRef}{self.wwffRef}' \ No newline at end of file + return f'{self.received_time_pt.strftime("%H:%M")} | {self.callsign} | {self.spot_deeplink()} | freq: {self.frequency} | mode: {self.mode} | loc: {self.summitRef}{self.wwffRef}' \ No newline at end of file From 5474d128f06b4e4351b7a97214fefaa72fdee014 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 06:33:18 +0000 Subject: [PATCH 08/11] save and pass messageid --- spotbot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spotbot.py b/spotbot.py index 8961e0b..eb108a9 100644 --- a/spotbot.py +++ b/spotbot.py @@ -17,7 +17,7 @@ def process(self): previous_message, message_id = self.get_last_message() previous_message = self.strikethrough_mesage(previous_message) content = self.combine_messages(previous_message, self.ham) - self.discord_http.post_message(content, message_id) + message_id = self.discord_http.post_message(content, message_id) self.table.upsert_entity(self.ham.callsign, message_id) def strikethrough_mesage(self, message): From b4d8baade93dfd4ccb430bef98bd9f9256778e82 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 07:25:31 +0000 Subject: [PATCH 09/11] testing the SpotBot.process with fake classes --- spotbot.py | 8 +++----- tables.py | 6 ++++++ test.py | 60 +++++++++++++++++++++++++++++++++++++++--------------- 3 files changed, 53 insertions(+), 21 deletions(-) diff --git a/spotbot.py b/spotbot.py index eb108a9..e59bedb 100644 --- a/spotbot.py +++ b/spotbot.py @@ -2,15 +2,13 @@ import os import datetime from hamalertmessage import HamAlertMessage -from tables import HamAlertTable -from discord_http import DiscordHttp class SpotBot: - def __init__(self, http_req): + def __init__(self, http_req, table, discord_http): self.http_req = http_req self.ham = HamAlertMessage(http_req.get_json()) - self.table = HamAlertTable() - self.discord_http = DiscordHttp() + self.table = table + self.discord_http = discord_http def process(self): logging.info('Processing HamAlert message') diff --git a/tables.py b/tables.py index d30db98..83ce344 100644 --- a/tables.py +++ b/tables.py @@ -10,6 +10,12 @@ def __init__(self): table_service_client = TableServiceClient.from_connection_string(conn_str=connection_string) self.table_client = table_service_client.get_table_client(table_name=table_name) + def initialize_table(self): + connection_string = os.getenv('AzureWebJobsStorage') + table_name = os.getenv('TABLE_NAME') + table_service_client = TableServiceClient.from_connection_string(conn_str=connection_string) + self.table_client = table_service_client.get_table_client(table_name=table_name) + def query_for_entity(self, callsign): entities = [ent for ent in self.table_client.query_entities(f"PartitionKey eq '{callsign}' and RowKey eq '{callsign}'")] if len(entities) > 0: diff --git a/test.py b/test.py index bc447ef..c35d9cd 100644 --- a/test.py +++ b/test.py @@ -5,21 +5,49 @@ class TestSpotBot(unittest.TestCase): - ''' - def test_function_app_basic(self): - dd = datetime.strptime("2024-10-13T01:05:03", "%Y-%m-%dT%H:%M:%S") - req_body = {"callsign":"KI7HSG", "source": "pota", "frequency": "14.074", "mode": "FT8", "wwffRef":"US-0052"} - content = spotbot.create_content(req_body, dd) - expected = '01:05 | KI7HSG | [pota](https://api.pota.app/spot/comments/KI7HSG/US-0052) | freq: 14.074 | mode: FT8 | loc: US-0052' - self.assertEqual(content, expected) - - def test_function_app(self): - dd = datetime.strptime("2024-10-13T01:05:03", "%Y-%m-%dT%H:%M:%S") - req_body = {"callsign":"KI7HSG", "source": "sotawatch", "frequency": "14.074", "mode": "FT8", "summitRef": "ABCD"} - content = spotbot.create_content(req_body, dd) - expected = '01:05 | KI7HSG | [sotawatch](https://sotl.as/activators/KI7HSG) | freq: 14.074 | mode: FT8 | loc: ABCD' - self.assertEqual(content, expected) - ''' - + def test_spotbot(self): + sb = spotbot.SpotBot(FakeHttpRequest(), table=FakeHamAlertTable(FakeEntity("1234", "KI7HSG")), discord_http=FakeDiscordHttp()) + sb.process() + self.assertEqual(sb.table.saved_callsign, "KI7HSG") + self.assertEqual(sb.table.saved_messageId, "9876") + dt = sb.ham.received_time_pt.strftime("%H:%M") + self.assertEqual(sb.discord_http.posted_message, f"~~01:05 | KI7HSG | [pota](https://api.pota.app/spot/comments/KI7HSG/US-0052) | freq: 14.074 | mode: FT8 | loc: US-0052~~\n{dt} | KI7HSG | [sotawatch](https://sotl.as/activators/KI7HSG) | freq: 14.074 | mode: FT8 | loc: ABCD") + +''' +Fake classes for testing +''' + +class FakeHttpRequest: + def get_json(self): + return {"callsign":"KI7HSG", "source": "sotawatch", "frequency": "14.074", "mode": "FT8", "summitRef": "ABCD"} + +class FakeHamAlertTable: + def __init__(self, fake_entity): + self.saved_callsign = None + self.saved_messageId = None + self.fake_entity = fake_entity + def query_for_entity(self, callsign): + return self.fake_entity + def upsert_entity(self, callsign, messageId): + self.saved_callsign = callsign + self.saved_messageId = messageId + +class FakeEntity(dict): + def __init__(self, messageId, callsign): + self['MessageId'] = messageId + self['PartitionKey'] = callsign + self['RowKey'] = callsign + self.metadata = {"timestamp": datetime.now(timezone('US/Pacific'))} + +class FakeDiscordHttp: + def __init__(self): + self.posted_message = None + def post_message(self, content, messageId=None): + self.posted_message = content + return "9876" + def get_message_from_id(self, messageId): + return '01:05 | KI7HSG | [pota](https://api.pota.app/spot/comments/KI7HSG/US-0052) | freq: 14.074 | mode: FT8 | loc: US-0052' + + if __name__ == '__main__': unittest.main() From 0cdd4fafea7571b36b622e2c07ce0f3c0cbee5b1 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 07:36:34 +0000 Subject: [PATCH 10/11] fix bug when no previous message --- spotbot.py | 7 +++++-- test.py | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/spotbot.py b/spotbot.py index e59bedb..d85fbf4 100644 --- a/spotbot.py +++ b/spotbot.py @@ -13,8 +13,11 @@ def __init__(self, http_req, table, discord_http): def process(self): logging.info('Processing HamAlert message') previous_message, message_id = self.get_last_message() - previous_message = self.strikethrough_mesage(previous_message) - content = self.combine_messages(previous_message, self.ham) + if previous_message: + previous_message = self.strikethrough_mesage(previous_message) + content = self.combine_messages(previous_message, self.ham) + else: + content = str(self.ham) message_id = self.discord_http.post_message(content, message_id) self.table.upsert_entity(self.ham.callsign, message_id) diff --git a/test.py b/test.py index c35d9cd..9b7e97e 100644 --- a/test.py +++ b/test.py @@ -13,6 +13,15 @@ def test_spotbot(self): dt = sb.ham.received_time_pt.strftime("%H:%M") self.assertEqual(sb.discord_http.posted_message, f"~~01:05 | KI7HSG | [pota](https://api.pota.app/spot/comments/KI7HSG/US-0052) | freq: 14.074 | mode: FT8 | loc: US-0052~~\n{dt} | KI7HSG | [sotawatch](https://sotl.as/activators/KI7HSG) | freq: 14.074 | mode: FT8 | loc: ABCD") + def test_spotbot_2(self): + sb = spotbot.SpotBot(FakeHttpRequest(), table=FakeHamAlertTable(None), discord_http=FakeDiscordHttp()) + sb.process() + self.assertEqual(sb.table.saved_callsign, "KI7HSG") + self.assertEqual(sb.table.saved_messageId, "9876") + dt = sb.ham.received_time_pt.strftime("%H:%M") + self.assertEqual(sb.discord_http.posted_message, f"{dt} | KI7HSG | [sotawatch](https://sotl.as/activators/KI7HSG) | freq: 14.074 | mode: FT8 | loc: ABCD") + + ''' Fake classes for testing ''' From 5b7cd7043545de70cae7a329c35b91105b3d7601 Mon Sep 17 00:00:00 2001 From: Trevor Blanarik Date: Sat, 19 Oct 2024 07:41:02 +0000 Subject: [PATCH 11/11] pass params --- function_app.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/function_app.py b/function_app.py index 0f40f96..897b555 100644 --- a/function_app.py +++ b/function_app.py @@ -1,6 +1,8 @@ import logging import azure.functions as func import spotbot as sb +import tables +import discord_http import cleanup app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION) @@ -8,7 +10,7 @@ @app.route(route="spotbot", methods=[func.HttpMethod.POST]) def spotbot(req: func.HttpRequest) -> func.HttpResponse: try: - sb.SpotBot(req).process() + sb.SpotBot(req, tables.HamAlertTable(), discord_http.DiscordHttp()).process() except Exception as _excpt: logging.error(f"Exception occurred: {_excpt}") return func.HttpResponse(body=f"Exception occurred: {_excpt}", status_code=500)