Added mention command filter to dispatching_reatures example

This commit is contained in:
LasterAlex 2024-08-18 13:54:09 +03:00
parent 8d9ca4d719
commit 9d591ac3e6
No known key found for this signature in database
2 changed files with 39 additions and 15 deletions

View file

@ -4,6 +4,7 @@
use rand::Rng;
use teloxide::{
dispatching::HandlerExt,
prelude::*,
types::{Dice, ReplyParameters},
utils::command::BotCommands,
@ -52,12 +53,31 @@ async fn main() {
.branch(
// Filtering allow you to filter updates by some condition.
dptree::filter(|msg: Message| msg.chat.is_group() || msg.chat.is_supergroup())
.branch(
// Filtering by mention allows to filter only `/repeat@my_bot` commands.
// Use if you want to make sure that users refer specifically to your bot.
// Same as filter_command, the next handlers will receive a parsed
// `GroupCommand`.
dptree::entry().filter_mention_command::<GroupCommand>().endpoint(
|bot: Bot, msg: Message, cmd: GroupCommand| async move {
match cmd {
GroupCommand::Repeat { text } => {
bot.send_message(msg.chat.id, "You said: ".to_owned() + &text)
.await?;
Ok(())
}
}
},
),
)
.branch(
// An endpoint is the last update handler.
.endpoint(|msg: Message, bot: Bot| async move {
dptree::endpoint(|msg: Message, bot: Bot| async move {
log::info!("Received a message from a group chat.");
bot.send_message(msg.chat.id, "This is a group chat.").await?;
respond(())
}),
),
)
.branch(
// There are some extension filtering functions on `Message`. The following filter will
@ -116,6 +136,14 @@ enum MaintainerCommands {
Rand { from: u64, to: u64 },
}
/// Group commands
#[derive(BotCommands, Clone)]
#[command(rename_rule = "lowercase")]
enum GroupCommand {
/// Repeats a message
Repeat { text: String },
}
async fn simple_commands_handler(
cfg: ConfigParameters,
bot: Bot,

View file

@ -149,6 +149,7 @@ where
}
#[cfg(test)]
#[cfg(feature = "macros")]
mod tests {
use crate::{self as teloxide, dispatching::UpdateFilterExt, utils::command::BotCommands};
use chrono::DateTime;
@ -161,7 +162,6 @@ mod tests {
use super::HandlerExt;
#[cfg(feature = "macros")]
#[derive(BotCommands, Clone)]
#[command(rename_rule = "lowercase")]
enum Cmd {
@ -255,11 +255,9 @@ mod tests {
}
#[tokio::test]
#[cfg(feature = "macros")]
async fn test_filter_command() {
let h = dptree::entry().branch(
Update::filter_message().filter_command::<Cmd>().endpoint(|| async {}),
);
let h = dptree::entry()
.branch(Update::filter_message().filter_command::<Cmd>().endpoint(|| async {}));
let me = make_me();
let update = make_update("/test@".to_owned() + me.username());
@ -276,11 +274,9 @@ mod tests {
}
#[tokio::test]
#[cfg(feature = "macros")]
async fn test_filter_mention_command() {
let h = dptree::entry().branch(
Update::filter_message().filter_mention_command::<Cmd>().endpoint(|| async {}),
);
let h = dptree::entry()
.branch(Update::filter_message().filter_mention_command::<Cmd>().endpoint(|| async {}));
let me = make_me();
let update = make_update("/test@".to_owned() + me.username());