leafish 0.1.0__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.
Files changed (113) hide show
  1. leafish/__init__.py +77 -0
  2. leafish/auth/__init__.py +1 -0
  3. leafish/auth/microsoft.py +299 -0
  4. leafish/auth/offline.py +14 -0
  5. leafish/auth/session.py +48 -0
  6. leafish/bot.py +2086 -0
  7. leafish/config.py +57 -0
  8. leafish/data/__init__.py +1 -0
  9. leafish/data/registry.py +236 -0
  10. leafish/data/versions/.gitkeep +0 -0
  11. leafish/data/versions/1.21.11/attributes.json +247 -0
  12. leafish/data/versions/1.21.11/biomes.json +652 -0
  13. leafish/data/versions/1.21.11/blockCollisionShapes.json +146215 -0
  14. leafish/data/versions/1.21.11/blockLoot.json +13199 -0
  15. leafish/data/versions/1.21.11/blocks.json +44682 -0
  16. leafish/data/versions/1.21.11/commands.json +20257 -0
  17. leafish/data/versions/1.21.11/effects.json +242 -0
  18. leafish/data/versions/1.21.11/enchantments.json +980 -0
  19. leafish/data/versions/1.21.11/entities.json +4363 -0
  20. leafish/data/versions/1.21.11/entityLoot.json +1234 -0
  21. leafish/data/versions/1.21.11/foods.json +442 -0
  22. leafish/data/versions/1.21.11/items.json +10026 -0
  23. leafish/data/versions/1.21.11/language.json +7769 -0
  24. leafish/data/versions/1.21.11/loginPacket.json +19819 -0
  25. leafish/data/versions/1.21.11/mapIcons.json +212 -0
  26. leafish/data/versions/1.21.11/materials.json +233 -0
  27. leafish/data/versions/1.21.11/particles.json +462 -0
  28. leafish/data/versions/1.21.11/protocol.json +11655 -0
  29. leafish/data/versions/1.21.11/recipes.json +31864 -0
  30. leafish/data/versions/1.21.11/sounds.json +7354 -0
  31. leafish/data/versions/1.21.11/tints.json +465 -0
  32. leafish/data/versions/1.21.11/version.json +6 -0
  33. leafish/data/versions/1.21.11/windows.json +229 -0
  34. leafish/data/versions/1.21.4/attributes.json +226 -0
  35. leafish/data/versions/1.21.4/biomes.json +652 -0
  36. leafish/data/versions/1.21.4/blockCollisionShapes.json +142311 -0
  37. leafish/data/versions/1.21.4/blockLoot.json +13199 -0
  38. leafish/data/versions/1.21.4/blocks.json +41063 -0
  39. leafish/data/versions/1.21.4/commands.json +18720 -0
  40. leafish/data/versions/1.21.4/effects.json +236 -0
  41. leafish/data/versions/1.21.4/enchantments.json +959 -0
  42. leafish/data/versions/1.21.4/entities.json +4130 -0
  43. leafish/data/versions/1.21.4/entityLoot.json +1234 -0
  44. leafish/data/versions/1.21.4/foods.json +412 -0
  45. leafish/data/versions/1.21.4/items.json +9098 -0
  46. leafish/data/versions/1.21.4/language.json +7002 -0
  47. leafish/data/versions/1.21.4/loginPacket.json +18031 -0
  48. leafish/data/versions/1.21.4/mapIcons.json +212 -0
  49. leafish/data/versions/1.21.4/materials.json +134 -0
  50. leafish/data/versions/1.21.4/particles.json +450 -0
  51. leafish/data/versions/1.21.4/protocol.json +9456 -0
  52. leafish/data/versions/1.21.4/recipes.json +29693 -0
  53. leafish/data/versions/1.21.4/sounds.json +6606 -0
  54. leafish/data/versions/1.21.4/tints.json +422 -0
  55. leafish/data/versions/1.21.4/version.json +6 -0
  56. leafish/data/versions/1.21.4/windows.json +229 -0
  57. leafish/entities/__init__.py +1 -0
  58. leafish/entities/entity.py +162 -0
  59. leafish/entities/manager.py +197 -0
  60. leafish/events/__init__.py +1 -0
  61. leafish/events/emitter.py +176 -0
  62. leafish/events/events.py +63 -0
  63. leafish/exceptions.py +81 -0
  64. leafish/inventory/__init__.py +1 -0
  65. leafish/inventory/inventory.py +230 -0
  66. leafish/inventory/item.py +62 -0
  67. leafish/modules/__init__.py +1 -0
  68. leafish/modules/actions.py +625 -0
  69. leafish/modules/anvil.py +137 -0
  70. leafish/modules/chat.py +121 -0
  71. leafish/modules/client.py +269 -0
  72. leafish/modules/collector.py +86 -0
  73. leafish/modules/containers.py +268 -0
  74. leafish/modules/crafting.py +446 -0
  75. leafish/modules/creative.py +94 -0
  76. leafish/modules/farming.py +131 -0
  77. leafish/modules/fishing.py +161 -0
  78. leafish/modules/health.py +31 -0
  79. leafish/modules/movement.py +165 -0
  80. leafish/modules/pathfinder.py +257 -0
  81. leafish/modules/physics.py +265 -0
  82. leafish/modules/player.py +146 -0
  83. leafish/modules/pvp.py +192 -0
  84. leafish/modules/scoreboard.py +121 -0
  85. leafish/modules/smelting.py +163 -0
  86. leafish/modules/state.py +118 -0
  87. leafish/modules/windows.py +327 -0
  88. leafish/pathfinder/__init__.py +27 -0
  89. leafish/pathfinder/goals.py +268 -0
  90. leafish/plugins/__init__.py +177 -0
  91. leafish/protocol/__init__.py +1 -0
  92. leafish/protocol/compression.py +58 -0
  93. leafish/protocol/connection.py +210 -0
  94. leafish/protocol/encryption.py +75 -0
  95. leafish/protocol/framing.py +259 -0
  96. leafish/protocol/protodef.py +145 -0
  97. leafish/protocol/session.py +290 -0
  98. leafish/protocol/versions/__init__.py +1 -0
  99. leafish/utils/__init__.py +1 -0
  100. leafish/utils/geometry.py +173 -0
  101. leafish/utils/math.py +38 -0
  102. leafish/utils/nbt.py +477 -0
  103. leafish/utils/text.py +71 -0
  104. leafish/utils/vectors.py +145 -0
  105. leafish/version.py +86 -0
  106. leafish/world/__init__.py +1 -0
  107. leafish/world/block.py +59 -0
  108. leafish/world/chunk_codec.py +231 -0
  109. leafish/world/world.py +442 -0
  110. leafish-0.1.0.dist-info/METADATA +112 -0
  111. leafish-0.1.0.dist-info/RECORD +113 -0
  112. leafish-0.1.0.dist-info/WHEEL +4 -0
  113. leafish-0.1.0.dist-info/licenses/LICENSE +21 -0
