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
|
//! A relatively simple bot for demonstrating some of Azalea's capabilities.
//!
//! Usage:
//! - Modify the consts below if necessary.
//! - Run `cargo r --example testbot`
//! - Commands are prefixed with `!` in chat. You can send them either in public
//! chat or as a /msg.
//! - Some commands to try are `!goto`, `!killaura true`, `!down`. Check the
//! `commands` directory to see all of them.
#![feature(async_closure)]
#![feature(trivial_bounds)]
mod commands;
pub mod killaura;
use std::sync::Arc;
use std::time::Duration;
use azalea::brigadier::command_dispatcher::CommandDispatcher;
use azalea::ecs::prelude::*;
use azalea::pathfinder::PathfinderDebugParticles;
use azalea::prelude::*;
use azalea::swarm::prelude::*;
use azalea::ClientInformation;
use commands::{register_commands, CommandSource};
use parking_lot::Mutex;
const USERNAME: &str = "azalea";
const ADDRESS: &str = "localhost";
/// The bot will only listen to commands sent by the player with this username.
const OWNER_USERNAME: &str = "py5";
/// Whether the bot should run /particle a ton of times to show where it's
/// pathfinding to. You should only have this on if the bot has operator
/// permissions, otherwise it'll just spam the server console unnecessarily.
const PATHFINDER_DEBUG_PARTICLES: bool = false;
#[tokio::main]
async fn main() {
{
use std::thread;
use std::time::Duration;
use parking_lot::deadlock;
// Create a background thread which checks for deadlocks every 10s
thread::spawn(move || loop {
thread::sleep(Duration::from_secs(10));
let deadlocks = deadlock::check_deadlock();
if deadlocks.is_empty() {
continue;
}
println!("{} deadlocks detected", deadlocks.len());
for (i, threads) in deadlocks.iter().enumerate() {
println!("Deadlock #{i}");
for t in threads {
println!("Thread Id {:#?}", t.thread_id());
println!("{:#?}", t.backtrace());
}
}
});
}
let account = Account::offline(USERNAME);
let mut commands = CommandDispatcher::new();
register_commands(&mut commands);
let commands = Arc::new(commands);
let builder = SwarmBuilder::new();
builder
.set_handler(handle)
.set_swarm_handler(swarm_handle)
.add_account_with_state(
account,
State {
commands: commands.clone(),
..Default::default()
},
)
.join_delay(Duration::from_millis(100))
.start(ADDRESS)
.await
.unwrap();
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BotTask {
#[default]
None,
}
#[derive(Component, Clone)]
pub struct State {
pub commands: Arc<CommandDispatcher<Mutex<CommandSource>>>,
pub killaura: bool,
pub task: Arc<Mutex<BotTask>>,
}
impl Default for State {
fn default() -> Self {
Self {
commands: Arc::new(CommandDispatcher::new()),
killaura: true,
task: Arc::new(Mutex::new(BotTask::None)),
}
}
}
#[derive(Resource, Default, Clone)]
struct SwarmState;
async fn handle(bot: Client, event: azalea::Event, state: State) -> anyhow::Result<()> {
match event {
azalea::Event::Init => {
bot.set_client_information(ClientInformation {
view_distance: 32,
..Default::default()
})
.await?;
if PATHFINDER_DEBUG_PARTICLES {
bot.ecs
.lock()
.entity_mut(bot.entity)
.insert(PathfinderDebugParticles);
}
}
azalea::Event::Chat(chat) => {
let (Some(username), content) = chat.split_sender_and_content() else {
return Ok(());
};
if username != OWNER_USERNAME {
return Ok(());
}
println!("{:?}", chat.message());
let command = if chat.is_whisper() {
Some(content)
} else {
content.strip_prefix('!').map(|s| s.to_owned())
};
if let Some(command) = command {
match state.commands.execute(
command,
Mutex::new(CommandSource {
bot: bot.clone(),
chat: chat.clone(),
state: state.clone(),
}),
) {
Ok(_) => {}
Err(err) => {
eprintln!("{err:?}");
let command_source = CommandSource {
bot,
chat: chat.clone(),
state: state.clone(),
};
command_source.reply(&format!("{err:?}"));
}
}
}
}
azalea::Event::Tick => {
killaura::tick(bot.clone(), state.clone())?;
let task = *state.task.lock();
match task {
BotTask::None => {}
}
}
_ => {}
}
Ok(())
}
async fn swarm_handle(
mut swarm: Swarm,
event: SwarmEvent,
_state: SwarmState,
) -> anyhow::Result<()> {
match &event {
SwarmEvent::Disconnect(account, join_opts) => {
println!("bot got kicked! {}", account.username);
tokio::time::sleep(Duration::from_secs(5)).await;
swarm
.add_and_retry_forever_with_opts(account, State::default(), join_opts)
.await;
}
SwarmEvent::Chat(chat) => {
if chat.message().to_string() == "The particle was not visible for anybody" {
return Ok(());
}
println!("{}", chat.message().to_ansi());
}
_ => {}
}
Ok(())
}
|