ol_rusty/src/commands/roles.rs
Tom fff7611e9b Cargo fmt
And fix pagination for ephemeral commands
2023-04-08 20:41:04 +02:00

92 lines
2.8 KiB
Rust

use crate::{Context, Error};
use poise::serenity_prelude::RoleId;
#[derive(Debug, poise::ChoiceParameter)]
pub enum Action {
#[name = "Add specified role."]
Add,
#[name = "Remove specified role."]
Remove,
#[name = "Toggle specified role (default)."]
Toggle,
}
async fn autocomplete_role<'a>(
ctx: Context<'_>,
partial: &'a str,
) -> impl Iterator<Item = String> + 'a {
let mut roles: Vec<String> = match super::super::SETTINGS
.read()
.unwrap()
.get_table("roles")
.unwrap()
.get(&ctx.guild_id().expect("Not in a guild").to_string())
{
None => {
vec![]
}
Some(val) => match val.clone().into_table() {
Err(_) => {
vec![]
}
Ok(val) => val
.into_keys()
.filter(|str| str.contains(partial))
.collect(),
},
};
roles.sort_unstable();
roles.into_iter() //.map(|a| a.to_owned())
}
#[poise::command(slash_command, ephemeral, guild_only)]
pub async fn roles(
ctx: Context<'_>,
#[description = "Which role to add or remove?"]
#[autocomplete = "autocomplete_role"]
role: String,
#[description = "Remove or add role (default to add)"] action: Option<Action>,
) -> Result<(), Error> {
let role = super::super::SETTINGS
.read()
.unwrap()
.get_table("roles")
.unwrap()
.get(&ctx.guild_id().unwrap().to_string())
.expect("Command is only supported in a server")
.clone()
.into_table()
.expect("Config error, something in the configuration is wrong. Please contact someone to fix the bot.")
.get(&role)
.expect("Configured role does not exist")
.clone()
.into_uint()
.expect("Config error, specified role does not have the role_id configured.");
let role_ding = RoleId(role);
let mut member = ctx.author_member().await.expect("Where's my member....");
let mem = member.to_mut();
// if let Some(mut author) = ctx.author_member().await.as_mut().expect("Somehow there's no member object attached...") {
match action {
Some(Action::Remove) => {
mem.remove_role(ctx, role_ding).await?;
ctx.say(format!("Role {} Added", role)).await?
}
Some(Action::Add) => {
mem.add_role(ctx, role_ding).await?;
ctx.say(format!("Role {} Added", role)).await?
}
_ => {
if mem.roles.contains(&role_ding) {
mem.remove_role(ctx, role_ding).await?;
ctx.say(format!("Role {} Added", role)).await?
} else {
mem.add_role(ctx, role_ding).await?;
ctx.say(format!("Role {} Added", role)).await?
}
}
};
Ok(())
}