feat: add matrix support

This commit is contained in:
Ryan 2025-03-14 23:24:36 -04:00
parent 571581767e
commit e70b8eca84
Signed by: ErrorNoInternet
GPG Key ID: 2486BFB7B1E6A4A3
14 changed files with 2136 additions and 31 deletions

1713
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -28,12 +28,14 @@ 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"] }
@ -43,5 +45,7 @@ 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,12 +7,14 @@ 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,6 +2,7 @@ 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

@ -3,7 +3,7 @@ use crate::{
commands::CommandSource, commands::CommandSource,
http::serve, http::serve,
lua::{client, direction::Direction, player::Player, vec3::Vec3}, lua::{client, direction::Direction, player::Player, vec3::Vec3},
particle, matrix, particle,
replay::recorder::Recorder, replay::recorder::Recorder,
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result};
@ -209,6 +209,7 @@ 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?;
matrix_init(state.clone(), &globals);
let Some(address): Option<SocketAddr> = globals let Some(address): Option<SocketAddr> = globals
.get::<String>("HttpAddress") .get::<String>("HttpAddress")
@ -269,7 +270,20 @@ async fn lua_init(client: Client, state: &State, globals: &Table) -> Result<()>
call_listeners(state, "init", || Ok(())).await call_listeners(state, "init", || Ok(())).await
} }
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>,

27
src/lua/matrix/client.rs Normal file
View File

@ -0,0 +1,27 @@
use super::room::Room;
use matrix_sdk::{Client as MatrixClient, ruma::UserId};
use mlua::{Error, UserData};
use std::sync::Arc;
pub struct Client(pub Arc<MatrixClient>);
impl UserData for Client {
fn add_fields<F: mlua::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: mlua::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)
});
}
}

12
src/lua/matrix/member.rs Normal file
View File

@ -0,0 +1,12 @@
use matrix_sdk::room::RoomMember;
use mlua::UserData;
pub struct Member(pub RoomMember);
impl UserData for Member {
fn add_fields<F: mlua::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()));
}
}

3
src/lua/matrix/mod.rs Normal file
View File

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

43
src/lua/matrix/room.rs Normal file
View File

@ -0,0 +1,43 @@
use super::member::Member;
use matrix_sdk::{
RoomMemberships, room::Room as MatrixRoom, ruma::events::room::message::RoomMessageEventContent,
};
use mlua::{Error, UserData};
pub struct Room(pub MatrixRoom);
impl UserData for Room {
fn add_fields<F: mlua::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: mlua::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

@ -4,6 +4,7 @@ pub mod container;
pub mod direction; pub mod direction;
pub mod events; pub mod events;
pub mod logging; pub mod logging;
pub mod matrix;
pub mod nochatreports; pub mod nochatreports;
pub mod player; pub mod player;
pub mod system; pub mod system;

View File

@ -1,4 +1,4 @@
#![feature(let_chains)] #![feature(if_let_guard, let_chains)]
mod arguments; mod arguments;
mod build_info; mod build_info;
@ -6,6 +6,7 @@ mod commands;
mod events; mod events;
mod http; mod http;
mod lua; mod lua;
mod matrix;
mod particle; mod particle;
mod replay; mod replay;

125
src/matrix/bot.rs Normal file
View File

@ -0,0 +1,125 @@
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(())
}

57
src/matrix/mod.rs Normal file
View File

@ -0,0 +1,57 @@
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(())
}

158
src/matrix/verification.rs Normal file
View File

@ -0,0 +1,158 @@
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(())
}