feat: enhance message handling with content pattern matching and update environment configuration
This commit is contained in:
@@ -50,6 +50,7 @@ logging.basicConfig(
|
||||
load_dotenv()
|
||||
|
||||
WEBHOOK_URL = os.getenv('DISCORD_WEBHOOK_URL')
|
||||
TEST_MESSAGE_DELETE_PATTERN = r"test notification"
|
||||
|
||||
|
||||
def get_state() -> dict:
|
||||
@@ -158,13 +159,16 @@ def create_embed(type: str, tz_list: list[str] | None = None) -> dict:
|
||||
return embed
|
||||
|
||||
|
||||
def send_notification(message: str) -> None:
|
||||
def send_notification(message: str) -> bool:
|
||||
"""
|
||||
Send a notification to the Discord webhook.
|
||||
|
||||
Returns:
|
||||
bool: True when the webhook accepted the notification, False otherwise.
|
||||
"""
|
||||
if not WEBHOOK_URL:
|
||||
logging.error("WEBHOOK_URL not set")
|
||||
return
|
||||
return False
|
||||
|
||||
_update_state(
|
||||
last_type=message,
|
||||
@@ -192,6 +196,7 @@ def send_notification(message: str) -> None:
|
||||
logging.info(f"Notification sent: {message}")
|
||||
_update_state(last_success_at=datetime.now(),
|
||||
last_status_code=response.status_code)
|
||||
return True
|
||||
else:
|
||||
logging.error(
|
||||
f"Failed to send notification: {response.status_code} - "
|
||||
@@ -199,9 +204,23 @@ def send_notification(message: str) -> None:
|
||||
)
|
||||
_update_state(last_status_code=response.status_code,
|
||||
last_error=response.text)
|
||||
return False
|
||||
except requests.RequestException as e:
|
||||
logging.error(f"Error sending notification: {e}")
|
||||
_update_state(last_error=str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _schedule_startup_test_cleanup(test_sent: bool) -> None:
|
||||
"""Schedule one-time cleanup for the startup test notification."""
|
||||
if not test_sent:
|
||||
return
|
||||
|
||||
def cleanup_startup_test_message() -> schedule.CancelJob:
|
||||
delete_old_messages(1, content_pattern=TEST_MESSAGE_DELETE_PATTERN)
|
||||
return schedule.CancelJob
|
||||
|
||||
schedule.every(1).minutes.do(cleanup_startup_test_message)
|
||||
|
||||
|
||||
def schedule_notification(interval: str, at: str, type: str) -> None:
|
||||
@@ -237,10 +256,9 @@ def main() -> None:
|
||||
|
||||
logging.info("Scheduler started.")
|
||||
|
||||
# Test the notification on startup
|
||||
send_notification("test")
|
||||
# delete the test message after a short delay to keep the channel clean
|
||||
schedule.every(1).minutes.do(delete_old_messages, 1)
|
||||
# Send one startup test message and cleanup only if send succeeded.
|
||||
test_sent = send_notification("test")
|
||||
_schedule_startup_test_cleanup(test_sent)
|
||||
|
||||
# delete old messages on startup to clean up any previous notifications
|
||||
# delete_old_messages(6)
|
||||
|
||||
Reference in New Issue
Block a user