Skip to main content

Chat

Struct Chat 

Source
pub struct Chat {
    pub id: ChatId,
    pub kind: ChatKind,
}
Expand description

This object represents a chat.

The official docs.

Fields§

§id: ChatId

A unique identifier for this chat.

§kind: ChatKind

Implementations§

Source§

impl Chat

Source

pub fn is_private(&self) -> bool

Source

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(msg.chat.id, value.to_string()).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(msg.chat.id, format!("You said: {text}"))
64                                        .await?;
65                                    Ok(())
66                                }
67                            }
68                        },
69                    ),
70                )
71                .branch(
72                    // An endpoint is the last update handler.
73                    dptree::endpoint(|msg: Message, bot: Bot| async move {
74                        log::info!("Received a message from a group chat.");
75                        bot.send_message(msg.chat.id, "This is a group chat.").await?;
76                        respond(())
77                    }),
78                ),
79        )
80        .branch(
81            // There are some extension filtering functions on `Message`. The following filter will
82            // filter only messages with dices.
83            Message::filter_dice().endpoint(|bot: Bot, msg: Message, dice: Dice| async move {
84                bot.send_message(msg.chat.id, format!("Dice value: {}", dice.value))
85                    .reply_to(msg)
86                    .await?;
87                Ok(())
88            }),
89        );
90
91    Dispatcher::builder(bot, handler)
92        // Here you specify initial dependencies that all handlers will receive; they can be
93        // database connections, configurations, and other auxiliary arguments. It is similar to
94        // `actix_web::Extensions`.
95        .dependencies(dptree::deps![parameters])
96        // If no handler succeeded to handle an update, this closure will be called.
97        .default_handler(|upd| async move {
98            log::warn!("Unhandled update: {upd:?}");
99        })
100        // If the dispatcher fails for some reason, execute this handler.
101        .error_handler(LoggingErrorHandler::with_custom_text(
102            "An error has occurred in the dispatcher",
103        ))
104        .enable_ctrlc_handler()
105        .build()
106        .dispatch()
107        .await;
108}
109
110#[derive(Clone)]
111struct ConfigParameters {
112    bot_maintainer: UserId,
113    maintainer_username: Option<String>,
114}
115
116/// Simple commands
117#[derive(BotCommands, Clone)]
118#[command(rename_rule = "lowercase")]
119enum SimpleCommand {
120    /// Shows this message.
121    Help,
122    /// Shows maintainer info.
123    Maintainer,
124    /// Shows your ID.
125    MyId,
126}
127
128/// Maintainer commands
129#[derive(BotCommands, Clone)]
130#[command(rename_rule = "lowercase")]
131enum MaintainerCommands {
132    /// Generate a number within range
133    #[command(parse_with = "split")]
134    Rand { from: u64, to: u64 },
135}
136
137/// Group commands
138#[derive(BotCommands, Clone)]
139#[command(rename_rule = "lowercase")]
140enum GroupCommand {
141    /// Repeats a message
142    Repeat { text: String },
143}
144
145async fn simple_commands_handler(
146    cfg: ConfigParameters,
147    bot: Bot,
148    me: teloxide_ng::types::Me,
149    msg: Message,
150    cmd: SimpleCommand,
151) -> Result<(), teloxide_ng::RequestError> {
152    let text = match cmd {
153        SimpleCommand::Help => {
154            if msg.from.unwrap().id == cfg.bot_maintainer {
155                format!(
156                    "{}\n\n{}",
157                    SimpleCommand::descriptions(),
158                    MaintainerCommands::descriptions()
159                )
160            } else if msg.chat.is_group() || msg.chat.is_supergroup() {
161                SimpleCommand::descriptions().username_from_me(&me).to_string()
162            } else {
163                SimpleCommand::descriptions().to_string()
164            }
165        }
166        SimpleCommand::Maintainer => {
167            if msg.from.as_ref().unwrap().id == cfg.bot_maintainer {
168                "Maintainer is you!".into()
169            } else if let Some(username) = cfg.maintainer_username {
170                format!("Maintainer is @{username}")
171            } else {
172                format!("Maintainer ID is {}", cfg.bot_maintainer)
173            }
174        }
175        SimpleCommand::MyId => {
176            format!("{}", msg.from.unwrap().id)
177        }
178    };
179
180    bot.send_message(msg.chat.id, text).await?;
181
182    Ok(())
183}
Source

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(msg.chat.id, value.to_string()).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(msg.chat.id, format!("You said: {text}"))
64                                        .await?;
65                                    Ok(())
66                                }
67                            }
68                        },
69                    ),
70                )
71                .branch(
72                    // An endpoint is the last update handler.
73                    dptree::endpoint(|msg: Message, bot: Bot| async move {
74                        log::info!("Received a message from a group chat.");
75                        bot.send_message(msg.chat.id, "This is a group chat.").await?;
76                        respond(())
77                    }),
78                ),
79        )
80        .branch(
81            // There are some extension filtering functions on `Message`. The following filter will
82            // filter only messages with dices.
83            Message::filter_dice().endpoint(|bot: Bot, msg: Message, dice: Dice| async move {
84                bot.send_message(msg.chat.id, format!("Dice value: {}", dice.value))
85                    .reply_to(msg)
86                    .await?;
87                Ok(())
88            }),
89        );
90
91    Dispatcher::builder(bot, handler)
92        // Here you specify initial dependencies that all handlers will receive; they can be
93        // database connections, configurations, and other auxiliary arguments. It is similar to
94        // `actix_web::Extensions`.
95        .dependencies(dptree::deps![parameters])
96        // If no handler succeeded to handle an update, this closure will be called.
97        .default_handler(|upd| async move {
98            log::warn!("Unhandled update: {upd:?}");
99        })
100        // If the dispatcher fails for some reason, execute this handler.
101        .error_handler(LoggingErrorHandler::with_custom_text(
102            "An error has occurred in the dispatcher",
103        ))
104        .enable_ctrlc_handler()
105        .build()
106        .dispatch()
107        .await;
108}
109
110#[derive(Clone)]
111struct ConfigParameters {
112    bot_maintainer: UserId,
113    maintainer_username: Option<String>,
114}
115
116/// Simple commands
117#[derive(BotCommands, Clone)]
118#[command(rename_rule = "lowercase")]
119enum SimpleCommand {
120    /// Shows this message.
121    Help,
122    /// Shows maintainer info.
123    Maintainer,
124    /// Shows your ID.
125    MyId,
126}
127
128/// Maintainer commands
129#[derive(BotCommands, Clone)]
130#[command(rename_rule = "lowercase")]
131enum MaintainerCommands {
132    /// Generate a number within range
133    #[command(parse_with = "split")]
134    Rand { from: u64, to: u64 },
135}
136
137/// Group commands
138#[derive(BotCommands, Clone)]
139#[command(rename_rule = "lowercase")]
140enum GroupCommand {
141    /// Repeats a message
142    Repeat { text: String },
143}
144
145async fn simple_commands_handler(
146    cfg: ConfigParameters,
147    bot: Bot,
148    me: teloxide_ng::types::Me,
149    msg: Message,
150    cmd: SimpleCommand,
151) -> Result<(), teloxide_ng::RequestError> {
152    let text = match cmd {
153        SimpleCommand::Help => {
154            if msg.from.unwrap().id == cfg.bot_maintainer {
155                format!(
156                    "{}\n\n{}",
157                    SimpleCommand::descriptions(),
158                    MaintainerCommands::descriptions()
159                )
160            } else if msg.chat.is_group() || msg.chat.is_supergroup() {
161                SimpleCommand::descriptions().username_from_me(&me).to_string()
162            } else {
163                SimpleCommand::descriptions().to_string()
164            }
165        }
166        SimpleCommand::Maintainer => {
167            if msg.from.as_ref().unwrap().id == cfg.bot_maintainer {
168                "Maintainer is you!".into()
169            } else if let Some(username) = cfg.maintainer_username {
170                format!("Maintainer is @{username}")
171            } else {
172                format!("Maintainer ID is {}", cfg.bot_maintainer)
173            }
174        }
175        SimpleCommand::MyId => {
176            format!("{}", msg.from.unwrap().id)
177        }
178    };
179
180    bot.send_message(msg.chat.id, text).await?;
181
182    Ok(())
183}
Source

