The world's most clever kitty cat
1use std::sync::Arc;
2
3use twilight_interactions::command::{CommandModel, CreateCommand};
4use twilight_model::{
5 application::interaction::{Interaction, application_command::CommandData},
6 http::attachment::Attachment,
7};
8
9use crate::{BotContext, BrainHandle, brain::format_token, cmd::DEFER_INTER_RESP, prelude::*};
10
11#[derive(CommandModel, CreateCommand)]
12#[command(name = "weights", desc = "Get the weights of a token")]
13pub struct WeightsCommand {
14 /// Token to view the weights of
15 token: String,
16}
17
18async fn get_output(token: &str, brain: &BrainHandle) -> Option<String> {
19 let brain = brain.read().await;
20
21 brain.get_weights(token).map(|edges| {
22 let sep = String::from("\n");
23 let mut all_weights = edges.iter_weights().collect::<Vec<_>>();
24
25 all_weights.sort_by_key(|(_, w, _)| *w);
26
27 let formatted_weights = all_weights
28 .into_iter()
29 .map(|(token, weight, chance)| {
30 let token_fmt = format_token(token);
31 format!("{token_fmt}: {:.1}% ({weight})", chance * 100.0)
32 })
33 .intersperse(sep)
34 .collect::<String>();
35
36 format!("Weights for {token}:\n{formatted_weights}")
37 })
38}
39
40impl WeightsCommand {
41 pub async fn handle(inter: Interaction, data: CommandData, ctx: Arc<BotContext>) -> Result {
42 let Self { token } =
43 Self::from_interaction(data.into()).context("Failed to parse command data")?;
44
45 let client = ctx.http.interaction(ctx.app_id);
46
47 client
48 .create_response(inter.id, &inter.token, &DEFER_INTER_RESP)
49 .await
50 .context("Failed to defer")?;
51
52 let content = get_output(&token, &ctx.brain_handle)
53 .await
54 .unwrap_or_else(|| String::from("Bingus doesn't know that word!"));
55
56 let update = client.update_response(&inter.token);
57
58 if content.encode_utf16().count() < 2000 {
59 update.content(Some(content.as_str())).await
60 } else {
61 let data = content.into_bytes();
62 let attachment = Attachment::from_bytes(String::from("weights.txt"), data, 1);
63 update
64 .content(Some(
65 "Weights were too long to fit into one message, check the text file!",
66 ))
67 .attachments(&[attachment])
68 .await
69 }
70 .context("Failed to reply")?;
71
72 Ok(())
73 }
74}