added RegexFilter

This commit is contained in:
p0lunin 2020-01-17 14:54:51 +02:00
parent 2bd67ff0b3
commit c3d90abe7d
3 changed files with 84 additions and 1 deletions

View file

@ -5,6 +5,9 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
regex_filter = ["regex"]
[dependencies] [dependencies]
serde_json = "1.0.44" serde_json = "1.0.44"
serde = { version = "1.0.101", features = ["derive"] } serde = { version = "1.0.101", features = ["derive"] }
@ -23,4 +26,6 @@ futures = "0.3.1"
pin-project = "0.4.6" pin-project = "0.4.6"
serde_with_macros = "1.0.1" serde_with_macros = "1.0.1"
either = "1.5.3" either = "1.5.3"
mime = "0.3.16" mime = "0.3.16"
regex = {version = "1.3.3", optional = true}

View file

@ -2,6 +2,8 @@
pub use main::*; pub use main::*;
#[cfg(feature = "regex_filter")]
pub use regex_filter::*;
pub use command::*; pub use command::*;
pub use message_caption::*; pub use message_caption::*;
pub use message_text::*; pub use message_text::*;
@ -13,3 +15,6 @@ mod command;
mod message_caption; mod message_caption;
mod message_text; mod message_text;
mod message_text_caption; mod message_text_caption;
#[cfg(feature = "regex_filter")]
mod regex_filter;

View file

@ -0,0 +1,73 @@
use regex::Regex;
use crate::dispatching::Filter;
use crate::types::Message;
// TODO: docs
pub struct RegexFilter {
regexp: Regex
}
impl Filter<Message> for RegexFilter {
fn test(&self, value: &Message) -> bool {
self.regexp.is_match(value.text()?)
}
}
impl RegexFilter {
pub fn new(regexp: Regex) -> Self {
Self {
regexp
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{
Chat, ChatKind, ForwardKind, MediaKind, MessageKind, Sender, User,
};
#[test]
fn match_true() {
let filter = RegexFilter::new(Regex::new(r"\w+").unwrap());
let message = create_message_with_text("text".to_string());
assert!(filter.test(&message));
}
fn create_message_with_text(text: String) -> Message {
Message {
id: 0,
date: 0,
chat: Chat {
id: 0,
kind: ChatKind::Private {
type_: (),
username: None,
first_name: None,
last_name: None,
},
photo: None,
},
kind: MessageKind::Common {
from: Sender::User(User {
id: 0,
is_bot: false,
first_name: "".to_string(),
last_name: None,
username: None,
language_code: None,
}),
forward_kind: ForwardKind::Origin {
reply_to_message: None,
},
edit_date: None,
media_kind: MediaKind::Text {
text,
entities: vec![],
},
reply_markup: None,
},
}
}
}