pub fn is_channel(&self) -> bool

Source

pub fn is_chat(&self) -> bool

Source§

impl Chat

Getters

Source

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(chat_member.chat.id, format!("Welcome to {telegram_group_name} {username}!"))
63        .await?;
64
65    Ok(())
66}
Source

pub fn username(&self) -> Option<&str>

A username, for private chats, supergroups and channels if available.

Source

pub fn first_name(&self) -> Option<&str>

A first name of the other party in a private chat.

Source

pub fn last_name(&self) -> Option<&str>

A last name of the other party in a private chat.

Trait Implementations§

Source§

impl Clone for Chat

Source§

fn clone(&self) -> Chat

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Chat

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Chat

Source§

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
Source§

impl GetChatId for Chat

Source§

impl Hash for Chat

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Chat

Source§

fn eq(&self, other: &Chat) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Chat

Source§

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
Source§

impl Eq for Chat

Source§

impl StructuralPartialEq for Chat

Auto Trait Implementations§

§

impl Freeze for Chat

§

impl RefUnwindSafe for Chat

§

impl Send for Chat

§

impl Sync for Chat

§

impl Unpin for Chat

§

impl UnwindSafe for Chat

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> Erasable for T

Source§

const ACK_1_1_0: bool = true

Available on non-enforce_1_1_0_semantics only.
Whether this implementor has acknowledged the 1.1.0 update to unerase’s documented implementation requirements. Read more
Source§

unsafe fn unerase(this: NonNull<Erased>) -> NonNull<T>

Unerase this erased pointer. Read more
Source§

fn erase(this: NonNull<Self>) -> NonNull<Erased>

Turn this erasable pointer into an erased pointer. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,