nurtex 0.5.2

Lightweight library for creating Minecraft bots. Asynchronous, optimized, ease of coding.
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
#![allow(dead_code)]

use std::io::{self, Error, ErrorKind};
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;

use azalea_core::direction::Direction;
use azalea_core::position::{BlockPos, Vec3};
use azalea_entity::LookDirection;
use azalea_protocol::common::movements::MoveFlags;
use azalea_protocol::connect::{Connection, Proxy};
use azalea_protocol::packets::game::s_chat::LastSeenMessagesUpdate;
use azalea_protocol::packets::game::s_player_action::Action;
use azalea_protocol::packets::game::{
  ClientboundGamePacket, ServerboundChat, ServerboundGamePacket, ServerboundMovePlayerPos, ServerboundMovePlayerRot, ServerboundPlayerAction, ServerboundSwing, ServerboundUseItem,
};
use azalea_protocol::packets::handshake::s_intention::ServerboundIntention;
use azalea_protocol::packets::handshake::{ClientboundHandshakePacket, ServerboundHandshakePacket};
use azalea_protocol::packets::login::s_hello::ServerboundHello;
use azalea_protocol::packets::login::s_login_acknowledged::ServerboundLoginAcknowledged;
use azalea_protocol::packets::{ClientIntention, PROTOCOL_VERSION};
use tokio::io::AsyncWriteExt;
use tokio::sync::{RwLock, mpsc};
use tokio::task::JoinHandle;
use tokio::time::timeout;
use uuid::Uuid;

use crate::bot::components::BotComponents;
use crate::bot::components::position::Position;
use crate::bot::components::rotation::Rotation;
use crate::bot::events::{BotEvent, EventInvoker, PacketPayload, RotationPayload};
use crate::bot::events::{DisconnectPayload, PositionPayload};
use crate::bot::handlers::base::{process_configuration, process_login};
use crate::bot::handlers::custom::{PacketProcessorFn, default_packet_processor};
use crate::bot::options::{BotInformation, BotPlugins, BotStatus};
use crate::bot::physics::Physics;
use crate::bot::terminal::{BotCommand, BotTerminal};
use crate::bot::transmitter::{BotPackage, BotTransmitter, NullPackage};
use crate::bot::world::entity::Entity;
use crate::bot::world::{Storage, StorageLock};
use crate::utils::time::{sleep, timestamp};

/// Основная структура бота, состояния, компоненты, методы подключения -
/// всё хранится именно здесь. Данный объект содержит в себе всю
/// информацию о мире (`Storage`), но при запуске роя бот будет отправлять
/// все данные в `SharedStorage` (если в `Swarm` значение у
/// флага `use_shared_storage` является `true` для этого бота).
///
/// Пример создания и подключения бота к серверу:
/// ```rust, ignore
/// // Создаём бота
/// let mut bot = create_bot("NurtexBot");
///
/// // Подключаем бота к серверу
/// bot.connect_to("server.com", 25565).await?;
/// ```
pub struct Bot<P: BotPackage = NullPackage> {
  /// Статус подключения бота
  pub status: BotStatus,

  /// Юзернейм бота
  pub username: String,

  /// UUID бота
  pub uuid: Uuid,

  /// Подключение бота в состоянии Play
  pub connection: Option<Connection<ClientboundGamePacket, ServerboundGamePacket>>,

  /// Компоненты бота
  pub components: BotComponents,

  /// Плагины бота и их настройки
  pub plugins: BotPlugins,

  /// Local-хранилище бота
  pub local_storage: StorageLock,

  /// Shared-хранилище бота (опциональное)
  pub shared_storage: Option<StorageLock>,

  /// Физика бота
  pub physics: Physics,

  terminal: Arc<BotTerminal>,
  transmitter: Arc<BotTransmitter<P>>,
  transmitter_interval: u64,
  connection_timeout: u64,
  proxy: Option<Proxy>,
  information: BotInformation,
  command_receiver: mpsc::Receiver<BotCommand>,
  packet_processor: PacketProcessorFn<P>,
  event_invoker: Arc<EventInvoker>,
}

