import json import math import os import requests import time from keepalive import…
- User
import json import math import os import requests import time from keep_alive import keep_alive
keep_alive()
url = ("https://api.mcstatus.io/v2/status/java/" + os.environ['SERVER_IP'])
while True: response = requests.get(url) json_data = json.loads(response.text)
expires_at = json_data['expires_at'] / 1000 current_time = time.time()
print("Current time:", current_time, " Expires at:", expires_at) players_list = json_data['players']['list'] players_online = json_data['players']['online'] players_list_names = [player["name_clean"] for player in players_list] print("Players online:", players_online) if players_online > 0: print(players_list_names)
Read the players list from the file
with open("players.json", "r") as file: file_data = file.read() file_list_names = eval(file_data)
Compare the lists
common_players = set(players_list_names) & set(file_list_names) new_players = set(players_list_names) - set(file_list_names) removed_players = set(file_list_names) - set(players_list_names)
if len(common_players) > 0: print("Common Players:", common_players) if len(new_players) > 0: print("New Players:", new_players) if len(removed_players) > 0: print("Removed Players:", removed_players)
if len(removed_players) or len(new_players): list_leaving = f"- {', '.join(removed_players)}" list_joining = f"+ {', '.join(new_players)}"
web_content = f"<t:{math.trunc(expires_at)}> Online: {players_online}" web_content += "```diff" if len(removed_players) > 0: web_content += f"\n{list_leaving}" if len(new_players) > 0: web_content += f"\n{list_joining}" web_content += "```" data = { 'content': web_content}
requests.post(os.environ['WEBHOOK_URL'], json=data)with open("players.json", "w") as file: json.dump(players_list_names, file)
time.sleep(expires_at - current_time)
- Assistant
The code snippet is a script that interacts with the Minecraft server API to check the status of a Minecraft server and notify a Discord channel whenever a player joins or leaves the server.
The script does the following:
- User
where do i put catching exceptions
- Assistant
To catch exceptions in the script, you can use a try-except block. Here's an example of where you can implement exception handling in the code:
try: response = requests.get(url) response.raise_for_status() # Raise an exception for HTTP errors json_data = json.loads(response.text) # Rest of the code for processing the JSON data and sending the Discord message except requests.exceptions.RequestException as e: print("An error occurred while making the API request:", e) except json.JSONDecodeError as e: print("An error occurred while parsing the JSON response:", e) except Exception as e: print("An unexpected error occurred:", e)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.