Skip to content

Examples

Runnable example scripts are available in the examples/ directory.

Available Examples

Example Description
basic_usage.py Get started with the SDK
async_usage.py Async client with concurrent requests
leaderboards.py Elo, phase, and record leaderboards
matches.py Match listings and details
versus.py Head-to-head player statistics
weekly_race.py Weekly race data
error_handling.py Exception handling patterns

Running Examples

# Clone the repository
git clone https://github.com/camodotgg/mcsrranked-python
cd mcsrranked-python

# Install dependencies
uv sync

# Run an example
uv run python examples/basic_usage.py

Basic Usage

examples/basic_usage.py
"""Basic usage examples for the MCSR Ranked SDK."""

import mcsrranked

# Get a user's profile
user = mcsrranked.users.get("Feinberg")
print(f"Player: {user.nickname}")
print(f"Elo: {user.elo_rate}")
print(f"Rank: #{user.elo_rank}")
print(f"Country: {user.country}")
print()

# Get user's recent matches
matches = mcsrranked.users.matches(user.uuid, count=5)
print(f"Recent matches for {user.nickname}:")
for match in matches:
    winner = "Win" if match.result and match.result.uuid == user.uuid else "Loss"
    time_str = f"{match.result.time}ms" if match.result else "N/A"
    print(f"  Match {match.id}: {winner} - {time_str}")
print()

# Get the elo leaderboard
leaderboard = mcsrranked.leaderboards.elo()
print(f"Season {leaderboard.season.number} Top 10:")
for player in leaderboard.users[:10]:
    print(f"  #{player.elo_rank} {player.nickname}: {player.elo_rate}")

Async Usage

examples/async_usage.py
"""Async usage examples for the MCSR Ranked SDK."""

import asyncio

from mcsrranked import AsyncMCSRRanked


async def main() -> None:
    """Demonstrate async SDK usage."""
    async with AsyncMCSRRanked() as client:
        # Fetch multiple users concurrently
        users = await asyncio.gather(
            client.users.get("Feinberg"),
            client.users.get("k4yfour"),
            client.users.get("Couriway"),
        )

        print("Players fetched concurrently:")
        for user in users:
            elo = user.elo_rate or "Unranked"
            print(f"  {user.nickname}: {elo}")
        print()

        # Fetch leaderboard and live data concurrently
        leaderboard, live = await asyncio.gather(
            client.leaderboards.elo(),
            client.live.get(),
        )

        print(
            f"Season {leaderboard.season.number} leader: {leaderboard.users[0].nickname}"
        )
        print(f"Online players: {live.players}")
        print(f"Live matches: {len(live.live_matches)}")


if __name__ == "__main__":
    asyncio.run(main())

Leaderboards

examples/leaderboards.py
"""Leaderboard examples for the MCSR Ranked SDK."""

import mcsrranked

# Elo leaderboard (top 150 players)
print("=== Elo Leaderboard ===")
elo_lb = mcsrranked.leaderboards.elo()
print(f"Season {elo_lb.season.number}")
print(f"Starts: {elo_lb.season.starts_at}")
print(f"Ends: {elo_lb.season.ends_at}")
print()
for player in elo_lb.users[:5]:
    print(f"#{player.elo_rank} {player.nickname}: {player.elo_rate}")
print()

# Elo leaderboard filtered by country
print("=== US Elo Leaderboard ===")
us_lb = mcsrranked.leaderboards.elo(country="us")
for player in us_lb.users[:5]:
    print(f"#{player.elo_rank} {player.nickname}: {player.elo_rate}")
print()

# Phase points leaderboard
print("=== Phase Points Leaderboard ===")
phase_lb = mcsrranked.leaderboards.phase()
if phase_lb.phase.number:
    print(f"Phase {phase_lb.phase.number}")
for phase_player in phase_lb.users[:5]:
    points = phase_player.season_result.phase_point
    print(f"{phase_player.nickname}: {points} points")
print()

