Refactors for less nesting, slight performance and memory improvement for count command
All checks were successful
/ check_lfs (pull_request) Successful in 3s
/ lint_fmt (pull_request) Successful in 9s
/ lint_clippy (pull_request) Successful in 16s
/ build (pull_request) Successful in 1m19s

This commit is contained in:
Roman Moisieiev 2025-09-11 13:39:10 +01:00
parent 6353d77360
commit f3f08962a4
9 changed files with 161 additions and 287 deletions

View file

@ -10,31 +10,19 @@ use skynet_discord_bot::common::{
use sqlx::{Error, Pool, Sqlite}; use sqlx::{Error, Pool, Sqlite};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String { pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let sub_options = if let Some(CommandDataOption { let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(options), value: CommandDataOptionValue::SubCommand(sub_options),
.. ..
}) = command.data.options.first() }) = command.data.options.first()
{ else {
options
} else {
return "Please provide sub options".to_string(); return "Please provide sub options".to_string();
}; };
let wolves_api = if let Some(x) = sub_options.first() { let Some(CommandDataOptionValue::String(wolves_api)) = sub_options.first().map(|opt| &opt.value) else {
match &x.value {
CommandDataOptionValue::String(key) => key.to_string(),
_ => return "Please provide a wolves API key".to_string(),
}
} else {
return "Please provide a wolves API key".to_string(); return "Please provide a wolves API key".to_string();
}; };
let role_current = if let Some(x) = sub_options.get(1) { let Some(&CommandDataOptionValue::Role(role_current)) = sub_options.get(1).map(|opt| &opt.value) else {
match &x.value {
CommandDataOptionValue::Role(role) => role.to_owned(),
_ => return "Please provide a valid role for ``Role Current``".to_string(),
}
} else {
return "Please provide a valid role for ``Role Current``".to_string(); return "Please provide a valid role for ``Role Current``".to_string();
}; };
@ -47,12 +35,7 @@ pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
None None
}; };
let bot_channel_id = if let Some(x) = sub_options.get(2) { let Some(&CommandDataOptionValue::Channel(bot_channel_id)) = sub_options.get(2).map(|opt| &opt.value) else {
match &x.value {
CommandDataOptionValue::Channel(channel) => channel.to_owned(),
_ => return "Please provide a valid channel for ``Bot Channel``".to_string(),
}
} else {
return "Please provide a valid channel for ``Bot Channel``".to_string(); return "Please provide a valid channel for ``Bot Channel``".to_string();
}; };
@ -63,7 +46,7 @@ pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let server_data = Servers { let server_data = Servers {
server: command.guild_id.unwrap_or_default(), server: command.guild_id.unwrap_or_default(),
wolves_api, wolves_api: wolves_api.to_string(),
wolves_id: 0, wolves_id: 0,
role_past, role_past,
role_current, role_current,
@ -72,13 +55,10 @@ pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
bot_channel_id, bot_channel_id,
}; };
match add_server(&db, ctx, &server_data).await { if let Err(e) = add_server(&db, ctx, &server_data).await {
Ok(_) => {}
Err(e) => {
println!("{e:?}"); println!("{e:?}");
return format!("Failure to insert into Servers {server_data:?}"); return format!("Failure to insert into Servers {server_data:?}");
} }
}
"Added/Updated server info".to_string() "Added/Updated server info".to_string()
} }

View file

