Dough Git

clove/proxyBot

src/commands/autoproxy/mod.rs

back to src/commands/autoproxy

// src/commands/autoproxy/mod.rs

use serenity::all::GuildId;

use crate::Bot;

impl Bot {
    pub(super) async fn autoproxy(
        &self,
        guild: GuildId,
        args: &[String],
    ) -> anyhow::Result<String> {
        let global = args.iter().any(|arg| arg == "-g");
        let choice = args
        .iter()
        .find(|arg| arg.as_str() != "-g")
        .map(String::as_str);
        let mut settings = self.settings.lock().await;
        let current = settings.guilds.get(&guild).copied().unwrap_or(false);
        let current_name = if current { "on" } else { "off" };
        let total = settings.guilds.len();

        let enabled = match choice {
            Some("on") => true,
            Some("off") => false,
            None if global => {
                let enabled_count = settings.guilds.values().filter(|&&enabled| enabled).count();
                return Ok(format!(
                    "Autoproxy is **on** in {enabled_count} of {total} servers."
                ));
            }
            None => return Ok(format!("Autoproxy in this server is **{current_name}**.")),
            _ if global => return Ok("Use `d$autoproxy -g on` or `d$autoproxy -g off`.".into()),
            _ => {
                return Ok(
                    "Use `d$autoproxy on|off`, or `d$autoproxy -g on|off` for every server.".into(),
                );
            }
        };

        let choice = if enabled { "on" } else { "off" };
        let mut updated = settings.clone();
        let response = if global {
            updated
            .guilds
            .values_mut()
            .for_each(|value| *value = enabled);
            format!("Autoproxy is now **{choice}** in all {total} servers.")
        } else if current == enabled {
            return Ok(format!("Autoproxy in this server is already **{choice}**."));
        } else {
            updated.guilds.insert(guild, enabled);
            format!("Autoproxy in this server is now **{choice}**.")
        };
        updated.save()?;
        *settings = updated;
        Ok(response)
    }
}