calagoapi-minecraft 1.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,631 @@
1
+ import json
2
+ import threading
3
+ import time
4
+
5
+ from hungerbridge import BridgeClient, HungerBridgeError, ReleaseAsset, Stream, redeem_pickup
6
+ from hungerbridge.protocol import MAX_HISTORY
7
+ from hungerbridge.releases import find_release, parse_asset_name
8
+
9
+ from calagoapi import Server
10
+ from calagoapi.console import Console
11
+ from calagoapi.utils.convert import formatDuration
12
+ from calagoapi.utils.exceptions import NotFoundError, WaitTimeoutError
13
+
14
+ from calagoapi_minecraft import bridge as _bridge
15
+ from calagoapi_minecraft import properties as _properties
16
+ from calagoapi_minecraft.config import checkToken, settings
17
+ from calagoapi_minecraft.exceptions import BridgeNotConfiguredError, MinecraftError
18
+ from calagoapi_minecraft.versions import VersionManager
19
+
20
+
21
+ # default Minecraft port, used when an address has none
22
+ DEFAULT_PORT = 25565
23
+
24
+
25
+ def _history(history) -> int:
26
+ '''streamConsole(history=...) -> the bridge's ?history=N (None for none)'''
27
+ if history is True:
28
+ return MAX_HISTORY
29
+ return int(history) if history else None
30
+
31
+
32
+ class MinecraftServer(Server):
33
+ '''
34
+ A Minecraft server: everything a Server has, plus Minecraft features.
35
+
36
+ Two channels are used, and every method uses exactly one of them:
37
+
38
+ - the panel / node daemon (inherited from Server): power (start, stop, ...),
39
+ resources (getRAM, getCPU, ...), files, backups, server.properties, the
40
+ Version Changer (`server.versions`), sendPanelCommand() and `server.console`;
41
+ - HungerBridge, the plugin/mod inside the game, through HungerBridgePy
42
+ (`server.bridge`): sendCommand() with output, streamConsole(), players,
43
+ TPS/MSPT, world and JVM metrics, writeLog().
44
+
45
+ Bridge methods need a token: `enable('minecraft', config={'bridge_token': ...})`,
46
+ `bridge_token=` here, connectBridge(), or createBridgeToken(). Without one they
47
+ raise BridgeNotConfiguredError. Errors from the bridge are HungerBridgePy's
48
+ `hungerbridge.HungerBridgeError` subclasses.
49
+
50
+ Args:
51
+ panel: The Panel the server lives on.
52
+ server_id: Server UUID (or short id).
53
+ name: Optional display name.
54
+ data: Optional server data, if already fetched.
55
+ address: Address players use ("host" or "host:port"); overrides getAddress().
56
+ bridge_url: HungerBridge URL, e.g. "http://10.0.0.5:1913". Defaults to the
57
+ `bridge_url` config, then the server's address with `bridge_port`.
58
+ bridge_token: "tokenId:secret" for this server; defaults to the `bridge_token` config.
59
+
60
+ Example:
61
+ enable('minecraft', config={'bridge_token': 'bot:9f2c...'})
62
+ server = panel.minecraft.getServer('abc123', bridge_url='http://10.0.0.5:1913')
63
+
64
+ print(server.sendCommand('list')) # output of the command
65
+ print(f'{server.getPlayerCount()} online, TPS {server.getTPS()}')
66
+ print(f'container RAM {server.getRAM()} MiB, JVM heap {server.getMemoryInfo()["used"]} MiB')
67
+ '''
68
+ def __init__(self, panel, server_id: str = None, name: str = None, data: dict = None, *,
69
+ address: str = None, bridge_url: str = None, bridge_token: str = None):
70
+ super().__init__(panel, server_id, name, data)
71
+ checkToken(bridge_token, 'bridge_token')
72
+ self.address = address
73
+ self.versions = VersionManager(self)
74
+ self._bridge_url = bridge_url.rstrip('/') if bridge_url else None
75
+ self._bridge_token = bridge_token
76
+ self._bridge = None
77
+ self._bridge_lock = threading.RLock()
78
+
79
+ def getAddress(self) -> str:
80
+ '''Returns the address players use: `address` if set (port 25565 by default), else the allocation.'''
81
+ if self.address:
82
+ return self.address if ':' in self.address else f'{self.address}:{DEFAULT_PORT}'
83
+ return super().getAddress()
84
+
85
+
86
+ # HungerBridge connection
87
+ def getBridgeUrl(self) -> str:
88
+ '''
89
+ Returns the HungerBridge URL for this server: bridge_url, else the `bridge_url`
90
+ config, else the server's host with the `bridge_port` config (1913).
91
+
92
+ HungerBridge binds 127.0.0.1 by default; set its `bind-address` (or a proxy) so
93
+ the URL is reachable from where your code runs.
94
+ '''
95
+ if self._bridge_url:
96
+ return self._bridge_url
97
+ config = settings()
98
+ if config['bridge_url']:
99
+ return config['bridge_url'].rstrip('/')
100
+ address = self.getAddress()
101
+ if not address:
102
+ raise BridgeNotConfiguredError(f'{self.name} has no address to reach HungerBridge on; pass bridge_url')
103
+ host = address.rsplit(':', 1)[0]
104
+ return f'http://{host}:{config["bridge_port"]}'
105
+
106
+ def hasBridge(self) -> bool:
107
+ '''Returns True if a bridge client or token is configured (no request is made).'''
108
+ return self._bridge is not None or bool(self._bridge_token or settings()['bridge_token'])
109
+
110
+ @property
111
+ def bridge(self) -> BridgeClient:
112
+ '''
113
+ The HungerBridgePy client of this server (`hungerbridge.BridgeClient`), created
114
+ on first use. Everything HungerBridgePy offers is available here.
115
+
116
+ Raises:
117
+ BridgeNotConfiguredError: No bridge token is configured.
118
+
119
+ Example:
120
+ server.bridge.getTokenInfo()
121
+ server.bridge.stopServer() # HungerBridge's stop; server.stop() is the panel's
122
+ '''
123
+ with self._bridge_lock:
124
+ if self._bridge is None:
125
+ token = self._bridge_token or settings()['bridge_token']
126
+ if not token:
127
+ raise BridgeNotConfiguredError(
128
+ f'{self.name} has no HungerBridge token. Use enable("minecraft", config={{"bridge_token": '
129
+ f'"id:secret"}}), server.connectBridge(url, "id:secret") or server.createBridgeToken().')
130
+ self._bridge = _bridge.newClient(self.getBridgeUrl(), token)
131
+ return self._bridge
132
+
133
+ def connectBridge(self, url: str = None, token: str = None, **options) -> BridgeClient:
134
+ '''
135
+ Sets the bridge URL and/or token for this server and returns the new client.
136
+
137
+ Args:
138
+ url: HungerBridge URL; keeps the current one when None.
139
+ token: "tokenId:secret"; keeps the current one when None.
140
+ **options: BridgeClient options, e.g. timeout=(5, 30), static_delay=0.2.
141
+
142
+ Example:
143
+ server.connectBridge('http://10.0.0.5:1913', 'bot:9f2c...')
144
+ '''
145
+ checkToken(token, 'token')
146
+ with self._bridge_lock:
147
+ if url:
148
+ self._bridge_url = url.rstrip('/')
149
+ if token:
150
+ self._bridge_token = token
151
+ self.closeBridge()
152
+ if options:
153
+ token = self._bridge_token or settings()['bridge_token']
154
+ if not token:
155
+ raise BridgeNotConfiguredError(f'{self.name} has no HungerBridge token; pass token=')
156
+ self._bridge = _bridge.newClient(self.getBridgeUrl(), token, **options)
157
+ return self.bridge
158
+
159
+ def setBridge(self, client: BridgeClient) -> 'MinecraftServer':
160
+ '''Uses an existing HungerBridgePy client for this server.'''
161
+ with self._bridge_lock:
162
+ if client is not self._bridge:
163
+ self.closeBridge()
164
+ self._bridge = client
165
+ return self
166
+
167
+ def closeBridge(self) -> None:
168
+ '''Closes the bridge client's connections. The next bridge call opens a new client.'''
169
+ with self._bridge_lock:
170
+ client, self._bridge = self._bridge, None
171
+ if client is not None:
172
+ _bridge.closeClient(client)
173
+
174
+ def isBridgeReachable(self) -> bool:
175
+ '''Returns True if HungerBridge answers an authenticated ping.'''
176
+ try:
177
+ return self.bridge.isOk()
178
+ except (HungerBridgeError, BridgeNotConfiguredError):
179
+ return False
180
+
181
+ def waitForBridge(self, timeout: float = 120, interval: float = 2) -> bool:
182
+ '''
183
+ Blocks until HungerBridge answers (after a start, restart or installBridge()).
184
+ Returns False on timeout.
185
+
186
+ Example:
187
+ server.restart()
188
+ server.waitForBridge(timeout=180)
189
+ '''
190
+ deadline = time.monotonic() + timeout
191
+ while True:
192
+ if self.isBridgeReachable():
193
+ return True
194
+ if time.monotonic() + interval > deadline:
195
+ return False
196
+ time.sleep(interval)
197
+
198
+ def redeemBridgePickup(self, pickup_url: str) -> BridgeClient:
199
+ '''
200
+ Redeems a one-time token pickup and connects the bridge with the new token.
201
+
202
+ Args:
203
+ pickup_url: The full URL, or the "/pickup/<id>?passkey=<hex>" part printed by
204
+ `hb token create` (resolved against getBridgeUrl()).
205
+ '''
206
+ url = pickup_url if pickup_url.startswith(('http://', 'https://')) else f'{self.getBridgeUrl()}{pickup_url}'
207
+ token_id, secret = redeem_pickup(url)
208
+ return self.connectBridge(token=f'{token_id}:{secret}')
209
+
210
+ def createBridgeToken(self, token_id: str = 'calagoapi', policy: str = 'admin', expiry: int = None,
211
+ timeout: float = 30, url: str = None) -> str:
212
+ '''
213
+ Creates a HungerBridge token through the server console and connects the bridge with it.
214
+
215
+ Runs `hb token create <token_id> <policy> [expiry]` over the daemon console (the
216
+ command is console-only), reads the pickup URL it prints, redeems it, and returns
217
+ the token so you can store it (e.g. as the `bridge_token` config).
218
+
219
+ Args:
220
+ token_id: Id of the new token.
221
+ policy: Policy from HungerBridge's policies.yaml ('admin' needs to exist there).
222
+ expiry: Lifetime in seconds; None uses the policy default.
223
+ timeout: Seconds to wait for the pickup URL.
224
+ url: Bridge URL to use for this server (see getBridgeUrl()).
225
+
226
+ Returns:
227
+ The token, "tokenId:secret".
228
+
229
+ Raises:
230
+ MinecraftError: No pickup URL appeared (bridge not installed, unknown policy, ...).
231
+
232
+ Example:
233
+ token = server.createBridgeToken(url='http://10.0.0.5:1913')
234
+ save_somewhere(token)
235
+ '''
236
+ if url:
237
+ self._bridge_url = url.rstrip('/')
238
+ command = f'hb token create {token_id} {policy}' + (f' {int(expiry)}' if expiry else '')
239
+ deadline = time.monotonic() + timeout
240
+ pickup = None
241
+ with Console(self) as console:
242
+ console.sendCommand(command)
243
+ while pickup is None:
244
+ remaining = deadline - time.monotonic()
245
+ try:
246
+ line = console.waitFor('/pickup/', timeout=max(remaining, 0.01)) if remaining > 0 else None
247
+ except WaitTimeoutError:
248
+ line = None
249
+ if line is None:
250
+ raise MinecraftError(
251
+ f'No HungerBridge pickup URL appeared on the console of {self.name} within {timeout}s after '
252
+ f'"{command}". Is HungerBridge installed and does policy {policy!r} exist?')
253
+ pickup = _bridge.findPickup(line)
254
+ client = self.redeemBridgePickup(pickup)
255
+ return f'{client.credentials.token_id}:{client.credentials.secret}'
256
+
257
+ def getBridgeInfo(self) -> dict:
258
+ '''Returns platform, minecraft_version, bridge_version, port and protocol_version.'''
259
+ return self.bridge.getServerMeta()
260
+
261
+ def getBridgeTokenInfo(self) -> dict:
262
+ '''Returns the token's token_id, policy_id, permissions and expiry.'''
263
+ return self.bridge.getTokenInfo()
264
+
265
+ def getPlatform(self) -> str:
266
+ '''Returns 'paper', 'folia' or 'fabric' (as reported by HungerBridge).'''
267
+ return self.bridge.getPlatform()
268
+
269
+ def getMinecraftVersion(self) -> str:
270
+ '''Returns the running Minecraft version, e.g. '1.21.11' (as reported by HungerBridge).'''
271
+ return self.bridge.getMinecraftVersion()
272
+
273
+
274
+ # commands and console (HungerBridge)
275
+ def sendCommand(self, command: str, *, silent: bool = False, showConsole: bool = False):
276
+ '''
277
+ Runs a console command through HungerBridge and returns its output.
278
+
279
+ The command runs as the console on the server thread (Folia: the global region);
280
+ HungerBridge waits up to 5 seconds for it. Uses HungerBridgePy's runCommand().
281
+
282
+ Args:
283
+ command: The command, without a leading slash.
284
+ silent: Do not capture output (returns None).
285
+ showConsole: Also print the command and its output to the server console.
286
+
287
+ Returns:
288
+ The captured output lines joined with newlines, or None when silent.
289
+
290
+ Example:
291
+ print(server.sendCommand('list'))
292
+ server.sendCommand('save-all', silent=True)
293
+ '''
294
+ return self.bridge.runCommand(command, showConsole=showConsole, silent=silent)
295
+
296
+ def sendCommands(self, commands: list, *, silent: bool = False, showConsole: bool = False) -> list:
297
+ '''Runs several commands in order. Returns their outputs.'''
298
+ return [self.sendCommand(command, silent=silent, showConsole=showConsole) for command in commands]
299
+
300
+ def sendPanelCommand(self, command: str) -> None:
301
+ '''
302
+ Sends a command through the panel instead of HungerBridge (Server.sendCommand).
303
+
304
+ Works without HungerBridge, returns no output. Use it when the bridge is not
305
+ installed or not running.
306
+ '''
307
+ return Server.sendCommand(self, command)
308
+
309
+ def streamConsole(self, history: int = 0, timeout: float = None, *, reconnect: bool = None, sanitize: bool = True):
310
+ '''
311
+ Yields console log lines live, from HungerBridge's log stream (HungerBridgePy streamLogs()).
312
+
313
+ Args:
314
+ history: Replay this many recent lines first (at most 200; True means 200).
315
+ timeout: Stop when nothing is logged for this many seconds. None streams forever.
316
+ reconnect: Reconnect (and replay only missed lines) when the stream drops.
317
+ None uses the `stream_reconnect` config (default True).
318
+ sanitize: Strip colours and unescape line breaks.
319
+
320
+ Lines look like "[12:00:05 INFO]: Steve joined the game". Permanent errors (bad
321
+ token, missing permission) are raised as HungerBridgeError subclasses.
322
+
323
+ Example:
324
+ for line in server.streamConsole(history=20):
325
+ if 'joined the game' in line:
326
+ server.say('Welcome!')
327
+ '''
328
+ if reconnect is None:
329
+ reconnect = settings()['stream_reconnect']
330
+ return self.bridge.streamLogs(_history(history), timeout=timeout, reconnect=reconnect, sanitize=sanitize)
331
+
332
+ def onConsoleLine(self, callback, history: int = 0, *, reconnect: bool = None, sanitize: bool = True) -> Stream:
333
+ '''
334
+ Calls `callback(line)` for every console log line, in a background thread.
335
+
336
+ Returns the HungerBridgePy Stream; call `.disconnect()` on it to stop.
337
+
338
+ Example:
339
+ stream = server.onConsoleLine(print, history=10)
340
+ ...
341
+ stream.disconnect()
342
+ '''
343
+ if reconnect is None:
344
+ reconnect = settings()['stream_reconnect']
345
+
346
+ def deliver(line):
347
+ callback(Stream.sanitize(line) if sanitize else line)
348
+
349
+ def deliverHistory(lines):
350
+ for line in lines:
351
+ deliver(line)
352
+
353
+ stream = self.bridge.openStream(history_handler=deliverHistory, new_log_handler=deliver)
354
+ stream.connect(history=_history(history), reconnect=reconnect)
355
+ return stream
356
+
357
+ def writeLog(self, message: str, level: str = 'info', thread: str = None) -> dict:
358
+ '''
359
+ Writes a line to the server log (any level name, e.g. 'INFO', 'WARN' or a custom 'BOT').
360
+
361
+ Example:
362
+ server.writeLog('backup finished', level='BOT', thread='calagoapi')
363
+ '''
364
+ return self.bridge.log(message, level=level, thread=thread)
365
+
366
+
367
+ # chat and players (commands through HungerBridge)
368
+ def say(self, message: str):
369
+ '''Broadcasts a chat message as the server.'''
370
+ return self.sendCommand(f'say {message}')
371
+
372
+ def broadcast(self, message: str, prefix: str = None):
373
+ '''
374
+ Shows a message to every player with tellraw (HungerBridgePy broadcast()).
375
+
376
+ Example:
377
+ server.broadcast('Event starts now', prefix='[Event] ')
378
+ '''
379
+ return self.bridge.broadcast(message, prefix)
380
+
381
+ def tellraw(self, target: str, component):
382
+ '''
383
+ Sends a JSON text component.
384
+
385
+ Example:
386
+ server.tellraw('@a', {'text': 'Hello', 'color': 'gold'})
387
+ '''
388
+ if not isinstance(component, str):
389
+ component = json.dumps(component, ensure_ascii=False)
390
+ return self.sendCommand(f'tellraw {target} {component}')
391
+
392
+ def kick(self, player: str, reason: str = None):
393
+ '''Kicks a player.'''
394
+ return self.sendCommand(f'kick {player} {reason}' if reason else f'kick {player}')
395
+
396
+ def ban(self, player: str, reason: str = None):
397
+ '''Bans a player.'''
398
+ return self.sendCommand(f'ban {player} {reason}' if reason else f'ban {player}')
399
+
400
+ def pardon(self, player: str):
401
+ '''Unbans a player.'''
402
+ return self.sendCommand(f'pardon {player}')
403
+
404
+ def op(self, player: str):
405
+ '''Gives a player operator status.'''
406
+ return self.sendCommand(f'op {player}')
407
+
408
+ def deop(self, player: str):
409
+ '''Removes operator status from a player.'''
410
+ return self.sendCommand(f'deop {player}')
411
+
412
+ def whitelistAdd(self, player: str):
413
+ '''Adds a player to the whitelist.'''
414
+ return self.sendCommand(f'whitelist add {player}')
415
+
416
+ def whitelistRemove(self, player: str):
417
+ '''Removes a player from the whitelist.'''
418
+ return self.sendCommand(f'whitelist remove {player}')
419
+
420
+ def saveAll(self):
421
+ '''Saves every world.'''
422
+ return self.sendCommand('save-all')
423
+
424
+ def getPlayers(self) -> list:
425
+ '''Returns the names of the online players (capped by HungerBridge's players.max-list).'''
426
+ return self.bridge.getPlayers('list') or []
427
+
428
+ def getPlayerCount(self) -> int:
429
+ '''Returns how many players are online.'''
430
+ return self.bridge.getPlayers('count')
431
+
432
+ def getMaxPlayers(self) -> int:
433
+ '''Returns the number of player slots.'''
434
+ return self.bridge.getMaxPlayers()
435
+
436
+
437
+ # game performance and world (HungerBridge)
438
+ def getTPS(self, mode: str = 'current') -> float:
439
+ '''
440
+ Returns ticks per second: mode 'current', '1m', '5m' or '15m' (-1 if unavailable).
441
+
442
+ Example:
443
+ if server.getTPS('1m') < 18:
444
+ print('lagging')
445
+ '''
446
+ return self.bridge.getTPS(mode)
447
+
448
+ def getMSPT(self) -> float:
449
+ '''Returns milliseconds per tick.'''
450
+ return self.bridge.getMSPT()
451
+
452
+ def getPerformance(self) -> dict:
453
+ '''
454
+ Returns one snapshot for dashboards (three bridge calls):
455
+ {'tps': {'current', '1m', '5m', '15m'}, 'mspt', 'players', 'max_players'}.
456
+ '''
457
+ players = self.bridge.getPlayerStats()
458
+ return {
459
+ 'tps': self.bridge.getTPSStats(),
460
+ 'mspt': self.bridge.getMSPT(),
461
+ 'players': players['count'],
462
+ 'max_players': players['max'],
463
+ }
464
+
465
+ def getWorldTime(self) -> int:
466
+ '''Returns the overworld time of day in ticks (0-23999).'''
467
+ return self.bridge.getWorldTime()
468
+
469
+ def getWorldTimeInfo(self) -> dict:
470
+ '''Returns time (tick of day), full_time, day and server_time.'''
471
+ return self.bridge.getWorldTimeInfo()
472
+
473
+ def getWeather(self) -> str:
474
+ '''Returns 'clear', 'rain' or 'thunder'.'''
475
+ return self.bridge.getWorldWeather()
476
+
477
+ def getLoadedChunks(self) -> dict:
478
+ '''Returns loaded chunks: total, world, world_nether, world_the_end.'''
479
+ return self.bridge.getLoadedChunks()
480
+
481
+ def getLoadedEntities(self) -> dict:
482
+ '''Returns loaded entities: total, world, world_nether, world_the_end.'''
483
+ return self.bridge.getLoadedEntities()
484
+
485
+
486
+ # JVM information (HungerBridge) - additional to getRAM()/getCPU()/getUptime() (panel)
487
+ def getMemoryInfo(self, unit: str = 'mib') -> dict:
488
+ '''
489
+ Returns JVM memory: heap_*, nonheap_*, jvm_*, process_* and the summary keys used,
490
+ total (committed heap), free and max, in `unit` ('b', 'kib', 'mib', 'gib', 'mb', ...).
491
+
492
+ getRAM() stays the container's memory as the panel reports it.
493
+ '''
494
+ return self.bridge.getMemoryStats(unit)
495
+
496
+ def getProcessInfo(self, unit: str = 'mib') -> dict:
497
+ '''Returns the server process: process_used, process_virtual (in `unit`) and uptime_ms.'''
498
+ info = self.bridge.getProcessMemory(unit)
499
+ info['uptime_ms'] = self.bridge.getUptime()
500
+ return info
501
+
502
+ def getProcessorInfo(self) -> dict:
503
+ '''
504
+ Returns load (the JVM process's CPU load, 0-1) and processors (available cores).
505
+
506
+ getCPU() stays the container's CPU usage as the panel reports it.
507
+ '''
508
+ return self.bridge.getCPUStats()
509
+
510
+ def getThreadInfo(self) -> dict:
511
+ '''Returns JVM thread counts: current, peak, daemon.'''
512
+ return self.bridge.getThreadStats()
513
+
514
+ def getGarbageCollectorInfo(self) -> dict:
515
+ '''Returns gc_type, gc_count, gc_time_ms, last_gc_pause_ms and avg_gc_pause_ms.'''
516
+ return self.bridge.getGCStats()
517
+
518
+ def getNetworkInfo(self) -> dict:
519
+ '''Returns bytes_in_per_sec, bytes_out_per_sec, total_bytes_in and total_bytes_out (host, Linux only).'''
520
+ return self.bridge.getNetworkStats()
521
+
522
+ def getJVMUptime(self, formatted: bool = False):
523
+ '''Returns how long the JVM runs, in milliseconds, or like "3h 12m" with formatted=True.'''
524
+ uptime = self.bridge.getUptime()
525
+ return formatDuration(uptime) if formatted and uptime is not None else uptime
526
+
527
+
528
+ # installing HungerBridge (panel files + HungerBridgePy release lookup)
529
+ def findBridgeRelease(self, minecraft_version: str, loader: str, release: str = None) -> ReleaseAsset:
530
+ '''
531
+ Finds the HungerBridge jar for a Minecraft version and loader (HungerBridgePy find_release()).
532
+
533
+ Args:
534
+ minecraft_version: e.g. '1.21.11', or 'latest'.
535
+ loader: 'paper' or 'fabric' (server types such as 'PURPUR' work too).
536
+ release: Release tag; None uses the `release` config ('latest').
537
+ '''
538
+ config = settings()
539
+ return find_release(minecraft_version, loader, release or config['release'],
540
+ repository=config['repository'], api_url=config['github_api'])
541
+
542
+ def installBridge(self, minecraft_version: str = None, loader: str = None, release: str = None,
543
+ replace: bool = True) -> ReleaseAsset:
544
+ '''
545
+ Downloads the matching HungerBridge jar into /plugins (Paper, Purpur, Folia) or
546
+ /mods (Fabric). Restart the server afterwards.
547
+
548
+ The loader and Minecraft version are detected unless given: from the Version
549
+ Changer, a running bridge, or the egg name and startup variables.
550
+
551
+ Args:
552
+ minecraft_version: e.g. '1.21.11', or 'latest'.
553
+ loader: 'paper' or 'fabric'.
554
+ release: HungerBridge release tag; None uses the `release` config.
555
+ replace: Delete other HungerBridge jars in that directory first.
556
+
557
+ Returns:
558
+ The installed hungerbridge.ReleaseAsset (name, url, loader, minecraft_version, release).
559
+
560
+ Example:
561
+ server.installBridge()
562
+ server.restart()
563
+ server.waitForBridge()
564
+ '''
565
+ loader, minecraft_version = _bridge.detectPlatform(self, loader, minecraft_version)
566
+ if loader is None or minecraft_version is None:
567
+ raise MinecraftError(
568
+ f'Cannot tell which HungerBridge jar {self.name} needs (loader={loader!r}, '
569
+ f'minecraft_version={minecraft_version!r}). Pass them, e.g. installBridge("1.21.11", "paper").')
570
+ asset = self.findBridgeRelease(minecraft_version, loader, release)
571
+ if replace:
572
+ try:
573
+ old = [f.getName() for f in self.files.listFiles(asset.directory)
574
+ if f.getName() != asset.name and parse_asset_name(f.getName())]
575
+ except NotFoundError:
576
+ old = []
577
+ if old:
578
+ self.files.deleteFiles(asset.directory, old)
579
+ self.files.pullFile(asset.url, asset.directory, name=asset.name)
580
+ return asset
581
+
582
+
583
+ # server.properties and EULA (panel files)
584
+ def getProperties(self) -> dict:
585
+ '''
586
+ Reads server.properties.
587
+
588
+ Returns:
589
+ dict of property name -> string value.
590
+
591
+ Example:
592
+ print(server.getProperties()['max-players'])
593
+ '''
594
+ return _properties.parse(self.files.readFile('/server.properties'))
595
+
596
+ def getProperty(self, key: str, default=None) -> str:
597
+ '''Returns one server.properties value.'''
598
+ return self.getProperties().get(key, default)
599
+
600
+ def setProperty(self, key: str, value) -> None:
601
+ '''Changes one server.properties value. Takes effect after a restart.'''
602
+ return self.setProperties({key: value})
603
+
604
+ def setProperties(self, values: dict) -> None:
605
+ '''
606
+ Changes several server.properties values, keeping comments and order.
607
+
608
+ Example:
609
+ server.setProperties({'motd': 'Welcome!', 'max-players': 100, 'pvp': False})
610
+ '''
611
+ text = self.files.readFile('/server.properties')
612
+ return self.files.writeFile('/server.properties', _properties.update(text, values))
613
+
614
+ def getMOTD(self) -> str:
615
+ '''Returns the message of the day from server.properties.'''
616
+ return self.getProperty('motd')
617
+
618
+ def setMOTD(self, motd: str) -> None:
619
+ '''Sets the message of the day.'''
620
+ return self.setProperty('motd', motd)
621
+
622
+ def acceptEula(self) -> None:
623
+ '''Writes eula=true to eula.txt.'''
624
+ return self.files.writeFile('/eula.txt', 'eula=true\n')
625
+
626
+ def isEulaAccepted(self) -> bool:
627
+ '''Returns True if eula.txt contains eula=true.'''
628
+ try:
629
+ return 'eula=true' in self.files.readFile('/eula.txt').replace(' ', '').lower()
630
+ except NotFoundError:
631
+ return False