pub struct Chat {
pub id: ChatId,
pub kind: ChatKind,
}Expand description
This object represents a chat.
Fields§
§id: ChatIdA unique identifier for this chat.
kind: ChatKindImplementations§
Source§impl Chat
impl Chat
pub fn is_private(&self) -> bool
Sourcepub fn is_group(&self) -> bool
pub fn is_group(&self) -> bool
Examples found in repository?
examples/dispatching_features.rs (line 53)
12async fn main() {
13 pretty_env_logger::init();
14 log::info!("Starting dispatching features bot...");
15
16 let bot = Bot::from_env();
17
18 let parameters = ConfigParameters {
19 bot_maintainer: UserId(0), // Paste your ID to run this bot.
20 maintainer_username: None,
21 };
22
23 let handler = Update::filter_message()
24 // You can use branching to define multiple ways in which an update will be handled. If the
25 // first branch fails, an update will be passed to the second branch, and so on.
26 .branch(
27 dptree::entry()
28 // Filter commands: the next handlers will receive a parsed `SimpleCommand`.
29 .filter_command::<SimpleCommand>()
30 // If a command parsing fails, this handler will not be executed.
31 .endpoint(simple_commands_handler),
32 )
33 .branch(
34 // Filter a maintainer by a user ID.
35 dptree::filter(|cfg: ConfigParameters, msg: Message| {
36 msg.from.map(|user| user.id == cfg.bot_maintainer).unwrap_or_default()
37 })
38 .filter_command::<MaintainerCommands>()
39 .endpoint(|msg: Message, bot: Bot, cmd: MaintainerCommands| async move {
40 match cmd {
41 MaintainerCommands::Rand { from, to } => {
42 let value: u64 = rand::rng().random_range(from..=to);
43
44 bot.send_message(value.to_string()).chat_id(msg.chat.id).await?;
45
46 Ok(())
47 }
48 }
49 }),
50 )
51 .branch(
52 // Filtering allow you to filter updates by some condition.
53 dptree::filter(|msg: Message| msg.chat.is_group() || msg.chat.is_supergroup())
54 .branch(
55 // Filtering by mention allows to filter only `/repeat@my_bot` commands.
56 // Use if you want to make sure that users refer specifically to your bot.
57 // Same as filter_command, the next handlers will receive a parsed
58 // `GroupCommand`.
59 dptree::entry().filter_mention_command::<GroupCommand>().endpoint(
60 |bot: Bot, msg: Message, cmd: GroupCommand| async move {
61 match cmd {
62 GroupCommand::Repeat { text } => {
63 bot.send_message(format!("You said: {text}"))
64 .chat_id(msg.chat.id)
65 .await?;
66 Ok(())
67 }
68 }
69 },
70 ),
71 )
72 .branch(
73 // An endpoint is the last update handler.
74 dptree::endpoint(|msg: Message, bot: Bot| async move {
75 log::info!("Received a message from a group chat.");
76 bot.send_message("This is a group chat.").chat_id(msg.chat.id).await?;
77 respond(())
78 }),
79 ),
80 )
81 .branch(
82 // There are some extension filtering functions on `Message`. The following filter will
83 // filter only messages with dices.
84 Message::filter_dice().endpoint(|bot: Bot, msg: Message, dice: Dice| async move {
85 bot.send_message(format!("Dice value: {}", dice.value))
86 .chat_id(msg.chat.id)
87 .reply_to(msg)
88 .await?;
89 Ok(())
90 }),
91 );
92
93 Dispatcher::builder(bot, handler)
94 // Here you specify initial dependencies that all handlers will receive; they can be
95 // database connections, configurations, and other auxiliary arguments. It is similar to
96 // `actix_web::Extensions`.
97 .dependencies(dptree::deps![parameters])
98 // If no handler succeeded to handle an update, this closure will be called.
99 .default_handler(|upd| async move {
100 log::warn!("Unhandled update: {upd:?}");
101 })
102 // If the dispatcher fails for some reason, execute this handler.
103 .error_handler(LoggingErrorHandler::with_custom_text(
104 "An error has occurred in the dispatcher",
105 ))
106 .enable_ctrlc_handler()
107 .build()
108 .dispatch()
109 .await;
110}
111
112#[derive(Clone)]
113struct ConfigParameters {
114 bot_maintainer: UserId,
115 maintainer_username: Option<String>,
116}
117
118/// Simple commands
119#[derive(BotCommands, Clone)]
120#[command(rename_rule = "lowercase")]
121enum SimpleCommand {
122 /// Shows this message.
123 Help,
124 /// Shows maintainer info.
125 Maintainer,
126 /// Shows your ID.
127 MyId,
128}
129
130/// Maintainer commands
131#[derive(BotCommands, Clone)]
132#[command(rename_rule = "lowercase")]
133enum MaintainerCommands {
134 /// Generate a number within range
135 #[command(parse_with = "split")]
136 Rand { from: u64, to: u64 },
137}
138
139/// Group commands
140#[derive(BotCommands, Clone)]
141#[command(rename_rule = "lowercase")]
142enum GroupCommand {
143 /// Repeats a message
144 Repeat { text: String },
145}
146
147async fn simple_commands_handler(
148 cfg: ConfigParameters,
149 bot: Bot,
150 me: teloxide::types::BotFullInfo,
151 msg: Message,
152 cmd: SimpleCommand,
153) -> Result<(), teloxide::RequestError> {
154 let text = match cmd {
155 SimpleCommand::Help => {
156 if msg.from.unwrap().id == cfg.bot_maintainer {
157 format!(
158 "{}\n\n{}",
159 SimpleCommand::descriptions(),
160 MaintainerCommands::descriptions()
161 )
162 } else if msg.chat.is_group() || msg.chat.is_supergroup() {
163 SimpleCommand::descriptions().username_from_me(&me).to_string()
164 } else {
165 SimpleCommand::descriptions().to_string()
166 }
167 }
168 SimpleCommand::Maintainer => {
169 if msg.from.as_ref().unwrap().id == cfg.bot_maintainer {
170 "Maintainer is you!".into()
171 } else if let Some(username) = cfg.maintainer_username {
172 format!("Maintainer is @{username}")
173 } else {
174 format!("Maintainer ID is {}", cfg.bot_maintainer)
175 }
176 }
177 SimpleCommand::MyId => {
178 format!("{}", msg.from.unwrap().id)
179 }
180 };
181
182 bot.send_message(text).chat_id(msg.chat.id).await?;
183
184 Ok(())
185}Sourcepub fn is_supergroup(&self) -> bool
pub fn is_supergroup(&self) -> bool
Examples found in repository?
examples/dispatching_features.rs (line 53)
12async fn main() {
13 pretty_env_logger::init();
14 log::info!("Starting dispatching features bot...");
15
16 let bot = Bot::from_env();
17
18 let parameters = ConfigParameters {
19 bot_maintainer: UserId(0), // Paste your ID to run this bot.
20 maintainer_username: None,
21 };
22
23 let handler = Update::filter_message()
24 // You can use branching to define multiple ways in which an update will be handled. If the
25 // first branch fails, an update will be passed to the second branch, and so on.
26 .branch(
27 dptree::entry()
28 // Filter commands: the next handlers will receive a parsed `SimpleCommand`.
29 .filter_command::<SimpleCommand>()
30 // If a command parsing fails, this handler will not be executed.
31 .endpoint(simple_commands_handler),
32 )
33 .branch(
34 // Filter a maintainer by a user ID.
35 dptree::filter(|cfg: ConfigParameters, msg: Message| {
36 msg.from.map(|user| user.id == cfg.bot_maintainer).unwrap_or_default()
37 })
38 .filter_command::<MaintainerCommands>()
39 .endpoint(|msg: Message, bot: Bot, cmd: MaintainerCommands| async move {
40 match cmd {
41 MaintainerCommands::Rand { from, to } => {
42 let value: u64 = rand::rng().random_range(from..=to);
43
44 bot.send_message(value.to_string()).chat_id(msg.chat.id).await?;
45
46 Ok(())
47 }
48 }
49 }),
50 )
51 .branch(
52 // Filtering allow you to filter updates by some condition.
53 dptree::filter(|msg: Message| msg.chat.is_group() || msg.chat.is_supergroup())
54 .branch(
55 // Filtering by mention allows to filter only `/repeat@my_bot` commands.
56 // Use if you want to make sure that users refer specifically to your bot.
57 // Same as filter_command, the next handlers will receive a parsed
58 // `GroupCommand`.
59 dptree::entry().filter_mention_command::<GroupCommand>().endpoint(
60 |bot: Bot, msg: Message, cmd: GroupCommand| async move {
61 match cmd {
62 GroupCommand::Repeat { text } => {
63 bot.send_message(format!("You said: {text}"))
64 .chat_id(msg.chat.id)
65 .await?;
66 Ok(())
67 }
68 }
69 },
70 ),
71 )
72 .branch(
73 // An endpoint is the last update handler.
74 dptree::endpoint(|msg: Message, bot: Bot| async move {
75 log::info!("Received a message from a group chat.");
76 bot.send_message("This is a group chat.").chat_id(msg.chat.id).await?;
77 respond(())
78 }),
79 ),
80 )
81 .branch(
82 // There are some extension filtering functions on `Message`. The following filter will
83 // filter only messages with dices.
84 Message::filter_dice().endpoint(|bot: Bot, msg: Message, dice: Dice| async move {
85 bot.send_message(format!("Dice value: {}", dice.value))
86 .chat_id(msg.chat.id)
87 .reply_to(msg)
88 .await?;
89 Ok(())
90 }),
91 );
92
93 Dispatcher::builder(bot, handler)
94 // Here you specify initial dependencies that all handlers will receive; they can be
95 // database connections, configurations, and other auxiliary arguments. It is similar to
96 // `actix_web::Extensions`.
97 .dependencies(dptree::deps![parameters])
98 // If no handler succeeded to handle an update, this closure will be called.
99 .default_handler(|upd| async move {
100 log::warn!("Unhandled update: {upd:?}");
101 })
102 // If the dispatcher fails for some reason, execute this handler.
103 .error_handler(LoggingErrorHandler::with_custom_text(
104 "An error has occurred in the dispatcher",
105 ))
106 .enable_ctrlc_handler()
107 .build()
108 .dispatch()
109 .await;
110}
111
112#[derive(Clone)]
113struct ConfigParameters {
114 bot_maintainer: UserId,
115 maintainer_username: Option<String>,
116}
117
118/// Simple commands
119#[derive(BotCommands, Clone)]
120#[command(rename_rule = "lowercase")]
121enum SimpleCommand {
122 /// Shows this message.
123 Help,
124 /// Shows maintainer info.
125 Maintainer,
126 /// Shows your ID.
127 MyId,
128}
129
130/// Maintainer commands
131#[derive(BotCommands, Clone)]
132#[command(rename_rule = "lowercase")]
133enum MaintainerCommands {
134 /// Generate a number within range
135 #[command(parse_with = "split")]
136 Rand { from: u64, to: u64 },
137}
138
139/// Group commands
140#[derive(BotCommands, Clone)]
141#[command(rename_rule = "lowercase")]
142enum GroupCommand {
143 /// Repeats a message
144 Repeat { text: String },
145}
146
147async fn simple_commands_handler(
148 cfg: ConfigParameters,
149 bot: Bot,
150 me: teloxide::types::BotFullInfo,
151 msg: Message,
152 cmd: SimpleCommand,
153) -> Result<(), teloxide::RequestError> {
154 let text = match cmd {
155 SimpleCommand::Help => {
156 if msg.from.unwrap().id == cfg.bot_maintainer {
157 format!(
158 "{}\n\n{}",
159 SimpleCommand::descriptions(),
160 MaintainerCommands::descriptions()
161 )
162 } else if msg.chat.is_group() || msg.chat.is_supergroup() {
163 SimpleCommand::descriptions().username_from_me(&me).to_string()
164 } else {
165 SimpleCommand::descriptions().to_string()
166 }
167 }
168 SimpleCommand::Maintainer => {
169 if msg.from.as_ref().unwrap().id == cfg.bot_maintainer {
170 "Maintainer is you!".into()
171 } else if let Some(username) = cfg.maintainer_username {
172 format!("Maintainer is @{username}")
173 } else {
174 format!("Maintainer ID is {}", cfg.bot_maintainer)
175 }
176 }
177 SimpleCommand::MyId => {
178 format!("{}", msg.from.unwrap().id)
179 }
180 };
181
182 bot.send_message(text).chat_id(msg.chat.id).await?;
183
184 Ok(())
185}pub fn is_channel(&self) -> bool
pub fn is_chat(&self) -> bool
Source§impl Chat
Getters
impl Chat
Getters
Sourcepub fn title(&self) -> Option<&str>
pub fn title(&self) -> Option<&str>
A title, for supergroups, channels and group chats.
Examples found in repository?
examples/chat_member_updates.rs (line 54)
51async fn new_chat_member(bot: Bot, chat_member: ChatMemberUpdated) -> ResponseResult<()> {
52 let user = chat_member.old_chat_member.user.clone();
53
54 let telegram_group_name = chat_member.chat.title().unwrap_or("");
55
56 // We get a "@username" mention via `mention()` method if the user has a
57 // username, otherwise we create a textual mention with "Full Name" as the
58 // text linking to the user
59 let username =
60 user.mention().unwrap_or_else(|| html::user_mention(user.id, user.full_name().as_str()));
61
62 bot.send_message(format!("Welcome to {telegram_group_name} {username}!"))
63 .chat_id(chat_member.chat.id)
64 .await?;
65
66 Ok(())
67}Sourcepub fn username(&self) -> Option<&str>
pub fn username(&self) -> Option<&str>
A username, for private chats, supergroups and channels if available.
Sourcepub fn first_name(&self) -> Option<&str>
pub fn first_name(&self) -> Option<&str>
A first name of the other party in a private chat.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Chat
impl<'de> Deserialize<'de> for Chat
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<Chat, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<Chat, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
impl Eq for Chat
Source§impl Serialize for Chat
impl Serialize for Chat
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Serialize this value into the given Serde serializer. Read more
impl StructuralPartialEq for Chat
Auto Trait Implementations§
impl Forget for Chat
impl Freeze for Chat
impl Move for Chat
impl RefUnwindSafe for Chat
impl Send for Chatwhere
RawVecInner: Send,
impl Sync for Chatwhere
RawVecInner: Sync,
impl Unpin for Chat
impl UnsafeUnpin for Chat
impl UnwindSafe for Chatwhere
RawVecInner: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key and return true if they are equal.Source§impl<T> Erasable for T
impl<T> Erasable for T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more