diff --git a/README.md b/README.md index 773af02..dd28433 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ ## Introduction -This bot gathers player statistics, sends broadcast messages, and uses an RCON-API integration to communicate with players. Follow the steps below to install and run the bot. +This bot gathers player statistics, sends broadcast messages, and uses an RCON-API integration to communicate with players. The bot now loads broadcast messages from a TXT file and sends them based on the specified interval. Follow the steps below to install and run the bot. -ToDo: +## ToDo: Execute the following commands after downloading: 1. Copy the `.env.dist` file to `.env` and enter your values. 2. Run the command `pip install python-dotenv`. @@ -27,58 +27,79 @@ Before installing the bot, make sure you have the following: First, clone this repository to your local machine: -``` -bash +```bash git clone https://github.com/hackletloose/hall-braod-stats.git cd hall-broad-stats ``` + ### 2. Setup a virtual Environment (Optional) + It is recommended to use a virtual environment to manage dependencies: -``` + +```bash python3 -m venv venv source venv/bin/activate # On Windows use: venv\Scripts\activate ``` + ### 3. Install Required Packages + Install the required Python packages using pip: -``` + +```bash pip install -r requirements.txt ``` + ### 4. Set Up Environment Variables -Create a .env file in the root directory with the following content: -``` + +Create a `.env` file in the root directory with the following content: + +```bash API_TOKEN=your_api_token_here BASE_URL=https://your-api-base-url.com LOGGING_ENABLED=true +MESSAGE_FILE=messages.txt +``` + +Replace `your_api_token_here` with your actual API token, and `https://your-api-base-url.com` with the correct URL for your server. The `MESSAGE_FILE` points to the text file containing broadcast messages. + +### 5. Configure the `messages.txt` File + +The `messages.txt` file is used to send pre-set messages through the bot. Each line in the file should have the format: + ``` -Replace your_api_token_here with your actual API token and https://your-api-base-url.com with the correct URL for your server. -### 5. Configure the broadcast.json File -Make sure the broadcast.json file contains valid broadcast messages. This file is used to send pre-set messages through the bot. Modify the file as needed: + +``` + +For example: + ``` -[ - { - "content": "Welcome to the battlefield!" - }, - { - "content": "Top players are being ranked now!" - } -] +7 Welcome to the server! Please follow the server rules. +60 Join our Discord for VIP access! ``` + ### 6. Run the Bot -Disable the AutoBroadcast funktion in your crcon! + Start the bot using the following command: -``` + +```bash python broad-stats.py ``` + ### 7. Usage -Disable the AutoBroadcast funktion in your crcon! + The bot will now: - Fetch player statistics from the API. -- Send regular broadcast messages. +- Send regular broadcast messages based on the `messages.txt` file. - Rank players in various categories (kills, defense, etc.). + ### 8. Logging -If logging is enabled, you will see log messages printed to the console. To enable/disable logging, modify the LOGGING_ENABLED variable in the .env file. + +If logging is enabled, you will see log messages printed to the console. To enable/disable logging, modify the `LOGGING_ENABLED` variable in the `.env` file. + ### Troubleshooting -- Error accessing API: Check if the API_TOKEN and BASE_URL are correct in the .env file. -- No player data: Ensure the server is running and accessible via the API. -- Module not found: Ensure all dependencies are installed using the command pip install -r requirements.txt. + +- **Error accessing API**: Check if the `API_TOKEN` and `BASE_URL` are correct in the `.env` file. +- **No player data**: Ensure the server is running and accessible via the API. +- **Module not found**: Ensure all dependencies are installed using the command `pip install -r requirements.txt`. + diff --git a/broad-stats.py b/broad-stats.py index 80b3e53..8d9187a 100644 --- a/broad-stats.py +++ b/broad-stats.py @@ -1,4 +1,3 @@ -import json import requests import time import random @@ -6,18 +5,11 @@ from dotenv import load_dotenv import os -# .env-Datei laden load_dotenv() - -# Umgebungsvariablen abrufen api_token = os.getenv('API_TOKEN') BASE_URL = os.getenv('BASE_URL') LOGGING_ENABLED = os.getenv('LOGGING_ENABLED', 'false').lower() == 'true' -# JSON-Daten laden -with open('broadcast.json', 'r') as json_file: - json_data = json.load(json_file) - def log(message): if LOGGING_ENABLED: print(f"[LOG]: {message}") @@ -28,7 +20,6 @@ def get_team_view(api_token): response = requests.get(url, headers=headers) if response.status_code == 200: team_view_data = response.json() - # Überprüfung hinzugefügt, ob Spielerdaten vorhanden sind if "allies" in team_view_data["result"] and "axis" in team_view_data["result"]: allies = team_view_data["result"]["allies"]["squads"] axis = team_view_data["result"]["axis"]["squads"] @@ -43,7 +34,7 @@ def get_team_view(api_token): all_players.append(player_info) return all_players else: - log("Keine Spielerdaten verfügbar.") + log("No player data available.") return [] else: log(f"Error accessing API: {response.status_code}") @@ -67,70 +58,63 @@ def send_broadcast(api_token, message): headers = {"Authorization": f"Bearer {api_token}"} response = requests.post(api_url, json=api_data, headers=headers) if response.status_code == 200: - log(f"Daten erfolgreich an die API gesendet: {message}") + log(f"Data successfully sent to the API: {message}") else: - log(f"Fehler beim Senden der Daten an die API: {response.status_code}") + log(f"Error sending data to the API. {response.status_code}") def print_top_players(all_players, category_name, title): if not all_players or not all(isinstance(player, dict) for player in all_players): - log(f"Ungültige Spielerdaten: {all_players}") + log(f"Invalid player data: {all_players}") return sorted_players = sorted(all_players, key=lambda x: x.get(category_name, 0), reverse=True) top_players_str = f"{title} " for idx, player in enumerate(sorted_players[:5], 1): - player_name = player.get('name', 'Unbekannt') - player_stat = player.get(category_name, 'Unbekannt') + player_name = player.get('name', 'unknown') + player_stat = player.get(category_name, 'unknown') top_players_str += f"{idx}. {player_name} ({player_stat}), " log(top_players_str.rstrip(" ____ ")) send_broadcast(api_token, top_players_str.rstrip(" , ") + " " + top_players_str.rstrip(" , ") + " " + top_players_str.rstrip(" , ") + " " + top_players_str.rstrip(" , ") + " " + top_players_str.rstrip(" , ") + " " + top_players_str.rstrip(" , ")) +def load_messages_from_txt(file_path): + messages = [] + with open(file_path, 'r') as file: + for line in file: + if line.strip(): + time_value, message = line.split(' ', 1) + messages.append((int(time_value), message.strip())) + return messages + def main(api_token): - json_index = 0 + file_path = 'messages.txt' + messages = load_messages_from_txt(file_path) categories = ["kills", "level", "deaths", "offense", "defense", "support", "combat"] - while True: - # Nachricht aus Spielerstatistiken senden - selected_category = "kills" - all_players = get_team_view(api_token) - print_top_players(all_players, selected_category, f"Unser TOP-Killermaschinen: ") - countdown = 120 - while countdown > 0: - sys.stdout.write(f"\rCountdown: {countdown} Sekunden") - sys.stdout.flush() - time.sleep(1) - countdown -= 1 - - # Nachricht aus JSON senden - send_broadcast(api_token, json_data[json_index]["content"]) - json_index = (json_index + 1) % len(json_data) - # Countdown - countdown = 120 - while countdown > 0: - sys.stdout.write(f"\rCountdown: {countdown} Sekunden") - sys.stdout.flush() - time.sleep(1) - countdown -= 1 + for time_value, message in messages: + log(f"Sende Nachricht: {message}") + send_broadcast(api_token, message) + log(f"Wait {time_value} Seconds until the next message.") + time.sleep(time_value) selected_category = random.choice(categories) all_players = get_team_view(api_token) if all_players: if selected_category == "kills": - print_top_players(all_players, selected_category, f"Unser TOP-Killermaschinen: ") + print_top_players(all_players, selected_category, f"Our top killing machines: ") elif selected_category == "level": - print_top_players(all_players, selected_category, f"TOP-Levels auf dem Server: ") + print_top_players(all_players, selected_category, f"Top levels on the server: ") elif selected_category == "deaths": - print_top_players(all_players, selected_category, f"Versager mit den meisten Toden: ") + print_top_players(all_players, selected_category, f"Losers with the most deaths: ") elif selected_category == "offense": - print_top_players(all_players, selected_category, f"Die beste Offensive: ") + print_top_players(all_players, selected_category, f"The best offensive: ") elif selected_category == "defense": - print_top_players(all_players, selected_category, f"Die beste Defense: ") + print_top_players(all_players, selected_category, f"The best defence: ") elif selected_category == "support": - print_top_players(all_players, selected_category, f"Der beste Support: ") + print_top_players(all_players, selected_category, f"The best supporters: ") else: - print_top_players(all_players, selected_category, f"Die bestem im Gefecht: ") + print_top_players(all_players, selected_category, f"The best in combat: ") countdown = 120 while countdown > 0: - sys.stdout.write(f"\rCountdown: {countdown} Sekunden") + sys.stdout.write(f"\rCountdown: {countdown} Seconds") sys.stdout.flush() time.sleep(1) countdown -= 1 diff --git a/broadcast.json b/broadcast.json deleted file mode 100644 index 8b82874..0000000 --- a/broadcast.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "content": "Willkommen beim {servername} Bitte Serverregeln beachten! Discord: https://discord.gg/1bv Anmerkungen, Kritik oder ähnliches kann gerne mit !admin gemeldet werden Willkommen beim {servername}\n Bitte Serverregeln beachten! Discord: https://discord.gg/1bv Anmerkungen, Kritik oder ähnliches kann gerne mit !admin gemeldet werden" - }, - { - "content": "Schließt euch in den Squads zusammen - Vermeidet Solo/Single Squads Bei Nichtbeachtung der Regeln werden wir handeln! Nächste Map {nextmap} Schließt euch in den Squads zusammen - Vermeidet Solo/Single Squads Bei Nichtbeachtung der Regeln werden wir handeln! Nächste Map {nextmap}" - }, - { - "content": "Du willst VIP bekommen? Dann joine unserem Discord und registriere dich mit deiner SteamID Erhalte einen 14-tägigen VIP Zugang. Wie das geht, erfährst du bei uns auf dem Discord Discord: https://discord.gg/1bv" - }, - { - "content": "Protected by hackletloose.eu hackletloose.eu - Ein Zusammenschluss deutscher Serverbetreiber und Administratoren Protected by hackletloose.eu https://discord.gg/hackletloose" - } -] \ No newline at end of file diff --git a/messages.txt b/messages.txt new file mode 100644 index 0000000..06ea62f --- /dev/null +++ b/messages.txt @@ -0,0 +1,11 @@ +7 Willkommen beim {servername}\n Bitte Serverregeln beachten! +7 Discord: https://discord.gg/1bv +7 Anmerkungen, Kritik oder ähnliches kann gerne mit !admin gemeldet werden +7 Schließt euch in den Squads zusammen - Vermeidet Solo/Single Squads +7 Bei nicht Beachtung der Regeln werden wir handeln! +7 Nächste Map {nextmap} +60 Du willst VIP bekommen? +60 Dann joine unserem Discord und registriere dich mit deiner SteamID +60 Erhalte einen 14-tägigen VIP Zugang. Wie das geht, erfährst du bei uns auf dem Discord +60 Discord: https://discord.gg/1bv +60 Protected by hackletloose.eu \ No newline at end of file