# Record leaderboard (best times)
print("=== All-Time Record Leaderboard ===")
records = mcsrranked.leaderboards.record()
for record in records[:5]:
    minutes = record.time // 60000
    seconds = (record.time % 60000) // 1000
    ms = record.time % 1000
    print(f"#{record.rank} {record.user.nickname}: {minutes}:{seconds:02d}.{ms:03d}")
print()

# Record leaderboard - distinct (one per player)
print("=== Personal Best Records ===")
pb_records = mcsrranked.leaderboards.record(distinct=True)
for record in pb_records[:5]:
    minutes = record.time // 60000
    seconds = (record.time % 60000) // 1000
    ms = record.time % 1000
    print(f"#{record.rank} {record.user.nickname}: {minutes}:{seconds:02d}.{ms:03d}")

Matches

examples/matches.py
"""Match examples for the MCSR Ranked SDK."""

import mcsrranked
from mcsrranked import MatchType


def format_time(ms: int) -> str:
    """Format milliseconds as MM:SS.mmm."""
    minutes = ms // 60000
    seconds = (ms % 60000) // 1000
    millis = ms % 1000
    return f"{minutes}:{seconds:02d}.{millis:03d}"


# Get recent matches
print("=== Recent Matches ===")
matches = mcsrranked.matches.list(count=5)
for match in matches:
    match_type = MatchType(match.type).name
    players = ", ".join(p.nickname for p in match.players)
    time_str = format_time(match.result.time) if match.result else "N/A"
    print(f"Match {match.id} ({match_type}): {players} - {time_str}")
print()

# Get ranked matches only
print("=== Recent Ranked Matches ===")
ranked = mcsrranked.matches.list(type=MatchType.RANKED, count=5)
for match in ranked:
    players = " vs ".join(p.nickname for p in match.players)
    winner = next(
        (
            p.nickname
            for p in match.players
            if match.result and p.uuid == match.result.uuid
        ),
        "Draw",
    )
    print(f"Match {match.id}: {players} - Winner: {winner}")
print()

# Get detailed match info
print("=== Detailed Match Info ===")
match = mcsrranked.matches.get(ranked[0].id)
print(f"Match ID: {match.id}")
print(f"Season: {match.season}")
print(f"Type: {MatchType(match.type).name}")
print(f"Date: {match.date}")
print()

print("Players:")
for player in match.players:
    print(f"  {player.nickname} ({player.uuid})")
print()

print("Elo Changes:")
for change in match.changes:
    found_player = next((p for p in match.players if p.uuid == change.uuid), None)
    name = found_player.nickname if found_player else change.uuid
    change_str = (
        f"+{change.change}"
        if change.change and change.change > 0
        else str(change.change)
    )
    print(f"  {name}: {change_str} (now {change.elo_rate})")
print()

if match.timelines:
    print("Timeline:")
    for event in match.timelines[:10]:
        found_player = next((p for p in match.players if p.uuid == event.uuid), None)
        name = found_player.nickname if found_player else event.uuid[:8]
        print(f"  {format_time(event.time)} - {name}: {event.type}")

Versus

examples/versus.py
"""Versus (head-to-head) examples for the MCSR Ranked SDK."""

import mcsrranked


def format_time(ms: int) -> str:
    """Format milliseconds as MM:SS.mmm."""
    minutes = ms // 60000
    seconds = (ms % 60000) // 1000
    millis = ms % 1000
    return f"{minutes}:{seconds:02d}.{millis:03d}"


# Get versus stats between two players
player1 = "Feinberg"
player2 = "k4yfour"

print(f"=== {player1} vs {player2} ===")
stats = mcsrranked.users.versus(player1, player2)

# Display players
for player in stats.players:
    elo = player.elo_rate or "Unranked"
    print(f"{player.nickname}: {elo} elo")
print()

# Display ranked results
print("Ranked Results:")
ranked = stats.results.ranked
total = ranked.get("total", 0)
for uuid, wins in ranked.items():
    if uuid != "total":
        found_player = next((p for p in stats.players if p.uuid == uuid), None)
        name = found_player.nickname if found_player else uuid[:8]
        print(f"  {name}: {wins} wins")
print(f"  Total matches: {total}")
print()