@ -8,24 +8,21 @@ pub mod committee {
use skynet_discord_bot::common::{database::DataBase, set_roles::committee::db_roles_get}; use skynet_discord_bot::common::{database::DataBase, set_roles::committee::db_roles_get};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String { pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let sub_options = if let Some(CommandDataOption { let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(key), value: CommandDataOptionValue::SubCommand(sub_options),
.. ..
}) = command.data.options.first() }) = command.data.options.first()
{ else {
key
} else {
return "Please provide a wolves API key".to_string(); return "Please provide a wolves API key".to_string();
}; };
let all = if let Some(x) = sub_options.first() { let all = sub_options
match x.value { .first()
.map(|x| match x.value {
CommandDataOptionValue::Boolean(y) => y, CommandDataOptionValue::Boolean(y) => y,
_ => false, _ => false,
} })
} else { .unwrap_or(false);
false
};
let db = { let db = {
let data_read = ctx.data.read().await; let data_read = ctx.data.read().await;
@ -41,30 +38,24 @@ pub mod committee {
cs.push((committee.count, committee.name_role.to_owned())); cs.push((committee.count, committee.name_role.to_owned()));
} }
cs.sort_by_key(|(count, _)| *count); cs.sort_by_key(|(count, _)| std::cmp::Reverse(*count));
cs.reverse();
// msg can be a max 2000 chars long // msg can be a max 2000 chars long
let mut limit = 2000 - 3; let limit = 2000 - 3;
let mut response = vec!["```".to_string()]; let mut response = "```".to_string();
for (count, name) in cs { for (count, name) in cs {
let leading = if count < 10 { " " } else { "" }; use std::fmt::Write;
let len_before = response.len();
let line = format!("{leading}{count} {name}"); _ = writeln!(response, "{count:>2} {name}");
if response.len() >= limit {
let length = line.len() + 1; // Discard the line that didn't fit
response.truncate(len_before);
if length < (limit + 3) {
response.push(line);
limit -= length;
} else {
break; break;
} }
} }
response.push("```".to_string()); response.push_str("```");
response
response.join("\n")
} }
pub fn register() -> CreateCommand { pub fn register() -> CreateCommand {
@ -99,12 +90,8 @@ pub mod servers {
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone() data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
}; };
let mut committees = HashMap::new(); let committees = get_committees(&db).await.into_iter().flatten().map(|committee| (committee.id, committee));
if let Some(x) = get_committees(&db).await { let committees: HashMap<_, _> = committees.collect();
for committee in x {
committees.insert(committee.id, committee.to_owned());
}
}
let mut cs = vec![]; let mut cs = vec![];
// pull it from a DB // pull it from a DB
@ -127,40 +114,22 @@ pub mod servers {
cs.reverse(); cs.reverse();
// msg can be a max 2000 chars long // msg can be a max 2000 chars long
let mut limit = 2000 - 3; let limit = 2000 - 3;
let mut response = vec!["```".to_string()]; let mut response = "```".to_string();
for (current, past, name) in cs { for (current, past, name) in cs {
let current_leading = if current < 10 { use std::fmt::Write;
" " let len_before = response.len();
} else if current < 100 { _ = writeln!(response, "{current:>3} {past:>} {name}");
" " if response.len() >= limit {
} else { // Discard the line that didn't fit
"" response.truncate(len_before);
};
let past_leading = if past < 10 {
" "
} else if past < 100 {
" "
} else {
""
};
let line = format!("{current_leading}{current} {past_leading}{past} {name}");
let length = line.len() + 1;
// +3 is to account for the closing fence
if length < (limit + 3) {
response.push(line);
limit -= length;
} else {
break; break;
} }
} }
response.push("```".to_string()); response.push_str("```");
response.join("\n") response
} }
#[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)] #[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]

View file

