Add Prefixed command constructor

This commit is contained in:
Joscha 2023-01-26 20:00:04 +01:00
parent ac2a3cdd9f
commit 3bc50dcf26
2 changed files with 41 additions and 0 deletions

View file

@ -1,6 +1,7 @@
mod bang; mod bang;
mod clap; mod clap;
mod hidden; mod hidden;
mod prefixed;
use std::future::Future; use std::future::Future;
@ -12,6 +13,7 @@ use crate::conn::{self, ConnTx, Joined};
pub use self::bang::*; pub use self::bang::*;
pub use self::clap::*; pub use self::clap::*;
pub use self::hidden::*; pub use self::hidden::*;
pub use self::prefixed::*;
use super::instance::InstanceConfig; use super::instance::InstanceConfig;

View file

@ -0,0 +1,39 @@
use async_trait::async_trait;
use crate::api::Message;
use super::{Command, Context};
pub struct Prefixed<C> {
prefix: String,
inner: C,
}
impl<C> Prefixed<C> {
pub fn new<S: ToString>(prefix: S, inner: C) -> Self {
Self {
prefix: prefix.to_string(),
inner,
}
}
}
#[async_trait]
impl<B, E, C> Command<B, E> for Prefixed<C>
where
B: Send,
C: Command<B, E> + Send + Sync,
{
fn description(&self, ctx: &Context) -> Option<String> {
let inner = self.inner.description(ctx)?;
Some(format!("{} - {inner}", self.prefix))
}
async fn execute(&self, arg: &str, msg: &Message, ctx: &Context, bot: &mut B) -> Result<(), E> {
if let Some(rest) = arg.trim_start().strip_prefix(&self.prefix) {
self.inner.execute(rest, msg, ctx, bot).await
} else {
Ok(())
}
}
}