Gotify实战:5种你可能没想到的自动化通知场景(附Python代码)
Gotify实战5种你可能没想到的自动化通知场景附Python代码当开发者谈论消息推送时第一反应往往是服务器监控或CI/CD告警。但Gotify这个轻量级开源工具的能力远不止于此——它更像是一把瑞士军刀能在各种自动化场景中优雅地解决最后一公里通知问题。本文将带你探索五个非常规但极具实用价值的应用场景每个方案都配有可立即投入生产的Python实现。1. CI/CD流水线中的智能交互通知传统CI/CD通知只是单向推送构建结果而结合Gotify的WebSocket特性我们可以实现带交互按钮的部署审批流程。以下示例展示如何在GitLab Pipeline中嵌入审批功能# gitlab_interactive_notification.py import requests import json from datetime import datetime GOTIFY_URL https://your-gotify-server.com/message APP_TOKEN your_app_token def send_approval_request(pipeline_id, project_name): message { title: f部署审批请求 - {project_name}, message: fPipeline #{pipeline_id} 等待部署到生产环境, priority: 8, extras: { client::display: { contentType: text/markdown }, client::notification: { click: { url: fhttps://gitlab.com/your-project/-/pipelines/{pipeline_id} } }, actions: [ { label: ✅ 批准, url: fhttps://your-api-server.com/approve?pipeline{pipeline_id}, clear: True }, { label: ❌ 拒绝, url: fhttps://your-api-server.com/reject?pipeline{pipeline_id}, clear: True } ] } } response requests.post( f{GOTIFY_URL}?token{APP_TOKEN}, jsonmessage, headers{Content-Type: application/json} ) return response.status_code 200关键实现要点使用extras.actions字段创建可点击按钮priority设为8高优先级确保及时提醒通过client::notification.click实现点击跳转到Pipeline详情效果对比传统通知增强版通知仅文本消息带Markdown格式需主动查看日志一键跳转GitLab需登录系统审批直接消息内操作2. 智能家居异常状态预警系统将Gotify与Home Assistant集成可以打造比IFTTT更灵活的自动化预警机制。下面是通过设备状态变化触发多级报警的示例# home_automation_alert.py import requests from enum import Enum class AlertLevel(Enum): INFO 5 WARNING 7 CRITICAL 9 def send_home_alert(device_name, current_state, expected_state, levelAlertLevel.WARNING): priority level.value state_emoji { on: , off: , open: , closed: , detected: ⚠️, normal: ✅ }.get(current_state.lower(), ) message ( f{state_emoji} **家居设备异常**\n f设备: {device_name}\n f当前状态: {current_state}\n f预期状态: {expected_state}\n f时间: {datetime.now().strftime(%Y-%m-%d %H:%M:%S)} ) if priority AlertLevel.CRITICAL.value: message \n\n 请立即处理 payload { message: message, title: f智能家居警报 - {device_name}, priority: priority } requests.post(GOTIFY_URL, jsonpayload)典型应用场景安防预警当门窗传感器在布防时段被触发时发送CRITICAL级警报能耗监控空调在无人时段运行超过2小时发送WARNING提醒设备离线网关设备失去连接时自动通知3. 爬虫异常实时通知中心对于分布式爬虫系统Gotify可以成为轻量级的监控中心。以下代码展示如何实现带诊断信息的爬虫异常上报# crawler_monitor.py import traceback import psutil import platform def send_crawler_alert(crawler_name, exceptionNone, urlNone): system_info { CPU: f{psutil.cpu_percent()}%, Memory: f{psutil.virtual_memory().percent}%, OS: platform.platform() } if exception: error_msg f\n{traceback.format_exc()[:500]}\n title f爬虫异常 - {crawler_name} message ( f❌ **捕获未处理异常**\n f最后请求URL: {url or N/A}\n f系统状态:\n{format_system_info(system_info)}\n f异常详情:\n{error_msg} ) priority 8 else: title f爬虫心跳 - {crawler_name} message ( f✅ **正常运行中**\n f系统状态:\n{format_system_info(system_info)} ) priority 3 send_gotify_notification(title, message, priority) def format_system_info(info): return \n.join([f- {k}: {v} for k,v in info.items()])最佳实践建议在爬虫的异常处理模块中调用send_crawler_alert定时发送心跳信息防止进程僵死附加当前任务URL方便问题复现使用Markdown代码块格式化异常堆栈4. 个性化股票价格提醒服务相比传统财经APP的固定阈值提醒用Gotify可以实现更智能的股票监控。以下是支持技术指标触发的实现# stock_alert.py import yfinance as yf from ta.trend import MACD def check_stock_alert(symbol, config): stock yf.Ticker(symbol) hist stock.history(period1mo) # 计算MACD指标 macd MACD(hist[Close]).macd() signal MACD(hist[Close]).macd_signal() current_price hist.iloc[-1][Close] prev_price hist.iloc[-2][Close] change (current_price - prev_price) / prev_price * 100 alerts [] # 价格突破提醒 if config.get(upper_limit) and current_price config[upper_limit]: alerts.append(f突破上限 ${config[upper_limit]}) if config.get(lower_limit) and current_price config[lower_limit]: alerts.append(f跌破下限 ${config[lower_limit]}) # MACD金叉死叉提醒 if macd[-1] signal[-1] and macd[-2] signal[-2]: alerts.append(出现MACD金叉) elif macd[-1] signal[-1] and macd[-2] signal[-2]: alerts.append(出现MACD死叉) if alerts: message ( f **{symbol} 价格提醒**\n f当前价: ${current_price:.2f} ({change:.2f}%)\n f触发条件:\n- \n- .join(alerts) ) send_gotify_notification( titlef股票警报 - {symbol}, messagemessage, priority7 )扩展功能建议添加RSI超买超卖提醒支持自选股列表轮询生成价格变化趋势图作为附件设置安静时段避免夜间打扰5. 自动化测试报告智能推送将测试结果通过Gotify推送可以比邮件更及时地发现问题。以下是生成带详情的测试报告示例# test_reporter.py import unittest from io import StringIO class TestReporter(unittest.TestResult): def __init__(self, suite_name): super().__init__() self.suite_name suite_name self.buffer StringIO() def format_failure(self, test, err): self.buffer.write(f### ❌ {test._testMethodName}\n) self.buffer.write(f\n{err[1]}\n\n) def format_success(self, test): self.buffer.write(f✅ {test._testMethodName}\n) def send_report(self): total self.testsRun failed len(self.failures) passed total - failed message ( f **测试套件 {self.suite_name} 完成**\n f通过率: {passed}/{total} ({passed/total*100:.1f}%)\n\n f{self.buffer.getvalue()} ) priority 6 if failed else 3 send_gotify_notification( titlef测试报告 - {self.suite_name}, messagemessage, prioritypriority ) # 使用示例 if __name__ __main__: suite unittest.defaultTestLoader.discover(tests) reporter TestReporter(核心功能测试) suite.run(reporter) reporter.send_report()报告优化技巧为失败用例添加截图附件按模块分组测试结果添加历史通过率对比重要失败用例高亮显示集成到Jenkins/TeamCity等CI系统高级技巧结构化消息与消息管理Gotify的真正威力在于其灵活的消息结构。以下是一些提升使用体验的技巧1. Markdown表格推送def send_markdown_table(data): table_header | Metric | Value | Status |\n|--------|-------|--------|\n table_rows \n.join( [f| {k} | {v} | {✅ if v threshold else ❌} | for k, v, threshold in data] ) send_gotify_notification( title系统状态报告, messagetable_header table_rows, extras{client::display: {contentType: text/markdown}} )2. 消息自动过期设置def send_temporary_message(content, expire_hours1): send_gotify_notification( title临时通知, messagecontent, extras{client::notification: {autoDelete: expire_hours * 3600}} )3. 消息聚合发送避免通知轰炸from collections import defaultdict class MessageAggregator: def __init__(self, timeout300): self.buffer defaultdict(list) self.timeout timeout def add_message(self, category, content): self.buffer[category].append(content) def flush(self): for category, messages in self.buffer.items(): combined \n.join(f- {msg} for msg in messages) send_gotify_notification( titlef聚合通知 - {category}, messagecombined, priority5 ) self.buffer.clear()这些方案展示了Gotify在常规监控之外的创新应用可能。它的轻量级特性和开放API使其成为自动化工作流中理想的最后一公里通知解决方案远比商业SaaS产品更灵活可控。