Compare commits

..

No commits in common. "73db39c8b2e3358f08ac12b3391c9d5bc75e5eac" and "571581767ec6f8a4c6b25619a99d267c658cde0f" have entirely different histories.

20 changed files with 55 additions and 2187 deletions

View File

@ -10,17 +10,12 @@ on:
jobs: jobs:
errornowatcher: errornowatcher:
name: errornowatcher (${{ matrix.os }}, ${{ matrix.feature.name }}) name: errornowatcher (${{ matrix.os }})
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-24.04, ubuntu-24.04-arm] os: [ubuntu-24.04, ubuntu-24.04-arm]
feature:
- name: default
- name: mimalloc
flags: "-F mimalloc"
steps: steps:
- name: Clone repository - name: Clone repository
@ -38,16 +33,16 @@ jobs:
~/.cargo/registry/cache/ ~/.cargo/registry/cache/
~/.cargo/git/db/ ~/.cargo/git/db/
target/ target/
key: build-${{ matrix.os }}-${{ matrix.feature.name }}-${{ hashFiles('**.toml', 'Cargo.*') }} key: build-${{ matrix.os }}-${{ hashFiles('**.toml', 'Cargo.*') }}
- name: Switch to nightly toolchain - name: Switch to nightly toolchain
run: rustup default nightly run: rustup default nightly
- name: Build in release mode - name: Build in release mode
run: cargo build --release ${{ matrix.feature.flags }} run: cargo build --release
- name: Upload build artifacts - name: Upload build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: errornowatcher_${{ matrix.feature.name }}_${{ matrix.os }} name: errornowatcher_${{ matrix.os }}
path: target/release/errornowatcher path: target/release/errornowatcher

View File

@ -28,23 +28,9 @@ jobs:
run: taplo fmt --check Cargo.toml run: taplo fmt --check Cargo.toml
rust: rust:
name: Rust (${{ matrix.feature.name }}) name: Rust
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
strategy:
matrix:
feature:
- name: default
- name: minimal-mimalloc
flags: "--no-default-features -F mimalloc"
- name: minimal
flags: "--no-default-features"
- name: mimalloc
flags: "-F mimalloc"
steps: steps:
- name: Clone repository - name: Clone repository
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -61,7 +47,7 @@ jobs:
~/.cargo/registry/cache/ ~/.cargo/registry/cache/
~/.cargo/git/db/ ~/.cargo/git/db/
target/ target/
key: build-${{ matrix.os }}-${{ matrix.feature.name }}-${{ hashFiles('**.toml', 'Cargo.*') }} key: build-${{ matrix.os }}-${{ hashFiles('**.toml', 'Cargo.*') }}
- name: Switch to nightly toolchain - name: Switch to nightly toolchain
run: rustup default nightly run: rustup default nightly
@ -69,8 +55,8 @@ jobs:
- name: Install components - name: Install components
run: rustup component add clippy rustfmt run: rustup component add clippy rustfmt
- name: cargo clippy ${{ matrix.feature.flags }} - name: cargo clippy
run: cargo clippy ${{ matrix.feature.flags }} -- -D warnings -D clippy::pedantic run: cargo clippy -- -D clippy::pedantic
- name: cargo fmt - name: cargo fmt
if: always() if: always()

