83 lines
2.3 KiB
Python
83 lines
2.3 KiB
Python
import time
|
|
import requests
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='Automated Server Restart Script')
|
|
|
|
parser.add_argument('api_url', metavar='server_api_url', type=str, help='ServerAPI Base URL')
|
|
parser.add_argument('token', metavar='token', type=str, help='ServerAPI Token')
|
|
parser.add_argument('--webhook', metavar='discord_webhook', type=str, help='Discord Webhook URL')
|
|
|
|
|
|
def send_discord_webhook(url: str, msg: str) -> bool:
|
|
request = {"content": msg}
|
|
r = requests.post(url, json=request)
|
|
return r.ok
|
|
|
|
|
|
def send_request(url: str, token: str, endpoint: str, request: dict) -> bool:
|
|
headers = {"X-ServerAPI-Token": token}
|
|
|
|
r = requests.post(f"{url}{endpoint}/", headers=headers, json=request)
|
|
return r.ok
|
|
|
|
|
|
def send_command(url: str, token: str, command: str, *args) -> bool:
|
|
request = {"command": command, "args": list(args)}
|
|
return send_request(url, token, "custom", request)
|
|
|
|
|
|
def send_broadcast(url: str, token: str, sender: str, msg: str) -> bool:
|
|
request = {"from": sender, "message": msg}
|
|
return send_request(url, token, "broadcast", request)
|
|
|
|
|
|
def main():
|
|
args = parser.parse_args()
|
|
url = args.api_url
|
|
token = args.token
|
|
webhook = args.webhook
|
|
|
|
print("Sending 5 minute warning")
|
|
r = send_command(url, token, "broadcast", "There will be an automatic server restart in 5 minutes.")
|
|
|
|
if not r:
|
|
print("Failed to send 5 minute warning")
|
|
quit(1)
|
|
|
|
time.sleep(60*4)
|
|
|
|
print("Sending 1 minute warning")
|
|
r = send_command(url, token, "broadcast", "There will be an automatic server restart in 1 minute.")
|
|
|
|
if not r:
|
|
print("Failed to send 1 minute broadcast")
|
|
quit(1)
|
|
|
|
time.sleep(60)
|
|
|
|
print("Sending final warnings")
|
|
for i in range(0, 5):
|
|
r = send_command(url, token, "broadcast", "The server is restarting, get safe!")
|
|
if not r:
|
|
print("Failed to send final restart broadcast")
|
|
quit(1)
|
|
|
|
time.sleep(2)
|
|
|
|
if webhook:
|
|
r = send_discord_webhook(webhook, "Server is going offline for an automated restart.")
|
|
if not r:
|
|
print("Failed to send webhook")
|
|
|
|
print("Restarting")
|
|
r = send_command(url, token, "restart")
|
|
|
|
if not r:
|
|
print("Failed to restart server")
|
|
quit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|