nurtex 1.2.1

Create efficient and lightweight Minecraft bots or clients.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
use std::io::ErrorKind;
use std::sync::Arc;
use std::time::Duration;

use hashbrown::HashMap;
use tokio::sync::{RwLock, broadcast};
use tokio::task::JoinHandle;
use uuid::Uuid;

use crate::bot::connection::spawn_connection;
use crate::bot::handlers::Handlers;
use crate::bot::plugins::Plugins;
use crate::bot::types::{Connection, PacketReader, PacketWriter};
use crate::bot::{BotComponents, BotProfile, ClientInfo};
use crate::protocol::connection::{ClientsidePacket, NurtexConnection};
use crate::protocol::packets::play::ServersidePlayPacket;
use crate::protocol::types::{BlockPos, Rotation, Vector3};
use crate::registry::BlockKind;
use crate::storage::Storage;
use crate::world::{Entity, EntityId};

#[cfg(feature = "proxy")]
use crate::proxy::Proxy;

#[cfg(feature = "speedometer")]
use crate::speedometer::Speedometer;

#[cfg(feature = "random")]
use crate::random::generate_username;

/// Структура Minecraft бота.
///
/// ## Примеры
/// ```rust, ignore
/// use nurtex::bot::{Bot, BotChatExt};
///
/// #[tokio::main]
/// async fn main() -> std::io::Result<()> {
///   // Создаём бота
///   let mut bot = Bot::create("nurtex_bot");
///
///   // Подключаем бота к серверу
///   bot.connect("localhost", 25565);
///
///   // Ждём немножко
///   tokio::time::sleep(std::time::Duration::from_secs(3)).await;
///
///   // Отправляем сообщение в чат
///   bot.chat_message("Привет, мир!").await?;
///
///   // Ожидаем окончания хэндла подключения
///   bot.wait_handle().await
/// }
/// ```
///
/// Больше актуальных примеров: [смотреть](https://github.com/NurtexMC/nurtex/blob/main/nurtex/examples)
pub struct Bot {
  pub profile: Arc<RwLock<BotProfile>>,
  pub connection: Connection,
  handle: Option<JoinHandle<core::result::Result<(), std::io::Error>>>,
  entity_id: Arc<EntityId>,
  username: String,
  protocol_version: i32,
  connection_timeout: u64,
  reader_tx: PacketReader,
  writer_tx: PacketWriter,
  #[cfg(feature = "proxy")]
  proxy: Option<Arc<Proxy>>,
  plugins: Arc<Plugins>,
  #[cfg(feature = "speedometer")]
  speedometer: Option<Arc<Speedometer>>,
  components: Arc<RwLock<BotComponents>>,
  storage: Arc<Storage>,
  handlers: Arc<Handlers>,
}

impl Bot {
  /// Метод создания нового бота
  pub fn create(username: impl Into<String>) -> Self {
    Self::create_with_options(username, 45, 45)
  }

  /// Метод создания нового бота с случайным юзернеймом
  #[cfg(feature = "random")]
  pub fn create_random() -> Self {
    use rand::Rng;
    Self::create_with_options(generate_username(rand::thread_rng().gen_range(5..=14)), 45, 45)
  }

  /// Метод создания нового бота с прокси
  #[cfg(feature = "proxy")]
  pub fn create_with_proxy(username: impl Into<String>, proxy: Proxy) -> Self {
    Self::create_with_options(username, 45, 45).with_proxy(proxy)
  }

  /// Метод создания нового бота со спидометром
  #[cfg(feature = "speedometer")]
  pub fn create_with_speedometer(username: impl Into<String>, speedometer: Arc<Speedometer>) -> Self {
    Self::create_with_options(username, 45, 45).with_speedometer(speedometer)
  }