1713
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -28,14 +28,12 @@ bevy_log = "0"
clap = { version = "4", features = ["derive", "string"] } clap = { version = "4", features = ["derive", "string"] }
console-subscriber = { version = "0", optional = true } console-subscriber = { version = "0", optional = true }
ctrlc = { version = "3", features = ["termination"] } ctrlc = { version = "3", features = ["termination"] }
dirs = "6"
futures = "0" futures = "0"
futures-locks = "0" futures-locks = "0"
http-body-util = "0" http-body-util = "0"
hyper = { version = "1", features = ["server"] } hyper = { version = "1", features = ["server"] }
hyper-util = "0" hyper-util = "0"
log = { version = "0" } log = { version = "0" }
matrix-sdk = { version = "0", optional = true }
mimalloc = { version = "0", optional = true } mimalloc = { version = "0", optional = true }
mlua = { version = "0", features = ["async", "luajit", "send"] } mlua = { version = "0", features = ["async", "luajit", "send"] }
ncr = { version = "0", features = ["cfb8", "ecb", "gcm"] } ncr = { version = "0", features = ["cfb8", "ecb", "gcm"] }
@ -45,7 +43,5 @@ tokio = { version = "1", features = ["macros"] }
zip = { version = "2", default-features = false, features = ["flate2"] } zip = { version = "2", default-features = false, features = ["flate2"] }
[features] [features]
default = ["matrix"]
console-subscriber = ["dep:console-subscriber"] console-subscriber = ["dep:console-subscriber"]
mimalloc = ["dep:mimalloc"] mimalloc = ["dep:mimalloc"]
matrix = ["dep:matrix-sdk"]

View File