leafish/bot.py ADDED
@@ -0,0 +1,2086 @@
1
+ """LeafishBot: the central public API object."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ import time
9
+ from typing import Any
10
+
11
+ from .auth.microsoft import MicrosoftAuth
12
+ from .auth.offline import OfflineAuth
13
+ from .auth.session import AuthSession
14
+ from .config import BotConfig
15
+ from .entities.entity import Player
16
+ from .entities.manager import EntityManager
17
+ from .events.emitter import EventEmitter
18
+ from .exceptions import LeafishError
19
+ from .inventory.inventory import Inventory
20
+ from .inventory.item import Item
21
+ from .modules.actions import ActionsModule
22
+ from .modules.anvil import AnvilModule
23
+ from .modules.chat import ChatModule
24
+ from .modules.client import ClientModule
25
+ from .modules.collector import CollectorModule
26
+ from .modules.containers import ContainerModule, SimpleClick
27
+ from .modules.crafting import CraftingModule
28
+ from .modules.creative import CreativeModule
29
+ from .modules.farming import FarmingModule
30
+ from .modules.fishing import FishingModule
31
+ from .modules.health import HealthModule
32
+ from .modules.movement import CONTROL_STATES, MovementModule
33
+ from .modules.pathfinder import Pathfinder
34
+ from .modules.physics import PhysicsEngine
35
+ from .modules.player import PlayerModule
36
+ from .modules.pvp import PVPModule
37
+ from .modules.scoreboard import BossBar, Particle, ScoreBoard, Team
38
+ from .modules.smelting import SmeltingModule
39
+ from .modules.state import (
40
+ AbilitiesInfo,
41
+ ExperienceInfo,
42
+ GameInfo,
43
+ SettingsInfo,
44
+ TimeInfo,
45
+ WeatherInfo,
46
+ )
47
+ from .modules.windows import (
48
+ AnvilWindow,
49
+ EnchantmentTableWindow,
50
+ FurnaceWindow,
51
+ )
52
+ from .plugins import PluginManager
53
+ from .protocol.protodef import ProtocolCodec
54
+ from .protocol.session import ClientSession
55
+ from .utils.geometry import ray_box_distance
56
+ from .utils.math import yaw_pitch_to_direction
57
+ from .utils.text import component_to_text, nbt_to_python
58
+ from .utils.vectors import BlockPos, Vec3
59
+ from .world.chunk_codec import ChunkDecodeError, decode_chunk_sections
60
+ from .world.world import World
61
+
62
+ log = logging.getLogger("leafish.bot")
63
+
64
+
65
+ class LeafishBot:
66
+ """A connected (or connecting) Minecraft bot."""
67
+
68
+ def __init__(
69
+ self,
70
+ config: BotConfig,
71
+ auth: AuthSession,
72
+ codec: ProtocolCodec,
73
+ ) -> None:
74
+ self.config = config
75
+ self.auth = auth
76
+ self.codec = codec
77
+ self.emitter = EventEmitter()
78
+
79
+ # Core state -----------------------------------------------------
80
+ self.entity: Player | None = None
81
+ """The bot's own player entity."""
82
+ self.entity_id: int | None = None
83
+ self.username: str = auth.username
84
+ self.uuid: str = auth.uuid
85
+ self.game_mode: str | None = None
86
+ self.server_brand: str | None = None
87
+ self.spawned = False
88
+
89
+ # Subsystems -------------------------------------------------------
90
+ self.world = World(self, codec.minecraft_version)
91
+ self.entities = EntityManager(self.world.gamedata.entity_type_ids)
92
+ self.inventory = Inventory(self)
93
+ self.physics = PhysicsEngine(self)
94
+ self.movement = MovementModule(self)
95
+ self.vitals = HealthModule(self)
96
+ self.chat_module = ChatModule(self)
97
+ self.actions = ActionsModule(self)
98
+ self.crafting = CraftingModule(self)
99
+ self.pathfinder = Pathfinder(self)
100
+ self.pvp = PVPModule(self)
101
+ self.fishing = FishingModule(self)
102
+ self.collector = CollectorModule(self)
103
+ self.farming = FarmingModule(self)
104
+ self.containers = ContainerModule(self)
105
+ self.anvil = AnvilModule(self)
106
+ self.smelting = SmeltingModule(self)
107
+ self.creative = CreativeModule(self)
108
+ self.player = PlayerModule(self)
109
+ self.client = ClientModule(self)
110
+ self.simple_click = SimpleClick(self)
111
+ self.plugins = PluginManager(self)
112
+
113
+ # State objects -----------------------------------------------------
114
+ self.chat_patterns: dict[str, dict] = {}
115
+ self.feature_flags: set[str] | None = None
116
+ self._game = GameInfo()
117
+ self._time = TimeInfo()
118
+ self._abilities = AbilitiesInfo()
119
+ self._experience = ExperienceInfo()
120
+ self.settings = SettingsInfo(view_distance=config.view_distance)
121
+ self._weather = WeatherInfo()
122
+
123
+ # Scoreboard / team / boss-bar / title state -------------------------
124
+ self.scoreboards: dict[str, ScoreBoard] = {}
125
+ self.teams: dict[str, Team] = {}
126
+ self.boss_bars: dict[str, BossBar] = {}
127
+ self._title_state: dict[str, Any] = {}
128
+ self._scoreboard_slots: dict[int, str] = {}
129
+ self.cursor_item: Item | None = None
130
+
131
+ # Movement control states --------------------------------------------
132
+ self.control_states: dict[str, bool] = {c: False for c in CONTROL_STATES}
133
+ self.using_held_item: bool = False
134
+ """Whether the held item is currently activated (bow drawn, eating)."""
135
+
136
+ # Window state --------------------------------------------------------
137
+ self.current_window_id: int | None = None
138
+ self.inventory_state_id: int = 0
139
+
140
+ # Session -------------------------------------------------------------
141
+ self.session: ClientSession | None = None
142
+ self._disconnect_waiters: list[asyncio.Future] = []
143
+ self._first_position_received = False
144
+ self._ended = False
145
+ self._disconnect_task: asyncio.Task | None = None
146
+
147
+ # -- event API (delegated to emitter) ----------------------------------------
148
+
149
+ def on(self, event: str, handler=None):
150
+ return self.emitter.on(event, handler)
151
+
152
+ def once(self, event: str, handler=None):
153
+ return self.emitter.once(event, handler)
154
+
155
+ def off(self, event: str, handler=None):
156
+ self.emitter.off(event, handler)
157
+
158
+ def emit(self, event: str, *args, **kwargs) -> None:
159
+ self.emitter.emit(event, *args, **kwargs)
160
+
161
+ async def wait_for(self, event: str, timeout: float | None = None):
162
+ return await self.emitter.wait_for(event, timeout)
163
+
164
+ async def wait_until_disconnected(self) -> None:
165
+ if self.session is not None:
166
+ await self.session.wait_until_disconnected()
167
+
168
+ # -- connection lifecycle ----------------------------------------------------
169
+
170
+ async def _start(self) -> None:
171
+ self.session = ClientSession(
172
+ self.config,
173
+ self.codec,
174
+ on_packet=self._on_packet,
175
+ on_state_change=self._on_state_change,
176
+ )
177
+ await self.session.connect_and_login(
178
+ self.username,
179
+ self.uuid,
180
+ access_token=self.auth.access_token,
181
+ )
182
+ self.physics.start()
183
+ self._disconnect_task = asyncio.create_task(
184
+ self._watch_disconnect(), name="leafish-disconnect-watch"
185
+ )
186
+
187
+ async def _watch_disconnect(self) -> None:
188
+ """Stop subsystems and emit ``end`` when the connection drops."""
189
+ assert self.session is not None
190
+ await self.session.wait_until_disconnected()
191
+ await self._cleanup_after_disconnect()
192
+
193
+ async def _cleanup_after_disconnect(self) -> None:
194
+ if self._ended:
195
+ return
196
+ self._ended = True
197
+ await self.physics.stop()
198
+ # Stop any in-progress automation so tasks don't outlive the
199
+ # connection. Each stop is best-effort.
200
+ for stop in (
201
+ self.pathfinder.stop,
202
+ self.pvp.stop,
203
+ self.movement.stop_moving,
204
+ ):
205
+ with contextlib.suppress(Exception): # cleanup must not raise
206
+ await stop()
207
+ reason = "client disconnect"
208
+ if self.session is not None:
209
+ reason = self.session.state.disconnect_reason or reason
210
+ self.emit("end", reason)
211
+
212
+ async def disconnect(self, reason: str = "client disconnect") -> None:
213
+ """Disconnect gracefully."""
214
+ if self.session is not None:
215
+ await self.session.disconnect(reason)
216
+ await self.physics.stop()
217
+ await self._cleanup_after_disconnect()
218
+
219
+ async def quit(self, reason: str = "client quit") -> None:
220
+ """Alias for :meth:`disconnect`."""
221
+ await self.disconnect(reason)
222
+
223
+ # -- packet plumbing ---------------------------------------------------------
224
+
225
+ async def _send_play(self, name: str, params: dict[str, Any] | None = None) -> None:
226
+ if self.session is None:
227
+ raise LeafishError("Bot is not connected")
228
+ await self.session.send("play", "toServer", name, params)
229
+
230
+ async def _on_state_change(self, state: str) -> None:
231
+ if state == "play":
232
+ self.emit("login")
233
+
234
+ async def _on_packet(
235
+ self, state: str, direction: str, name: str, params: dict[str, Any]
236
+ ) -> None:
237
+ if direction != "toClient":
238
+ return
239
+ if state == "configuration":
240
+ if name == "registry_data":
241
+ self._on_registry_data(params)
242
+ elif name == "feature_flags":
243
+ self.feature_flags = set(params.get("features") or [])
244
+ return
245
+ if state != "play":
246
+ return
247
+ handler = getattr(self, f"_packet_{name}", None)
248
+ if handler is not None:
249
+ try:
250
+ result = handler(params)
251
+ if asyncio.iscoroutine(result):
252
+ await result
253
+ except Exception:
254
+ log.exception("Packet handler for '%s' failed", name)
255
+ self.emit("error", name, params)
256
+
257
+ async def _click_window_slot(
258
+ self, window_id: int, slot: int, button: int = 0,
259
+ state_id: int | None = None,
260
+ ) -> None:
261
+ await self._send_play(
262
+ "window_click",
263
+ {
264
+ "windowId": window_id,
265
+ "stateId": (
266
+ self.inventory_state_id if state_id is None else state_id
267
+ ),
268
+ "slot": slot,
269
+ "mouseButton": button,
270
+ "mode": 0,
271
+ "changedSlots": [],
272
+ "cursorItem": None,
273
+ },
274
+ )
275
+
276
+ def _on_registry_data(self, params: dict[str, Any]) -> None:
277
+ """Capture synchronized registries sent during the config state."""
278
+ reg = params.get("id")
279
+ entries = params.get("entries") or []
280
+ if reg == "minecraft:dimension_type":
281
+ for entry in entries:
282
+ value = nbt_to_python(entry.get("value"))
283
+ if isinstance(value, dict):
284
+ self.world.dimension_types[entry.get("key", "")] = {
285
+ "min_y": int(value.get("min_y", -64)),
286
+ "height": int(value.get("height", 384)),
287
+ }
288
+ elif reg == "minecraft:dimension":
289
+ for entry in entries:
290
+ value = nbt_to_python(entry.get("value"))
291
+ if isinstance(value, dict):
292
+ self.world.dimensions[entry.get("key", "")] = value
293
+ elif reg == "minecraft:worldgen/biome":
294
+ self.world.biome_count = len(entries)
295
+
296
+ # -- play-state packet handlers -------------------------------------------------
297
+
298
+ def _packet_login(self, params: dict[str, Any]) -> None:
299
+ self.entity_id = params.get("entityId")
300
+ ws = params.get("worldState", params.get("commonPlayerSpawnInfo", {}))
301
+ self.game_mode = ws.get("gamemode")
302
+ self._game.game_mode = self.game_mode
303
+ self._game.hardcore = bool(params.get("isHardcore", False))
304
+ self._game.max_players = params.get("maxPlayers")
305
+ self._game.view_distance = params.get("viewDistance")
306
+ self._game.simulation_distance = params.get("simulationDistance")
307
+ names = params.get("worldNames") or []
308
+ if names:
309
+ self._game.level_type = names[0]
310
+ self.world.apply_dimension(ws.get("name"), ws.get("dimension"))
311
+ self._game.dimension = ws.get("name") or self.world.dimension
312
+ if self.entity is None and self.entity_id is not None:
313
+ self.entity = Player(id=self.entity_id, uuid=self.uuid, name=self.username)
314
+
315
+ async def _packet_position(self, params: dict[str, Any]) -> None:
316
+ entity = self.entity
317
+ if entity is None:
318
+ return
319
+ flags = params.get("flags") or {}
320
+ if isinstance(flags, dict):
321
+ flag_set = {k for k, v in flags.items() if v and k != "_value"}
322
+ else:
323
+ flag_set = set(flags if isinstance(flags, list) else [flags])
324
+ x = float(params.get("x", 0))
325
+ y = float(params.get("y", 0))
326
+ z = float(params.get("z", 0))
327
+ if "x" in flag_set:
328
+ x += entity.position.x
329
+ if "y" in flag_set:
330
+ y += entity.position.y
331
+ if "z" in flag_set:
332
+ z += entity.position.z
333
+ entity.set_position(x, y, z)
334
+ vx = float(params.get("dx", 0))
335
+ vy = float(params.get("dy", 0))
336
+ vz = float(params.get("dz", 0))
337
+ if "dx" in flag_set:
338
+ vx += entity.velocity.x
339
+ if "dy" in flag_set:
340
+ vy += entity.velocity.y
341
+ if "dz" in flag_set:
342
+ vz += entity.velocity.z
343
+ entity.velocity = Vec3(vx, vy, vz)
344
+ yaw = float(params.get("yaw", entity.yaw))
345
+ pitch = float(params.get("pitch", entity.pitch))
346
+ if "yaw" in flag_set:
347
+ yaw += entity.yaw
348
+ if "pitch" in flag_set:
349
+ pitch += entity.pitch
350
+ entity.set_rotation(yaw, pitch)
351
+ entity.on_ground = "onGround" in flag_set or (
352
+ isinstance(flags, dict) and bool(flags.get("onGround"))
353
+ ) or (isinstance(flags, int) and bool(flags & 1))
354
+ # Confirm the teleport.
355
+ teleport_id = params.get("teleportId")
356
+ if teleport_id is not None:
357
+ await self._send_play("teleport_confirm", {"teleportId": teleport_id})
358
+ if not self._first_position_received:
359
+ self._first_position_received = True
360
+ self.spawned = True
361
+ self.emit("spawn")
362
+ else:
363
+ self.emit("forced_move")
364
+
365
+ def _packet_respawn(self, params: dict[str, Any]) -> None:
366
+ ws = params.get("worldState", params.get("commonPlayerSpawnInfo", {}))
367
+ self.game_mode = ws.get("gamemode")
368
+ self._game.game_mode = self.game_mode
369
+ self._game.dimension = ws.get("name")
370
+ self.world.apply_dimension(ws.get("name"), ws.get("dimension"))
371
+ self._game.min_y = self.world.min_y
372
+ self._game.height = self.world.height
373
+ self.world.chunks.clear()
374
+ self.entities.clear()
375
+ self.player._sleeping = False
376
+ self.emit("respawn")
377
+ self.emit("spawn_reset")
378
+ self.spawned = False
379
+ self._first_position_received = False
380
+
381
+ def _packet_player_chat(self, params: dict[str, Any]) -> None:
382
+ sender_uuid = params.get("senderUuid")
383
+ username = self._player_name(sender_uuid) or str(sender_uuid)
384
+ message = params.get("plainMessage") or ""
385
+ self.emit("chat", username, message)
386
+ self.emit("player_chat", username, message, params)
387
+ self._dispatch_chat_patterns(username, message)
388
+
389
+ def _packet_system_chat(self, params: dict[str, Any]) -> None:
390
+ text = component_to_text(nbt_to_python(params.get("content")))
391
+ self.emit("chat", None, text)
392
+ self.emit("message", {"type": "system", "text": text})
393
+
394
+ def _packet_profileless_chat(self, params: dict[str, Any]) -> None:
395
+ message = component_to_text(nbt_to_python(params.get("message")))
396
+ name = component_to_text(nbt_to_python(params.get("name"))) or None
397
+ self.emit("chat", name, message)
398
+ self._dispatch_chat_patterns(name, message)
399
+
400
+ def _dispatch_chat_patterns(self, username, message: str) -> None:
401
+ """Emit ``chat:<name>`` for registered chat patterns."""
402
+ for name, spec in self.chat_patterns.items():
403
+ chat_type = spec.get("chatType", "chat")
404
+ if chat_type != "chat":
405
+ continue
406
+ patterns = spec.get("patterns") or [spec.get("pattern")]
407
+ for pattern in patterns:
408
+ if pattern is None:
409
+ continue
410
+ m = pattern.search(message or "")
411
+ if m is not None:
412
+ self.emit(f"chat:{name}", username, message, m)
413
+ break
414
+
415
+ def _packet_player_info(self, params: dict[str, Any]) -> None:
416
+ action = params.get("action") or {}
417
+ if isinstance(action, dict):
418
+ actions = {k for k, v in action.items() if v and k != "_value"}
419
+ else:
420
+ actions = set(action if isinstance(action, list) else [action])
421
+ for entry in params.get("data", []):
422
+ uuid_str = entry.get("uuid")
423
+ player = entry.get("player") or {}
424
+ name = None
425
+ if isinstance(player, dict):
426
+ name = player.get("name")
427
+ if "add_player" in actions or "update_display_name" in actions:
428
+ from .entities.entity import Player as _P
429
+
430
+ existing = self.entities.players.get(uuid_str)
431
+ if existing is None:
432
+ existing = _P(id=-1, uuid=uuid_str, name=name)
433
+ self.entities.players[uuid_str] = existing
434
+ self.emit("player_join", existing)
435
+ if name:
436
+ existing.name = name
437
+ if "update_game_mode" in actions:
438
+ existing.game_mode = entry.get("gamemode")
439
+ if "update_latency" in actions:
440
+ existing.latency = entry.get("latency")
441
+ self.emit("player_updated", existing)
442
+ if "remove_player" in actions or "remove" in actions:
443
+ removed = self.entities.players.pop(uuid_str, None)
444
+ if removed is not None:
445
+ self.emit("player_leave", removed)
446
+
447
+ def _packet_player_remove(self, params: dict[str, Any]) -> None:
448
+ for uuid_str in params.get("players", []):
449
+ removed = self.entities.players.pop(uuid_str, None)
450
+ if removed is not None:
451
+ self.emit("player_leave", removed)
452
+
453
+ def _packet_playerlist_header(self, params: dict[str, Any]) -> None:
454
+ self.emit("playerlist_header", params)
455
+
456
+ def _packet_update_health(self, params: dict[str, Any]) -> None:
457
+ old = self.vitals.health
458
+ self.vitals.update_health(params)
459
+ self.emit("health", self.vitals.health, self.vitals.food)
460
+ self.emit("food", self.vitals.food, self.vitals.food_saturation)
461
+ if old != self.vitals.health:
462
+ self.emit("entity_hurt", self.entity)
463
+
464
+ def _packet_experience(self, params: dict[str, Any]) -> None:
465
+ self.vitals.update_experience(params)
466
+ self._experience.level = self.vitals.experience_level
467
+ self._experience.progress = self.vitals.experience_progress
468
+ self._experience.points = self.vitals.experience_total
469
+ self._experience.total = self.vitals.experience_total
470
+ self.emit("experience", self.vitals.experience_level,
471
+ self.vitals.experience_progress)
472
+
473
+ def _packet_held_item_slot(self, params: dict[str, Any]) -> None:
474
+ # Clientbound slot is the hotbar index (0-8) in modern versions.
475
+ slot_id = int(params.get("slot", params.get("slotId", 0)))
476
+ if not 0 <= slot_id <= 8:
477
+ return
478
+ self.inventory.held_slot = slot_id
479
+ self.emit("held_item_changed", slot_id)
480
+
481
+ def _packet_set_player_inventory(self, params: dict[str, Any]) -> None:
482
+ self.inventory.update_slot(0, int(params.get("slotId", 0)), params.get("contents", {}))
483
+ self.emit("inventory_update")
484
+
485
+ def _packet_set_slot(self, params: dict[str, Any]) -> None:
486
+ wid = int(params.get("windowId", 0))
487
+ slot = int(params.get("slot", 0))
488
+ if wid == 0:
489
+ self.inventory_state_id = int(params.get("stateId", 0))
490
+ self.inventory.update_slot(wid, slot, params.get("item", {}))
491
+ else:
492
+ self.containers.set_state(wid, int(params.get("stateId", 0)))
493
+ self.containers.update_slot(wid, slot, params.get("item", {}))
494
+ self.emit("inventory_update")
495
+
496
+ def _packet_window_items(self, params: dict[str, Any]) -> None:
497
+ wid = int(params.get("windowId", 0))
498
+ items = params.get("items", [])
499
+ if wid == 0:
500
+ self.inventory_state_id = int(params.get("stateId", 0))
501
+ self.inventory.update_contents(
502
+ wid, items, params.get("carriedItem"),
503
+ )
504
+ else:
505
+ self.containers.set_state(wid, int(params.get("stateId", 0)))
506
+ self.containers.update_contents(wid, items)
507
+ self.emit("inventory_update")
508
+
509
+ def _packet_open_window(self, params: dict[str, Any]) -> None:
510
+ wid = params.get("windowId")
511
+ title = component_to_text(nbt_to_python(params.get("windowTitle")))
512
+ self.current_window_id = wid
513
+ if wid is not None:
514
+ self.containers.open_window(
515
+ int(wid), title, params.get("inventoryType"),
516
+ )
517
+ self.emit("window_open", self.current_window_id, title, params)
518
+
519
+ def _packet_close_window(self, params: dict[str, Any]) -> None:
520
+ wid = params.get("windowId", self.current_window_id)
521
+ if self.current_window_id == wid:
522
+ self.current_window_id = None
523
+ if wid is not None:
524
+ self.containers.close_window(int(wid))
525
+ self.emit("window_close", wid)
526
+
527
+ def _packet_craft_progress_bar(self, params: dict[str, Any]) -> None:
528
+ wid = int(params.get("windowId", 0))
529
+ prop = int(params.get("property", 0))
530
+ value = int(params.get("value", 0))
531
+ self.containers.set_property(wid, prop, value)
532
+ self.emit("window_property", wid, prop, value)
533
+
534
+ def _packet_trade_list(self, params: dict[str, Any]) -> None:
535
+ wid = int(params.get("windowId", 0))
536
+ trades = params.get("trades", [])
537
+ self.containers.set_extras(
538
+ wid,
539
+ trades=trades,
540
+ villagerLevel=params.get("villagerLevel"),
541
+ experience=params.get("experience"),
542
+ isRegularVillager=params.get("isRegularVillager"),
543
+ canRestock=params.get("canRestock"),
544
+ )
545
+ self.emit("trade_list", wid, trades)
546
+ self.emit("villager_trade_list", wid, trades)
547
+
548
+ def _packet_open_horse_window(self, params: dict[str, Any]) -> None:
549
+ wid = params.get("windowId")
550
+ self.current_window_id = wid
551
+ if wid is not None:
552
+ nb = int(params.get("nbSlots", 0))
553
+ self.containers.open_window(
554
+ int(wid), "Horse", None)
555
+ self.containers.set_extras(
556
+ int(wid), entityId=params.get("entityId"),
557
+ slotCount=nb)
558
+ win = self.containers.windows.get(int(wid))
559
+ if win is not None:
560
+ win.player_offset = max(0, nb)
561
+ self.emit("open_horse_window", params)
562
+
563
+ def _packet_declare_recipes(self, params: dict[str, Any]) -> None:
564
+ self.emit("declare_recipes", params)
565
+
566
+ def _packet_craft_recipe_response(self, params: dict[str, Any]) -> None:
567
+ self.emit("craft_recipe_response", params)
568
+
569
+ # -- entities -----------------------------------------------------------------
570
+
571
+ def _packet_spawn_entity(self, params: dict[str, Any]) -> None:
572
+ entity = self.entities.spawn(params)
573
+ self.emit("entity_spawn", entity)
574
+
575
+ def _packet_entity_metadata(self, params: dict[str, Any]) -> None:
576
+ entity = self.entities.update_metadata(
577
+ params["entityId"], params.get("metadata", [])
578
+ )
579
+ if entity is not None:
580
+ self.emit("entity_metadata_update", entity)
581
+
582
+ def _packet_entity_equipment(self, params: dict[str, Any]) -> None:
583
+ entity = self.entities.update_equipment(
584
+ params["entityId"], params.get("equipments", [])
585
+ )
586
+ if entity is not None:
587
+ self.emit("entity_equipment_update", entity)
588
+
589
+ def _packet_entity_destroy(self, params: dict[str, Any]) -> None:
590
+ removed = self.entities.destroy(params.get("entityIds", []))
591
+ for e in removed:
592
+ self.emit("entity_destroy", e)
593
+
594
+ def _packet_entity_velocity(self, params: dict[str, Any]) -> None:
595
+ e = self.entities.get(params["entityId"])
596
+ if e is not None:
597
+ v = params.get("velocity", {})
598
+ e.velocity = Vec3(v.get("x", 0), v.get("y", 0), v.get("z", 0))
599
+ self.emit("entity_update", e)
600
+
601
+ def _packet_sync_entity_position(self, params: dict[str, Any]) -> None:
602
+ e = self.entities.teleport(params["entityId"], params)
603
+ if e is not None:
604
+ self.emit("entity_teleport", e)
605
+
606
+ def _packet_entity_teleport(self, params: dict[str, Any]) -> None:
607
+ e = self.entities.teleport(params["entityId"], params)
608
+ if e is not None:
609
+ self.emit("entity_teleport", e)
610
+
611
+ def _packet_entity_move_look(self, params: dict[str, Any]) -> None:
612
+ e = self.entities.move_relative(
613
+ params["entityId"],
614
+ params.get("dX", 0), params.get("dY", 0), params.get("dZ", 0),
615
+ yaw=params.get("yaw"), pitch=params.get("pitch"),
616
+ on_ground=params.get("onGround"),
617
+ )
618
+ if e is not None:
619
+ self.emit("entity_move", e)
620
+
621
+ def _packet_rel_entity_move(self, params: dict[str, Any]) -> None:
622
+ e = self.entities.move_relative(
623
+ params["entityId"],
624
+ params.get("dX", 0), params.get("dY", 0), params.get("dZ", 0),
625
+ on_ground=params.get("onGround"),
626
+ )
627
+ if e is not None:
628
+ self.emit("entity_move", e)
629
+
630
+ def _packet_entity_look(self, params: dict[str, Any]) -> None:
631
+ e = self.entities.get(params["entityId"])
632
+ if e is not None:
633
+ e.set_rotation(
634
+ float(params.get("yaw", 0)) * 360.0 / 256.0,
635
+ float(params.get("pitch", 0)) * 360.0 / 256.0,
636
+ )
637
+ e.on_ground = bool(params.get("onGround", False))
638
+ self.emit("entity_update", e)
639
+
640
+ # -- world ---------------------------------------------------------------------
641
+
642
+ def _packet_map_chunk(self, params: dict[str, Any]) -> None:
643
+ cx, cz = int(params.get("x", 0)), int(params.get("z", 0))
644
+ raw = params.get("chunkData")
645
+ if raw is None:
646
+ data = b""
647
+ elif isinstance(raw, (bytes, bytearray)):
648
+ data = bytes(raw)
649
+ else:
650
+ data = bytes(raw)
651
+ heightmaps = {
652
+ hm.get("type"): hm.get("data")
653
+ for hm in (params.get("heightmaps") or [])
654
+ if isinstance(hm, dict)
655
+ }
656
+ block_entities = params.get("blockEntities") or []
657
+ try:
658
+ sections = decode_chunk_sections(
659
+ data,
660
+ section_count=self.world.section_count,
661
+ min_section_y=self.world.min_section_y,
662
+ )
663
+ except ChunkDecodeError:
664
+ log.exception("Failed to decode chunk column (%d, %d)", cx, cz)
665
+ sections = []
666
+ self.world.load_chunk_data(
667
+ cx, cz, sections,
668
+ heightmaps=heightmaps, block_entities=block_entities,
669
+ )
670
+ self.world.apply_light_update(cx, cz, params)
671
+ self.emit("chunk_column_load", cx, cz)
672
+
673
+ def _packet_unload_chunk(self, params: dict[str, Any]) -> None:
674
+ cx, cz = params.get("chunkX", 0), params.get("chunkZ", 0)
675
+ self.world.unload_chunk(cx, cz)
676
+ self.emit("chunk_column_unload", cx, cz)
677
+
678
+ def _packet_block_change(self, params: dict[str, Any]) -> None:
679
+ loc = params.get("location", {})
680
+ pos = _pos_from_bitfield(loc)
681
+ state_id = params.get("type")
682
+ if pos is not None and isinstance(state_id, int):
683
+ self.world.set_block_state(pos, state_id)
684
+ self.emit("block_update", pos, state_id)
685
+
686
+ def _packet_multi_block_change(self, params: dict[str, Any]) -> None:
687
+ coords = params.get("chunkCoordinates") or {}
688
+ try:
689
+ cx = int(coords.get("x", 0))
690
+ cz = int(coords.get("z", 0))
691
+ section_y = int(coords.get("y", 0))
692
+ except (AttributeError, TypeError, ValueError):
693
+ return
694
+ for record in params.get("records") or []:
695
+ record = int(record)
696
+ state_id = record >> 12
697
+ local = record & 0xFFF
698
+ lx = (local >> 8) & 0xF
699
+ lz = (local >> 4) & 0xF
700
+ ly = local & 0xF
701
+ pos = BlockPos(cx * 16 + lx, section_y * 16 + ly, cz * 16 + lz)
702
+ self.world.set_block_state(pos, state_id)
703
+ self.emit("multi_block_change", params)
704
+
705
+ def _packet_tile_entity_data(self, params: dict[str, Any]) -> None:
706
+ pos = _pos_from_bitfield(params.get("location"))
707
+ nbt = nbt_to_python(params.get("nbtData"))
708
+ block = self.world.block_at(pos) if pos is not None else None
709
+ if block is not None:
710
+ block.block_entity = nbt if isinstance(nbt, dict) else {"data": nbt}
711
+ self.emit("block_entity_data", pos, nbt, params)
712
+
713
+ def _packet_update_light(self, params: dict[str, Any]) -> None:
714
+ self.world.apply_light_update(
715
+ params.get("chunkX", 0), params.get("chunkZ", 0), params,
716
+ )
717
+ self.emit("update_light", params)
718
+
719
+ def _packet_chunk_biomes(self, params: dict[str, Any]) -> None:
720
+ # Biome-only updates carry raw paletted-container bytes per chunk;
721
+ # stored for consumers until light/biome queries are needed.
722
+ self.emit("chunk_biomes", params)
723
+
724
+ def _packet_game_state_change(self, params: dict[str, Any]) -> None:
725
+ reason = params.get("reason")
726
+ self.emit("game_state_change", reason, params.get("gameMode"))
727
+ if reason in ("start_raining", "stop_raining", "rain_level_change",
728
+ "thunder_level_change"):
729
+ # The packet's gameMode field carries the 0-1 level for the
730
+ # *_level_change reasons.
731
+ value = params.get("gameMode")
732
+ w = self.world.weather
733
+ if reason in ("start_raining", "stop_raining"):
734
+ self.world.set_weather(
735
+ {"raining": reason == "start_raining"})
736
+ self._weather.raining = bool(w.get("raining", self._weather.raining))
737
+ self._weather.thundering = reason == "thunder_level_change" or bool(
738
+ w.get("thundering", self._weather.thundering))
739
+ if reason == "rain_level_change" and value is not None:
740
+ self._weather.rain_level = float(value)
741
+ w["rain_level"] = float(value)
742
+ if reason == "thunder_level_change" and value is not None:
743
+ self._weather.thunder_level = float(value)
744
+ w["thunder_level"] = float(value)
745
+ self.emit("weather_update", self.world.weather)
746
+
747
+ def _packet_update_time(self, params: dict[str, Any]) -> None:
748
+ age = int(params.get("age", 0))
749
+ day_time = int(params.get("time", 0))
750
+ tick = bool(params.get("tickDayTime", False))
751
+ self.world.set_time(age, day_time, tick)
752
+ self._time.big_time = age
753
+ self._time.time = day_time
754
+ self._time.tick_day_time = tick
755
+ self._time.do_daylight_cycle = tick
756
+ self.emit("time_update", self.world.time, self.world.time_of_day)
757
+ self.emit("time", self._time)
758
+
759
+ def _packet_abilities(self, params: dict[str, Any]) -> None:
760
+ flags = params.get("flags", 0)
761
+ # Abilities flags byte (i8): bit0 invulnerable, bit1 flying,
762
+ # bit2 allow-flying, bit3 creative/instabuild, bit4 god-mode.
763
+ ab = self._abilities
764
+ value = int(flags) if isinstance(flags, int) else 0
765
+ ab.invulnerable = bool(value & 0x01)
766
+ ab.flying = bool(value & 0x02)
767
+ ab.may_fly = bool(value & 0x04)
768
+ ab.instabuild = bool(value & 0x08)
769
+ ab.may_build = True # no dedicated flag in modern protocol
770
+ ab.flying_speed = float(params.get("flyingSpeed", ab.flying_speed))
771
+ ab.walking_speed = float(params.get("walkingSpeed", ab.walking_speed))
772
+ self.emit("abilities", params)
773
+ self.emit("abilities_update", ab)
774
+
775
+ def _packet_entity_status(self, params: dict[str, Any]) -> None:
776
+ self.emit("entity_status", params.get("entityId"), params.get("entityStatus"))
777
+
778
+ def _packet_entity_update_attributes(self, params: dict[str, Any]) -> None:
779
+ self.emit("entity_update_attributes", params)
780
+
781
+ def _packet_explosion(self, params: dict[str, Any]) -> None:
782
+ self.client.record_explosion(params)
783
+ self.emit("explosion", params)
784
+
785
+ def _packet_world_event(self, params: dict[str, Any]) -> None:
786
+ self.emit("world_event", params)
787
+
788
+ def _packet_entity_head_rotation(self, params: dict[str, Any]) -> None:
789
+ e = self.entities.get(params["entityId"])
790
+ if e is not None:
791
+ e.head_yaw = float(params.get("headYaw", 0)) * 360.0 / 256.0
792
+
793
+ def _packet_update_view_position(self, params: dict[str, Any]) -> None:
794
+ self.emit("update_view_position", params)
795
+
796
+ def _packet_spawn_position(self, params: dict[str, Any]) -> None:
797
+ # RespawnData: {globalPos: {dimension, pos: {x,y,z}}, yaw, pitch}
798
+ gp = params.get("globalPos") or {}
799
+ pos = gp.get("pos") or {}
800
+ with contextlib.suppress(AttributeError, TypeError, ValueError):
801
+ self.world.spawn_point = BlockPos(
802
+ int(pos.get("x", 0)), int(pos.get("y", 0)), int(pos.get("z", 0))
803
+ )
804
+ self.emit("spawn_position", params)
805
+
806
+ def _packet_difficulty(self, params: dict[str, Any]) -> None:
807
+ self._game.difficulty = params.get("difficulty")
808
+ self._game.extra["difficulty_locked"] = params.get("difficultyLocked")
809
+ self.emit("difficulty", params.get("difficulty"))
810
+
811
+ def _packet_server_data(self, params: dict[str, Any]) -> None:
812
+ motd = component_to_text(nbt_to_python(params.get("motd")))
813
+ if motd:
814
+ self._game.server_brand = motd
815
+ self.emit("server_data", params)
816
+
817
+ def _packet_tab_complete(self, params: dict[str, Any]) -> None:
818
+ self.emit("tab_complete_response", params)
819
+
820
+ def _packet_open_sign_entity(self, params: dict[str, Any]) -> None:
821
+ pos = _pos_from_bitfield(params.get("location"))
822
+ self.emit("open_sign_entity", params)
823
+ self.emit("sign_open", pos)
824
+
825
+ def _packet_chunk_batch_start(self, params: dict[str, Any]) -> None:
826
+ self.emit("chunk_batch_start")
827
+
828
+ def _packet_chunk_batch_finished(self, params: dict[str, Any]) -> None:
829
+ self.emit("chunk_batch_finished", params)
830
+
831
+ def _packet_custom_payload(self, params: dict[str, Any]) -> None:
832
+ self.emit("custom_payload", params.get("channel"), params.get("data"))
833
+
834
+ async def _packet_cookie_request(self, params: dict[str, Any]) -> None:
835
+ # Acknowledge cookie requests to keep the server happy.
836
+ with contextlib.suppress(Exception):
837
+ await self._send_play(
838
+ "custom_payload",
839
+ {"channel": "minecraft:cookie", "data": b""},
840
+ )
841
+
842
+ def _packet_kick_disconnect(self, params: dict[str, Any]) -> None:
843
+ text = component_to_text(nbt_to_python(params.get("reason")))
844
+ self.emit("kicked", text)
845
+
846
+ # -- combat / damage ---------------------------------------------------------
847
+
848
+ def _packet_hurt_animation(self, params: dict[str, Any]) -> None:
849
+ e = self._entity_or_self(_entity_id(params, "entityId"))
850
+ if e is not None:
851
+ e.set_rotation(e.yaw, e.pitch, head_yaw=params.get("yaw"))
852
+ self.emit("entity_hurt", e, params)
853
+ self.emit("entity_hurt_animation", params)
854
+
855
+ def _packet_damage_event(self, params: dict[str, Any]) -> None:
856
+ e = self._entity_or_self(_entity_id(params, "entityId"))
857
+ self.emit("entity_hurt", e, params)
858
+ self.emit("entity_damaged", e, params)
859
+ self.emit("damage_event", params)
860
+
861
+ def _packet_death_combat_event(self, params: dict[str, Any]) -> None:
862
+ e = self._entity_or_self(_entity_id(params, "playerId"))
863
+ if e is not None:
864
+ e.health = 0.0
865
+ text = component_to_text(nbt_to_python(params.get("message")))
866
+ if e is not None and e.id == self.entity_id:
867
+ self.emit("death", text)
868
+ self.emit("entity_dead", e, text)
869
+ self.emit("death_combat_event", params)
870
+
871
+ def _packet_enter_combat_event(self, params: dict[str, Any]) -> None:
872
+ self.emit("enter_combat")
873
+
874
+ def _packet_end_combat_event(self, params: dict[str, Any]) -> None:
875
+ self.emit("end_combat", params.get("duration"))
876
+
877
+ def _packet_animation(self, params: dict[str, Any]) -> None:
878
+ e = self._entity_or_self(_entity_id(params, "entityId"))
879
+ if e is not None:
880
+ self.emit("entity_swing_arm", e)
881
+ self.emit("animation", params)
882
+
883
+ # -- item pickup ---------------------------------------------------------------
884
+
885
+ def _packet_collect(self, params: dict[str, Any]) -> None:
886
+ collected = self._entity_or_self(_entity_id(params, "collectedEntityId"))
887
+ collector = self._entity_or_self(_entity_id(params, "collectorEntityId"))
888
+ count = int(params.get("pickupItemCount", 1))
889
+ self.emit("player_collect", collector, collected, count)
890
+ self.emit("item_collected", collected, collector, count)
891
+ if collected is not None:
892
+ self.entities.destroy([collected.id])
893
+ self.emit("entity_destroy", collected)
894
+
895
+ # -- block actions ---------------------------------------------------------------
896
+
897
+ def _packet_block_action(self, params: dict[str, Any]) -> None:
898
+ pos = _pos_from_bitfield(params.get("location"))
899
+ block = self.world.block_at(pos) if pos is not None else None
900
+ name = (block.name if block is not None else "") or ""
901
+ byte1 = int(params.get("byte1", 0))
902
+ byte2 = int(params.get("byte2", 0))
903
+ if "piston" in name:
904
+ self.emit("piston_move", block, byte1 == 0, byte2)
905
+ elif "note_block" in name:
906
+ self.emit("note_heard", block, byte1, byte2)
907
+ elif any(k in name for k in (
908
+ "chest", "barrel", "shulker", "furnace", "hopper",
909
+ "dispenser", "dropper", "brewing", "enchanting", "anvil",
910
+ "trapped_chest", "ender_chest",
911
+ )):
912
+ self.emit("chest_lid_move", block, bool(byte1), byte2)
913
+ self.emit("block_action", block, params)
914
+
915
+ def _packet_block_break_animation(self, params: dict[str, Any]) -> None:
916
+ pos = _pos_from_bitfield(params.get("location"))
917
+ block = self.world.block_at(pos) if pos is not None else None
918
+ stage = int(params.get("destroyStage", 0))
919
+ if stage < 0:
920
+ self.emit("block_break_progress_end", block, params.get("entityId"))
921
+ else:
922
+ self.emit(
923
+ "block_break_progress_observed",
924
+ block, stage, params.get("entityId"),
925
+ )
926
+
927
+ # -- vehicles -------------------------------------------------------------------
928
+
929
+ def _entity_or_self(self, entity_id: int):
930
+ """Look up an entity, falling back to the bot's own entity."""
931
+ e = self.entities.get(entity_id)
932
+ if e is None and entity_id == self.entity_id:
933
+ return self.entity
934
+ return e
935
+
936
+ def _packet_attach_entity(self, params: dict[str, Any]) -> None:
937
+ eid = _entity_id(params, "entityId")
938
+ e = self._entity_or_self(eid)
939
+ vehicle_id = int(params.get("vehicleId", -1))
940
+ if e is not None:
941
+ vehicle = self.entities.get(vehicle_id) if vehicle_id >= 0 else None
942
+ e.vehicle = vehicle
943
+ if eid == self.entity_id:
944
+ self.player.vehicle = vehicle
945
+ if vehicle is None:
946
+ self.emit("dismount", None)
947
+ else:
948
+ self.emit("mount", vehicle)
949
+ self.emit("entity_attach", e, vehicle_id)
950
+ self.emit("attach_entity", params)
951
+
952
+ def _packet_set_passengers(self, params: dict[str, Any]) -> None:
953
+ e = self._entity_or_self(_entity_id(params, "entityId"))
954
+ passengers = [
955
+ self._entity_or_self(pid)
956
+ for pid in params.get("passengers", [])
957
+ ]
958
+ if e is not None:
959
+ e.passengers = [p for p in passengers if p is not None]
960
+ self.emit("entity_passengers", e, passengers)
961
+
962
+ # -- titles ---------------------------------------------------------------------
963
+
964
+ def _packet_set_title_text(self, params: dict[str, Any]) -> None:
965
+ text = component_to_text(nbt_to_python(params.get("text")))
966
+ self._title_state["text"] = text
967
+ self.emit("title", text, "title")
968
+
969
+ def _packet_set_title_subtitle(self, params: dict[str, Any]) -> None:
970
+ text = component_to_text(nbt_to_python(params.get("text")))
971
+ self._title_state["subtitle"] = text
972
+ self.emit("title", text, "subtitle")
973
+
974
+ def _packet_set_title_time(self, params: dict[str, Any]) -> None:
975
+ times = (
976
+ int(params.get("fadeIn", 0)),
977
+ int(params.get("stay", 0)),
978
+ int(params.get("fadeOut", 0)),
979
+ )
980
+ self._title_state.update(
981
+ {"fadeIn": times[0], "stay": times[1], "fadeOut": times[2]}
982
+ )
983
+ self.emit("title_times", *times)
984
+
985
+ def _packet_clear_titles(self, params: dict[str, Any]) -> None:
986
+ self._title_state.clear()
987
+ self.emit("title_clear", bool(params.get("reset", True)))
988
+
989
+ # -- particles / sounds -----------------------------------------------------------
990
+
991
+ def _packet_world_particles(self, params: dict[str, Any]) -> None:
992
+ particle_obj = params.get("particle")
993
+ particle_id = (
994
+ particle_obj.get("type") or particle_obj.get("id")
995
+ if isinstance(particle_obj, dict) else particle_obj
996
+ )
997
+ particle = Particle(
998
+ particle_id=particle_id,
999
+ name=_sound_name(particle_id),
1000
+ position=Vec3(
1001
+ float(params.get("x", 0)),
1002
+ float(params.get("y", 0)),
1003
+ float(params.get("z", 0)),
1004
+ ),
1005
+ offset=Vec3(
1006
+ float(params.get("offsetX", 0)),
1007
+ float(params.get("offsetY", 0)),
1008
+ float(params.get("offsetZ", 0)),
1009
+ ),
1010
+ max_speed=float(params.get("velocityOffset", 0) or 0),
1011
+ count=int(params.get("amount", 0) or 0),
1012
+ long_distance_render=bool(params.get("longDistance", False)),
1013
+ always_show=bool(params.get("alwaysShow", False)),
1014
+ data=particle_obj.get("data") if isinstance(particle_obj, dict) else None,
1015
+ )
1016
+ self.emit("particle", particle)
1017
+ self.emit("world_particles", params)
1018
+
1019
+ def _packet_sound_effect(self, params: dict[str, Any]) -> None:
1020
+ name = _sound_name(params.get("sound"))
1021
+ pos = Vec3(
1022
+ int(params.get("x", 0)) / 8.0,
1023
+ int(params.get("y", 0)) / 8.0,
1024
+ int(params.get("z", 0)) / 8.0,
1025
+ )
1026
+ self.emit(
1027
+ "sound_effect_heard", name, pos,
1028
+ float(params.get("volume", 1.0)), float(params.get("pitch", 1.0)),
1029
+ )
1030
+ self.emit("sound_effect", params)
1031
+
1032
+ def _packet_entity_sound_effect(self, params: dict[str, Any]) -> None:
1033
+ name = _sound_name(params.get("sound"))
1034
+ e = self._entity_or_self(_entity_id(params, "entityId"))
1035
+ self.emit(
1036
+ "entity_sound_effect_heard", name, e,
1037
+ float(params.get("volume", 1.0)), float(params.get("pitch", 1.0)),
1038
+ )
1039
+ self.emit("entity_sound_effect", params)
1040
+
1041
+ def _packet_entity_effect(self, params: dict[str, Any]) -> None:
1042
+ e = self._entity_or_self(_entity_id(params, "entityId"))
1043
+ effect = {
1044
+ "id": params.get("effectId"),
1045
+ "amplifier": params.get("amplifier"),
1046
+ "duration": params.get("duration"),
1047
+ "flags": params.get("flags"),
1048
+ }
1049
+ if e is not None:
1050
+ e.effects[effect["id"]] = effect
1051
+ self.emit("entity_effect", e, effect)
1052
+
1053
+ def _packet_remove_entity_effect(self, params: dict[str, Any]) -> None:
1054
+ e = self._entity_or_self(_entity_id(params, "entityId"))
1055
+ eid = params.get("effectId")
1056
+ if e is not None:
1057
+ e.effects.pop(eid, None)
1058
+ self.emit("entity_effect_end", e, eid)
1059
+ self.emit("remove_entity_effect", params)
1060
+
1061
+ # -- scoreboard / teams / boss bars ------------------------------------------------
1062
+
1063
+ def _packet_boss_bar(self, params: dict[str, Any]) -> None:
1064
+ uuid = params.get("entityUUID")
1065
+ action = int(params.get("action", 0))
1066
+ bar = self.boss_bars.get(str(uuid))
1067
+ if action == 0: # add
1068
+ bar = BossBar(uuid=uuid or "")
1069
+ self.boss_bars[str(uuid)] = bar
1070
+ self._apply_boss_bar(bar, params)
1071
+ self.emit("boss_bar_created", bar)
1072
+ elif action == 1: # remove
1073
+ bar = self.boss_bars.pop(str(uuid), None)
1074
+ if bar is not None:
1075
+ self.emit("boss_bar_deleted", bar)
1076
+ elif bar is not None:
1077
+ self._apply_boss_bar(bar, params)
1078
+ self.emit("boss_bar_updated", bar)
1079
+
1080
+ def _apply_boss_bar(self, bar: BossBar, params: dict[str, Any]) -> None:
1081
+ # protolib materializes absent switch fields as None.
1082
+ title = params.get("title")
1083
+ if title is not None:
1084
+ bar.title = _component_text(title)
1085
+ health = params.get("health")
1086
+ if health is not None:
1087
+ bar.health = float(health)
1088
+ color = params.get("color")
1089
+ if color is not None:
1090
+ bar.color = color
1091
+ dividers = params.get("dividers")
1092
+ if dividers is not None:
1093
+ bar.division = int(dividers)
1094
+ flags_raw = params.get("flags")
1095
+ if flags_raw is not None:
1096
+ flags = int(flags_raw)
1097
+ bar.flags = flags
1098
+ bar.darkened_sky = bool(flags & 0x01)
1099
+ bar.dragon_bar = bool(flags & 0x02)
1100
+ bar.create_fog = bool(flags & 0x04)
1101
+
1102
+ def _packet_teams(self, params: dict[str, Any]) -> None:
1103
+ name = params.get("team", "")
1104
+ mode = params.get("mode")
1105
+ mode_name = mode if isinstance(mode, str) else str(mode)
1106
+ if mode_name == "add":
1107
+ team = Team(name=name)
1108
+ self._apply_team_fields(team, params)
1109
+ self.teams[name] = team
1110
+ self.emit("team_created", team)
1111
+ elif mode_name == "remove":
1112
+ team = self.teams.pop(name, None)
1113
+ if team is not None:
1114
+ self.emit("team_removed", team)
1115
+ elif mode_name == "change":
1116
+ team = self.teams.get(name)
1117
+ if team is not None:
1118
+ self._apply_team_fields(team, params)
1119
+ self.emit("team_updated", team)
1120
+ elif mode_name in ("join", "leave"):
1121
+ team = self.teams.get(name)
1122
+ if team is None:
1123
+ return
1124
+ for pname in params.get("players", []) or []:
1125
+ if mode_name == "join":
1126
+ team.members.add(pname)
1127
+ self.emit("team_member_added", team, pname)
1128
+ else:
1129
+ team.members.discard(pname)
1130
+ self.emit("team_member_removed", team, pname)
1131
+
1132
+ def _apply_team_fields(self, team: Team, params: dict[str, Any]) -> None:
1133
+ team.display_name = _component_text(params.get("name")) or team.name
1134
+ flags = params.get("flags")
1135
+ if isinstance(flags, dict):
1136
+ team.friendly_fire = int(bool(flags.get("friendly_fire")))
1137
+ elif flags is not None:
1138
+ team.friendly_fire = int(flags)
1139
+ if params.get("nameTagVisibility") is not None:
1140
+ team.name_tag_visibility = params.get("nameTagVisibility")
1141
+ if params.get("formatting") is not None:
1142
+ team.color = params.get("formatting")
1143
+ if params.get("collisionRule") is not None:
1144
+ team.collision_rule = params.get("collisionRule")
1145
+ team.prefix = _component_text(params.get("prefix"))
1146
+ team.suffix = _component_text(params.get("suffix"))
1147
+
1148
+ @property
1149
+ def team_map(self) -> dict[str, Team]:
1150
+ """Teams keyed by team name."""
1151
+ return dict(self.teams)
1152
+
1153
+ def _packet_scoreboard_objective(self, params: dict[str, Any]) -> None:
1154
+ name = params.get("name", "")
1155
+ action = int(params.get("action", 0))
1156
+ if action == 1: # remove
1157
+ board = self.scoreboards.pop(name, None)
1158
+ if board is not None:
1159
+ self.emit("scoreboard_deleted", board)
1160
+ return
1161
+ board = self.scoreboards.get(name)
1162
+ if board is None:
1163
+ board = ScoreBoard(name=name)
1164
+ self.scoreboards[name] = board
1165
+ self.emit("scoreboard_created", board)
1166
+ if params.get("displayText") is not None:
1167
+ board.title = _component_text(params.get("displayText"))
1168
+ if params.get("type") is not None:
1169
+ board.type = params.get("type")
1170
+ self.emit("scoreboard_title_changed", board)
1171
+
1172
+ def _packet_scoreboard_display_objective(self, params: dict[str, Any]) -> None:
1173
+ position = int(params.get("position", 0))
1174
+ name = params.get("name", "")
1175
+ self._scoreboard_slots[position] = name
1176
+ board = self.scoreboards.get(name)
1177
+ self.emit("scoreboard_position", position, board or name)
1178
+
1179
+ def _packet_scoreboard_score(self, params: dict[str, Any]) -> None:
1180
+ score_name = params.get("scoreName", "")
1181
+ board = self.scoreboards.get(score_name)
1182
+ if board is None:
1183
+ return
1184
+ item = board.update(params)
1185
+ self.emit("score_updated", board, item)
1186
+
1187
+ def _packet_reset_score(self, params: dict[str, Any]) -> None:
1188
+ entity_name = params.get("entity_name", "")
1189
+ objective = params.get("objective_name")
1190
+ if objective is None:
1191
+ for board in self.scoreboards.values():
1192
+ for key in [k for k, v in board.items_map.items()
1193
+ if v.name == entity_name]:
1194
+ board.items_map.pop(key, None)
1195
+ else:
1196
+ board = self.scoreboards.get(objective)
1197
+ if board is not None:
1198
+ for key in [k for k, v in board.items_map.items()
1199
+ if v.name == entity_name]:
1200
+ board.items_map.pop(key, None)
1201
+ self.emit("score_removed", entity_name, objective)
1202
+
1203
+ @property
1204
+ def scoreboard(self):
1205
+ """The sidebar scoreboard (position 1) when present."""
1206
+ name = self._scoreboard_slots.get(1)
1207
+ return self.scoreboards.get(name) if name else None
1208
+
1209
+ # -- misc packets -----------------------------------------------------------------
1210
+
1211
+ def _packet_update_view_distance(self, params: dict[str, Any]) -> None:
1212
+ vd = params.get("viewDistance")
1213
+ if vd is not None:
1214
+ self.settings.view_distance = int(vd)
1215
+ self._game.view_distance = int(vd)
1216
+ self.emit("update_view_distance", params)
1217
+
1218
+ def _packet_set_cursor_item(self, params: dict[str, Any]) -> None:
1219
+ item = Item.from_slot(params.get("contents", {}))
1220
+ if item is not None and item.item_id is not None and item.name is None:
1221
+ item.name = self.world.gamedata.item_name(item.item_id)
1222
+ self.cursor_item = item
1223
+ self.emit("cursor_item", item)
1224
+
1225
+ def _packet_tags(self, params: dict[str, Any]) -> None:
1226
+ self.emit("tags", params)
1227
+
1228
+ def _packet_open_book(self, params: dict[str, Any]) -> None:
1229
+ self.emit("open_book", params)
1230
+
1231
+ def _packet_map(self, params: dict[str, Any]) -> None:
1232
+ self.emit("map", params)
1233
+
1234
+ def _packet_chat_suggestions(self, params: dict[str, Any]) -> None:
1235
+ self.emit("chat_suggestions", params)
1236
+
1237
+ # -- lookups ---------------------------------------------------------------------
1238
+
1239
+ def _player_name(self, uuid_str: str | None) -> str | None:
1240
+ if not uuid_str:
1241
+ return None
1242
+ p = self.entities.players.get(uuid_str)
1243
+ return p.name if p else None
1244
+
1245
+ def nearest_entity(self, predicate=None, max_distance: float | None = None):
1246
+ if self.entity is None:
1247
+ return None
1248
+ return self.entities.nearest(self.entity.position, predicate, max_distance)
1249
+
1250
+ def entity_at(self, position) -> Any:
1251
+ """Entity whose collision box contains *position*.
1252
+
1253
+ When several entities overlap, the nearest to the point wins;
1254
+ returns ``None`` if no entity contains the position.
1255
+ """
1256
+ point = position if isinstance(position, Vec3) else Vec3(*position)
1257
+ best = None
1258
+ best_d = float("inf")
1259
+ for e in self.entities.all():
1260
+ if not e.contains_point(point):
1261
+ continue
1262
+ d = point.distance_squared_to(e.position)
1263
+ if d < best_d:
1264
+ best_d = d
1265
+ best = e
1266
+ return best
1267
+
1268
+ def find_entity(self, predicate) -> Any:
1269
+ for e in self.entities.all():
1270
+ if predicate(e):
1271
+ return e
1272
+ return None
1273
+
1274
+ # -- world lookups -----------------------------------------------------------------
1275
+
1276
+ def block_at(self, position):
1277
+ return self.world.block_at(position)
1278
+
1279
+ def find_block(self, names, **kwargs):
1280
+ return self.world.find_block(names, **kwargs)
1281
+
1282
+ def find_blocks(self, names, **kwargs):
1283
+ return self.world.find_blocks(names, **kwargs)
1284
+
1285
+ def can_dig_block(self, block) -> bool:
1286
+ return self.world.can_dig_block(block)
1287
+
1288
+ # -- cursor / line of sight ------------------------------------------------------
1289
+
1290
+ def _eye_position(self) -> Vec3 | None:
1291
+ entity = self.entity
1292
+ if entity is None:
1293
+ return None
1294
+ return entity.position + Vec3(0.0, entity.eye_height, 0.0)
1295
+
1296
+ def _look_direction(self) -> Vec3 | None:
1297
+ entity = self.entity
1298
+ if entity is None:
1299
+ return None
1300
+ x, y, z = yaw_pitch_to_direction(entity.yaw, entity.pitch)
1301
+ return Vec3(x, y, z)
1302
+
1303
+ def block_at_cursor(self, max_distance: float = 5.0):
1304
+ """Block the bot is looking at within *max_distance* blocks.
1305
+
1306
+ Returns the :class:`~leafish.world.block.Block` or ``None``.
1307
+ """
1308
+ eye = self._eye_position()
1309
+ direction = self._look_direction()
1310
+ if eye is None or direction is None:
1311
+ return None
1312
+ result = self.world.raycast(eye, direction, max_distance)
1313
+ return result[0] if result else None
1314
+
1315
+ def entity_at_cursor(self, max_distance: float = 5.0):
1316
+ """Nearest entity whose collision box the view ray intersects.
1317
+
1318
+ Approximation: entity boxes only (blocks do not occlude the
1319
+ result). Returns ``None`` when nothing is under the crosshair.
1320
+ """
1321
+ eye = self._eye_position()
1322
+ direction = self._look_direction()
1323
+ if eye is None or direction is None:
1324
+ return None
1325
+ best = None
1326
+ best_t = max_distance
1327
+ for e in self.entities.all():
1328
+ if e is self.entity:
1329
+ continue
1330
+ t = ray_box_distance(eye, direction, e.bounding_box())
1331
+ if t is not None and t <= best_t:
1332
+ best_t = t
1333
+ best = e
1334
+ return best
1335
+
1336
+ def can_see_block(self, block_or_pos, max_distance: float | None = None) -> bool:
1337
+ """Whether *block_or_pos* has line of sight from the bot's eyes.
1338
+
1339
+ *max_distance* additionally caps the allowed distance.
1340
+ """
1341
+ eye = self._eye_position()
1342
+ if eye is None:
1343
+ return False
1344
+ target = self.world._to_block_pos(block_or_pos)
1345
+ center = Vec3(target.x + 0.5, target.y + 0.5, target.z + 0.5)
1346
+ offset = center - eye
1347
+ dist = offset.length
1348
+ if dist < 1e-6:
1349
+ return True
1350
+ if max_distance is not None and dist > max_distance:
1351
+ return False
1352
+ result = self.world.raycast(eye, offset, dist + 0.6)
1353
+ if result is None:
1354
+ return True
1355
+ hit_block, _hit = result
1356
+ if hit_block.position == target:
1357
+ return True
1358
+ # A nearer solid block occludes; a farther one does not.
1359
+ hit_center = Vec3(
1360
+ hit_block.position.x + 0.5,
1361
+ hit_block.position.y + 0.5,
1362
+ hit_block.position.z + 0.5,
1363
+ )
1364
+ return eye.distance_to(hit_center) > dist
1365
+
1366
+ def can_see_entity(self, entity,
1367
+ max_distance: float | None = None) -> bool:
1368
+ """Whether *entity* has line of sight from the bot's eyes."""
1369
+ eye = self._eye_position()
1370
+ if eye is None or entity is None:
1371
+ return False
1372
+ center = entity.position + Vec3(0.0, entity.height / 2.0, 0.0)
1373
+ offset = center - eye
1374
+ dist = offset.length
1375
+ if dist < 1e-6:
1376
+ return True
1377
+ if max_distance is not None and dist > max_distance:
1378
+ return False
1379
+ result = self.world.raycast(eye, offset, dist + 0.6)
1380
+ if result is None:
1381
+ return True
1382
+ hit_block, _hit = result
1383
+ hit_center = Vec3(
1384
+ hit_block.position.x + 0.5,
1385
+ hit_block.position.y + 0.5,
1386
+ hit_block.position.z + 0.5,
1387
+ )
1388
+ return eye.distance_to(hit_center) > dist
1389
+
1390
+ # -- chat -------------------------------------------------------------------------
1391
+
1392
+ async def chat(self, message: str) -> None:
1393
+ await self.chat_module.chat(message)
1394
+
1395
+ async def command(self, command: str) -> None:
1396
+ await self.chat_module.command(command)
1397
+
1398
+ async def chat_command(self, command: str) -> None:
1399
+ """Alias for :meth:`command`."""
1400
+ await self.command(command)
1401
+
1402
+ # -- movement -----------------------------------------------------------------------
1403
+
1404
+ async def set_control_state(self, control: str, value: bool) -> None:
1405
+ await self.movement.set_control_state(control, value)
1406
+
1407
+ async def look(self, yaw: float, pitch: float) -> None:
1408
+ await self.movement.look(yaw, pitch)
1409
+
1410
+ async def look_at(self, target) -> None:
1411
+ await self.movement.look_at(target)
1412
+
1413
+ async def move_to(self, target, timeout: float | None = None) -> None:
1414
+ await self.movement.move_to(target, timeout)
1415
+
1416
+ # -- pathfinding -----------------------------------------------------------------
1417
+
1418
+ def find_path(self, start, goal, **kwargs):
1419
+ return self.pathfinder.find_path(start, goal, **kwargs)
1420
+
1421
+ async def goto(self, goal, timeout: float | None = None) -> bool:
1422
+ return await self.pathfinder.goto(goal, timeout=timeout)
1423
+
1424
+ async def stop_moving(self) -> None:
1425
+ await self.movement.stop_moving()
1426
+
1427
+ # -- plugins ------------------------------------------------------------------
1428
+
1429
+ def load_plugin(self, plugin, name: str | None = None) -> str:
1430
+ """Load a plugin (callable ``fn(bot)`` or object with inject/unload)."""
1431
+ return self.plugins.load(plugin, name)
1432
+
1433
+ def unload_plugin(self, name: str) -> bool:
1434
+ return self.plugins.unload(name)
1435
+
1436
+ # -- inventory ------------------------------------------------------------------------
1437
+
1438
+ @property
1439
+ def held_item(self):
1440
+ return self.inventory.held_item
1441
+
1442
+ async def set_quick_bar_slot(self, slot: int) -> None:
1443
+ await self.inventory.set_held_slot(slot)
1444
+
1445
+ async def craft(self, item_name: str, count: int = 1,
1446
+ crafting_table: bool = False) -> int:
1447
+ """Craft *count* of *item_name*; returns items actually crafted."""
1448
+ return await self.crafting.craft(item_name, count, crafting_table)
1449
+
1450
+ def recipes_for(self, item_name: str):
1451
+ """All recipe variants producing *item_name*."""
1452
+ return self.crafting.recipes_for(item_name)
1453
+
1454
+ def craftable_recipes(self):
1455
+ """Recipes the bot can currently craft from its inventory."""
1456
+ return self.crafting.craftable_recipes()
1457
+
1458
+ def missing_ingredients(self, recipe):
1459
+ """Ingredients still required for *recipe* (name -> count)."""
1460
+ return self.crafting.missing_ingredients(recipe)
1461
+
1462
+ async def fish(self, timeout: float = 60.0, **opts) -> bool:
1463
+ """Cast the fishing rod and catch one fish."""
1464
+ return await self.fishing.fish(timeout, **opts)
1465
+
1466
+ async def collect(self, max_distance: float = 8.0, count: int | None = None,
1467
+ **kwargs) -> int:
1468
+ """Pick up nearby dropped-item entities; returns count collected."""
1469
+ return await self.collector.collect(max_distance, count, **kwargs)
1470
+
1471
+ async def harvest(self, names=None, max_distance: int = 32) -> int:
1472
+ """Dig mature crops in range; returns blocks harvested."""
1473
+ return await self.farming.harvest(names, max_distance)
1474
+
1475
+ async def plant(self, seed_name: str | None = None,
1476
+ max_distance: int = 16) -> int:
1477
+ """Plant seeds on empty farmland in range."""
1478
+ return await self.farming.plant(seed_name, max_distance)
1479
+
1480
+ async def tend_farm(self, names=None, max_distance: int = 32) -> dict:
1481
+ """Harvest mature crops and replant with available seeds."""
1482
+ return await self.farming.tend(names, max_distance)
1483
+
1484
+ # -- containers -----------------------------------------------------------------
1485
+
1486
+ async def click_window(self, window_id: int, slot: int, button: int = 0,
1487
+ mode: int = 0) -> None:
1488
+ """Send a window_click on any open window."""
1489
+ await self.containers.click(window_id, slot, button, mode)
1490
+
1491
+ async def shift_click(self, window_id: int, slot: int) -> None:
1492
+ """Shift-click (quick-move) a slot in an open window."""
1493
+ await self.containers.shift_click(window_id, slot)
1494
+
1495
+ async def close_window(self, window_id: int | None = None) -> None:
1496
+ """Close an open window (defaults to the current one)."""
1497
+ await self.containers.close(window_id)
1498
+
1499
+ async def deposit_all(self, window_id: int,
1500
+ name: str | None = None) -> int:
1501
+ """Shift-click player-inventory items into an open container."""
1502
+ return await self.containers.deposit_all(window_id, name)
1503
+
1504
+ async def withdraw(self, window_id: int, name: str,
1505
+ count: int | None = None) -> int:
1506
+ """Shift-click items out of a container into the player inventory."""
1507
+ return await self.containers.withdraw(window_id, name, count)
1508
+
1509
+ async def repair(self, item_name: str, material_name: str | None = None,
1510
+ window_id: int | None = None) -> int:
1511
+ """Repair/rename via an anvil window; returns items taken."""
1512
+ return await self.anvil.repair(item_name, material_name, window_id)
1513
+
1514
+ async def smelt(self, item_name: str, count: int = 1, *,
1515
+ fuel: str | None = None, block=None,
1516
+ window_id: int | None = None,
1517
+ timeout: float = 120.0) -> int:
1518
+ """Smelt *count* of *item_name* in a furnace window.
1519
+
1520
+ Returns the number of output items collected. Pass *block* to
1521
+ open a furnace first, or have one open already.
1522
+ """
1523
+ return await self.smelting.smelt(
1524
+ item_name, count, fuel=fuel, block=block,
1525
+ window_id=window_id, timeout=timeout)
1526
+
1527
+ async def interact_block(self, block, face=None) -> None:
1528
+ """Right-click a block (open containers, press buttons)."""
1529
+ await self.actions.interact_block(block, face)
1530
+
1531
+ async def open_container(self, block, timeout: float = 5.0) -> int | None:
1532
+ """Right-click *block* and wait for a container window to open.
1533
+
1534
+ Returns the new window id, or ``None`` if none opened in time.
1535
+ """
1536
+ return await self.containers.open_container(block, timeout)
1537
+
1538
+ async def open_window(self, block, timeout: float = 5.0):
1539
+ """Open *block*'s window and return a typed window view.
1540
+
1541
+ The concrete class depends on the container: ``FurnaceWindow``,
1542
+ ``EnchantmentTableWindow``, ``AnvilWindow``, ``VillagerWindow``
1543
+ or the generic ``Window``. Returns ``None`` on timeout.
1544
+ """
1545
+ return await self.containers.open_typed(block, timeout)
1546
+
1547
+ async def open_furnace(self, block, timeout: float = 5.0) -> FurnaceWindow | None:
1548
+ """Open a furnace/blast furnace/smoker at *block*."""
1549
+ win = await self.open_window(block, timeout)
1550
+ return win if isinstance(win, FurnaceWindow) else None
1551
+
1552
+ async def open_enchantment_table(
1553
+ self, block, timeout: float = 5.0) -> EnchantmentTableWindow | None:
1554
+ """Open an enchanting table at *block*."""
1555
+ win = await self.open_window(block, timeout)
1556
+ return win if isinstance(win, EnchantmentTableWindow) else None
1557
+
1558
+ async def open_anvil(self, block, timeout: float = 5.0) -> AnvilWindow | None:
1559
+ """Open an anvil at *block*."""
1560
+ win = await self.open_window(block, timeout)
1561
+ return win if isinstance(win, AnvilWindow) else None
1562
+
1563
+ async def open_villager(self, entity, timeout: float = 5.0):
1564
+ """Open a villager/trader *entity*'s trading window."""
1565
+ before = set(self.containers.windows)
1566
+ await self.actions.use_on(entity)
1567
+ deadline = time.monotonic() + timeout
1568
+ while time.monotonic() < deadline:
1569
+ new = [w for w in self.containers.windows if w not in before]
1570
+ if new:
1571
+ return self.containers.window_view(new[0])
1572
+ await asyncio.sleep(0.05)
1573
+ return None
1574
+
1575
+ @property
1576
+ def current_window(self):
1577
+ """Typed view of the currently open window, or ``None``."""
1578
+ if self.current_window_id is None:
1579
+ return None
1580
+ return self.containers.window_view(self.current_window_id)
1581
+
1582
+ # -- world actions ------------------------------------------------------------------
1583
+
1584
+ async def dig(self, block, force: bool = False):
1585
+ await self.actions.dig(block, force=force)
1586
+
1587
+ async def stop_digging(self):
1588
+ await self.actions.stop_digging()
1589
+
1590
+ async def place_block(self, block, face=None):
1591
+ await self.actions.place_block(block, face)
1592
+
1593
+ async def attack(self, entity):
1594
+ await self.actions.attack(entity)
1595
+
1596
+ async def equip(self, item, destination: str | None = None):
1597
+ await self.actions.equip(item, destination)
1598
+
1599
+ async def unequip(self, destination: str = "hand"):
1600
+ """Move the item in *destination* back into the inventory."""
1601
+ await self.inventory.unequip(destination)
1602
+
1603
+ # -- item use ------------------------------------------------------------------
1604
+
1605
+ async def use_item(self, hand: int = 0) -> None:
1606
+ """Send ``use_item`` with the held item (or empty hand)."""
1607
+ await self.actions.use_item(hand)
1608
+
1609
+ async def consume(self):
1610
+ """Eat/drink the held item."""
1611
+ await self.actions.consume()
1612
+
1613
+ async def activate_item(self, off_hand: bool = False) -> None:
1614
+ """Start using the held item (bow, food, ...)."""
1615
+ await self.actions.activate_item(off_hand=off_hand)
1616
+
1617
+ async def deactivate_item(self) -> None:
1618
+ """Stop using the held item."""
1619
+ await self.actions.deactivate_item()
1620
+
1621
+ # -- entity / block interaction ---------------------------------------------------
1622
+
1623
+ async def use_on(self, entity, point=None, hand: int = 0) -> None:
1624
+ """Right-click *entity* (mount, feed, trade, ...)."""
1625
+ await self.actions.use_on(entity, point=point, hand=hand)
1626
+
1627
+ async def activate_entity(self, entity, hand: int = 0) -> None:
1628
+ await self.actions.activate_entity(entity, hand=hand)
1629
+
1630
+ async def activate_entity_at(self, entity, position, hand: int = 0) -> None:
1631
+ await self.actions.activate_entity_at(entity, position, hand=hand)
1632
+
1633
+ async def activate_block(self, block, direction=None, cursor_pos=None) -> None:
1634
+ """Right-click a block with explicit face/cursor position."""
1635
+ await self.actions.activate_block(block, direction, cursor_pos)
1636
+
1637
+ async def place_entity(self, entity, face=None) -> None:
1638
+ """Place the held block against the block under *entity*."""
1639
+ await self.actions.place_entity(entity, face)
1640
+
1641
+ # -- player state ------------------------------------------------------------------
1642
+
1643
+ async def respawn(self) -> None:
1644
+ """Request respawn (after death or dimension change)."""
1645
+ await self.player.respawn()
1646
+
1647
+ async def sleep(self, bed_block) -> None:
1648
+ """Sleep in *bed_block*."""
1649
+ await self.player.sleep(bed_block)
1650
+
1651
+ async def wake(self) -> None:
1652
+ """Wake up from sleep."""
1653
+ await self.player.wake()
1654
+
1655
+ @property
1656
+ def is_sleeping(self) -> bool:
1657
+ """Whether the bot believes it is sleeping."""
1658
+ return self.player.is_abed
1659
+
1660
+ async def is_abed(self, bed_block=None) -> bool:
1661
+ """Whether the bot is currently sleeping.
1662
+
1663
+ When *bed_block* is given, also verifies the bot is near that bed.
1664
+ """
1665
+ if not self.player.is_abed:
1666
+ return False
1667
+ if bed_block is None:
1668
+ return True
1669
+ pos = getattr(bed_block, "position", bed_block)
1670
+ entity = self.entity
1671
+ if entity is None or pos is None:
1672
+ return False
1673
+ p = pos if isinstance(pos, Vec3) else Vec3(*pos)
1674
+ return entity.position.distance_to(p) < 4.0
1675
+
1676
+ async def elytra_fly(self) -> None:
1677
+ """Deploy elytra (requires elytra equipped and airborne)."""
1678
+ await self.player.elytra_fly()
1679
+
1680
+ async def mount(self, entity) -> None:
1681
+ """Mount *entity* (boat, minecart, horse, ...)."""
1682
+ await self.player.mount(entity)
1683
+
1684
+ async def dismount(self) -> None:
1685
+ """Dismount the current vehicle."""
1686
+ await self.player.dismount()
1687
+
1688
+ async def move_vehicle(self, left: float = 0.0, forward: float = 0.0) -> None:
1689
+ """Steer the mounted vehicle."""
1690
+ await self.player.move_vehicle(left, forward)
1691
+
1692
+ # -- inventory helpers ---------------------------------------------------------------
1693
+
1694
+ async def toss(self, item, count: int | None = None) -> None:
1695
+ """Drop *count* items (or the whole stack) from *item*'s slot."""
1696
+ await self.inventory.toss(item, count)
1697
+
1698
+ async def toss_stack(self, item) -> None:
1699
+ """Drop the entire stack held by *item*'s slot."""
1700
+ await self.inventory.toss_stack(item)
1701
+
1702
+ async def move_slot_item(self, source_slot: int, dest_slot: int) -> None:
1703
+ await self.inventory.move_slot_item(source_slot, dest_slot)
1704
+
1705
+ async def put_away(self, slot: int) -> None:
1706
+ await self.inventory.put_away(slot)
1707
+
1708
+ async def transfer(self, options: dict | None = None) -> None:
1709
+ await self.inventory.transfer(options)
1710
+
1711
+ async def put_selected_item_range(self, start: int, end: int,
1712
+ window_id: int | None = None,
1713
+ slot: int | None = None) -> None:
1714
+ await self.inventory.put_selected_item_range(
1715
+ start, end, window_id=window_id, slot=slot
1716
+ )
1717
+
1718
+ # -- digging / item info ---------------------------------------------------------------
1719
+
1720
+ def dig_time(self, block_or_pos) -> float:
1721
+ """Estimated digging time in seconds for a block/position."""
1722
+ return self.actions.dig_time(block_or_pos)
1723
+
1724
+ # -- client helpers ---------------------------------------------------------------------
1725
+
1726
+ async def tab_complete(self, text: str, assume_command: bool = False,
1727
+ timeout: float = 5.0) -> list[str]:
1728
+ """Request chat/command tab-completion; returns matches."""
1729
+ return await self.client.tab_complete(
1730
+ text, assume_command=assume_command, timeout=timeout
1731
+ )
1732
+
1733
+ async def accept_resource_pack(self) -> None:
1734
+ await self.client.accept_resource_pack()
1735
+
1736
+ async def deny_resource_pack(self) -> None:
1737
+ await self.client.deny_resource_pack()
1738
+
1739
+ async def update_sign(self, block, text, back: bool = False,
1740
+ timeout: float = 5.0) -> bool:
1741
+ """Write text onto a sign block. Returns True on success."""
1742
+ return await self.client.update_sign(block, text, back=back,
1743
+ timeout=timeout)
1744
+
1745
+ async def write_book(self, hand: int, pages: list[str],
1746
+ title: str | None = None) -> None:
1747
+ """Write *pages* into the book held in *hand* (0 or 1)."""
1748
+ await self.client.write_book(hand, pages, title=title)
1749
+
1750
+ async def set_command_block(self, pos, command: str, *, mode: int = 0,
1751
+ flags: int = 0) -> None:
1752
+ """Update the command block at *pos*."""
1753
+ await self.client.set_command_block(pos, command, mode=mode, flags=flags)
1754
+
1755
+ async def update_held_item(self) -> None:
1756
+ """Re-send the current hotbar selection to the server."""
1757
+ await self.client.update_held_item()
1758
+
1759
+ def support_feature(self, name: str) -> bool:
1760
+ """Whether the server advertised feature flag *name*."""
1761
+ return self.client.support_feature(name)
1762
+
1763
+ def set_settings(self, options: dict) -> None:
1764
+ """Update client settings.
1765
+
1766
+ Recognized keys mirror Mineflayer's ``bot.settings``: ``chat``,
1767
+ ``colorsEnabled``, ``viewDistance``, ``difficulty``,
1768
+ ``skinParts``, ``enableTextFiltering``, ``enableServerListing``,
1769
+ ``particleStatus``, ``mainHand``. Values are stored locally; only
1770
+ settings the protocol can actually change are applied.
1771
+ """
1772
+ mapping = {
1773
+ "chat": "chat_colors",
1774
+ "colorsEnabled": "chat_colors",
1775
+ "viewDistance": "view_distance",
1776
+ "difficulty": "difficulty",
1777
+ "skinParts": "skin_parts",
1778
+ "enableTextFiltering": "enable_text_filtering",
1779
+ "enableServerListing": "enable_server_listing",
1780
+ "particleStatus": "particle_status",
1781
+ "mainHand": "main_hand",
1782
+ }
1783
+ for key, value in options.items():
1784
+ attr = mapping.get(key)
1785
+ if attr is None:
1786
+ continue
1787
+ setattr(self.settings, attr, value)
1788
+ if attr == "view_distance":
1789
+ self.config.view_distance = int(value)
1790
+
1791
+ def has_plugin(self, name: str) -> bool:
1792
+ """Whether a plugin named *name* is loaded."""
1793
+ return name in self.plugins.plugins
1794
+
1795
+ def load_plugins(self, plugins: dict) -> None:
1796
+ """Load several plugins from a ``{name: plugin}`` mapping."""
1797
+ for name, plugin in plugins.items():
1798
+ self.load_plugin(plugin, name=name)
1799
+
1800
+ def get_explosion_damages(self, entity=None, position=None,
1801
+ radius: float = 0.0,
1802
+ raw_damages: bool = False) -> dict:
1803
+ """Explosion damage exposure for *entity* (default: the bot)."""
1804
+ return self.client.get_explosion_damages(
1805
+ entity, position, radius, raw_damages
1806
+ )
1807
+
1808
+ # -- chat -------------------------------------------------------------------------
1809
+
1810
+ async def await_message(self, pattern=None, timeout: float = 30.0,
1811
+ chat_type: str = "chat"):
1812
+ """Wait for an incoming message; see :meth:`ChatModule.await_message`."""
1813
+ return await self.chat_module.await_message(
1814
+ pattern, timeout=timeout, chat_type=chat_type
1815
+ )
1816
+
1817
+ def add_chat_pattern(self, name: str, pattern, chat_type: str = "chat") -> None:
1818
+ self.chat_module.add_chat_pattern(name, pattern, chat_type)
1819
+
1820
+ def add_chat_pattern_set(self, name: str, patterns,
1821
+ chat_type: str = "chat") -> None:
1822
+ self.chat_module.add_chat_pattern_set(name, patterns, chat_type)
1823
+
1824
+ def remove_chat_pattern(self, name: str) -> None:
1825
+ self.chat_module.remove_chat_pattern(name)
1826
+
1827
+ # -- movement extras ------------------------------------------------------------------
1828
+
1829
+ def get_control_state(self, control: str) -> bool:
1830
+ return self.movement.get_control_state(control)
1831
+
1832
+ async def clear_control_states(self) -> None:
1833
+ await self.movement.clear_control_states()
1834
+
1835
+ async def wait_for_ticks(self, ticks: int) -> None:
1836
+ """Wait approximately *ticks* server ticks (20 ticks = 1s)."""
1837
+ await asyncio.sleep(ticks / 20.0)
1838
+
1839
+ async def wait_for_chunks_to_load(self, timeout: float = 10.0) -> bool:
1840
+ """Wait until the chunk containing the bot is loaded.
1841
+
1842
+ Returns ``True`` when loaded, ``False`` on timeout.
1843
+ """
1844
+ entity = self.entity
1845
+ if entity is None:
1846
+ return False
1847
+ cx = int(entity.position.x) >> 4
1848
+ cz = int(entity.position.z) >> 4
1849
+ loop = asyncio.get_running_loop()
1850
+ deadline = loop.time() + timeout
1851
+
1852
+ def loaded() -> bool:
1853
+ return self.world.chunk_at(cx, cz) is not None
1854
+
1855
+ while not loaded():
1856
+ if loop.time() >= deadline:
1857
+ return False
1858
+ fut = self.emitter.wait_for_nowait("chunk_column_load")
1859
+ with contextlib.suppress(TimeoutError):
1860
+ await asyncio.wait_for(
1861
+ fut, timeout=max(0.05, deadline - loop.time())
1862
+ )
1863
+ return True
1864
+
1865
+ async def swing_arm(self):
1866
+ await self._send_play("arm_animation", {"hand": 0})
1867
+
1868
+ # -- state properties ---------------------------------------------------------------
1869
+
1870
+ @property
1871
+ def health(self) -> float:
1872
+ """Current health (0-20)."""
1873
+ return self.vitals.health
1874
+
1875
+ @property
1876
+ def food(self) -> int:
1877
+ """Current food level (0-20)."""
1878
+ return self.vitals.food
1879
+
1880
+ @property
1881
+ def food_saturation(self) -> float:
1882
+ return self.vitals.food_saturation
1883
+
1884
+ @property
1885
+ def oxygen(self) -> int | None:
1886
+ """Alias for :attr:`oxygen_level`."""
1887
+ return self.oxygen_level
1888
+
1889
+ @property
1890
+ def oxygen_level(self) -> int | None:
1891
+ """Breath/air level; ``None`` — modern servers don't send it."""
1892
+ return None
1893
+
1894
+ @property
1895
+ def weather(self) -> WeatherInfo:
1896
+ """Current weather state (raining, thunder, levels)."""
1897
+ return self._weather
1898
+
1899
+ @property
1900
+ def experience(self) -> ExperienceInfo:
1901
+ """Experience level/progress/points."""
1902
+ return self._experience
1903
+
1904
+ @property
1905
+ def quick_bar_slot(self) -> int:
1906
+ """Currently selected hotbar slot (0-8)."""
1907
+ return self.inventory.held_slot
1908
+
1909
+ @property
1910
+ def spawn_point(self):
1911
+ """World spawn position (BlockPos) or ``None``."""
1912
+ return self.world.spawn_point
1913
+
1914
+ @property
1915
+ def game(self) -> GameInfo:
1916
+ """Server/game information (dimension, difficulty, game mode...)."""
1917
+ return self._game
1918
+
1919
+ @property
1920
+ def abilities(self) -> AbilitiesInfo:
1921
+ """Player abilities (flying, invulnerable, ...)."""
1922
+ return self._abilities
1923
+
1924
+ @property
1925
+ def time(self) -> TimeInfo:
1926
+ """World clock state."""
1927
+ return self._time
1928
+
1929
+ @property
1930
+ def is_raining(self) -> bool:
1931
+ return bool(self.world.weather.get("raining"))
1932
+
1933
+ @property
1934
+ def rain_state(self) -> float:
1935
+ return float(self.world.weather.get("rain_level", 0.0))
1936
+
1937
+ @property
1938
+ def thunder_state(self) -> float:
1939
+ return float(self.world.weather.get("thunder_level", 0.0))
1940
+
1941
+ @property
1942
+ def physics_enabled(self) -> bool:
1943
+ """Whether client-side physics simulation is running."""
1944
+ return self.physics.enabled
1945
+
1946
+ @physics_enabled.setter
1947
+ def physics_enabled(self, value: bool) -> None:
1948
+ self.physics.enabled = bool(value)
1949
+
1950
+ @property
1951
+ def target_dig_block(self):
1952
+ """The block currently being dug, or ``None``."""
1953
+ pos = self.actions._digging
1954
+ return self.world.block_at(pos) if pos is not None else None
1955
+
1956
+ @property
1957
+ def tablist(self) -> dict:
1958
+ """Player tab-list entries keyed by UUID."""
1959
+ return dict(self.entities.players)
1960
+
1961
+ @property
1962
+ def players(self) -> dict:
1963
+ """All tracked player entities keyed by UUID."""
1964
+ return dict(self.entities.players)
1965
+
1966
+
1967
+ # ---------------------------------------------------------------------------
1968
+ # Factory
1969
+ # ---------------------------------------------------------------------------
1970
+
1971
+
1972
+ class Leafish:
1973
+ """Entry point for creating bots."""
1974
+
1975
+ @staticmethod
1976
+ async def create_bot(
1977
+ host: str = "localhost",
1978
+ port: int = 25565,
1979
+ username: str | None = None,
1980
+ auth: str = "offline",
1981
+ version: str = "latest",
1982
+ **kwargs,
1983
+ ) -> LeafishBot:
1984
+ """Create and connect a bot.
1985
+
1986
+ Args:
1987
+ host: Server hostname or IP.
1988
+ port: Server port (default 25565).
1989
+ username: Minecraft username (required for offline auth; for
1990
+ Microsoft auth the profile name is used).
1991
+ auth: ``"offline"`` or ``"microsoft"``.
1992
+ version: Minecraft version string or ``"latest"``.
1993
+ """
1994
+ plugins = kwargs.pop("plugins", None) or {}
1995
+ config = BotConfig(host=host, port=port, version=version, **{
1996
+ k: v for k, v in kwargs.items() if k in BotConfig.__dataclass_fields__
1997
+ })
1998
+ if username is not None and not config.username:
1999
+ config.username = username
2000
+
2001
+ codec = ProtocolCodec.for_version(version)
2002
+
2003
+ if config.auth == "offline":
2004
+ name = username or config.username
2005
+ provider = OfflineAuth()
2006
+ auth_session = await provider.authenticate(name)
2007
+ elif config.auth == "microsoft":
2008
+ provider = MicrosoftAuth(cache_path=config.token_cache_path)
2009
+ try:
2010
+ auth_session = await provider.authenticate(username)
2011
+ finally:
2012
+ await provider.close()
2013
+ else:
2014
+ raise LeafishError(f"Unknown auth mode '{config.auth}'")
2015
+
2016
+ config.username = auth_session.username
2017
+ bot = LeafishBot(config, auth_session, codec)
2018
+ await bot._start()
2019
+ for name, plugin in plugins.items():
2020
+ bot.load_plugin(plugin, name=name)
2021
+ bot.emit("connect")
2022
+ return bot
2023
+
2024
+ @staticmethod
2025
+ async def create_bots(*configs: dict) -> list[LeafishBot]:
2026
+ """Create several bots concurrently.
2027
+
2028
+ Each config is a kwargs dict for :meth:`create_bot`, e.g.::
2029
+
2030
+ bots = await Leafish.create_bots(
2031
+ {"host": "localhost", "username": "Alice", "auth": "offline"},
2032
+ {"host": "localhost", "username": "Bob", "auth": "offline"},
2033
+ )
2034
+ """
2035
+ return list(await asyncio.gather(
2036
+ *(Leafish.create_bot(**cfg) for cfg in configs)
2037
+ ))
2038
+
2039
+
2040
+ def _pos_from_bitfield(loc: Any) -> BlockPos | None:
2041
+ """Convert a decoded ``position`` bitfield dict to BlockPos."""
2042
+ if not isinstance(loc, dict):
2043
+ return None
2044
+ try:
2045
+ return BlockPos(int(loc["x"]), int(loc["y"]), int(loc["z"]))
2046
+ except (KeyError, TypeError, ValueError):
2047
+ return None
2048
+
2049
+
2050
+ def _entity_id(params: dict[str, Any], key: str) -> int:
2051
+ """Extract an entity id, returning -1 (never a real id) when absent."""
2052
+ value = params.get(key)
2053
+ return int(value) if value is not None else -1
2054
+
2055
+
2056
+ def _sound_name(value: Any) -> str | None:
2057
+ """Extract a sound/particle/holder name from a decoded value."""
2058
+ if value is None:
2059
+ return None
2060
+ if isinstance(value, str):
2061
+ return value
2062
+ if isinstance(value, dict):
2063
+ kind = value.get("type")
2064
+ if kind == "reference":
2065
+ return f"registry:{value.get('id')}"
2066
+ if kind == "inline":
2067
+ return _sound_name(value.get("value"))
2068
+ for key in ("id", "name", "value", "key"):
2069
+ v = value.get(key)
2070
+ if isinstance(v, str):
2071
+ return v
2072
+ if isinstance(v, dict) and "value" in v:
2073
+ return str(v["value"])
2074
+ return str(value)
2075
+
2076
+
2077
+ def _component_text(value: Any) -> str:
2078
+ """Best-effort chat-component/NBT -> plain text extraction."""
2079
+ if value is None:
2080
+ return ""
2081
+ if isinstance(value, str):
2082
+ return value
2083
+ try:
2084
+ return component_to_text(nbt_to_python(value)) or ""
2085
+ except Exception:
2086
+ return ""