  /// Метод создания нового бота с заданными опциями
  pub fn create_with_options(username: impl Into<String>, reader_capacity: usize, writer_capacity: usize) -> Self {
    let (reader_tx, _) = broadcast::channel(reader_capacity);
    let (writer_tx, _) = broadcast::channel(writer_capacity);

    let name = username.into();
    let profile = BotProfile::new(name.clone());

    Self {
      profile: Arc::new(RwLock::new(profile)),
      connection: Arc::new(RwLock::new(None::<NurtexConnection>)),
      plugins: Arc::new(Plugins::default()),
      protocol_version: 774,
      connection_timeout: 14000,
      #[cfg(feature = "proxy")]
      proxy: None,
      entity_id: Arc::new(EntityId::negative()),
      username: name,
      handle: None,
      reader_tx: Arc::new(reader_tx),
      writer_tx: Arc::new(writer_tx),
      #[cfg(feature = "speedometer")]
      speedometer: None,
      components: Arc::new(RwLock::new(BotComponents::default())),
      storage: Arc::new(Storage::null()),
      handlers: Arc::new(Handlers::new()),
    }
  }

  /// Метод запуска `reader` (выполняется автоматически при подключении бота)
  pub fn run_reader(connection: Connection, reader_tx: PacketReader) -> JoinHandle<()> {
    tokio::spawn(async move {
      // Может быть гонка условий с NurtexConnection, поэтому небольшая задержка нужна
      tokio::time::sleep(Duration::from_millis(500)).await;

      loop {
        let connected = {
          match tokio::time::timeout(Duration::from_secs(7), connection.read()).await {
            Ok(g) => g.is_some(),
            Err(_) => false,
          }
        };

        if !connected {
          tokio::time::sleep(Duration::from_millis(100)).await;
          continue;
        }

        let packet_result = {
          match tokio::time::timeout(Duration::from_secs(14), connection.read()).await {
            Ok(r) => {
              if let Some(g) = r.as_ref() {
                g.read_packet().await
              } else {
                None
              }
            }
            _ => None,
          }
        };

        match packet_result {
          Some(packet) => {
            if reader_tx.send(packet).is_err() {
              break;
            }
          }
          None => tokio::time::sleep(Duration::from_millis(50)).await,
        }
      }
    })
  }

  /// Метод запуска `writer` (выполняется автоматически при подключении бота)
  pub fn run_writer(connection: Connection, writer_tx: PacketWriter) -> JoinHandle<()> {
    let mut writer_rx = writer_tx.subscribe();

    tokio::spawn(async move {
      // Может быть гонка условий с NurtexConnection, поэтому небольшая задержка нужна
      tokio::time::sleep(Duration::from_millis(800)).await;

      let writer_fn = async |packet: ServersidePlayPacket| {
        if let Some(conn) = connection.read().await.as_ref() {
          let _ = conn.write_play_packet(packet).await;
        } else {
          tokio::time::sleep(Duration::from_millis(50)).await;
        }
      };

      loop {
        if let Ok(packet) = writer_rx.recv().await {
          match tokio::time::timeout(Duration::from_secs(14), writer_fn(packet)).await {
            Ok(_) => continue,
            Err(_) => tokio::time::sleep(Duration::from_millis(50)).await,
          }
        }
      }
    })
  }

  /// Метод установки плагинов
  pub fn with_plugins(mut self, plugins: Plugins) -> Self {
    self.plugins = Arc::new(plugins);
    self
  }

  /// Метод установки спидометра
  #[cfg(feature = "speedometer")]
  pub fn with_speedometer(mut self, speedometer: Arc<Speedometer>) -> Self {
    self.speedometer = Some(speedometer);
    self
  }

  /// Метод установки версии протокола
  pub fn with_protocol_version(mut self, protocol_version: i32) -> Self {
    self.protocol_version = protocol_version;
    self
  }

  /// Метод установки таймаута подключения
  pub fn with_connection_timeout(mut self, timeout: u64) -> Self {
    self.connection_timeout = timeout;
    self
  }

  /// Метод установки прокси
  #[cfg(feature = "proxy")]
  pub fn with_proxy(mut self, proxy: Proxy) -> Self {
    self.proxy = Some(Arc::new(proxy));
    self
  }

