1
0

bot-telegram.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. # coding: utf-8
  3. # Create by : https://github.com/lidalao/ServerStatus
  4. # 版本:0.0.1, 支持Python版本:2.7 to 3.9
  5. # 支持操作系统: Linux, OSX, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
  6. import os
  7. import sys
  8. import requests
  9. import time
  10. import traceback
  11. NODE_STATUS_URL = 'http://serverstatus/json/stats.json'
  12. offs = []
  13. counterOff = {}
  14. counterOn = {}
  15. def _send(text):
  16. chat_id = os.getenv('TG_CHAT_ID')
  17. bot_token = os.environ.get('TG_BOT_TOKEN')
  18. url = f"https://api.telegram.org/bot{bot_token}/sendMessage?parse_mode=HTML&disable_web_page_preview=true&chat_id=" + chat_id + "&text=" + text
  19. try:
  20. requests.get(url)
  21. except Exception as e:
  22. print("catch exception: ", traceback.format_exc())
  23. def send2tg(srv, flag):
  24. if srv not in counterOff:
  25. counterOff[srv] = 0
  26. if srv not in counterOn:
  27. counterOn[srv] = 0
  28. if flag == 1 : # online
  29. if srv in offs:
  30. if counterOn[srv] < 10:
  31. counterOn[srv] += 1
  32. return
  33. #1. Remove srv from offs; 2. Send to tg: I am online
  34. offs.remove(srv)
  35. counterOn[srv] = 0
  36. text = '<b>Server Status</b>' + '\n主机上线: ' + srv
  37. _send(text)
  38. else: #offline
  39. if srv not in offs:
  40. if counterOff[srv] < 10:
  41. counterOff[srv] += 1
  42. return
  43. #1. Append srv to offs; 2. Send to tg: I am offline
  44. offs.append(srv)
  45. counterOff[srv] = 0
  46. text = '<b>Server Status</b>' + '\n主机下线: ' + srv
  47. _send(text)
  48. def sscmd(address):
  49. while True:
  50. r = requests.get(url=address, headers={"User-Agent": "ServerStatus/20211116"})
  51. try:
  52. jsonR = r.json()
  53. except Exception as e:
  54. print('未发现任何节点')
  55. continue
  56. for i in jsonR["servers"]:
  57. if i["online4"] is False and i["online6"] is False:
  58. send2tg(i["name"], 0)
  59. else:
  60. send2tg(i["name"], 1)
  61. time.sleep(3)
  62. if __name__ == '__main__':
  63. sscmd(NODE_STATUS_URL)