gotify.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. import httpx
  3. import json
  4. import os
  5. class GotifyNotifier:
  6. def __init__(self, title, message, token_name=''):
  7. self.gotify_url = 'https://gotify.erhe.top'
  8. self.app_token = self.match_token_name(token_name)
  9. self.title = title
  10. self.message = message
  11. def match_token_name(self, name):
  12. token_name_dict = {}
  13. # 读取项目根目录下的 gotify_config.json 文件
  14. gotify_config_path = os.path.join(PROJECT_PATH, 'gotify_config.json')
  15. with open(gotify_config_path, 'r') as f:
  16. token_name_dict = json.load(f)
  17. token = token_name_dict.get(name)
  18. if token:
  19. return token
  20. else:
  21. return token_name_dict['base']
  22. def send_message(self):
  23. # 构建POST请求的headers
  24. headers = {
  25. 'Content-Type': 'application/json'
  26. }
  27. # 构建POST请求的body
  28. body = {
  29. 'title': self.title,
  30. 'message': self.message
  31. }
  32. # 发送POST请求
  33. with httpx.Client() as client:
  34. response = client.post(
  35. url=f"{self.gotify_url}/message?token={self.app_token}",
  36. headers=headers,
  37. json=body
  38. )
  39. # 或者可以使用 curl
  40. # curl -k "https://gotify.erhe.top/message?token=A0Xg6ZE5946iBYg" -F "title=测试发送信息" -F "message=假装有信息,测试发送" -F "priority=5"
  41. # 检查响应状态码
  42. if response.status_code == 200:
  43. print('Gotify Message sent successfully!')
  44. else:
  45. print('Failed to send message:', response.text)