@ -7,14 +7,12 @@ A Minecraft bot with Lua scripting support, written in Rust with [azalea](https:
- Running Lua from - Running Lua from
- `errornowatcher.lua` - `errornowatcher.lua`
- in-game chat messages - in-game chat messages
- Matrix chat messages
- POST requests to HTTP server - POST requests to HTTP server
- Listening to in-game events - Listening to in-game events
- Pathfinding (from azalea) - Pathfinding (from azalea)
- Entity and chest interaction - Entity and chest interaction
- NoChatReports encryption - NoChatReports encryption
- Saving ReplayMod recordings - Saving ReplayMod recordings
- Matrix integration
## Usage ## Usage

View File

@ -2,7 +2,6 @@ Server = "localhost"
Username = "ErrorNoWatcher" Username = "ErrorNoWatcher"
HttpAddress = "127.0.0.1:8080" HttpAddress = "127.0.0.1:8080"
Owners = { "ErrorNoInternet" } Owners = { "ErrorNoInternet" }
MatrixOwners = { "@errornointernet:envs.net" }
for _, module in ipairs({ for _, module in ipairs({
"lib", "lib",

View File

@ -45,28 +45,30 @@ function entity_speed(uuid, seconds)
return speed return speed
end end
function tps(ms) function tps(seconds)
if not ms then if not seconds then
ms = 1000 seconds = 1
end end
add_listener("tick", function() add_listener("tick", function()
if not TpsTracking.ticks then if not TpsTracking.ticks then
TpsTracking.ticks = 0 TpsTracking.ticks = 0
sleep(ms) TpsTracking.start = clock_gettime(0)
TpsTracking.result = TpsTracking.ticks
remove_listeners("tick", "tps_tracking")
else else
TpsTracking.ticks = TpsTracking.ticks + 1 TpsTracking.ticks = TpsTracking.ticks + 1
if TpsTracking.ticks >= seconds * 20 then
TpsTracking.stop = clock_gettime(0)
remove_listeners("tick", "tps_tracking")
end
end end
end, "tps_tracking") end, "tps_tracking")
sleep(ms) sleep(seconds * 1000)
repeat repeat
sleep(20) sleep(20)
until TpsTracking.result until TpsTracking.stop
local tps = TpsTracking.result / (ms / 1000) local tps = seconds * 20 / (TpsTracking.stop - TpsTracking.start)
TpsTracking = {} TpsTracking = {}
return tps return tps
end end

View File

@ -19,9 +19,6 @@ use ncr::utils::trim_header;
use std::{net::SocketAddr, process::exit}; use std::{net::SocketAddr, process::exit};
use tokio::net::TcpListener; use tokio::net::TcpListener;
#[cfg(feature = "matrix")]
use crate::matrix;
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
pub async fn handle_event(client: Client, event: Event, state: State) -> Result<()> { pub async fn handle_event(client: Client, event: Event, state: State) -> Result<()> {
match event { match event {
@ -213,9 +210,6 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
let globals = state.lua.globals(); let globals = state.lua.globals();
lua_init(client, &state, &globals).await?; lua_init(client, &state, &globals).await?;
#[cfg(feature = "matrix")]
matrix_init(state.clone(), &globals);
let Some(address): Option<SocketAddr> = globals let Some(address): Option<SocketAddr> = globals
.get::<String>("HttpAddress") .get::<String>("HttpAddress")
.ok() .ok()
@ -275,21 +269,7 @@ async fn lua_init(client: Client, state: &State, globals: &Table) -> Result<()>
call_listeners(state, "init", || Ok(())).await call_listeners(state, "init", || Ok(())).await
} }
#[cfg(feature = "matrix")] async fn call_listeners<T, F>(state: &State, event_type: &'static str, getter: F) -> Result<()>
fn matrix_init(state: State, globals: &Table) {
if let Ok(homeserver_url) = globals.get::<String>("MatrixHomeserverUrl")
&& let Ok(username) = globals.get::<String>("MatrixUsername")
&& let Ok(password) = globals.get::<String>("MatrixPassword")
{
tokio::spawn(async move {
if let Err(error) = matrix::login(state, homeserver_url, username, &password).await {
error!("failed to log into matrix account: {error:?}");
}
});
}
}
pub async fn call_listeners<T, F>(state: &State, event_type: &'static str, getter: F) -> Result<()>
where where
T: Clone + IntoLuaMulti + Send + 'static, T: Clone + IntoLuaMulti + Send + 'static,
F: FnOnce() -> Result<T>, F: FnOnce() -> Result<T>,

View File

@ -1,5 +1,5 @@
use azalea::entity::LookDirection; use azalea::entity::LookDirection;
use mlua::{Error, FromLua, IntoLua, Lua, Result, Value}; use mlua::{FromLua, IntoLua, Lua, Result, Value};
#[derive(Clone)] #[derive(Clone)]
pub struct Direction { pub struct Direction {
@ -37,7 +37,7 @@ impl FromLua for Direction {
} }
}) })
} else { } else {
Err(Error::FromLuaConversionError { Err(mlua::Error::FromLuaConversionError {
from: value.type_name(), from: value.type_name(),
to: "Direction".to_string(), to: "Direction".to_string(),
message: None, message: None,

View File

@ -1,27 +0,0 @@
use super::room::Room;
use matrix_sdk::{Client as MatrixClient, ruma::UserId};
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
use std::sync::Arc;
pub struct Client(pub Arc<MatrixClient>);
impl UserData for Client {
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
f.add_field_method_get("rooms", |_, this| {
Ok(this.0.rooms().into_iter().map(Room).collect::<Vec<_>>())
});
f.add_field_method_get("user_id", |_, this| {
Ok(this.0.user_id().map(std::string::ToString::to_string))
});
}
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
m.add_async_method("create_dm", async |_, this, user_id: String| {
this.0
.create_dm(&UserId::parse(user_id).map_err(Error::external)?)
.await
.map_err(Error::external)
.map(Room)
});
}
}

View File

@ -1,12 +0,0 @@
use matrix_sdk::room::RoomMember;
use mlua::{UserData, UserDataFields};
pub struct Member(pub RoomMember);
impl UserData for Member {
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
f.add_field_method_get("id", |_, this| Ok(this.0.user_id().to_string()));
f.add_field_method_get("name", |_, this| Ok(this.0.name().to_owned()));
f.add_field_method_get("power_level", |_, this| Ok(this.0.power_level()));
}
}

View File

@ -1,3 +0,0 @@
pub mod client;
pub mod member;
pub mod room;

View File

@ -1,43 +0,0 @@
use super::member::Member;
use matrix_sdk::{
RoomMemberships, room::Room as MatrixRoom, ruma::events::room::message::RoomMessageEventContent,
};
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
pub struct Room(pub MatrixRoom);
impl UserData for Room {
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
f.add_field_method_get("id", |_, this| Ok(this.0.room_id().to_string()));
f.add_field_method_get("name", |_, this| Ok(this.0.name()));
f.add_field_method_get("topic", |_, this| Ok(this.0.topic()));
f.add_field_method_get("type", |_, this| {
Ok(this.0.room_type().map(|room_type| room_type.to_string()))
});
}
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
m.add_async_method("send", async |_, this, body: String| {
this.0
.send(RoomMessageEventContent::text_plain(body))
.await
.map_err(Error::external)
.map(|response| response.event_id.to_string())
});
m.add_async_method("leave", async |_, this, (): ()| {
this.0.leave().await.map_err(Error::external)
});
m.add_async_method("get_members", async |_, this, (): ()| {
this.0
.members(RoomMemberships::all())
.await
.map_err(Error::external)
.map(|members| {
members
.into_iter()
.map(|member| Member(member.clone()))
.collect::<Vec<_>>()
})
});
}
}

View File

@ -10,9 +10,6 @@ pub mod system;
pub mod thread; pub mod thread;
pub mod vec3; pub mod vec3;
#[cfg(feature = "matrix")]
pub mod matrix;
use crate::{ListenerMap, build_info::built}; use crate::{ListenerMap, build_info::built};
use mlua::{Lua, Table}; use mlua::{Lua, Table};
use std::io; use std::io;

View File

@ -1,9 +1,9 @@
use mlua::{UserData, UserDataFields}; use mlua::UserData;
pub struct AesKey(pub ncr::AesKey); pub struct AesKey(pub ncr::AesKey);
impl UserData for AesKey { impl UserData for AesKey {
fn add_fields<F: UserDataFields<Self>>(f: &mut F) { fn add_fields<F: mlua::UserDataFields<Self>>(f: &mut F) {
f.add_field_method_get("base64", |_, this| Ok(this.0.encode_base64())); f.add_field_method_get("base64", |_, this| Ok(this.0.encode_base64()));
f.add_field_method_get("bytes", |_, this| Ok(this.0.as_ref().to_vec())); f.add_field_method_get("bytes", |_, this| Ok(this.0.as_ref().to_vec()));
} }

View File

@ -1,5 +1,5 @@
use azalea::{BlockPos, entity::Position}; use azalea::{BlockPos, entity::Position};
use mlua::{Error, FromLua, IntoLua, Lua, Result, Value}; use mlua::{FromLua, IntoLua, Lua, Result, Value};
#[derive(Clone)] #[derive(Clone)]
pub struct Vec3 { pub struct Vec3 {
@ -63,7 +63,7 @@ impl FromLua for Vec3 {
}, },
) )
} else { } else {
Err(Error::FromLuaConversionError { Err(mlua::Error::FromLuaConversionError {
from: value.type_name(), from: value.type_name(),
to: "Vec3".to_string(), to: "Vec3".to_string(),
message: None, message: None,

View File

@ -1,4 +1,4 @@
#![feature(if_let_guard, let_chains)] #![feature(let_chains)]
mod arguments; mod arguments;
mod build_info; mod build_info;
@ -9,9 +9,6 @@ mod lua;
mod particle; mod particle;
mod replay; mod replay;
#[cfg(feature = "matrix")]
mod matrix;
use anyhow::Context; use anyhow::Context;
use arguments::Arguments; use arguments::Arguments;
use azalea::{ use azalea::{

View File

@ -1,125 +0,0 @@
use super::{COMMAND_PREFIX, Context};
use crate::{
events::call_listeners,
lua::{self, matrix::room::Room as LuaRoom},
};
use anyhow::Result;
use log::{debug, error};
use matrix_sdk::{
Client, Room, RoomState,
event_handler::Ctx,
ruma::events::room::{
member::StrippedRoomMemberEvent,
message::{MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent},
},
};
use std::time::Duration;
use tokio::time::sleep;
pub async fn on_regular_room_message(
event: OriginalSyncRoomMessageEvent,
room: Room,
ctx: Ctx<Context>,
) -> Result<()> {
if room.state() != RoomState::Joined {
return Ok(());
}
let MessageType::Text(text_content) = event.content.msgtype else {
return Ok(());
};
if ctx
.state
.lua
.globals()
.get::<Vec<String>>("MatrixOwners")
.unwrap_or_default()
.contains(&event.sender.to_string())
&& text_content.body.starts_with(COMMAND_PREFIX)
{
let body = text_content.body[COMMAND_PREFIX.len()..]
.trim_start_matches(':')
.trim();
let split = body.split_once(char::is_whitespace).unzip();
let code = split
.1
.map(|body| body.trim_start_matches("```lua").trim_matches(['`', '\n']));
let mut output = None;
match split.0.unwrap_or(body).to_lowercase().as_str() {
"reload" => output = Some(format!("{:#?}", lua::reload(&ctx.state.lua, None))),
"eval" if let Some(code) = code => {
output = Some(format!(
"{:#?}",
lua::eval(&ctx.state.lua, code, None).await
));
}
"exec" if let Some(code) = code => {
output = Some(format!(
"{:#?}",
lua::exec(&ctx.state.lua, code, None).await
));
}
"ping" => {
room.send(RoomMessageEventContent::text_plain("pong!"))
.await?;
}
_ => (),
}
if let Some(output) = output {
room.send(RoomMessageEventContent::text_html(
&output,
format!("<pre><code>{output}</code></pre>"),
))
.await?;
}
}
call_listeners(&ctx.state, "matrix_chat", || {
let table = ctx.state.lua.create_table()?;
table.set("room", LuaRoom(room))?;
table.set("sender_id", event.sender.to_string())?;
table.set("body", text_content.body)?;
Ok(table)
})
.await
}
pub async fn on_stripped_state_member(
member: StrippedRoomMemberEvent,
client: Client,
room: Room,
ctx: Ctx<Context>,
) -> Result<()> {
if let Some(user_id) = client.user_id()
&& member.state_key == user_id
&& ctx
.state
.lua
.globals()
.get::<Vec<String>>("MatrixOwners")
.unwrap_or_default()
.contains(&member.sender.to_string())
{
debug!("joining room {}", room.room_id());
while let Err(error) = room.join().await {
error!(
"failed to join room {}: {error:?}, retrying...",
room.room_id()
);
sleep(Duration::from_secs(10)).await;
}
debug!("successfully joined room {}", room.room_id());
call_listeners(&ctx.state, "matrix_join_room", || {
let table = ctx.state.lua.create_table()?;
table.set("room", LuaRoom(room))?;
table.set("sender", member.sender.to_string())?;
Ok(table)
})
.await?;
}
Ok(())
}

View File

@ -1,57 +0,0 @@
mod bot;
mod verification;
use crate::{State, lua::matrix::client::Client as LuaClient};
use anyhow::Result;
use bot::{on_regular_room_message, on_stripped_state_member};
use matrix_sdk::{Client, config::SyncSettings};
use std::{fs, sync::Arc};
use verification::{on_device_key_verification_request, on_room_message_verification_request};
const COMMAND_PREFIX: &str = "ErrorNoWatcher";
#[derive(Clone)]
pub struct Context {
state: State,
}
pub async fn login(
state: State,
homeserver_url: String,
username: String,
password: &str,
) -> Result<()> {
let mut client = Client::builder().homeserver_url(homeserver_url);
if let Some(db_path) = dirs::data_dir().map(|path| path.join("errornowatcher").join("matrix"))
&& fs::create_dir_all(&db_path).is_ok()
{
client = client.sqlite_store(db_path, None);
}
let client = Arc::new(client.build().await?);
client
.matrix_auth()
.login_username(username, password)
.device_id("ERRORNOWATCHER")
.initial_device_display_name("ErrorNoWatcher")
.await?;
client.add_event_handler(on_stripped_state_member);
let response = client.sync_once(SyncSettings::default()).await?;
client.add_event_handler(on_device_key_verification_request);
client.add_event_handler(on_room_message_verification_request);
client.add_event_handler(on_regular_room_message);
state
.lua
.globals()
.set("matrix", LuaClient(client.clone()))?;
client.add_event_handler_context(Context { state });
client
.sync(SyncSettings::default().token(response.next_batch))
.await?;
Ok(())
}

View File

@ -1,158 +0,0 @@
use std::time::Duration;
use anyhow::{Context, Result};
use futures::StreamExt;
use log::{error, info, warn};
use matrix_sdk::{
Client,
crypto::{Emoji, SasState, format_emojis},
encryption::verification::{
SasVerification, Verification, VerificationRequest, VerificationRequestState,
},
ruma::{
UserId,
events::{
key::verification::request::ToDeviceKeyVerificationRequestEvent,
room::message::{MessageType, OriginalSyncRoomMessageEvent},
},
},
};
use tokio::time::sleep;
async fn confirm_emojis(sas: SasVerification, emoji: [Emoji; 7]) {
info!("\n{}", format_emojis(emoji));
warn!("automatically confirming emojis in 10 seconds");
sleep(Duration::from_secs(10)).await;
if let Err(error) = sas.confirm().await {
error!("failed to confirm emojis: {error:?}");
}
}
async fn print_devices(user_id: &UserId, client: &Client) -> Result<()> {
info!("devices of user {user_id}");
for device in client
.encryption()
.get_user_devices(user_id)
.await?
.devices()
{
if device.device_id() == client.device_id().context("missing device id")? {
continue;
}
info!(
"\t{:<10} {:<30} {:<}",
device.device_id(),
device.display_name().unwrap_or("-"),
if device.is_verified() { "" } else { "" }
);
}
Ok(())
}
async fn sas_verification_handler(client: Client, sas: SasVerification) -> Result<()> {
info!(
"starting verification with {} {}",
&sas.other_device().user_id(),
&sas.other_device().device_id()
);
print_devices(sas.other_device().user_id(), &client).await?;
sas.accept().await?;
while let Some(state) = sas.changes().next().await {
match state {
SasState::KeysExchanged {
emojis,
decimals: _,
} => {
tokio::spawn(confirm_emojis(
sas.clone(),
emojis.context("only emojis supported")?.emojis,
));
}
SasState::Done { .. } => {
let device = sas.other_device();
info!(
"successfully verified device {} {} trust {:?}",
device.user_id(),
device.device_id(),
device.local_trust_state()
);
print_devices(sas.other_device().user_id(), &client).await?;
break;
}
SasState::Cancelled(info) => {
warn!("verification cancelled: {}", info.reason());
break;
}
SasState::Created { .. }
| SasState::Started { .. }
| SasState::Accepted { .. }
| SasState::Confirmed => (),
}
}
Ok(())
}
async fn request_verification_handler(client: Client, request: VerificationRequest) {
info!(
"accepting verification request from {}",
request.other_user_id()
);
if let Err(error) = request.accept().await {
error!("failed to accept verification request: {error:?}");
return;
}
while let Some(state) = request.changes().next().await {
match state {
VerificationRequestState::Created { .. }
| VerificationRequestState::Requested { .. }
| VerificationRequestState::Ready { .. } => (),
VerificationRequestState::Transitioned { verification } => {
if let Verification::SasV1(sas) = verification {
tokio::spawn(async move {
if let Err(error) = sas_verification_handler(client, sas).await {
error!("failed to handle sas verification request: {error:?}");
}
});
break;
}
}
VerificationRequestState::Done | VerificationRequestState::Cancelled(_) => break,
}
}
}
pub async fn on_device_key_verification_request(
event: ToDeviceKeyVerificationRequestEvent,
client: Client,
) -> Result<()> {
let request = client
.encryption()
.get_verification_request(&event.sender, &event.content.transaction_id)
.await
.context("request object wasn't created")?;
tokio::spawn(request_verification_handler(client, request));
Ok(())
}
pub async fn on_room_message_verification_request(
event: OriginalSyncRoomMessageEvent,
client: Client,
) -> Result<()> {
if let MessageType::VerificationRequest(_) = &event.content.msgtype {
let request = client
.encryption()
.get_verification_request(&event.sender, &event.event_id)
.await
.context("request object wasn't created")?;
tokio::spawn(request_verification_handler(client, request));
}
Ok(())
}