impl<P: BotPackage> Bot<P> {
  /// Метод создания нового бота.
  ///
  /// Пример использования:
  /// ```rust, ignore  
  /// // Создаём и настраиваем бота
  /// let mut bot: Bot<NullPackage> = Bot::create("NurtexBot".to_string())
  ///   .set_connection_timeout(30000)
  ///   .set_information(BotInformation {
  ///     client: ClientInformation {
  ///       main_hand: HumanoidArm::Left,
  ///       ..Default::default()
  ///     },
  ///     ..Default::default(),
  ///   });
  ///
  /// // Подключаем бота к серверу
  /// bot.connect_to("server.com", 25565).await?;
  /// ```
  pub fn create(username: String) -> Self {
    let (command_tx, command_rx) = mpsc::channel(30);

    let bot = Self {
      status: BotStatus::Offline,
      terminal: Arc::new(BotTerminal {
        username: username.clone(),
        cmd: command_tx,
      }),
      username: username,
      uuid: Uuid::nil(),
      connection: None,
      local_storage: Arc::new(RwLock::new(Storage::new())),
      shared_storage: None,
      components: BotComponents::default(),
      plugins: BotPlugins::default(),
      information: BotInformation::default(),
      physics: Physics::default(),
      transmitter: Arc::new(BotTransmitter::new(30)),
      transmitter_interval: 500,
      connection_timeout: 14000,
      proxy: None,
      command_receiver: command_rx,
      packet_processor: default_packet_processor,
      event_invoker: Arc::new(EventInvoker::new()),
    };

    bot
  }

  /// Метод запуска бота, который возвращает JoinHandle и не блокирует поток.
  pub fn spawn(mut self, server_host: &str, server_port: u16) -> JoinHandle<io::Result<()>> {
    let host = server_host.to_string();

    tokio::spawn(async move { self.connect_to(&host, server_port).await })
  }

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

  /// Метод установки прокси
  pub fn set_proxy(mut self, proxy: Proxy) -> Self {
    self.proxy = Some(proxy);
    self
  }

  /// Метод установки UUID
  pub fn set_uuid(mut self, uuid: Uuid) -> Self {
    self.uuid = uuid;
    self
  }

  /// Метод установки информации бота
  pub fn set_information(mut self, information: BotInformation) -> Self {
    self.information = information;
    self
  }

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

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

  /// Метод установки shared-хранилища
  pub fn set_shared_storage(mut self, storage: StorageLock) -> Self {
    self.shared_storage = Some(storage);
    self
  }

  /// Метод установки обработчика пакетов
  pub fn set_packet_processor(mut self, processor: PacketProcessorFn<P>) -> Self {
    self.packet_processor = processor;
    self
  }

  /// Метод установки инициатора событий
  pub fn set_event_invoker(mut self, invoker: EventInvoker) -> Self {
    self.event_invoker = Arc::new(invoker);
    self
  }

  /// Метод получения ссылки на информацию бота
  pub fn get_information_ref(&self) -> &BotInformation {
    &self.information
  }

  /// Метод отправки события всем получателям
  pub fn emit_event(&self, event: BotEvent) {
    let invoker = self.event_invoker.clone();
    let terminal = self.terminal.clone();

    tokio::spawn(async move {
      invoker.trigger(terminal.clone(), event).await;
    });
  }

  /// Метод создания подключения
  async fn create_connection(&self, address: SocketAddr) -> io::Result<Connection<ClientboundHandshakePacket, ServerboundHandshakePacket>> {
    let result = if let Some(proxy) = &self.proxy {
      Connection::new_with_proxy(&address, proxy.clone()).await
    } else {
      Connection::new(&address).await
    };

    result.map_err(|err| Error::new(ErrorKind::ConnectionRefused, err.to_string()))
  }

