Bring the codebase more up to date with Kon

This commit is contained in:
toast 2024-03-11 10:06:40 +11:00
parent 8df935de29
commit 9b24bd0882
8 changed files with 28 additions and 83 deletions

View File

@ -1,6 +1,6 @@
{ {
"rust-analyzer.showUnlinkedFileNotification": false,
"rust-analyzer.linkedProjects": [ "rust-analyzer.linkedProjects": [
"./Cargo.toml" "./Cargo.toml"
], ]
"rust-analyzer.showUnlinkedFileNotification": false
} }

9
Cargo.lock generated
View File

@ -1250,6 +1250,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"poise", "poise",
"reqwest", "reqwest",
"serde",
"serde_json", "serde_json",
"serenity", "serenity",
"sysinfo", "sysinfo",
@ -1423,18 +1424,18 @@ dependencies = [
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.194" version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b114498256798c94a0689e1a15fec6005dee8ac1f41de56404b67afc2a4b773" checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.194" version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3385e45322e8f9931410f01b3031ec534c3947d0e94c18049af4d9f9907d4e0" checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View File

@ -3,8 +3,6 @@ name = "rustbot"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
poise = "0.6.1" poise = "0.6.1"
reqwest = { version = "0.11.25", features = ["json"] } reqwest = { version = "0.11.25", features = ["json"] }
@ -14,6 +12,7 @@ tempfile = "3.10.1"
sysinfo = "0.30.7" sysinfo = "0.30.7"
tokio = { version = "1.36.0", features = ["macros", "signal", "rt-multi-thread"] } tokio = { version = "1.36.0", features = ["macros", "signal", "rt-multi-thread"] }
uptime_lib = "0.3.0" uptime_lib = "0.3.0"
serde = "1.0.197"
[[bin]] [[bin]]
name = "rustbot" name = "rustbot"
@ -26,3 +25,4 @@ debug = true
[profile.release] [profile.release]
opt-level = 3 opt-level = 3
debug = false debug = false
strip = true

View File

@ -1,7 +1,7 @@
version: '3.8' version: '3.8'
services: services:
bot: bot:
container_name: Rustbot container_name: rustbot
image: 'git.toast-server.net/toast/rustbot:main' image: 'git.toast-server.net/toast/rustbot:main'
build: . build: .
env_file: env_file:

View File

@ -1,65 +0,0 @@
use crate::Error;
use reqwest::get;
use std::collections::HashMap;
use serde_json::Value;
use poise::CreateReply;
use serenity::builder::{
CreateEmbed,
CreateEmbedAuthor,
CreateEmbedFooter
};
/// Retrieve the data from FS-Server
#[poise::command(slash_command)]
pub async fn data(
ctx: poise::Context<'_, (), Error>,
#[description = "DSS url to extract"] url: String
) -> Result<(), Error> {
// Find .xml and replace it with .json before passing to reqwest.
let url = url.replace(".xml", ".json");
// Send a GET request to the provided URL
let response = get(&url).await?.json::<HashMap<String, Value>>().await?;
// Extract the required values from the parsed JSON
let server = &response["server"];
let slots = &response["slots"];
// Variable list of JSON values
let name = server["name"].as_str().unwrap();
let ver = server["version"].as_str().unwrap();
let map = server["mapName"].as_str().unwrap();
let slot_cap = slots["capacity"].as_i64().unwrap();
let slot_cur = slots["used"].as_i64().unwrap();
let daytime = server["dayTime"].as_i64().unwrap();
// todo: Add careerSavegame support when passing in DSS url.
// So I can get the following values for Autosave, Timescale and Slot usage.
// Convert dayTime (ms) to a military time format
let hour = (daytime / 3600 / 1000) % 24;
let minute = (daytime / 60 / 1000) % 60;
let time = format!("{:02}:{:02}", hour, minute);
let embed = CreateEmbed::new().color(crate::EMBED_COLOR);
ctx.send(CreateReply::default()
.embed(embed
.title(name)
.description("*Nobody is playing*")
.fields(vec![
("Map", map, true),
("Version", ver, true),
("Time", &time, true),
("Slot usage", "xx/xx", true),
("Autosave", "xx", true),
("Timescale", "0x", true)
])
.author(CreateEmbedAuthor::new(format!("{}/{}", slot_cur, slot_cap)).clone())
.footer(CreateEmbedFooter::new("Last updated").clone())
.timestamp(poise::serenity_prelude::Timestamp::now())
)
).await?;
Ok(())
}

View File

@ -1,4 +1,3 @@
pub mod ping; pub mod ping;
pub mod eval; pub mod eval;
pub mod data;
pub mod uptime; pub mod uptime;

View File

@ -38,13 +38,13 @@ fn format_duration(secs: u64) -> String {
let mut formatted_string = String::new(); let mut formatted_string = String::new();
if days > 0 { if days > 0 {
formatted_string.push_str(&format!("{}d, ", days)); formatted_string.push_str(&format!("{}d, ", days));
} }
if hours > 0 || days > 0 { if hours > 0 || days > 0 {
formatted_string.push_str(&format!("{}h, ", hours)); formatted_string.push_str(&format!("{}h, ", hours));
} }
if minutes > 0 || hours > 0 { if minutes > 0 || hours > 0 {
formatted_string.push_str(&format!("{}m, ", minutes)); formatted_string.push_str(&format!("{}m, ", minutes));
} }
formatted_string.push_str(&format!("{}s", seconds)); formatted_string.push_str(&format!("{}s", seconds));

View File

@ -8,6 +8,8 @@ use serenity::{
CreateEmbed, CreateEmbed,
CreateEmbedAuthor CreateEmbedAuthor
}, },
Context,
Ready,
ClientBuilder, ClientBuilder,
GatewayIntents GatewayIntents
}; };
@ -18,8 +20,8 @@ pub static EMBED_COLOR: i32 = 0xf1d63c;
static BOT_READY_NOTIFY: u64 = 865673694184996888; static BOT_READY_NOTIFY: u64 = 865673694184996888;
async fn on_ready( async fn on_ready(
ctx: &serenity::Context, ctx: &Context,
ready: &serenity::Ready, ready: &Ready,
framework: &poise::Framework<(), Error> framework: &poise::Framework<(), Error>
) -> Result<(), Error> { ) -> Result<(), Error> {
println!("Connected to API as {}", ready.user.name); println!("Connected to API as {}", ready.user.name);
@ -40,8 +42,8 @@ async fn on_ready(
match commands { match commands {
Ok(cmdmap) => for command in cmdmap.iter() { Ok(cmdmap) => for command in cmdmap.iter() {
println!("Registered command globally: {}", command.name); println!("Registered command globally: {}", command.name);
}, },
Err(why) => println!("Error registering commands: {:?}", why) Err(why) => println!("Error registering commands: {:?}", why)
} }
} }
@ -58,7 +60,6 @@ async fn main() {
commands: vec![ commands: vec![
commands::ping::ping(), commands::ping::ping(),
commands::eval::eval(), commands::eval::eval(),
commands::data::data(),
commands::uptime::uptime() commands::uptime::uptime()
], ],
pre_command: |ctx| Box::pin(async move { pre_command: |ctx| Box::pin(async move {
@ -68,6 +69,15 @@ async fn main() {
}; };
println!("[{}] {} ran /{}", get_guild_name, ctx.author().name, ctx.command().qualified_name) println!("[{}] {} ran /{}", get_guild_name, ctx.author().name, ctx.command().qualified_name)
}), }),
on_error: |error| Box::pin(async move {
match error {
poise::FrameworkError::Command { error, ctx, .. } => {
println!("PoiseCommandError({}): {}", ctx.command().qualified_name, error);
}
other => println!("PoiseOtherError: {:?}", other)
}
}),
initialize_owners: true,
..Default::default() ..Default::default()
}) })
.setup(|ctx, ready, framework| Box::pin(on_ready(ctx, ready, framework))) .setup(|ctx, ready, framework| Box::pin(on_ready(ctx, ready, framework)))