@ -67,17 +67,11 @@ impl<'r> FromRow<'r, SqliteRow> for ServerMembersWolves {
} }
fn get_discord_from_row(row: &SqliteRow) -> Option<UserId> { fn get_discord_from_row(row: &SqliteRow) -> Option<UserId> {
match row.try_get("discord") { let x: i64 = row.try_get("discord").ok()?;
Ok(x) => { if x == 0 {
let tmp: i64 = x; return None;
if tmp == 0 {
None
} else {
Some(UserId::from(tmp as u64))
}
}
_ => None,
} }
Some(UserId::from(x as u64))
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]

View file

@ -49,7 +49,7 @@ pub async fn post<T: Serialize>(url: &str, bearer: &str, data: &T) {
.body_json(&data) .body_json(&data)
{ {
Ok(req) => { Ok(req) => {
req.await.ok(); _ = req.await;
} }
Err(e) => { Err(e) => {
dbg!(e); dbg!(e);
@ -71,20 +71,14 @@ pub struct ServerDetailsRes {
} }
async fn get<T: Serialize + DeserializeOwned>(url: &str, bearer: &str) -> Option<T> { async fn get<T: Serialize + DeserializeOwned>(url: &str, bearer: &str) -> Option<T> {
match surf::get(url) surf::get(url)
.header("Authorization", bearer) .header("Authorization", bearer)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.header("Accept", "Application/vnd.pterodactyl.v1+json") .header("Accept", "Application/vnd.pterodactyl.v1+json")
.recv_json() .recv_json()
.await .await
{ .map_err(|e| dbg!(e))
Ok(res) => Some(res), .ok()
Err(e) => {
dbg!(e);
None
}
}
} }
#[derive(Deserialize, Serialize, Debug)] #[derive(Deserialize, Serialize, Debug)]
@ -157,14 +151,9 @@ pub async fn whitelist_update(add: &Vec<(String, bool)>, server: &str, token: &s
let bearer = format!("Bearer {token}"); let bearer = format!("Bearer {token}");
for (name, java) in add { for (name, java) in add {
let data = if *java { let command = if *java { format!("whitelist add {name}") } else { format!("fwhitelist add {name}") };
BodyCommand { let data = BodyCommand {
command: format!("whitelist add {name}"), command,
}
} else {
BodyCommand {
command: format!("fwhitelist add {name}"),
}
}; };
post(&format!("{url_base}/command"), &bearer, &data).await; post(&format!("{url_base}/command"), &bearer, &data).await;
} }

View file

@ -54,62 +54,47 @@ impl Renderer {
count: 0, count: 0,
}; };
let colors = if args.colors.contains(':') { this.colors = if args.colors.contains(':') {
//? object let obj = args.colors.split(',').map(|s| {
let obj = args let mut iter = s.split(':');
.colors let [Some(a), Some(b), None] = std::array::from_fn(|_| iter.next()) else {
.split(',')
.map(|s| {
let s = s.split(':').collect::<Vec<&str>>();
if s.len() < 2 {
dbg!("Invalid color object, try checking help"); dbg!("Invalid color object, try checking help");
return None; return None;
} };
Some((s[0].to_string(), s[1].to_string())) Some((a.to_string(), b.to_string()))
}) });
.collect::<Vec<Option<(String, String)>>>();
let mut colors = Vec::new(); let colors = obj
.flatten()
for c in obj.into_iter().flatten() { .map(|c| {
std::fs::create_dir_all(args.output.join(&c.0))?; std::fs::create_dir_all(args.output.join(&c.0))?;
Ok(c)
colors.push(c); })
} .collect::<std::io::Result<_>>()?;
ColorType::Object(colors) ColorType::Object(colors)
} else { } else {
//? list let colors = args
// let colors = args.colors.split(",").map(|s| { .colors
// s.to_string() .split(',')
// }) .map(|color| -> std::io::Result<String> {
// .collect::<Vec<String>>();
let mut colors = Vec::new();
for color in args.colors.split(',') {
std::fs::create_dir_all(args.output.join(color))?; std::fs::create_dir_all(args.output.join(color))?;
colors.push(color.to_string()) Ok(color.to_string())
} })
.collect::<std::io::Result<_>>()?;
ColorType::Array(colors) ColorType::Array(colors)
}; };
this.colors = colors;
Ok(this) Ok(this)
} }
pub fn render(&mut self, fi: &Path, args: &Args) -> Result<()> { pub fn render(&mut self, fi: &Path, args: &Args) -> Result<()> {
match fi.extension() { if fi.extension().is_none_or(|ext| ext != "svg") {
Some(e) if e.to_str() == Some("svg") => {}
Some(_) | None => {
dbg!("Filer {:?} is not of type SVG", fi); dbg!("Filer {:?} is not of type SVG", fi);
// util::logger::warning(format!("File '{}' is not of SVG type", fi.clone().to_str().unwrap())); // util::logger::warning(format!("File '{}' is not of SVG type", fi.clone().to_str().unwrap()));
bail!("Failed to render"); bail!("Failed to render");
} }
};
match self.colors.clone() { match self.colors.clone() {
ColorType::Array(c) => { ColorType::Array(c) => {

View file

@ -60,17 +60,11 @@ pub mod get_config_icons {
let config_source = minimal(); let config_source = minimal();
let file_path = format!("{}/open-governance/{}/{}", &config.home, &config_source.source.directory, &config_source.source.file); let file_path = format!("{}/open-governance/{}/{}", &config.home, &config_source.source.directory, &config_source.source.file);
let contents = fs::read_to_string(file_path).unwrap_or_else(|e| { let contents = fs::read_to_string(file_path).map_err(|e| dbg!(e)).unwrap_or_default();
dbg!(e); let festivals = toml::from_str::<ConfigTomlRemote>(&contents)
"".to_string() .map(|config| config.festivals)
}); .map_err(|e| dbg!(e))
let festivals = match toml::from_str::<ConfigTomlRemote>(&contents) { .unwrap_or_default();
Ok(config_festivals) => config_festivals.festivals,
Err(e) => {
dbg!(e);
vec![]
}
};
ConfigToml { ConfigToml {
source: config_source.source, source: config_source.source,
@ -248,12 +242,9 @@ pub mod update_icon {
for tmp in paths.flatten() { for tmp in paths.flatten() {
let path_local = tmp.path().to_owned(); let path_local = tmp.path().to_owned();
let path_local2 = tmp.path().to_owned(); let path_local2 = tmp.path().to_owned();
let name = match path_local2.file_name() { let Some(name) = path_local2.file_name().map(ToOwned::to_owned) else {
None => {
dbg!(path_local2); dbg!(path_local2);
continue; continue;
}
Some(x) => x.to_owned(),
}; };
let mut path = tmp.path(); let mut path = tmp.path();
@ -308,16 +299,15 @@ pub mod update_icon {
fn logos_filter(festival_data: &FestivalData, existing: Vec<LogoData>) -> Vec<LogoData> { fn logos_filter(festival_data: &FestivalData, existing: Vec<LogoData>) -> Vec<LogoData> {
let mut filtered: Vec<LogoData> = vec![]; let mut filtered: Vec<LogoData> = vec![];
let allowed_files = vec![".png", ".jpeg", ".gif", ".svg"]; let allowed_extensions = ["png", "jpeg", "gif", "svg"];
'outer: for logo in existing { 'outer: for logo in existing {
let name_lowercase0 = logo.name.to_ascii_lowercase(); let name_lowercase = logo.name.to_ascii_lowercase();
let name_lowercase = name_lowercase0.to_str().unwrap_or_default(); let name_lowercase = name_lowercase.to_str().unwrap_or_default();
let mut allowed = false;
for allowed_type in &allowed_files { let allowed = {
if name_lowercase.ends_with(allowed_type) { let extension = name_lowercase.split('.').next_back().unwrap_or_default();
allowed = true; allowed_extensions.contains(&extension)
} };
}
if !allowed { if !allowed {
continue; continue;
} }
@ -332,13 +322,7 @@ pub mod update_icon {
} }
} else { } else {
// else filter using the excluded ones // else filter using the excluded ones
let mut excluded = false; let excluded = festival_data.exclusions.iter().any(|festival| name_lowercase.contains(festival));
for festival in &festival_data.exclusions {
if name_lowercase.contains(festival) {
excluded = true;
}
}
if !excluded { if !excluded {
filtered.push(logo); filtered.push(logo);
} }
@ -349,13 +333,15 @@ pub mod update_icon {
} }
async fn logo_set(ctx: &Context, db: &Pool<Sqlite>, server: &GuildId, logo_selected: &LogoData) { async fn logo_set(ctx: &Context, db: &Pool<Sqlite>, server: &GuildId, logo_selected: &LogoData) {
// add to teh database // add to the database
if !logo_set_db(db, logo_selected).await { if logo_set_db(db, logo_selected).await.is_err() {
// something went wrong // something went wrong
return; return;
} }
if let Some(logo_path) = logo_selected.path.to_str() { let Some(logo_path) = logo_selected.path.to_str() else {
return;
};
match CreateAttachment::path(logo_path).await { match CreateAttachment::path(logo_path).await {
Ok(icon) => { Ok(icon) => {
// assuming a `guild` has already been bound // assuming a `guild` has already been bound
@ -369,19 +355,12 @@ pub mod update_icon {
} }
} }
} }
}
async fn logo_set_db(db: &Pool<Sqlite>, logo_selected: &LogoData) -> bool { async fn logo_set_db(db: &Pool<Sqlite>, logo_selected: &LogoData) -> Result<(), ()> {
let name = match logo_selected.name.to_str() { let name = logo_selected.name.to_str().ok_or(())?;
None => return false, let path = logo_selected.path.to_str().ok_or(())?;
Some(x) => x,
};
let path = match logo_selected.path.to_str() {
None => return false,
Some(x) => x,
};
match sqlx::query_as::<_, ServerIcons>( sqlx::query_as::<_, ServerIcons>(
" "
INSERT OR REPLACE INTO server_icons (name, date, path) INSERT OR REPLACE INTO server_icons (name, date, path)
VALUES (?1, ?2, ?3) VALUES (?1, ?2, ?3)
@ -392,13 +371,9 @@ pub mod update_icon {
.bind(path) .bind(path)
.fetch_optional(db) .fetch_optional(db)
.await .await
{ .map_err(|e| {
Ok(_) => {}
Err(e) => {
dbg!(e); dbg!(e);
return false; })?;
} Ok(())
}
true
} }
} }

View file

@ -24,7 +24,7 @@ struct WolvesResultUserMin {
} }
async fn add_users_wolves(db: &Pool<Sqlite>, user: &WolvesResultUserMin) { async fn add_users_wolves(db: &Pool<Sqlite>, user: &WolvesResultUserMin) {
// expiry // expiry
match sqlx::query_as::<_, Wolves>( if let Err(e) = sqlx::query_as::<_, Wolves>(
" "
INSERT INTO wolves (id_wolves, email) INSERT INTO wolves (id_wolves, email)
VALUES ($1, $2) VALUES ($1, $2)
@ -36,13 +36,10 @@ async fn add_users_wolves(db: &Pool<Sqlite>, user: &WolvesResultUserMin) {
.fetch_optional(db) .fetch_optional(db)
.await .await
{ {
Ok(_) => {}
Err(e) => {
println!("Failure to insert into Wolves {user:?}"); println!("Failure to insert into Wolves {user:?}");
println!("{e:?}"); println!("{e:?}");
} }
} }
}
/** /**
This is getting data for Clubs and Socs This is getting data for Clubs and Socs
@ -91,7 +88,6 @@ pub mod cns {
wolves_id, wolves_id,
.. ..
} = &server_config; } = &server_config;
// dbg!(&server_config);
let existing_tmp = get_server_member(&db, server).await; let existing_tmp = get_server_member(&db, server).await;
let existing = existing_tmp.iter().map(|data| (data.id_wolves, data)).collect::<BTreeMap<_, _>>(); let existing = existing_tmp.iter().map(|data| (data.id_wolves, data)).collect::<BTreeMap<_, _>>();
@ -99,7 +95,6 @@ pub mod cns {
// list of users that need to be updated for this server // list of users that need to be updated for this server
let mut server_name_tmp = None; let mut server_name_tmp = None;
for user in wolves.get_members(wolves_api).await { for user in wolves.get_members(wolves_api).await {
// dbg!(&user.committee);
if server_name_tmp.is_none() { if server_name_tmp.is_none() {
server_name_tmp = Some(user.committee_id); server_name_tmp = Some(user.committee_id);
} }

View file

@ -106,21 +106,19 @@ pub fn get_config() -> Config {
} }
} }
if let Ok(x) = env::var("COMMITTEE_ROLE") { if let Ok(x) = env::var("COMMITTEE_ROLE") {
if let Ok(x) = x.trim().parse::<u64>() { if let Ok(x) = x.trim().parse() {
config.committee_role = RoleId::new(x); config.committee_role = RoleId::new(x);
} }
} }
if let Ok(x) = env::var("COMMITTEE_CATEGORY") { if let Ok(x) = env::var("COMMITTEE_CATEGORY") {
for part in x.split(',') { for id in x.split(',').flat_map(|part| part.trim().parse()) {
if let Ok(x) = part.trim().parse::<u64>() { config.committee_category.push(ChannelId::new(id));
config.committee_category.push(ChannelId::new(x));
}
} }
} }
if let Ok(x) = env::var("COMPSOC_DISCORD") { if let Ok(x) = env::var("COMPSOC_DISCORD") {
if let Ok(x) = x.trim().parse::<u64>() { if let Ok(x) = x.trim().parse() {
config.compsoc_server = GuildId::new(x); config.compsoc_server = GuildId::new(x)
} }
} }

View file

@ -54,15 +54,14 @@ impl EventHandler for Handler {
// committee server takes priority // committee server takes priority
let committee_server = config_global.committee_server; let committee_server = config_global.committee_server;
if new_member.guild_id.get() == committee_server.get() { if new_member.guild_id == committee_server {
let mut member = vec![new_member.clone()]; let mut member = vec![new_member.clone()];
update_committees(&db, &ctx, &config_global, &mut member).await; update_committees(&db, &ctx, &config_global, &mut member).await;
return; return;
} }
let config_server = match get_server_config(&db, &new_member.guild_id).await { let Some(config_server) = get_server_config(&db, &new_member.guild_id).await else {
None => return, return;
Some(x) => x,
}; };
if get_server_member(&db, &new_member.guild_id, &new_member).await.is_ok() { if get_server_member(&db, &new_member.guild_id, &new_member).await.is_ok() {
@ -81,10 +80,12 @@ impl EventHandler for Handler {
if let Err(e) = new_member.add_roles(&ctx, &roles).await { if let Err(e) = new_member.add_roles(&ctx, &roles).await {
println!("{e:?}"); println!("{e:?}");
} }
} else { return;
}
let tmp = get_committee(&db, config_server.wolves_id).await; let tmp = get_committee(&db, config_server.wolves_id).await;
if !tmp.is_empty() { let Some(committee) = tmp.first() else {
let committee = &tmp[0]; return;
};
let msg = format!( let msg = format!(
r#" r#"
Welcome {} to the {} server! Welcome {} to the {} server!
@ -101,8 +102,6 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
dbg!(err); dbg!(err);
} }
} }
}
}
// handles role updates // handles role updates
async fn guild_member_update(&self, ctx: Context, _old_data: Option<Member>, new_data: Option<Member>, _: GuildMemberUpdateEvent) { async fn guild_member_update(&self, ctx: Context, _old_data: Option<Member>, new_data: Option<Member>, _: GuildMemberUpdateEvent) {
@ -113,10 +112,9 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
}; };
// check if the role changed is part of the ones for this server // check if the role changed is part of the ones for this server
if let Some(x) = new_data { let Some(x) = new_data else { return };
on_role_change(&db, &ctx, x).await; on_role_change(&db, &ctx, x).await;
} }
}
async fn ready(&self, ctx: Context, ready: Ready) { async fn ready(&self, ctx: Context, ready: Ready) {
println!("[Main] {} is connected!", ready.user.name); println!("[Main] {} is connected!", ready.user.name);
@ -128,7 +126,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
}; };
let config = config_lock.read().await; let config = config_lock.read().await;
match Command::set_global_commands( if let Err(e) = Command::set_global_commands(
&ctx.http, &ctx.http,
vec![ vec![
commands::wolves::register(), commands::wolves::register(),
@ -140,22 +138,16 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
) )
.await .await
{ {
Ok(_) => {}
Err(e) => {
println!("{e:?}") println!("{e:?}")
} }
}
// Inter-Committee server // Inter-Committee server
match config.committee_server.set_commands(&ctx.http, vec![commands::count::committee::register()]).await { if let Err(e) = config.committee_server.set_commands(&ctx.http, vec![commands::count::committee::register()]).await {
Ok(_) => {}
Err(e) => {
println!("{e:?}") println!("{e:?}")
} }
}
// CompSoc Server // CompSoc Server
match config if let Err(e) = config
.compsoc_server .compsoc_server
.set_commands( .set_commands(
&ctx.http, &ctx.http,
@ -167,16 +159,13 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
) )
.await .await
{ {
Ok(_) => {}
Err(e) => {
println!("{e:?}") println!("{e:?}")
} }
} }
}
async fn interaction_create(&self, ctx: Context, interaction: Interaction) { async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::Command(command) = interaction { if let Interaction::Command(command) = interaction {
let _ = command.defer_ephemeral(&ctx.http).await; _ = command.defer_ephemeral(&ctx.http).await;
// println!("Received command interaction: {:#?}", command); // println!("Received command interaction: {:#?}", command);
let content = match command.data.name.as_str() { let content = match command.data.name.as_str() {
@ -190,7 +179,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
"link_minecraft" => commands::minecraft::user::add::run(&command, &ctx).await, "link_minecraft" => commands::minecraft::user::add::run(&command, &ctx).await,
"docs" => commands::wolves::link_docs::users::run(&command, &ctx).await, "docs" => commands::wolves::link_docs::users::run(&command, &ctx).await,
// "link" => commands::count::servers::run(&command, &ctx).await, // "link" => commands::count::servers::run(&command, &ctx).await,
&_ => format!("not implemented :( wolves {}", x.name.as_str()), _ => format!("not implemented :( wolves {}", x.name.as_str()),
}, },
}, },
@ -205,7 +194,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
None => "error".to_string(), None => "error".to_string(),
Some(z) => match z.name.as_str() { Some(z) => match z.name.as_str() {
"change" => commands::server_icon::admin::change::run(&command, &ctx).await, "change" => commands::server_icon::admin::change::run(&command, &ctx).await,
&_ => format!("not implemented :( count {}", x.name.as_str()), _ => format!("not implemented :( count {}", x.name.as_str()),
}, },
}, },
_ => { _ => {
@ -214,7 +203,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
}, },
// TODO: move teh minecraft commands in here as a subgroup // TODO: move teh minecraft commands in here as a subgroup
// "link" => commands::count::servers::run(&command, &ctx).await, // "link" => commands::count::servers::run(&command, &ctx).await,
&_ => format!("not implemented :( committee {}", x.name.as_str()), _ => format!("not implemented :( committee {}", x.name.as_str()),
}, },
}, },
"minecraft_add" => commands::minecraft::server::add::run(&command, &ctx).await, "minecraft_add" => commands::minecraft::server::add::run(&command, &ctx).await,
@ -226,7 +215,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
Some(x) => match x.name.as_str() { Some(x) => match x.name.as_str() {
"committee" => commands::count::committee::run(&command, &ctx).await, "committee" => commands::count::committee::run(&command, &ctx).await,
"servers" => commands::count::servers::run(&command, &ctx).await, "servers" => commands::count::servers::run(&command, &ctx).await,
&_ => format!("not implemented :( count {}", x.name.as_str()), _ => format!("not implemented :( count {}", x.name.as_str()),
}, },
}, },
@ -240,16 +229,16 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
Some(z) => match z.name.as_str() { Some(z) => match z.name.as_str() {
"icon" => commands::server_icon::user::current::icon::run(&command, &ctx).await, "icon" => commands::server_icon::user::current::icon::run(&command, &ctx).await,
"festival" => commands::server_icon::user::current::festival::run(&command, &ctx).await, "festival" => commands::server_icon::user::current::festival::run(&command, &ctx).await,
&_ => format!("not implemented :( count {}", x.name.as_str()), _ => format!("not implemented :( count {}", x.name.as_str()),
}, },
}, },
&_ => format!("not implemented :( {}", command.data.name.as_str()), _ => format!("not implemented :( {}", command.data.name.as_str()),
}; };
result result
} }
"stats" => commands::server_icon::user::stats::run(&command, &ctx).await, "stats" => commands::server_icon::user::stats::run(&command, &ctx).await,
&_ => format!("not implemented :( count {}", x.name.as_str()), _ => format!("not implemented :( count {}", x.name.as_str()),
}, },
}, },
_ => format!("not implemented :( {}", command.data.name.as_str()), _ => format!("not implemented :( {}", command.data.name.as_str()),