Skip to content

Commit

Permalink
make testbot take cli args
Browse files Browse the repository at this point in the history
  • Loading branch information
mat-1 committed Dec 23, 2024
1 parent 478fe72 commit 3b1fe49
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 20 deletions.
7 changes: 7 additions & 0 deletions azalea-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ impl TryFrom<&str> for ServerAddress {
Ok(ServerAddress { host, port })
}
}
impl TryFrom<String> for ServerAddress {
type Error = String;

fn try_from(string: String) -> Result<Self, Self::Error> {
ServerAddress::try_from(string.as_str())
}
}

impl From<SocketAddr> for ServerAddress {
/// Convert an existing `SocketAddr` into a `ServerAddress`. This just
Expand Down
79 changes: 59 additions & 20 deletions azalea/examples/testbot/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//!
//! Usage:
//! - Modify the consts below if necessary.
//! - Run `cargo r --example testbot`
//! - Run `cargo r --example testbot -- --owner <owner> --name <username/email>
//! --address <address>`.
//! - 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
Expand All @@ -15,6 +16,7 @@ mod commands;
pub mod killaura;

use std::time::Duration;
use std::{env, process};
use std::{sync::Arc, thread};

use azalea::brigadier::command_dispatcher::CommandDispatcher;
Expand All @@ -26,38 +28,35 @@ 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() {
let args = parse_args();

thread::spawn(deadlock_detection_thread);

let account = Account::offline(USERNAME);
let account = if args.name.contains('@') {
Account::microsoft(&args.name).await.unwrap()
} else {
Account::offline(&args.name)
};

let mut commands = CommandDispatcher::new();
register_commands(&mut commands);
let commands = Arc::new(commands);

let join_address = args.address.clone();

let builder = SwarmBuilder::new();
builder
.set_handler(handle)
.set_swarm_handler(swarm_handle)
.add_account_with_state(
account,
State {
commands: commands.clone(),
..Default::default()
},
)
.add_account_with_state(account, State::new(args, commands))
.join_delay(Duration::from_millis(100))
.start(ADDRESS)
.start(join_address)
.await
.unwrap();
}
Expand Down Expand Up @@ -92,17 +91,19 @@ pub enum BotTask {
None,
}

#[derive(Component, Clone)]
#[derive(Component, Clone, Default)]
pub struct State {
pub args: Args,
pub commands: Arc<CommandDispatcher<Mutex<CommandSource>>>,
pub killaura: bool,
pub task: Arc<Mutex<BotTask>>,
}

impl Default for State {
fn default() -> Self {
impl State {
fn new(args: Args, commands: CommandDispatcher<Mutex<CommandSource>>) -> Self {
Self {
commands: Arc::new(CommandDispatcher::new()),
args,
commands: Arc::new(commands),
killaura: true,
task: Arc::new(Mutex::new(BotTask::None)),
}
Expand Down Expand Up @@ -131,7 +132,7 @@ async fn handle(bot: Client, event: azalea::Event, state: State) -> anyhow::Resu
let (Some(username), content) = chat.split_sender_and_content() else {
return Ok(());
};
if username != OWNER_USERNAME {
if username != state.args.owner {
return Ok(());
}

Expand Down Expand Up @@ -201,3 +202,41 @@ async fn swarm_handle(

Ok(())
}

#[derive(Debug, Clone, Default)]
pub struct Args {
pub owner: String,
pub name: String,
pub address: String,
}

fn parse_args() -> Args {
let mut owner_username = None;
let mut bot_username = None;
let mut address = None;

let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--owner" | "-O" => {
owner_username = args.next();
}
"--name" | "-N" => {
bot_username = args.next();
}
"--address" | "-A" => {
address = args.next();
}
_ => {
eprintln!("Unknown argument: {}", arg);
process::exit(1);
}
}
}

Args {
owner: owner_username.unwrap_or_else(|| "admin".to_string()),
name: bot_username.unwrap_or_else(|| "azalea".to_string()),
address: address.unwrap_or_else(|| "localhost".to_string()),
}
}
1 change: 1 addition & 0 deletions azalea/src/swarm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ where
handler: Some(Box::new(move |bot, event, state: S| {
Box::pin(handler(bot, event, state))
})),
// if we added accounts before the State was set, we've gotta set it to the default now
states: vec![S::default(); self.accounts.len()],
app: self.app,
..self
Expand Down

0 comments on commit 3b1fe49

Please sign in to comment.