1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
use poise::serenity_prelude as serenity;
use crate::Data;
use crate::database;
use crate::error::{Error, Result};
type Context<'a> = poise::Context<'a, Data, Error>;
const PAGE_SIZE: i64 = 10;
/// Format seconds to human-readable duration
fn format_duration(seconds: f64) -> String {
let total = seconds as u64;
let hours = total / 3600;
let minutes = (total % 3600) / 60;
if hours > 0 {
format!("{}h {}m", hours, minutes)
} else {
format!("{}m", minutes)
}
}
/// Format number with thousands separator
fn format_number(n: i64) -> String {
let s = n.to_string();
let mut result = String::new();
for (i, c) in s.chars().rev().enumerate() {
if i > 0 && i % 3 == 0 {
result.push(',');
}
result.push(c);
}
result.chars().rev().collect()
}
/// Get rank suffix (1st, 2nd, 3rd, etc.)
fn rank_suffix(rank: i64) -> String {
let suffix = if rank % 100 >= 11 && rank % 100 <= 13 {
"th"
} else {
match rank % 10 {
1 => "st",
2 => "nd",
3 => "rd",
_ => "th",
}
};
format!("{}{}", rank, suffix)
}
/// Resolve user ID to display name
async fn resolve_display_name(ctx: Context<'_>, user_id: &str) -> String {
let id = user_id.parse::<u64>().unwrap_or(0);
let user_id_obj = serenity::UserId::new(id);
// Try to get from cache first
if let Some(user) = ctx.cache().user(user_id_obj) {
return user.name.clone();
}
// Fallback to API
if let Ok(user) = user_id_obj.to_user(ctx.http()).await {
return user.name;
}
user_id.to_string()
}
/// Create the stats embed for a user
async fn create_stats_embed(
ctx: Context<'_>,
user_id: &str,
stats: &database::UserStats,
) -> serenity::CreateEmbed {
let display_name = resolve_display_name(ctx, user_id).await;
// Get ranks for each metric
let msg_rank = database::get_user_rank(&ctx.data().db_pool, user_id, "messages").await.unwrap_or(0);
let active_rank = database::get_user_rank(&ctx.data().db_pool, user_id, "active").await.unwrap_or(0);
let afk_rank = database::get_user_rank(&ctx.data().db_pool, user_id, "afk").await.unwrap_or(0);
let total_rank = database::get_user_rank(&ctx.data().db_pool, user_id, "total").await.unwrap_or(0);
let rank_str = |rank: i64| if rank > 0 { format!(" (#{})", rank_suffix(rank)) } else { " (unranked)".to_string() };
let total_voice = stats.total_voice_active + stats.total_voice_afk;
serenity::CreateEmbed::default()
.title(format!("Stats for {}", display_name))
.color(serenity::Color::from_rgb(59, 130, 246))
.field(
"Messages",
format!("{}{}", format_number(stats.message_count), rank_str(msg_rank)),
true,
)
.field(
"Voice Active",
format!("{}{}", format_duration(stats.total_voice_active), rank_str(active_rank)),
true,
)
.field(
"Voice AFK",
format!("{}{}", format_duration(stats.total_voice_afk), rank_str(afk_rank)),
true,
)
.field(
"Total Voice",
format!("{}{}", format_duration(total_voice), rank_str(total_rank)),
true,
)
.footer(serenity::CreateEmbedFooter::new("Use /leaderboard messages|active|afk|total to see full leaderboard"))
}
/// Create the leaderboard embed
async fn create_leaderboard_embed(
ctx: Context<'_>,
metric: &str,
ascending: bool,
page: i64,
) -> Result<(serenity::CreateEmbed, i64)> {
let offset = (page - 1) * PAGE_SIZE;
let (entries, total_count) = database::get_leaderboard(
&ctx.data().db_pool,
metric,
ascending,
PAGE_SIZE,
offset,
)
.await?;
let total_pages = (total_count as f64 / PAGE_SIZE as f64).ceil() as i64;
let total_pages = total_pages.max(1);
let title = match metric {
"messages" => "Messages Leaderboard",
"active" => "Voice Active Leaderboard",
"afk" => "Voice AFK Leaderboard",
"total" => "Total Voice Leaderboard",
_ => "Leaderboard",
};
let direction = if ascending { "↑" } else { "↓" };
let mut description = String::new();
for (i, entry) in entries.iter().enumerate() {
let rank = offset + i as i64 + 1;
let display_name = resolve_display_name(ctx, &entry.user_id).await;
let value = match metric {
"messages" => format_number(entry.message_count),
"active" => format_duration(entry.total_voice_active),
"afk" => format_duration(entry.total_voice_afk),
"total" => format_duration(entry.total_voice_active + entry.total_voice_afk),
_ => format_number(entry.message_count),
};
description.push_str(&format!("**#{}** — {} — {}\n", rank_suffix(rank), display_name, value));
}
if description.is_empty() {
description = "No entries yet.".to_string();
}
// Get current user's rank and stats for footer
let user_id = ctx.author().id.to_string();
let user_stats = database::get_user_stats(&ctx.data().db_pool, &user_id).await?;
let user_rank = database::get_user_rank(&ctx.data().db_pool, &user_id, metric).await.unwrap_or(0);
let footer_text = if let Some(stats) = &user_stats {
let user_value = match metric {
"messages" => format_number(stats.message_count),
"active" => format_duration(stats.total_voice_active),
"afk" => format_duration(stats.total_voice_afk),
"total" => format_duration(stats.total_voice_active + stats.total_voice_afk),
_ => format_number(stats.message_count),
};
if user_rank > 0 {
format!("Your rank: #{} ({})", rank_suffix(user_rank), user_value)
} else {
"You are not ranked yet".to_string()
}
} else {
"You are not ranked yet".to_string()
};
let embed = serenity::CreateEmbed::default()
.title(format!("{} {}", title, direction))
.description(description)
.color(serenity::Color::from_rgb(59, 130, 246))
.footer(serenity::CreateEmbedFooter::new(footer_text))
.field("Page", format!("{}/{}", page, total_pages), true);
Ok((embed, total_pages))
}
/// Show your personal stats
#[poise::command(slash_command)]
pub async fn me(ctx: Context<'_>) -> Result<()> {
let user_id = ctx.author().id.to_string();
let stats = database::get_user_stats(&ctx.data().db_pool, &user_id).await?;
let embed = if let Some(stats) = &stats {
create_stats_embed(ctx, &user_id, stats).await
} else {
// User has no stats yet - show zeros
let empty_stats = database::UserStats {
user_id: user_id.clone(),
message_count: 0,
total_voice_active: 0.0,
total_voice_afk: 0.0,
};
create_stats_embed(ctx, &user_id, &empty_stats).await
};
ctx.send(
poise::CreateReply::default()
.embed(embed),
)
.await?;
Ok(())
}
/// Show messages leaderboard
#[poise::command(slash_command)]
pub async fn messages(
ctx: Context<'_>,
#[description = "Sort order (default: descending)"]
#[autocomplete = "sort_order_autocomplete"]
order: Option<String>,
) -> Result<()> {
let ascending = order.as_deref() == Some("ascending");
let page = 1;
let (embed, _total_pages) = create_leaderboard_embed(ctx, "messages", ascending, page).await?;
ctx.send(
poise::CreateReply::default()
.embed(embed),
)
.await?;
Ok(())
}
/// Show voice active leaderboard
#[poise::command(slash_command)]
pub async fn active(
ctx: Context<'_>,
#[description = "Sort order (default: descending)"]
#[autocomplete = "sort_order_autocomplete"]
order: Option<String>,
) -> Result<()> {
let ascending = order.as_deref() == Some("ascending");
let page = 1;
let (embed, _total_pages) = create_leaderboard_embed(ctx, "active", ascending, page).await?;
ctx.send(
poise::CreateReply::default()
.embed(embed),
)
.await?;
Ok(())
}
/// Show voice AFK leaderboard
#[poise::command(slash_command)]
pub async fn afk(
ctx: Context<'_>,
#[description = "Sort order (default: descending)"]
#[autocomplete = "sort_order_autocomplete"]
order: Option<String>,
) -> Result<()> {
let ascending = order.as_deref() == Some("ascending");
let page = 1;
let (embed, _total_pages) = create_leaderboard_embed(ctx, "afk", ascending, page).await?;
ctx.send(
poise::CreateReply::default()
.embed(embed),
)
.await?;
Ok(())
}
/// Show total voice leaderboard
#[poise::command(slash_command)]
pub async fn total(
ctx: Context<'_>,
#[description = "Sort order (default: descending)"]
#[autocomplete = "sort_order_autocomplete"]
order: Option<String>,
) -> Result<()> {
let ascending = order.as_deref() == Some("ascending");
let page = 1;
let (embed, _total_pages) = create_leaderboard_embed(ctx, "total", ascending, page).await?;
ctx.send(
poise::CreateReply::default()
.embed(embed),
)
.await?;
Ok(())
}
/// Autocomplete for sort order
async fn sort_order_autocomplete(
_ctx: Context<'_>,
_partial: &str,
) -> Vec<serenity::AutocompleteChoice> {
vec![
serenity::AutocompleteChoice::new("Descending (highest first)", "descending"),
serenity::AutocompleteChoice::new("Ascending (lowest first)", "ascending"),
]
}
/// Leaderboard commands
#[poise::command(
slash_command,
subcommands("me", "messages", "active", "afk", "total"),
subcommand_required
)]
pub async fn leaderboard(_ctx: Context<'_>) -> Result<()> {
Ok(())
}
pub fn commands() -> Vec<poise::Command<Data, Error>> {
vec![leaderboard()]
}
|