# Display casual results
print("Casual Results:")
casual = stats.results.casual
total = casual.get("total", 0)
for uuid, wins in casual.items():
    if uuid != "total":
        found_player = next((p for p in stats.players if p.uuid == uuid), None)
        name = found_player.nickname if found_player else uuid[:8]
        print(f"  {name}: {wins} wins")
print(f"  Total matches: {total}")
print()

# Display elo changes
print("Total Elo Changes:")
for uuid, change in stats.changes.items():
    found_player = next((p for p in stats.players if p.uuid == uuid), None)
    name = found_player.nickname if found_player else uuid[:8]
    sign = "+" if change > 0 else ""
    print(f"  {name}: {sign}{change}")
print()

# Get match history between the two players
print(f"=== Recent Matches Between {player1} and {player2} ===")
matches = mcsrranked.users.versus_matches(player1, player2, count=5)
for match in matches:
    winner = next(
        (
            p.nickname
            for p in match.players
            if match.result and p.uuid == match.result.uuid
        ),
        "Draw",
    )
    time_str = format_time(match.result.time) if match.result else "N/A"
    print(f"Match {match.id}: Winner: {winner} - {time_str}")

Weekly Race

examples/weekly_race.py
"""Weekly race examples for the MCSR Ranked SDK."""

import mcsrranked


def format_time(ms: int) -> str:
    """Format milliseconds as MM:SS.mmm."""
    minutes = ms // 60000
    seconds = (ms % 60000) // 1000
    millis = ms % 1000
    return f"{minutes}:{seconds:02d}.{millis:03d}"


# Get current weekly race
print("=== Current Weekly Race ===")
race = mcsrranked.weekly_races.get()
print(f"Race ID: {race.id}")
print(f"Ends at: {race.ends_at}")
print()

print("Seed Info:")
if race.seed.overworld:
    print(f"  Overworld: {race.seed.overworld}")
if race.seed.nether:
    print(f"  Nether: {race.seed.nether}")
if race.seed.the_end:
    print(f"  The End: {race.seed.the_end}")
print()

print("Top 10 Leaderboard:")
for entry in race.leaderboard[:10]:
    time_str = format_time(entry.time)
    replay = " [replay]" if entry.replay_exist else ""
    print(f"  #{entry.rank} {entry.player.nickname}: {time_str}{replay}")
print()

# Get a specific past weekly race
print("=== Past Weekly Race (ID 1) ===")
past_race = mcsrranked.weekly_races.get(race_id=1)
print(f"Race ID: {past_race.id}")
print(f"Winner: {past_race.leaderboard[0].player.nickname}")
print(f"Winning time: {format_time(past_race.leaderboard[0].time)}")

Error Handling

examples/error_handling.py
"""Error handling examples for the MCSR Ranked SDK."""

import mcsrranked
from mcsrranked import (
    AuthenticationError,
    NotFoundError,
)

# Handle user not found
print("=== Handling NotFoundError ===")
try:
    user = mcsrranked.users.get("this_user_definitely_does_not_exist_12345")
except NotFoundError as e:
    print(f"User not found: {e.message}")
    print(f"Status code: {e.status_code}")
print()

# Handle rate limiting (simulated)
print("=== Handling RateLimitError ===")
print("RateLimitError is raised when you exceed 500 requests per 10 minutes.")
print("Example handling:")
print("""
try:
    for i in range(1000):
        mcsrranked.users.get("Feinberg")
except RateLimitError as e:
    print(f"Rate limited! Wait and retry: {e.message}")
    time.sleep(60)  # Wait before retrying
""")
print()

# Handle authentication errors
print("=== Handling AuthenticationError ===")
print("AuthenticationError is raised when private_key is required but not provided.")
try:
    # This requires a private key
    live = mcsrranked.users.live("some_uuid")
except AuthenticationError as e:
    print(f"Auth error: {e.message}")
print()

# Catch-all error handling
print("=== Catch-all Error Handling ===")
print("Use MCSRRankedError to catch any SDK error:")
print("""
try:
    user = mcsrranked.users.get("someone")
except MCSRRankedError as e:
    print(f"SDK error: {e}")
""")