Skip to content

Examples

darkboy0p edited this page Feb 7, 2026 · 1 revision

📝 Examples & Recipes

1. Server Dashboard

from flask import Flask, render_template, jsonify
from minecraft_server_utility import ServerPinger
import threading
import time

app = Flask(__name__)

servers = {
    "Hypixel": "mc.hypixel.net",
    "Mineplex": "us.mineplex.com",
    "Cubecraft": "play.cubecraft.net"
}

server_status = {}

def update_status():
    while True:
        for name, host in servers.items():
            try:
                pinger = ServerPinger(host, timeout=3)
                info = pinger.ping()
                server_status[name] = {
                    'online': True,
                    'players': info['players']['online'],
                    'max_players': info['players']['max'],
                    'latency': info['latency'],
                    'version': info['version'],
                    'motd': info['motd']
                }
            except:
                server_status[name] = {'online': False}
        
        time.sleep(60)  # Update every minute

@app.route('/')
def index():
    return render_template('dashboard.html', servers=server_status)

@app.route('/api/status')
def api_status():
    return jsonify(server_status)

# Start background thread
thread = threading.Thread(target=update_status, daemon=True)
thread.start()

if __name__ == '__main__':
    app.run(debug=True)

2. Player Tracker

import sqlite3
import schedule
import time
from minecraft_server_utility import MojangAPI
from datetime import datetime

class PlayerTracker:
    def __init__(self, db_path='players.db'):
        self.db = sqlite3.connect(db_path)
        self.mojang = MojangAPI()
        self.create_tables()
    
    def create_tables(self):
        self.db.execute('''
            CREATE TABLE IF NOT EXISTS players (
                username TEXT PRIMARY KEY,
                uuid TEXT,
                first_seen TIMESTAMP,
                last_seen TIMESTAMP
            )
        ''')
        
        self.db.execute('''
            CREATE TABLE IF NOT EXISTS player_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT,
                timestamp TIMESTAMP,
                skin_url TEXT,
                FOREIGN KEY (username) REFERENCES players(username)
            )
        ''')
    
    def track_player(self, username):
        # Get player info
        uuid = self.mojang.get_uuid(username)
        skin_url = self.mojang.get_skin_url(uuid) if uuid else None
        
        # Store in database
        now = datetime.now()
        
        # Update or insert player
        self.db.execute('''
            INSERT OR REPLACE INTO players 
            (username, uuid, first_seen, last_seen)
            VALUES (?, ?, 
                COALESCE((SELECT first_seen FROM players WHERE username = ?), ?),
                ?)
        ''', (username, uuid, username, now, now))
        
        # Add to history
        if skin_url:
            self.db.execute('''
                INSERT INTO player_history (username, timestamp, skin_url)
                VALUES (?, ?, ?)
            ''', (username, now, skin_url))
        
        self.db.commit()
        return uuid, skin_url
    
    def get_player_history(self, username):
        cursor = self.db.execute('''
            SELECT timestamp, skin_url 
            FROM player_history 
            WHERE username = ? 
            ORDER BY timestamp DESC
        ''', (username,))
        
        return cursor.fetchall()
    
    def close(self):
        self.db.close()

# Usage
tracker = PlayerTracker()

# Track a player
uuid, skin = tracker.track_player("Technoblade")
print(f"UUID: {uuid}")
print(f"Skin: {skin}")

# Get history
history = tracker.get_player_history("Technoblade")
for timestamp, skin_url in history:
    print(f"{timestamp}: {skin_url}")

tracker.close()

3. Auto-Responder for Discord

import discord
from discord.ext import commands
from minecraft_server_utility import ServerPinger
import re

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

# Regex to detect server IPs in messages
SERVER_REGEX = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b:\d{1,5}\b'
HOSTNAME_REGEX = r'\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b:\d{1,5}\b'

@bot.event
async def on_message(message):
    # Don't respond to ourselves
    if message.author == bot.user:
        return
    
    # Check for server addresses in message
    server_matches = re.findall(SERVER_REGEX, message.content)
    hostname_matches = re.findall(HOSTNAME_REGEX, message.content)
    
    all_matches = server_matches + hostname_matches
    
    for match in all_matches:
        try:
            host, port = match.split(':')
            port = int(port)
            
            # Ping the server
            pinger = ServerPinger(host, port, timeout=3)
            info = pinger.ping()
            
            # Create response
            if info['online']:
                response = (f"🎮 **Server Status: {host}:{port}**\n"
                          f"🟢 **Online** | 👥 {info['players']['online']}/{info['players']['max']} players\n"
                          f"⚡ {info['latency']}ms | 🏷️ {info['version']}\n"
                          f"📝 {info['motd'][:50]}...")
            else:
                response = f"🔴 **Server {host}:{port} is offline**"
            
            await message.channel.send(response)
            
        except Exception as e:
            # Silently ignore errors
            pass
    
    # Process commands
    await bot.process_commands(message)

bot.run("YOUR_BOT_TOKEN")

Clone this wiki locally