azalea/client_impl/mod.rs
1use std::{collections::HashMap, sync::Arc};
2
3use azalea_auth::game_profile::GameProfile;
4use azalea_client::{
5 DefaultPlugins,
6 account::Account,
7 connection::RawConnection,
8 disconnect::DisconnectEvent,
9 join::{ConnectOpts, StartJoinServerEvent},
10 local_player::{Experience, Hunger, TabList, WorldHolder},
11 packet::game::SendGamePacketEvent,
12 player::{GameProfileComponent, PlayerInfo},
13 start_ecs_runner,
14 tick_counter::TicksConnected,
15};
16use azalea_core::entity_id::MinecraftEntityId;
17use azalea_entity::indexing::{EntityIdIndex, EntityUuidIndex};
18use azalea_protocol::{
19 address::{ResolvableAddr, ResolvedAddr},
20 connect::Proxy,
21 packets::{Packet, game::ServerboundGamePacket},
22 resolve::ResolveError,
23};
24use azalea_registry::{data_registry::DeserializableDataRegistry, registry_holder::RegistryHolder};
25use azalea_world::{PartialWorld, World, WorldName};
26use bevy_app::{App, AppExit};
27use bevy_ecs::{entity::Entity, resource::Resource, world::Mut};
28use parking_lot::RwLock;
29use tokio::sync::{mpsc, oneshot};
30use uuid::Uuid;
31
32use crate::{
33 bot::DefaultBotPlugins,
34 client_impl::error::AzaleaResult,
35 entity_ref::EntityRef,
36 events::{Event, LocalPlayerEvents},
37 swarm::DefaultSwarmPlugins,
38};
39
40pub mod attack;
41pub mod chat;
42pub mod client_information;
43pub mod entity_query;
44pub mod error;
45pub mod interact;
46pub mod inventory;
47pub mod mining;
48pub mod movement;
49
50/// A Minecraft client instance that can interact with the world.
51///
52/// To make a new client, use either [`azalea::ClientBuilder`] or
53/// [`Client::join`].
54///
55/// Note that `Client` is inaccessible from systems (i.e. plugins), but you can
56/// achieve everything that client can do with ECS events.
57///
58/// [`azalea::ClientBuilder`]: https://docs.rs/azalea/latest/azalea/struct.ClientBuilder.html
59#[derive(Clone)]
60pub struct Client {
61 /// The entity for this client in the ECS.
62 pub entity: Entity,
63
64 /// A mutually exclusive reference to the entity component system (ECS).
65 ///
66 /// You probably don't need to access this directly. Note that if you're
67 /// using a shared world (i.e. a swarm), the ECS will also contain all
68 /// entities in all worlds.
69 ///
70 /// You can nearly always use [`Self::component`], [`Self::query_self`],
71 /// [`Self::query_entity`], or another one of those related functions to
72 /// access the ECS instead.
73 pub ecs: Arc<RwLock<bevy_ecs::world::World>>,
74}
75
76pub struct StartClientOpts {
77 pub ecs_lock: Arc<RwLock<bevy_ecs::world::World>>,
78 pub account: Account,
79 pub connect_opts: ConnectOpts,
80 pub event_sender: Option<mpsc::UnboundedSender<Event>>,
81}
82
83impl StartClientOpts {
84 pub fn new(
85 account: Account,
86 address: ResolvedAddr,
87 event_sender: Option<mpsc::UnboundedSender<Event>>,
88 ) -> StartClientOpts {
89 Self::new_with_appexit_rx(account, address, event_sender).0
90 }
91
92 pub fn new_with_appexit_rx(
93 account: Account,
94 address: ResolvedAddr,
95 event_sender: Option<mpsc::UnboundedSender<Event>>,
96 ) -> (StartClientOpts, oneshot::Receiver<AppExit>) {
97 let mut app = App::new();
98 app.add_plugins((DefaultPlugins, DefaultBotPlugins, DefaultSwarmPlugins));
99
100 let (ecs_lock, start_running_systems, appexit_rx) = start_ecs_runner(app.main_mut());
101 start_running_systems();
102
103 (
104 Self {
105 ecs_lock,
106 account,
107 connect_opts: ConnectOpts {
108 address,
109 server_proxy: None,
110 sessionserver_proxy: None,
111 },
112 event_sender,
113 },
114 appexit_rx,
115 )
116 }
117
118 /// Configure the SOCKS5 proxy used for connecting to the server and for
119 /// authenticating with Mojang.
120 ///
121 /// To configure these separately, for example to only use the proxy for the
122 /// Minecraft server and not for authentication, you may use
123 /// [`Self::server_proxy`] and [`Self::sessionserver_proxy`] individually.
124 pub fn proxy(self, proxy: Proxy) -> Self {
125 self.server_proxy(proxy.clone()).sessionserver_proxy(proxy)
126 }
127 /// Configure the SOCKS5 proxy that will be used for connecting to the
128 /// Minecraft server.
129 ///
130 /// To avoid errors on servers with the "prevent-proxy-connections" option
131 /// set, you should usually use [`Self::proxy`] instead.
132 ///
133 /// Also see [`Self::sessionserver_proxy`].
134 pub fn server_proxy(mut self, proxy: Proxy) -> Self {
135 self.connect_opts.server_proxy = Some(proxy);
136 self
137 }
138 /// Configure the SOCKS5 proxy that this bot will use for authenticating the
139 /// server join with Mojang's API.
140 ///
141 /// Also see [`Self::proxy`] and [`Self::server_proxy`].
142 pub fn sessionserver_proxy(mut self, proxy: Proxy) -> Self {
143 self.connect_opts.sessionserver_proxy = Some(proxy);
144 self
145 }
146}
147
148impl Client {
149 /// Create a new client from the given [`GameProfile`], ECS Entity, ECS
150 /// World, and schedule runner function.
151 /// You should only use this if you want to change these fields from the
152 /// defaults, otherwise use [`Client::join`].
153 pub fn new(entity: Entity, ecs: Arc<RwLock<bevy_ecs::world::World>>) -> Self {
154 Self {
155 // default our id to 0, it'll be set later
156 entity,
157
158 ecs,
159 }
160 }
161
162 /// Connect to a Minecraft server.
163 ///
164 /// To change the render distance and other settings, use
165 /// [`Client::set_client_information`]. To watch for events like packets
166 /// sent by the server, use the `rx` variable this function returns.
167 ///
168 /// # Examples
169 ///
170 /// ```rust,no_run
171 /// use azalea::{Account, Client};
172 ///
173 /// #[tokio::main]
174 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
175 /// let account = Account::offline("bot");
176 /// let (client, rx) = Client::join(account, "localhost").await?;
177 /// client.chat("Hello, world!");
178 /// client.disconnect();
179 /// Ok(())
180 /// }
181 /// ```
182 pub async fn join(
183 account: Account,
184 address: impl ResolvableAddr,
185 ) -> Result<(Self, mpsc::UnboundedReceiver<Event>), ResolveError> {
186 let address = address.resolve().await?;
187 let (tx, rx) = mpsc::unbounded_channel();
188
189 let client = Self::start_client(StartClientOpts::new(account, address, Some(tx))).await;
190 Ok((client, rx))
191 }
192
193 pub async fn join_with_proxy(
194 account: Account,
195 address: impl ResolvableAddr,
196 proxy: Proxy,
197 ) -> Result<(Self, mpsc::UnboundedReceiver<Event>), ResolveError> {
198 let address = address.resolve().await?;
199 let (tx, rx) = mpsc::unbounded_channel();
200
201 let client =
202 Self::start_client(StartClientOpts::new(account, address, Some(tx)).proxy(proxy)).await;
203 Ok((client, rx))
204 }
205
206 /// Create a [`Client`] when you already have the ECS made with
207 /// [`start_ecs_runner`]. You'd usually want to use [`Self::join`] instead.
208 pub async fn start_client(
209 StartClientOpts {
210 ecs_lock,
211 account,
212 connect_opts,
213 event_sender,
214 }: StartClientOpts,
215 ) -> Self {
216 // send a StartJoinServerEvent
217
218 let (start_join_callback_tx, mut start_join_callback_rx) =
219 mpsc::unbounded_channel::<Entity>();
220
221 ecs_lock.write().write_message(StartJoinServerEvent {
222 account,
223 connect_opts,
224 start_join_callback_tx: Some(start_join_callback_tx),
225 });
226
227 let entity = start_join_callback_rx.recv().await.expect(
228 "start_join_callback should not be dropped before sending a message, this is a bug in Azalea",
229 );
230
231 if let Some(event_sender) = event_sender {
232 ecs_lock
233 .write()
234 .entity_mut(entity)
235 .insert(LocalPlayerEvents(event_sender));
236 }
237
238 Client::new(entity, ecs_lock)
239 }
240
241 /// Write a packet directly to the server.
242 pub fn write_packet(&self, packet: impl Packet<ServerboundGamePacket>) {
243 let packet = packet.into_variant();
244 self.ecs
245 .write()
246 .commands()
247 .trigger(SendGamePacketEvent::new(self.entity, packet));
248 }
249
250 /// Disconnect this client from the server by ending all tasks.
251 ///
252 /// The OwnedReadHalf for the TCP connection is in one of the tasks, so it
253 /// automatically closes the connection when that's dropped.
254 ///
255 /// Note that this will not return from your client builder. If you need
256 /// that, consider using [`Self::exit`] instead.
257 pub fn disconnect(&self) {
258 self.ecs.write().write_message(DisconnectEvent {
259 entity: self.entity,
260 reason: None,
261 });
262 }
263
264 /// End the entire client or swarm, and return from
265 /// [`ClientBuilder::start`] or [`SwarmBuilder::start`].
266 ///
267 /// You should typically avoid calling this if you intend on creating the
268 /// client again, because creating an entirely new swarm can be a
269 /// relatively expensive process.
270 ///
271 /// If you only want to change the server that the bots are connecting to,
272 /// it may be better to access the client's internal [`Swarm`] and call
273 /// [`Swarm::add_with_opts`] with a different server address.
274 ///
275 /// For convenience, this is also duplicated on `Swarm` as [`Swarm::exit`].
276 ///
277 /// [`ClientBuilder::start`]: crate::ClientBuilder::start
278 /// [`SwarmBuilder::start`]: crate::swarm::SwarmBuilder::start
279 /// [`Swarm`]: crate::swarm::Swarm
280 /// [`Swarm::add_with_opts`]: crate::swarm::Swarm::add_with_opts
281 /// [`Swarm::exit`]: crate::swarm::Swarm::exit
282 ///
283 /// ```no_run
284 /// // a bot that joins a server and prints "done!" when it's disconnected or if it fails to connect.
285 /// use azalea::{NoState, prelude::*};
286 /// #[tokio::main]
287 /// async fn main() {
288 /// let account = Account::offline("bot");
289 /// ClientBuilder::new()
290 /// .set_handler(handle)
291 /// .start(account, "localhost")
292 /// .await;
293 /// println!("done!");
294 /// }
295 /// async fn handle(bot: Client, event: Event, _state: NoState) -> eyre::Result<()> {
296 /// match event {
297 /// Event::Disconnect(_) | Event::ConnectionFailed(_) => {
298 /// bot.exit();
299 /// }
300 /// _ => {}
301 /// }
302 /// Ok(())
303 /// }
304 /// ```
305 pub fn exit(&self) {
306 self.ecs.write().write_message(AppExit::Success);
307 }
308
309 pub fn with_raw_connection<R>(&self, f: impl FnOnce(&RawConnection) -> R) -> AzaleaResult<R> {
310 self.query_self::<&RawConnection, _>(f)
311 }
312 pub fn with_raw_connection_mut<R>(
313 &self,
314 f: impl FnOnce(Mut<'_, RawConnection>) -> R,
315 ) -> AzaleaResult<R> {
316 self.query_self::<&mut RawConnection, _>(f)
317 }
318
319 /// Get a resource from the ECS. This will clone the resource and return it.
320 pub fn resource<T: Resource + Clone>(&self) -> T {
321 self.ecs.read().resource::<T>().clone()
322 }
323
324 /// Get a required ECS resource and call the given function with it.
325 pub fn map_resource<T: Resource, R>(&self, f: impl FnOnce(&T) -> R) -> R {
326 let ecs = self.ecs.read();
327 let value = ecs.resource::<T>();
328 f(value)
329 }
330
331 /// Get an optional ECS resource and call the given function with it.
332 pub fn map_get_resource<T: Resource, R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
333 let ecs = self.ecs.read();
334 let value = ecs.get_resource::<T>();
335 f(value)
336 }
337
338 /// Get an `RwLock` with a reference to our (potentially shared) Minecraft
339 /// world.
340 ///
341 /// This gets the [`World`] from the client's [`WorldHolder`]
342 /// component. If it's a normal client, then it'll be the same as the
343 /// world the client has loaded. If the client is using a shared world,
344 /// then the shared world will be a superset of the client's world.
345 pub fn world(&self) -> AzaleaResult<Arc<RwLock<World>>> {
346 let world_holder = self.component::<WorldHolder>()?;
347 Ok(world_holder.shared.clone())
348 }
349
350 /// Get an `RwLock` with a reference to the world that this client has
351 /// loaded.
352 ///
353 /// ```
354 /// # use azalea_core::position::ChunkPos;
355 /// # fn example(client: &azalea::Client) -> azalea::error::AzaleaResult<()> {
356 /// let world = client.partial_world()?;
357 /// let is_0_0_loaded = world.read().chunks.limited_get(&ChunkPos::new(0, 0)).is_some();
358 /// # Ok(())
359 /// # }
360 pub fn partial_world(&self) -> AzaleaResult<Arc<RwLock<PartialWorld>>> {
361 let world_holder = self.component::<WorldHolder>()?;
362 Ok(world_holder.partial.clone())
363 }
364
365 /// Returns whether we have a received the login packet yet.
366 pub fn logged_in(&self) -> bool {
367 // the login packet tells us the world name
368 self.query_self::<&WorldName, _>(|_| {}).is_ok()
369 }
370
371 /// Returns the client as an [`EntityRef`], allowing you to treat it as any
372 /// other entity.
373 pub fn entity(&self) -> EntityRef {
374 self.entity_ref_for(self.entity)
375 }
376
377 /// Create an [`EntityRef`] for the given ECS entity.
378 pub fn entity_ref_for(&self, entity: Entity) -> EntityRef {
379 EntityRef::new(self.clone(), entity)
380 }
381}
382
383impl Client {
384 /// Get the hunger level of this client, which includes both food and
385 /// saturation.
386 ///
387 /// This is a shortcut for `self.component::<Hunger>()?.to_owned()`.
388 pub fn hunger(&self) -> AzaleaResult<Hunger> {
389 Ok(self.component::<Hunger>()?.to_owned())
390 }
391
392 /// Get the experience of this client.
393 ///
394 /// This is a shortcut for `self.component::<Experience>().to_owned()`.
395 pub fn experience(&self) -> AzaleaResult<Experience> {
396 Ok(self.component::<Experience>()?.to_owned())
397 }
398
399 /// Get the username of this client's account.
400 ///
401 /// This is a shortcut for `bot.account().username().to_owned()`.
402 pub fn username(&self) -> String {
403 self.account().username().to_owned()
404 }
405 /// Get the username of this client, as sent to us by the server.
406 ///
407 /// This is a shortcut for `bot.profile()?.name.to_owned()`.
408 ///
409 /// In some cases, this may be different from [`Self::username`] if the
410 /// server sends us a [`GameProfile`] with a mismatching username. Using
411 /// [`Self::username`] is recommended if you're not sure which one to use.
412 pub fn server_username(&self) -> AzaleaResult<String> {
413 Ok(self.profile()?.name.to_owned())
414 }
415
416 /// Get the Minecraft UUID of this client's account.
417 ///
418 /// This is a shortcut for `**self.component::<EntityUuid>()`.
419 pub fn uuid(&self) -> Uuid {
420 self.account().uuid()
421 }
422
423 /// Get a map of player UUIDs to their information in the tab list.
424 ///
425 /// This is a shortcut for `*bot.component::<TabList>()`.
426 pub fn tab_list(&self) -> AzaleaResult<HashMap<Uuid, PlayerInfo>> {
427 Ok((**self.component::<TabList>()?).clone())
428 }
429
430 /// Returns the [`GameProfile`] for our client. This contains your username,
431 /// UUID, and skin data.
432 ///
433 /// These values are set by the server upon login, which means they might
434 /// not match up with your actual game profile. Also, note that the username
435 /// and skin that gets displayed in-game will actually be the ones from
436 /// the tab list, which you can get from [`Self::tab_list`].
437 ///
438 /// This as also available from the ECS as [`GameProfileComponent`].
439 pub fn profile(&self) -> AzaleaResult<GameProfile> {
440 Ok((**self.component::<GameProfileComponent>()?).clone())
441 }
442
443 /// Returns the [`Account`] for our client.
444 pub fn account(&self) -> Account {
445 self.component::<Account>()
446 .expect(
447 "clients cannot exist without an Account, and Account isn't removed from clients",
448 )
449 .clone()
450 }
451
452 /// A convenience function to get the Minecraft Uuid of a player by their
453 /// username, if they're present in the tab list.
454 ///
455 /// You can chain this with [`Client::entity_by_uuid`] to get the ECS
456 /// `Entity` for the player.
457 pub fn player_uuid_by_username(&self, username: &str) -> AzaleaResult<Option<Uuid>> {
458 Ok(self
459 .tab_list()?
460 .values()
461 .find(|player| player.profile.name == username)
462 .map(|player| player.profile.uuid))
463 }
464
465 /// Get an [`Entity`] in the world by its Minecraft UUID, if it's within
466 /// render distance.
467 ///
468 /// Also see [`Self::entity_by_uuid`] and
469 /// [`Self::entity_id_by_minecraft_id`].
470 pub fn entity_id_by_uuid(&self, uuid: Uuid) -> Option<Entity> {
471 self.map_resource::<EntityUuidIndex, _>(|entity_uuid_index| entity_uuid_index.get(&uuid))
472 }
473 /// Get an [`EntityRef`] in the world by its Minecraft UUID, if it's within
474 /// render distance.
475 ///
476 /// Also see [`Self::entity_id_by_uuid`].
477 pub fn entity_by_uuid(&self, uuid: Uuid) -> Option<EntityRef> {
478 self.entity_id_by_uuid(uuid).map(|e| self.entity_ref_for(e))
479 }
480
481 /// Get an [`Entity`] in the world by its [`MinecraftEntityId`].
482 ///
483 /// Also see [`Self::entity_by_uuid`] and [`Self::entity_id_by_uuid`].
484 pub fn entity_id_by_minecraft_id(&self, id: MinecraftEntityId) -> AzaleaResult<Option<Entity>> {
485 self.query_self::<&EntityIdIndex, _>(|entity_id_index| {
486 entity_id_index.get_by_minecraft_entity(id)
487 })
488 }
489 /// Get an [`EntityRef`] in the world by its [`MinecraftEntityId`].
490 ///
491 /// Also see [`Self::entity_id_by_uuid`].
492 pub fn entity_by_minecraft_id(&self, id: MinecraftEntityId) -> AzaleaResult<Option<EntityRef>> {
493 Ok(self
494 .entity_id_by_minecraft_id(id)?
495 .map(|e| EntityRef::new(self.clone(), e)))
496 }
497
498 /// Call the given function with the client's [`RegistryHolder`].
499 ///
500 /// Note that the player's world will be locked during this time, which may
501 /// result in a deadlock if you try to access the world again while
502 /// in the function.
503 pub fn with_registry_holder<R>(&self, f: impl FnOnce(&RegistryHolder) -> R) -> AzaleaResult<R> {
504 let world = self.world()?;
505 let registries = &world.read().registries;
506 Ok(f(registries))
507 }
508
509 /// Resolve the given registry to its data and call the given function with
510 /// it.
511 ///
512 /// To get the registry's [`Identifier`] name, you may simply use its
513 /// `Identifier::from` implementation.
514 pub fn with_resolved_registry<R: DeserializableDataRegistry, Ret>(
515 &self,
516 registry: R,
517 f: impl FnOnce(&R::DeserializesTo) -> Ret,
518 ) -> AzaleaResult<Option<Ret>> {
519 self.with_registry_holder(|registries| registry.resolve(registries).map(f))
520 }
521
522 /// Returns the number of ticks since the `login` packet was received, or 0
523 /// if the client isn't in the world.
524 ///
525 /// This is a shortcut for getting the [`TicksConnected`] component.
526 pub fn ticks_connected(&self) -> u64 {
527 self.component::<TicksConnected>().map(|c| c.0).unwrap_or(0)
528 }
529}