API-Referenz¶
Diese Seite bietet vollständige API-Dokumentation für d-back, automatisch aus den Docstrings des Quellcodes generiert. Alle Klassen und Methoden enthalten detaillierte Beschreibungen, Parameter, Rückgabewerte und Beispiele.
Einführung¶
Die d-back-API ist in zwei Hauptkomponenten organisiert:
- WebSocketServer: Die Haupt-Serverklasse zur Verwaltung von WebSocket-Verbindungen, HTTP-Anfragen und Nachrichten-Broadcasting
- MockDataProvider: Stellt Mock-Daten und periodische Hintergrundaufgaben für Entwicklung und Tests bereit
Alle API-Dokumentation folgt Google-Style-Docstrings mit umfassenden Beispielen. Für Nutzungsmuster und Integrationsleitfäden siehe das Benutzerhandbuch.
WebSocketServer¶
Die Haupt-Serverklasse zur Verwaltung von WebSocket-Verbindungen, HTTP-Anfragen und Nachrichten-Broadcasting. Dies ist Ihre primäre Schnittstelle zur d-back-Funktionalität.
WebSocketServer(port=3000, host='localhost')
¶
WebSocket server for managing real-time connections and broadcasting messages.
This server handles WebSocket connections for Discord-like applications, providing real-time communication, user presence management, message broadcasting, and static file serving. It supports custom data providers through callback registration and includes mock data functionality for testing.
The server automatically detects websockets library version and enables HTTP support when available (websockets 10.0+ with Python 3.8+).
Attributes:
| Name | Type | Description |
|---|---|---|
port |
int
|
The port number the server listens on. |
host |
str
|
The hostname or IP address the server binds to. |
server |
The websockets server instance. |
|
connections |
set
|
Set of active WebSocket connections. |
static_dir |
Path
|
Directory path for serving static files. |
mock_provider |
MockDataProvider
|
Provider for mock test data. |
Example
Basic usage::
server = WebSocketServer(port=3000, host="localhost")
await server.run_forever()
With custom data callbacks::
def get_servers():
return {
"server1": {"id": "server1", "name": "My Server", "default": True}
}
def get_users(server_id):
return {
"user123": {
"uid": "user123",
"username": "JohnDoe",
"status": "online",
"roleColor": "#3498db"
}
}
server = WebSocketServer()
server.on_get_server_data(get_servers)
server.on_get_user_data(get_users)
await server.run_forever()
Initialize the WebSocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
port
|
int
|
The port number to listen on. Defaults to 3000. |
3000
|
host
|
str
|
The hostname or IP address to bind to. Defaults to "localhost". Use "0.0.0.0" to accept connections from any interface. |
'localhost'
|
Note
The server initializes with mock data provider by default. Register custom callbacks using on_get_server_data() and on_get_user_data() to override mock data behavior.
Source code in d_back/server.py
start()
async
¶
Start the WebSocket server and wait for it to close.
This method initializes the websockets server with the configured host and port, registers the connection handler and HTTP request processor, and then waits for the server to close.
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
OSError
|
If the port is already in use or network binding fails. |
Exception
|
For other server startup failures. |
Note
This method blocks until the server is stopped. Use run_forever() for a more convenient async context manager approach.
Source code in d_back/server.py
stop()
async
¶
Gracefully stop the WebSocket server.
This method closes the server and waits for all existing connections to terminate. Active connections are allowed to finish their current operations before shutdown.
Returns:
| Type | Description |
|---|---|
None
|
None |
Note
After calling this method, the server can be restarted by calling start() again.
Source code in d_back/server.py
broadcast_message(server, uid, message, channel)
async
¶
Broadcast a chat message to all clients connected to the specified server.
Sends a message from a user to all WebSocket clients currently connected to the same Discord server. Automatically handles connection failures and removes closed connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server
|
str
|
The Discord server ID where the message is sent. |
required |
uid
|
str
|
The user ID of the message sender. |
required |
message
|
str
|
The text content of the message. |
required |
channel
|
str
|
The channel ID where the message is posted. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
ConnectionClosed
|
When attempting to send to a closed connection (handled internally, connection is removed). |
Examples:
await server.broadcast_message(
server="232769614004748288",
uid="user123",
message="Hello everyone!",
channel="general"
)
Source code in d_back/server.py
on_get_server_data(callback)
¶
Register a callback to provide server configuration data.
The callback function will be called to retrieve the list of available Discord servers and their configurations. This overrides the default mock data provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[], Awaitable[Dict[str, Dict[str, Any]]]]
|
An async callable that returns a dictionary of server configurations. Expected signature: async def callback() -> Dict[str, Dict[str, Any]] Each server dict should contain: id, name, default (bool), passworded (bool) |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
async def get_servers():
return {
"server1": {
"id": "server1",
"name": "My Server",
"default": True,
"passworded": False
}
}
server.on_get_server_data(get_servers)
Source code in d_back/server.py
on_get_user_data(callback)
¶
Register a callback to provide user data for a specific server.
The callback function will be called to retrieve user information for clients connecting to a Discord server. This overrides the default mock data provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[str], Awaitable[Dict[str, Dict[str, Any]]]]
|
An async callable that takes a server ID and returns user data. Expected signature: async def callback(server_id: str) -> Dict[str, Dict[str, Any]] Each user dict should contain: uid, username, status, roleColor |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
async def get_users(server_id):
return {
"user123": {
"uid": "user123",
"username": "JohnDoe",
"status": "online",
"roleColor": "#3498db"
}
}
server.on_get_user_data(get_users)
Source code in d_back/server.py
on_static_request(callback)
¶
Register a callback for custom static file handling.
The callback function allows you to serve custom content for specific paths, overriding the default static file handler. Return None to use default handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[str], Awaitable[Optional[Tuple[str, str]]]]
|
An async callable that takes a path and returns custom content. Expected signature: async def callback(path: str) -> Optional[Tuple[str, str]] Return None to let default handler process the request, or return (content_type, content) to serve custom content. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
async def custom_handler(path):
if path == "/api/custom":
return "application/json", '{"status": "ok"}'
return None # Let default handler take over
server.on_static_request(custom_handler)
Source code in d_back/server.py
on_validate_discord_user(callback)
¶
Register a callback to validate Discord OAuth users.
The callback function will be called to verify Discord OAuth tokens and validate user permissions for accessing the WebSocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[str, Dict[str, Any], str], Awaitable[bool]]
|
An async callable that validates a Discord OAuth token and user info. Expected signature: async def callback(token: str, user_info: Dict[str, Any], server_id: str) -> bool Should return True if the user is valid and authorized. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
async def validate_user(token, user_info, server_id):
# Verify token with Discord API
# Check user permissions for the specific server
return is_valid and is_authorized
server.on_validate_discord_user(validate_user)
Source code in d_back/server.py
on_get_client_id(callback)
¶
Register a callback to provide the OAuth2 client ID.
The callback function should return the Discord OAuth2 application client ID used for authentication. This is sent to connecting clients for OAuth flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[str], Awaitable[str]]
|
An async callable that returns the OAuth2 client ID for a server. Expected signature: async def callback(server_id: str) -> str Should return the Discord application client ID string. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
async def get_client_id(server_id):
return "123456789012345678"
server.on_get_client_id(get_client_id)
Source code in d_back/server.py
run_forever()
async
¶
Run the server forever with automatic HTTP support detection.
This method starts the WebSocket server and automatically detects whether HTTP static file serving is supported based on the Python version and websockets library version. Falls back to WebSocket-only mode if HTTP support is unavailable.
HTTP support requires
- Python 3.8 or higher
- websockets 10.0 or higher
- Available HTTP import modules (websockets.http11 or websockets.http)
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
Exception
|
If server fails to start on the configured host and port. |
KeyboardInterrupt
|
When server is interrupted by user (handled gracefully). |
Examples:
server = WebSocketServer(port=3000)
await server.run_forever() # Runs until interrupted
Note
This method runs indefinitely until interrupted. Use asyncio.create_task() if you need to run other async operations concurrently.
Source code in d_back/server.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
broadcast_presence(server, uid, status, username=None, role_color=None, delete=False)
async
¶
Broadcast a user presence update to all clients connected to a server.
Sends presence information (online status, username, role color) to all WebSocket connections associated with the specified Discord server. Used to notify clients when users come online, go offline, or change status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server
|
str
|
Discord server ID to broadcast to |
required |
uid
|
str
|
User ID whose presence is being updated |
required |
status
|
str
|
User's current status ("online", "idle", "dnd", "offline") |
required |
username
|
str
|
Optional username to include in the update |
None
|
role_color
|
str
|
Optional hex color code for the user's role (e.g., "#ff6b6b") |
None
|
delete
|
bool
|
If True, indicates the user should be removed from the presence list |
False
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
# Broadcast user coming online
await server.broadcast_presence(
server="232769614004748288",
uid="123456789012345001",
status="online",
username="vegeta897",
role_color="#ff6b6b"
)
# Broadcast user going offline
await server.broadcast_presence(
server="232769614004748288",
uid="123456789012345001",
status="offline",
delete=True
)
Source code in d_back/server.py
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 | |
broadcast_client_id_update(server, client_id)
async
¶
Broadcast an OAuth2 client ID update to all clients connected to a server.
Sends the Discord OAuth2 application client ID to all WebSocket connections associated with the specified Discord server. Used to dynamically update the client ID for OAuth authentication flows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server
|
str
|
Discord server ID to broadcast to |
required |
client_id
|
str
|
Discord OAuth2 application client ID to send |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
# Update client ID for all connections to a server
await server.broadcast_client_id_update(
server="232769614004748288",
client_id="123456789012345678"
)
Source code in d_back/server.py
MockDataProvider¶
Stellt Mock-Daten und periodische Hintergrundaufgaben für Entwicklung und Tests bereit. Diese Klasse wird automatisch verwendet, wenn keine benutzerdefinierten Callbacks registriert sind.
MockDataProvider(server_instance)
¶
Provides mock data and periodic background tasks for WebSocket server testing.
This class generates test data that simulates a Discord-like server environment with multiple servers, users, and real-time updates. It provides both static data (user lists, server configurations) and dynamic behaviors (status updates, message broadcasts) for development and testing purposes.
The mock provider includes predefined data for several test servers
- D-World: Main test server with 4 users
- Docs (WIP): Documentation server with 1 user
- OAuth2 Protected Server: Authentication testing server
- My Repos: Repository showcase server with 21 users
Attributes:
| Name | Type | Description |
|---|---|---|
server |
Reference to the WebSocketServer instance using this provider. |
Examples:
Basic usage:
server = WebSocketServer()
mock_provider = MockDataProvider(server)
# Get user data for a specific server
users = mock_provider.get_mock_user_data("232769614004748288")
# Returns: {"uid1": {"uid": "...", "username": "...", ...}, ...}
# Get all available servers
servers = mock_provider.get_mock_server_data()
# Returns: {"server_id": {"id": "...", "name": "...", ...}, ...}
Note
The mock data provider is automatically instantiated by WebSocketServer. You typically don't need to create instances manually unless testing the provider in isolation.
Initialize the mock data provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_instance
|
WebSocketServer
|
The WebSocketServer instance that owns this provider. Used for accessing server methods like _random_status(). |
required |
Source code in d_back/mock/data.py
get_mock_user_data(discord_server_id=None)
¶
Get mock user data for a specific Discord server.
Returns a dictionary of mock users with their profile information including user ID, username, online status, and role color. Each server has a predefined set of users for consistent testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
discord_server_id
|
str
|
Optional Discord server ID to get users for. Supported IDs: - "232769614004748288": D-World server (4 users) - "482241773318701056": Docs (WIP) server (1 user) - "123456789012345678": OAuth2 Protected server (1 user) - "987654321098765432": My Repos server (21 users) If None or unknown, returns empty dict. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary mapping user IDs to user data objects. Each user object contains: - uid (str): Unique user identifier - username (str): Display name - status (str): Online status ("online", "idle", "dnd", "offline") - roleColor (str): Hex color code for user's role (e.g., "#ff6b6b") |
Examples:
provider = MockDataProvider(server)
users = provider.get_mock_user_data("232769614004748288")
# Returns:
# {
# "123456789012345001": {
# "uid": "123456789012345001",
# "username": "vegeta897",
# "status": "online",
# "roleColor": "#ff6b6b"
# },
# ...
# }
Source code in d_back/mock/data.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
get_mock_server_data()
¶
Get mock server data with all available Discord servers.
Returns a dictionary mapping Discord server IDs to server configuration objects. Used for testing server selection, display, and navigation features.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Dict[str, Any]]: Dictionary mapping Discord server snowflake IDs to server configuration objects. Each server object contains: - id (str): Internal server identifier - name (str): Server display name - passworded (bool): Whether OAuth2 authentication is required - default (bool, optional): Whether this is the default server |
Examples:
provider = MockDataProvider(server)
servers = provider.get_mock_server_data()
# Returns:
# {
# "232769614004748288": {
# "id": "dworld",
# "name": "D-World",
# "default": True,
# "passworded": False
# },
# "482241773318701056": {
# "id": "docs",
# "name": "Docs (WIP)",
# "passworded": False
# },
# ...
# }
for snowflake_id, server_info in servers.items():
print(f"{server_info['name']} (ID: {snowflake_id})")
Source code in d_back/mock/data.py
periodic_status_updates(websocket)
async
¶
Periodically send mock user status changes to a connected client.
Background task that continuously generates random user status updates and sends them to the specified WebSocket connection. Simulates realistic user activity by randomly changing user statuses every 4 seconds.
This method runs until the WebSocket connection is closed or the task is cancelled. It selects random users from the current server and updates their online status (online, idle, dnd, offline).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
websocket
|
WebSocketServerProtocol
|
WebSocket connection to send updates to. Must have a discordServer attribute identifying which server's users to update. |
required |
Note
This is a coroutine that runs indefinitely for the lifetime of the WebSocket connection. It automatically handles ConnectionClosed exceptions gracefully.
Examples:
# Called automatically by the server for each connection
task = asyncio.create_task(
mock_provider.periodic_status_updates(websocket)
)
# Updates will be sent in this format:
# {
# "type": "presence",
# "server": "232769614004748288",
# "data": {
# "uid": "123456789012345001",
# "status": "online"
# }
# }
Raises:
| Type | Description |
|---|---|
ConnectionClosed
|
When the WebSocket connection is closed. This exception is caught and handled gracefully. |
Source code in d_back/mock/data.py
periodic_messages(websocket)
async
¶
Periodically send mock chat messages to a connected client.
Background task that continuously generates random chat messages from mock users and sends them to the specified WebSocket connection. Simulates realistic chat activity by sending messages every 5 seconds.
This method runs until the WebSocket connection is closed or the task is cancelled. It selects random users from the current server and random messages from a predefined list to create chat events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
websocket
|
WebSocketServerProtocol
|
WebSocket connection to send messages to. Must have a discordServer attribute identifying which server's users to use. |
required |
Note
This is a coroutine that runs indefinitely for the lifetime of the WebSocket connection. It automatically handles ConnectionClosed exceptions gracefully.
Examples:
# Called automatically by the server for each connection
task = asyncio.create_task(
mock_provider.periodic_messages(websocket)
)
# Messages will be sent in this format:
# {
# "type": "message",
# "server": "232769614004748288",
# "data": {
# "uid": "123456789012345001",
# "message": "hello",
# "channel": "527964146659229701"
# }
# }
Raises:
| Type | Description |
|---|---|
ConnectionClosed
|
When the WebSocket connection is closed. This exception is caught and handled gracefully. |
Source code in d_back/mock/data.py
Hilfsfunktionen¶
Hilfsfunktionen für Befehlszeilenschnittstelle und Versionsverwaltung.
parse_args¶
Parse command-line arguments for the D-Back WebSocket server.
Provides command-line interface for configuring server parameters including port, host, static file directory, and version information.
Returns:
| Type | Description |
|---|---|
|
argparse.Namespace: Parsed arguments containing: - port (int): Server port number (default: 3000) - host (str): Server hostname (default: 'localhost') - static_dir (str): Custom static files directory (default: None) |
Examples:
$ python -m d_back --port 8080 --host 0.0.0.0
$ python -m d_back --static-dir ./my-static-files
$ python -m d_back --version
Source code in d_back/server.py
get_version¶
Get the current version of the d_back package.
Attempts to retrieve the version from the package's version attribute. Falls back to "unknown" if the version cannot be determined.
Returns:
| Name | Type | Description |
|---|---|---|
str |
The package version string (e.g., "0.0.12") or "unknown". |
Examples:
>>> get_version()
'0.0.12'
Source code in d_back/server.py
main¶
Main async entry point for the D-Back WebSocket server.
Parses command-line arguments, initializes the WebSocket server with the specified configuration, and starts the server in run-forever mode.
This function handles
- Argument parsing for port, host, and static directory
- Server initialization and configuration
- Static directory validation
- Server startup and lifecycle management
Returns:
| Type | Description |
|---|---|
|
None |
Raises:
| Type | Description |
|---|---|
Exception
|
If server fails to start or encounters fatal errors. |
KeyboardInterrupt
|
Propagated from server interruption. |
Examples:
# Run with default settings
await main()
Note
This is the primary entry point when running d_back as a module. Use main_sync() for synchronous execution from main.
Source code in d_back/server.py
main_sync¶
Synchronous entry point wrapper for the D-Back WebSocket server.
Wraps the async main() function in asyncio.run() to provide a synchronous entry point. Handles KeyboardInterrupt gracefully for clean server shutdown.
Returns:
| Type | Description |
|---|---|
|
None |
Examples:
if __name__ == "__main__":
main_sync()
Note
This is the entry point used when running as a script or via setuptools console_scripts. It ensures proper async context management.
Source code in d_back/server.py
Verwendungsbeispiele¶
Für praktische Beispiele zur Verwendung dieser APIs siehe:
- Erste Schritte: Grundlegende Verwendung und erste Verbindung
- Konfiguration: Server-Einrichtung und -Konfiguration
- Callbacks & Anpassung: Callback-Verwendungsbeispiele
- Benutzerdefinierte Datenanbieter: Datenanbieter-Implementierungsmuster
Typhinweise¶
Alle Methoden enthalten umfassende Typhinweise für Parameter und Rückgabewerte. Beim Arbeiten mit Callbacks importieren Sie die erforderlichen Typen:
Für weitere Informationen über Python-Typhinweise siehe die offizielle typing-Dokumentation.