The world's most clever kitty cat
at main 70 lines 2.3 kB view raw
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 all_weights = edges 24 .iter_weights() 25 .map(|(token, weight, chance)| { 26 let token_fmt = format_token(token); 27 format!("- **{token_fmt}**: {:.1}% ({weight})", chance * 100.0) 28 }) 29 .intersperse(sep) 30 .collect::<String>(); 31 32 format!("Weights for {token}:\n{all_weights}") 33 }) 34} 35 36impl WeightsCommand { 37 pub async fn handle(inter: Interaction, data: CommandData, ctx: Arc<BotContext>) -> Result { 38 let Self { token } = 39 Self::from_interaction(data.into()).context("Failed to parse command data")?; 40 41 let client = ctx.http.interaction(ctx.app_id); 42 43 client 44 .create_response(inter.id, &inter.token, &DEFER_INTER_RESP) 45 .await 46 .context("Failed to defer")?; 47 48 let content = get_output(&token, &ctx.brain_handle) 49 .await 50 .unwrap_or_else(|| String::from("Bingus doesn't know that word!")); 51 52 let update = client.update_response(&inter.token); 53 54 if content.encode_utf16().count() < 2000 { 55 update.content(Some(content.as_str())).await 56 } else { 57 let data = content.into_bytes(); 58 let attachment = Attachment::from_bytes(String::from("weights.txt"), data, 1); 59 update 60 .content(Some( 61 "Weights were too long to fit into one message, check the text file!", 62 )) 63 .attachments(&[attachment]) 64 .await 65 } 66 .context("Failed to reply")?; 67 68 Ok(()) 69 } 70}