clash_api.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. import requests
  3. import configure
  4. from vs_types import NotFoundError, BizLogicError
  5. def switch_next_node():
  6. headers = {
  7. "Authorization": f"Bearer {configure.CLASH_API_KEY}",
  8. "Content-Type": "application/json"
  9. }
  10. try:
  11. resp = requests.get(f"{configure.CLASH_API_URL}/proxies", headers=headers, timeout=5)
  12. except Exception as e:
  13. raise BizLogicError(f'Fetch proxies error, e={e}')
  14. proxies_data = resp.json()
  15. proxies = proxies_data.get('proxies')
  16. if configure.CLASH_GROUP_NAME not in proxies:
  17. raise NotFoundError(message=f"Group '{configure.CLASH_GROUP_NAME}' not found")
  18. group = proxies[configure.CLASH_GROUP_NAME]
  19. all_nodes = group['all']
  20. current_node = group['now']
  21. try:
  22. idx = all_nodes.index(current_node)
  23. next_idx = (idx + 1) % len(all_nodes)
  24. next_node = all_nodes[next_idx]
  25. except ValueError:
  26. next_node = all_nodes[0]
  27. data = {"name": next_node}
  28. try:
  29. resp = requests.put(f"{configure.CLASH_API_URL}/proxies/{configure.CLASH_GROUP_NAME}", headers=headers, json=data, timeout=5)
  30. except Exception as e:
  31. raise BizLogicError(f'Switch to {next_node} error, e={e}')
  32. return next_node
  33. if __name__ == "__main__":
  34. switch_next_node()