  /// Метод установки информации клиента
  pub fn with_information(self, information: ClientInfo) -> Self {
    // Здесь почти невозможен исход с ошибкой, поэтому просто игнорируем
    match self.profile.try_write() {
      Ok(mut g) => g.information = information,
      Err(_) => {}
    }

    self
  }

  /// Метод установки обработчиков
  pub fn with_handlers(mut self, handlers: Handlers) -> Self {
    self.handlers = Arc::new(handlers);
    self
  }

  /// Метод установки общего хранилища
  pub fn set_shared_storage(mut self, storage: Arc<Storage>) -> Self {
    self.storage = storage;
    self
  }

  /// Метод установки общих обработчиков
  pub fn set_shared_handlers(mut self, handlers: Arc<Handlers>) -> Self {
    self.handlers = handlers;
    self
  }

  /// Метод получения юзернейма
  pub fn username(&self) -> &str {
    &self.username
  }

  /// Метод получения UUID
  pub async fn uuid(&self) -> Uuid {
    self.profile.read().await.uuid
  }

  /// Метод получения профиля бота
  pub fn get_profile(&self) -> Arc<RwLock<BotProfile>> {
    Arc::clone(&self.profile)
  }

  /// Метод получения прокси бота
  #[cfg(feature = "proxy")]
  pub fn get_proxy(&self) -> Option<Arc<Proxy>> {
    if let Some(proxy) = &self.proxy { Some(Arc::clone(&proxy)) } else { None }
  }

  /// Метод получения хранилища
  pub fn get_storage(&self) -> Arc<Storage> {
    Arc::clone(&self.storage)
  }

  /// Вспомогательный метод подписки на слушание пакетов
  pub fn subscribe_to_reader(&self) -> broadcast::Receiver<ClientsidePacket> {
    self.reader_tx.subscribe()
  }

  /// Метод получения копии `reader_tx`
  pub fn get_reader(&self) -> PacketReader {
    Arc::clone(&self.reader_tx)
  }

  /// Метод получения копии `writer_tx`
  pub fn get_writer(&self) -> PacketWriter {
    Arc::clone(&self.writer_tx)
  }

  /// Метод получения хэндла
  pub fn get_handle(&self) -> &Option<JoinHandle<core::result::Result<(), std::io::Error>>> {
    &self.handle
  }

  /// Метод отправки пакета
  pub fn send_packet(&self, packet: ServersidePlayPacket) {
    let _ = self.writer_tx.send(packet);
  }

  /// Метод подключения бота к серверу.
  ///
  /// ## Примеры
  ///
  /// ```rust, ignore
  /// use nurtex::Bot;
  ///
  /// #[tokio::main]
  /// async fn main() -> std::io::Result<()> {
  ///   // Создаём бота
  ///   let mut bot = Bot::create("nurtex_bot");
  ///
  ///   // Подключаем бота к серверу.
  ///   // Если после вызова этого метода выполняются
  ///   // какие-либо действия с ботом, рекомендуется
  ///   // подождать несколько секунд, чтобы бот
  ///   // полностью подключился к серверу
  ///   bot.connect("localhost", 25565);
  ///
  ///   // Ожидаем окончания хэндла подключения
  ///   bot.wait_handle().await
  /// }
  /// ```
  pub fn connect(&mut self, server_host: impl Into<String>, server_port: u16) {
    self.handle = Some(self.connect_with_handle(server_host, server_port));
  }