  /// Метод создания соединения с сервером и запуска цикла событий
  async fn start(&mut self, server_host: &str, server_port: u16) -> io::Result<()> {
    self.connection = None;

    let address_string = format!("{}:{}", server_host, server_port);

    let Some(address) = (match address_string.to_socket_addrs() {
      Ok(mut i) => i.next(),
      Err(err) => return Err(err),
    }) else {
      return Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Failed to retrieve socket address"));
    };

    let connection_result = timeout(Duration::from_millis(self.connection_timeout), self.perform_connection(address, server_host, server_port)).await;

    match connection_result {
      Ok(Ok(conn)) => {
        self.connection = Some(conn);
        self.status = BotStatus::Online;
        self.event_loop().await?;
        Ok(())
      }
      Ok(Err(err)) => Err(err),
      Err(_) => Err(io::Error::new(
        io::ErrorKind::TimedOut,
        format!("Failed to get a response from the server within the timeout period ({} ms)", self.connection_timeout),
      )),
    }
  }

  /// Метод полного процесса подключения бота к серверу
  async fn perform_connection(&mut self, address: SocketAddr, server_host: &str, server_port: u16) -> io::Result<Connection<ClientboundGamePacket, ServerboundGamePacket>> {
    let mut conn = self.create_connection(address).await?;

    self.status = BotStatus::Connecting;

    conn
      .write(ServerboundIntention {
        protocol_version: PROTOCOL_VERSION,
        hostname: server_host.to_string(),
        port: server_port,
        intention: ClientIntention::Login,
      })
      .await?;

    let mut conn = conn.login();
    conn
      .write(ServerboundHello {
        name: self.username.clone(),
        profile_id: self.uuid,
      })
      .await?;

    process_login(&mut conn).await?;
    conn.write(ServerboundLoginAcknowledged {}).await?;

    self.emit_event(BotEvent::LoginFinished);

    let mut conn = conn.config();
    process_configuration(self, &mut conn).await?;

    self.emit_event(BotEvent::ConfigurationFinished);

    let conn = conn.game();

    Ok(conn)
  }

  /// Метод, который подключает бота к серверу, ловит его ошибки и корректно обрабатывает их
  pub async fn connect_to(&mut self, server_host: &str, server_port: u16) -> io::Result<()> {
    loop {
      match self.start(server_host, server_port).await {
        Ok(_) => {
          break;
        }
        Err(err) => match err.kind() {
          ErrorKind::ConnectionRefused | ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted | ErrorKind::NotConnected | ErrorKind::TimedOut => {
            self.emit_event(BotEvent::Disconnect(DisconnectPayload {
              reason: err.to_string(),
              timestamp: timestamp(),
            }));

            self.status = BotStatus::Offline;

            if self.plugins.auto_reconnect.enabled {
              sleep(self.plugins.auto_reconnect.reconnect_delay).await;
            } else {
              return Err(err);
            }
          }
          _ => {
            return Err(err);
          }
        },
      }
    }

    Ok(())
  }

  /// Метод основного цикла событий
  async fn event_loop(&mut self) -> io::Result<()> {
    let mut tick_interval = tokio::time::interval(tokio::time::Duration::from_millis(50));
    tick_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

    let mut transmitter_interval = tokio::time::interval(tokio::time::Duration::from_millis(self.transmitter_interval));
    transmitter_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

    loop {
      if self.status != BotStatus::Online {
        return Ok(());
      }

      let Some(conn) = &mut self.connection else {
        continue;
      };

      tokio::select! {
        // Обработка пакета
        result = conn.read() => {
          match result {
            Ok(p) => {
              let packet: Arc<ClientboundGamePacket> = Arc::new(p);

              self.emit_event(BotEvent::Packet(PacketPayload {
                packet: packet.clone(),
                timestamp: timestamp()
              }));

              match (self.packet_processor)(self, packet).await {
                Ok(true) => continue,
                Ok(false) => return Ok(()),
                Err(e) => return Err(e),
              }
            }
            Err(_) => {}
          }
        }

        // Обработка внешней команды
        Some(command) = self.command_receiver.recv() => {
          match Box::pin(self.process_command(command)).await {
            Ok(true) => continue,
            Ok(false) => return Ok(()),
            Err(e) => return Err(e),
          }
        }

        // Обработка физического тика
        _ = tick_interval.tick() => {
          if let Err(e) = self.tick().await {
            return Err(e);
          }
        }

        // Обработка тика передатчика
        _ = transmitter_interval.tick() => {
          self.emit_package();
        }
      }
    }
  }

