Skip to content

Commit 2e122f0

Browse files
committed
feat(discord)!: add stats command
1 parent 1777f17 commit 2e122f0

3 files changed

Lines changed: 64 additions & 1 deletion

File tree

src/database/server.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,4 +255,21 @@ pub async fn search_servers(filters: SearchFilters, limit: i64) -> Result<Option
255255
}).collect();
256256

257257
Ok(Some(results))
258+
}
259+
260+
pub async fn get_database_counts() -> Result<(i64, i64, i64), sqlx::Error> {
261+
let pool = pool::get_pool();
262+
263+
let counts: (i64, i64, i64) = sqlx::query_as(
264+
r#"
265+
SELECT
266+
(SELECT COUNT(*) FROM servers) as server_count,
267+
(SELECT COUNT(*) FROM server_history) as history_count,
268+
(SELECT COUNT(*) FROM player_history) as player_count
269+
"#
270+
)
271+
.fetch_one(pool)
272+
.await?;
273+
274+
Ok(counts)
258275
}

src/discord/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ pub async fn start_bot() {
5454
commands: vec![
5555
server_searcher::search_server(),
5656
player_searcher::search_player(),
57-
cleanup_command::cleanup()
57+
cleanup_command::cleanup(),
58+
stats_command::stats()
5859
],
5960
prefix_options: PrefixFrameworkOptions {
6061
prefix: Some("!".into()),

src/discord/stats_command.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
use chrono::Utc;
2+
use poise::{command, CreateReply};
3+
use crate::database::server::get_database_counts;
4+
use crate::discord::{create_base_embed, create_error_embed, create_loading_embed, Context, Error};
5+
use crate::logger;
6+
7+
/// Shows stats about the bot and database
8+
#[command(slash_command)]
9+
pub async fn stats(
10+
ctx: Context<'_>
11+
) -> Result<(), Error> {
12+
let start_time = Utc::now();
13+
14+
let reply = ctx.send(
15+
CreateReply::default()
16+
.embed(create_loading_embed("fetching stats"))
17+
).await?;
18+
19+
match get_database_counts().await {
20+
Ok((server_count, history_count, player_count)) => {
21+
let response = create_base_embed(Some(start_time))
22+
.title("📶 Stats")
23+
.description("Some stats about ServerRawler")
24+
.field("💻 Indexed servers", format!("--> `{}`", server_count), true)
25+
.field("📅 Server data entries", format!("--> `{}`", history_count), false)
26+
.field("👥 Player join entries", format!("--> `{}`", player_count), false);
27+
28+
reply.edit(
29+
ctx,
30+
CreateReply::default()
31+
.embed(response)
32+
).await?;
33+
}
34+
Err(e) => {
35+
reply.edit(
36+
ctx,
37+
CreateReply::default()
38+
.embed(create_error_embed("Database error", Some(start_time)))
39+
).await?;
40+
logger::error(format!("Database stats error: {}", e)).prefix("Discord").send().await;
41+
}
42+
}
43+
44+
Ok(())
45+
}

0 commit comments

Comments
 (0)