  /// Метод подключения бота к серверу, возвращающий хэндл подключения
  pub fn connect_with_handle(&self, server_host: impl Into<String>, server_port: u16) -> JoinHandle<Result<(), std::io::Error>> {
    let connection = self.connection.clone();
    let profile = self.profile.clone();
    let components = self.components.clone();
    let entity_id = self.entity_id.clone();
    let plugins = self.plugins.clone();
    let reader_tx = self.reader_tx.clone();
    let writer_tx = self.writer_tx.clone();
    let storage = self.storage.clone();
    let handlers = self.handlers.clone();

    #[cfg(feature = "speedometer")]
    let speedometer = self.speedometer.clone();

    #[cfg(feature = "proxy")]
    let proxy = self.proxy.clone();

    let protocol_version = self.protocol_version;
    let coonnection_timeout = self.connection_timeout;

    let host = server_host.into();
    let port = server_port;

    tokio::spawn(async move {
      let mut reconnection_attempts = 0;
      let max_attempts = if plugins.auto_reconnect.enabled { plugins.auto_reconnect.max_attempts } else { 1 };

      loop {
        let reader_handle = Self::run_reader(Arc::clone(&connection), Arc::clone(&reader_tx));
        let writer_handle = Self::run_writer(Arc::clone(&connection), Arc::clone(&writer_tx));

        let result = spawn_connection(
          &connection,
          &profile,
          &components,
          &entity_id,
          #[cfg(feature = "speedometer")]
          &speedometer,
          &plugins,
          &reader_tx,
          &storage,
          protocol_version,
          coonnection_timeout,
          #[cfg(feature = "proxy")]
          &proxy,
          &host,
          port,
          &handlers,
        )
        .await;

        // На этом моменте бот считается не подключенным к серверу, поэтому нужно отменять reader / writer
        reader_handle.abort();
        writer_handle.abort();

        match result {
          Ok(_) => return Ok(()),
          Err(e) => match e.kind() {
            ErrorKind::ConnectionAborted | ErrorKind::ConnectionRefused | ErrorKind::ConnectionReset | ErrorKind::TimedOut | ErrorKind::NotConnected | ErrorKind::NetworkDown => {
              if !plugins.auto_reconnect.enabled || (max_attempts != -1 && reconnection_attempts >= max_attempts) {
                return Err(e);
              }

              reconnection_attempts += 1;

              tokio::time::sleep(Duration::from_millis(plugins.auto_reconnect.reconnect_delay)).await;
            }
            _ => return Err(e),
          },
        }
      }
    })
  }

  /// Метод ожидания завершения хэндла подключения
  pub async fn wait_handle(&mut self) -> std::io::Result<()> {
    if let Some(handle) = self.handle.as_mut() { handle.await? } else { Ok(()) }
  }

  /// Метод полноценной очистки и отключения бота
  pub async fn shutdown(&self) -> std::io::Result<()> {
    self.abort_handle();

    let mut conn_guard = self.connection.write().await;
    if let Some(conn) = conn_guard.as_ref() {
      conn.shutdown().await?;
    }

    *conn_guard = None;
    std::mem::drop(conn_guard);

    self.clear().await;

    Ok(())
  }

  /// Метод очистки данных бота
  pub async fn clear(&self) {
    *self.components.write().await = BotComponents::default();
  }

  /// Метод отмены хэндла бота
  pub fn abort_handle(&self) {
    if let Some(handle) = &self.handle {
      handle.abort();
    }
  }

  /// Метод переподключения бота
  pub async fn reconnect(&mut self, server_host: impl Into<String>, server_port: u16, reconnect_delay: u64) -> std::io::Result<()> {
    self.shutdown().await?;
    tokio::time::sleep(Duration::from_millis(reconnect_delay)).await;
    self.connect(server_host, server_port);
    Ok(())
  }

  /// Метод переподключения бота, возвращающий хэндл подключения
  pub async fn reconnect_with_handle(&mut self, server_host: impl Into<String>, server_port: u16, reconnect_delay: u64) -> std::io::Result<JoinHandle<Result<(), std::io::Error>>> {
    self.shutdown().await?;
    tokio::time::sleep(Duration::from_millis(reconnect_delay)).await;
    Ok(self.connect_with_handle(server_host, server_port))
  }

  /// Метод получения компонентов бота
  pub fn get_components(&self) -> Arc<RwLock<BotComponents>> {
    Arc::clone(&self.components)
  }

  /// Метод получения опциональной позиции бота
  pub fn try_get_position(&self) -> Option<Vector3> {
    match self.components.try_read() {
      Ok(g) => Some(g.position.clone()),
      Err(_) => None,
    }
  }

