Trying to make bot_name: N, where N: Into<String>

This commit is contained in:
Temirkhan Myrzamadi 2020-02-23 17:15:19 +06:00
parent c02af81dd1
commit 9e8f79a0b5
2 changed files with 32 additions and 21 deletions

View file

@ -23,7 +23,7 @@ pub trait DispatcherHandlerRxExt {
where
Self: Stream<Item = DispatcherHandlerCx<Message>>,
C: BotCommand,
N: Into<String>;
N: Into<String> + Send;
}
impl<T> DispatcherHandlerRxExt for T
@ -50,16 +50,22 @@ where
C: BotCommand,
N: Into<String> + Send,
{
Box::pin(self.text_messages().filter_map(|(cx, text)| async move {
C::parse(&text, &bot_name.into()).map(|(command, args)| {
(
cx,
command,
args.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>(),
)
})
let bot_name = bot_name.into();
Box::pin(self.text_messages().filter_map(move |(cx, text)| {
let bot_name = bot_name.clone();
async move {
C::parse(&text, &bot_name).map(|(command, args)| {
(
cx,
command,
args.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>(),
)
})
}
}))
}
}

View file

@ -101,7 +101,9 @@ pub use teloxide_macros::BotCommand;
pub trait BotCommand: Sized {
fn try_from(s: &str) -> Option<Self>;
fn descriptions() -> String;
fn parse<'a>(s: &'a str, bot_name: &str) -> Option<(Self, Vec<&'a str>)>;
fn parse<N>(s: &str, bot_name: N) -> Option<(Self, Vec<&str>)>
where
N: Into<String>;
}
/// Parses a string into a command with args.
@ -117,16 +119,16 @@ pub trait BotCommand: Sized {
/// assert_eq!(command, "/mute");
/// assert_eq!(args, vec!["5", "hours"]);
/// ```
pub fn parse_command<'a>(
text: &'a str,
bot_name: &str,
) -> Option<(&'a str, Vec<&'a str>)> {
pub fn parse_command<N>(text: &str, bot_name: N) -> Option<(&str, Vec<&str>)>
where
N: Into<String>,
{
let mut words = text.split_whitespace();
let mut splited = words.next()?.split('@');
let command = splited.next()?;
let bot = splited.next();
match bot {
Some(name) if name == bot_name => {}
Some(name) if name == bot_name.into() => {}
None => {}
_ => return None,
}
@ -146,11 +148,14 @@ pub fn parse_command<'a>(
/// assert_eq!(command, "mute");
/// assert_eq!(args, vec!["5", "hours"]);
/// ```
pub fn parse_command_with_prefix<'a>(
pub fn parse_command_with_prefix<'a, N>(
prefix: &str,
text: &'a str,
bot_name: &str,
) -> Option<(&'a str, Vec<&'a str>)> {
bot_name: N,
) -> Option<(&'a str, Vec<&'a str>)>
where
N: Into<String>,
{
if !text.starts_with(prefix) {
return None;
}
@ -159,7 +164,7 @@ pub fn parse_command_with_prefix<'a>(
let command = splited.next()?;
let bot = splited.next();
match bot {
Some(name) if name == bot_name => {}
Some(name) if name == bot_name.into() => {}
None => {}
_ => return None,
}