utils_gotify.py 1.7 KB

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