  /// Метод получения опционального здоровья бота
  pub fn try_get_health(&self) -> Option<Vector3> {
    match self.components.try_read() {
      Ok(g) => Some(g.position.clone()),
      Err(_) => None,
    }
  }

  /// Метод получения опциональной ротации бота
  pub fn try_get_rotation(&self) -> Option<f32> {
    match self.components.try_read() {
      Ok(g) => Some(g.health),
      Err(_) => None,
    }
  }

  /// Метод получения опциональных сущностей из хранилища
  pub fn try_get_entities(&self) -> Option<HashMap<i32, Entity>> {
    match self.storage.entities.try_read() {
      Ok(g) => {
        let mut entities = HashMap::with_capacity(g.len());

        for (entity_id, entity) in &*g {
          entities.insert(*entity_id, entity.clone());
        }

        Some(entities)
      }
      Err(_) => None,
    }
  }

  /// Метод получения ID сущности бота
  pub async fn get_entity_id(&self) -> i32 {
    self.entity_id.get()
  }

  /// Метод получения позиции бота
  pub async fn get_position(&self) -> Vector3 {
    let guard = self.components.read().await;
    guard.position.clone()
  }

  /// Метод получения ротации бота
  pub async fn get_rotation(&self) -> Rotation {
    let guard = self.components.read().await;
    guard.rotation.clone()
  }

  /// Метод получения здоровья бота
  pub async fn get_health(&self) -> f32 {
    let guard = self.components.read().await;
    guard.health
  }

  /// Метод получения всех сущностей из хранилища
  pub async fn get_entities(&self) -> HashMap<i32, Entity> {
    let guard = self.storage.entities.read().await;
    let mut entities = HashMap::with_capacity(guard.len());

    for (entity_id, entity) in &*guard {
      entities.insert(*entity_id, entity.clone());
    }

    entities
  }

  /// Метод получения блока по координатам
  pub async fn get_block(&self, pos: BlockPos) -> Option<BlockKind> {
    self.storage.get_block(pos).await
  }
}

#[cfg(test)]
mod tests {
  use std::io;
  use std::time::Duration;

  use crate::bot::handlers::Handlers;
  use crate::protocol::connection::ClientsidePacket;
  use crate::protocol::packets::play::ClientsidePlayPacket;
  use crate::protocol::types::BlockPos;
  use crate::proxy::Proxy;

  use crate::bot::plugins::{AutoReconnectPlugin, AutoRespawnPlugin, Plugins};
  use crate::bot::{Bot, BotChatExt};

  #[tokio::test]
  async fn test_packet_handling() -> io::Result<()> {
    let mut bot = Bot::create("nurtex_bot");

    bot.connect("localhost", 25565);

    let mut reader = bot.subscribe_to_reader();

    loop {
      if let Ok(ClientsidePacket::Play(packet)) = reader.recv().await {
        println!("Бот {} получил пакет: {:?}", bot.username(), packet);

        // + Доп проверка взаимодействия с чатом

        match packet {
          ClientsidePlayPacket::KeepAlive(p) => {
            bot.chat_message(format!("Получен KeepAlive: {}", p.id)).await?;
          }
          _ => {}
        }
      }
    }
  }

  #[tokio::test]
  async fn test_handlers() -> io::Result<()> {
    let mut handlers = Handlers::new();

    handlers.on_login(async |username| {
      println!("Бот {} залогинился", username);
      Ok(())
    });

    handlers.on_spawn(async |username| {
      println!("Бот {} заспавнился", username);
      Ok(())
    });

    handlers.on_chat(async |username, payload| {
      println!("Бот {} получил сообщение: {}", username, payload.message);
      Ok(())
    });

    handlers.on_disconnect(async |username, payload| {
      println!("Бот {} отключился в состоянии: {:?}", username, payload.state);
      Ok(())
    });

    let mut bot = Bot::create("nurtex_bot").with_handlers(handlers);

    bot.connect("localhost", 25565);
    bot.wait_handle().await
  }