  /// Метод проверки некого Entity ID на сходство с Entity ID текущего бота
  pub fn is_this_my_entity_id(&self, id: i32) -> bool {
    self.components.profile.entity_id.map_or(false, |entity_id| entity_id == id)
  }

  /// Метод выполнения определённых операций в физический тик
  async fn tick(&mut self) -> io::Result<()> {
    let Some(conn) = &mut self.connection else {
      return Err(Error::new(ErrorKind::NotConnected, "Connection could not be obtained"));
    };

    if self.plugins.physics.enabled {
      let storage = self.local_storage.read().await;
      self.components.tick(conn, &mut self.physics, &storage).await?;
      drop(storage);
    }

    Ok(())
  }

  /// Метод блокировки хранилища (local / shared)
  pub async fn lock_storage<F>(&self, f: F)
  where
    F: FnOnce(&mut Storage),
  {
    if let Some(shared_storage) = &self.shared_storage {
      if let Ok(mut guard) = timeout(Duration::from_millis(10), shared_storage.write()).await {
        f(&mut *guard);
        drop(guard);
      }
    } else {
      if let Ok(mut guard) = timeout(Duration::from_millis(10), self.local_storage.write()).await {
        f(&mut *guard);
        drop(guard);
      }
    }
  }

  /// Метод очистки данных бота
  pub async fn clear(&mut self) {
    let mut storage = self.local_storage.write().await;
    storage.clear();

    self.components.inventory.containers.clear();
  }

  /// Метод закрытия TcpStream (отключение от сервера)
  pub async fn disconnect(&mut self) -> io::Result<()> {
    let Some(conn) = self.connection.take() else {
      return Err(Error::new(ErrorKind::NotConnected, "Connection could not be obtained"));
    };

    let mut stream = match conn.unwrap() {
      Ok(s) => s,
      Err(err) => {
        return Err(Error::new(ErrorKind::Other, err.to_string()));
      }
    };

    stream.shutdown().await?;

    self.clear().await;

    self.emit_event(BotEvent::Disconnect(DisconnectPayload {
      reason: "Manual disconnect".to_string(),
      timestamp: timestamp(),
    }));

    Ok(())
  }

  /// Метод переподключения бота к серверу
  pub async fn reconnect(&mut self, server_host: &str, server_port: u16, interval: u64) -> io::Result<()> {
    self.disconnect().await?;
    sleep(interval).await;
    self.connect_to(server_host, server_port).await
  }

  /// Метод отправки сообщения в чат
  pub async fn chat(&mut self, message: impl Into<String>) -> io::Result<()> {
    let Some(conn) = &mut self.connection else {
      return Err(Error::new(ErrorKind::NotConnected, "Connection could not be obtained"));
    };

    conn
      .write(ServerboundGamePacket::Chat(ServerboundChat {
        message: message.into(),
        timestamp: timestamp(),
        salt: 0,
        signature: None,
        last_seen_messages: LastSeenMessagesUpdate::default(),
      }))
      .await
  }

  /// Метод обновления позиции
  pub fn update_position(&mut self, position: Position) {
    let pos = &mut self.components.position;
    let old_pos = pos.clone();

    if old_pos == position {
      return;
    }

    *pos = position.clone();

    self.emit_event(BotEvent::UpdatePosition(PositionPayload {
      position: position,
      old_position: old_pos,
      timestamp: timestamp(),
    }));
  }

  /// Метод обновления ротации
  pub fn update_rotation(&mut self, rotation: Rotation) {
    let rot = &mut self.components.rotation;
    let old_rot = rot.clone();

    if old_rot == rotation {
      return;
    }

    *rot = rotation.clone();

    self.emit_event(BotEvent::UpdateRotation(RotationPayload {
      rotation: rotation,
      old_rotation: old_rot,
      timestamp: timestamp(),
    }));
  }