  #[tokio::test]
  async fn test_auto_respawn() -> io::Result<()> {
    let mut bot = Bot::create("nurtex_bot").with_plugins(Plugins {
      auto_respawn: AutoRespawnPlugin {
        enabled: true,
        respawn_delay: 2000,
      },
      ..Default::default()
    });

    bot.connect("localhost", 25565);
    bot.wait_handle().await
  }

  #[tokio::test]
  async fn test_auto_reconnect() -> io::Result<()> {
    let mut bot = Bot::create("nurtex_bot").with_plugins(Plugins {
      auto_reconnect: AutoReconnectPlugin {
        enabled: true,
        reconnect_delay: 1000,
        max_attempts: 3,
      },
      ..Default::default()
    });

    bot.connect("localhost", 25565);

    // + Доп проверка на работоспособность reader'а пакетов после переподключения

    let mut reader = bot.subscribe_to_reader();

    loop {
      if let Ok(ClientsidePacket::Play(packet)) = reader.recv().await {
        println!("Бот {} получил пакет: {:?}", bot.username(), packet);
      }
    }
  }

  #[tokio::test]
  async fn test_entity_storage() -> io::Result<()> {
    let mut bot = Bot::create("nurtex_bot");

    bot.connect("localhost", 25565);

    tokio::time::sleep(Duration::from_secs(3)).await;

    for _ in 0..10 {
      for (_, entity) in bot.get_entities().await {
        println!("Сущность: {:?}", entity);
      }

      tokio::time::sleep(Duration::from_secs(3)).await;
    }

    Ok(())
  }

  #[tokio::test]
  async fn test_chunk_storage() -> io::Result<()> {
    let mut bot = Bot::create("nurtex_bot");

    bot.connect("localhost", 25565);

    tokio::time::sleep(Duration::from_secs(3)).await;

    let pos = bot.get_position().await;
    let feet_block = bot
      .get_block(BlockPos {
        x: pos.x as i32,
        y: (pos.y - 1.0) as i32,
        z: pos.z as i32,
      })
      .await;

    if let Some(block) = feet_block {
      println!("Блок под ногами: {:?}", block);
    }

    Ok(())
  }

  #[tokio::test]
  async fn test_bot_with_socks5_proxy() -> io::Result<()> {
    let proxy = Proxy::from("socks5://212.58.132.5:1080");
    let mut bot = Bot::create_with_proxy("l7jqw8d5", proxy);

    bot.connect("hub.holyworld.ru", 25565);

    let mut reader = bot.subscribe_to_reader();

    loop {
      if let Ok(ClientsidePacket::Play(packet)) = reader.recv().await {
        println!("Бот {} получил пакет: {:?}", bot.username(), packet);
      }
    }
  }

  #[tokio::test]
  async fn test_bot_with_socks4_proxy() -> io::Result<()> {
    let proxy = Proxy::from("socks4://68.71.242.118:4145");
    let mut bot = Bot::create_with_proxy("k72ido3d", proxy);

    bot.connect("hub.holyworld.ru", 25565);

    let mut reader = bot.subscribe_to_reader();

    loop {
      if let Ok(ClientsidePacket::Play(packet)) = reader.recv().await {
        println!("Бот {} получил пакет: {:?}", bot.username(), packet);
      }
    }
  }

  #[tokio::test]
  async fn test_reconnect() -> io::Result<()> {
    let mut handlers = Handlers::new();

    handlers.on_spawn(async |username| {
      println!("Бот {} заспавнился", username);
      Ok(())
    });

    let mut bot = Bot::create("nurtex_bot").with_handlers(handlers);

    let server_host = "localhost".to_string();
    let server_port = 25565;

    bot.connect(&server_host, server_port);

    tokio::time::sleep(Duration::from_secs(3)).await;

    bot.reconnect(&server_host, server_port, 1000).await?;

    bot.wait_handle().await
  }
}