  /// Метод получения текущей позиции
  pub fn get_position(&self) -> Position {
    self.components.position
  }

  /// Метод получения текущей ротации
  pub fn get_rotation(&self) -> Rotation {
    self.components.rotation
  }

  /// Метод получения сущности игрока по его юзернейму
  pub async fn get_player_by_username(&self, username: String) -> Option<Entity> {
    let mut entity = None;

    self
      .lock_storage(|storage| {
        for (_, e) in &storage.entities {
          let Some(player_info) = &e.player_info else {
            continue;
          };

          if player_info.username == username {
            entity = Some(e.clone());
            return;
          }
        }
      })
      .await;

    entity
  }

  /// Метод получения сущности игрока по его юзернейму
  pub async fn get_entity_by_uuid(&self, uuid: Uuid) -> Option<Entity> {
    let mut entity = None;

    self
      .lock_storage(|storage| {
        for (_, e) in &storage.entities {
          if e.uuid == uuid {
            entity = Some(e.clone());
            return;
          }
        }
      })
      .await;

    entity
  }

  /// Метод отправки пакета данных
  fn emit_package(&self) {
    if self.transmitter.receiver_count() > 0 {
      let package = P::describe(self);
      self.transmitter.emit(package);
    }
  }

  /// Метод получения терминала
  pub fn get_terminal(&self) -> Arc<BotTerminal> {
    self.terminal.clone()
  }

  /// Метод получения передатчика пакетов
  pub fn get_transmitter(&self) -> Arc<BotTransmitter<P>> {
    self.transmitter.clone()
  }

  /// Метод обработки внешней команды
  async fn process_command(&mut self, command: BotCommand) -> io::Result<bool> {
    let Some(conn) = &mut self.connection else {
      return Err(Error::new(ErrorKind::NotConnected, "Connection could not be obtained"));
    };

    match command {
      BotCommand::Chat(message) => {
        self.chat(message).await?;
      }
      BotCommand::SetDirection { yaw, pitch } => {
        conn
          .write(ServerboundGamePacket::MovePlayerRot(ServerboundMovePlayerRot {
            look_direction: LookDirection::new(yaw, pitch),
            flags: MoveFlags {
              on_ground: self.physics.on_ground,
              horizontal_collision: false,
            },
          }))
          .await?;
      }
      BotCommand::SetPosition { x, y, z } => {
        conn
          .write(ServerboundGamePacket::MovePlayerPos(ServerboundMovePlayerPos {
            pos: Vec3::new(x, y, z),
            flags: MoveFlags {
              on_ground: self.physics.on_ground,
              horizontal_collision: false,
            },
          }))
          .await?;
      }
      BotCommand::SwingArm(hand) => {
        conn.write(ServerboundGamePacket::Swing(ServerboundSwing { hand })).await?;
      }
      BotCommand::StartUseItem(hand) => {
        let rotation = self.components.rotation;

        conn
          .write(ServerboundGamePacket::UseItem(ServerboundUseItem {
            hand: hand,
            seq: 0,
            y_rot: rotation.yaw,
            x_rot: rotation.pitch,
          }))
          .await?;
      }
      BotCommand::ReleaseUseItem => {
        conn
          .write(ServerboundGamePacket::PlayerAction(ServerboundPlayerAction {
            action: Action::ReleaseUseItem,
            pos: BlockPos::new(0, 0, 0),
            direction: Direction::Down,
            seq: 0,
          }))
          .await?;
      }
      BotCommand::SendPacket(packet) => {
        conn.write(packet).await?;
      }
      BotCommand::Disconnect => {
        self.disconnect().await?;
        return Ok(false);
      }
      BotCommand::Reconnect {
        server_host,
        server_port,
        interval,
      } => {
        self.reconnect(&server_host, server_port, interval).await?;
      }
    }

    Ok(true)
  }
}