serenity/model/channel/guild_channel.rs
1use std::fmt;
2#[cfg(feature = "model")]
3use std::sync::Arc;
4
5#[cfg(feature = "model")]
6use crate::builder::{
7 Builder,
8 CreateAttachment,
9 CreateForumPost,
10 CreateInvite,
11 CreateMessage,
12 CreateStageInstance,
13 CreateThread,
14 CreateWebhook,
15 EditChannel,
16 EditMessage,
17 EditStageInstance,
18 EditThread,
19 EditVoiceState,
20 GetMessages,
21};
22#[cfg(feature = "cache")]
23use crate::cache::{self, Cache};
24#[cfg(feature = "collector")]
25use crate::collector::{MessageCollector, ReactionCollector};
26#[cfg(feature = "collector")]
27use crate::gateway::ShardMessenger;
28#[cfg(feature = "model")]
29use crate::http::{CacheHttp, Http, Typing};
30#[cfg(all(feature = "cache", feature = "model"))]
31use crate::internal::prelude::*;
32use crate::model::prelude::*;
33
34/// Represents a guild's text, news, or voice channel.
35///
36/// Some methods are available only for voice channels and some are only available for text
37/// channels. News channels are a subset of text channels and lack slow mode hence
38/// [`Self::rate_limit_per_user`] will be [`None`].
39///
40/// [Discord docs](https://discord.com/developers/docs/resources/channel#channel-object).
41#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
42#[derive(Clone, Debug, Default, Deserialize, Serialize)]
43#[non_exhaustive]
44pub struct GuildChannel {
45 /// The unique Id of the channel.
46 pub id: ChannelId,
47 /// The bitrate of the channel.
48 ///
49 /// **Note**: This is only available for voice and stage channels.
50 pub bitrate: Option<u32>,
51 /// The Id of the parent category for a channel, or of the parent text channel for a thread.
52 ///
53 /// **Note**: This is only available for channels in a category and thread channels.
54 pub parent_id: Option<ChannelId>,
55 /// The Id of the guild the channel is located in.
56 ///
57 /// The original voice channel has an Id equal to the guild's Id, incremented by one.
58 ///
59 /// [`id`]: GuildChannel::id
60 #[serde(default)]
61 pub guild_id: GuildId,
62 /// The type of the channel.
63 #[serde(rename = "type")]
64 pub kind: ChannelType,
65 /// The Id of the user who created this channel
66 ///
67 /// **Note**: This is only available for threads and forum posts
68 pub owner_id: Option<UserId>,
69 /// The Id of the last message sent in the channel.
70 ///
71 /// **Note**: This is only available for text channels.
72 pub last_message_id: Option<MessageId>,
73 /// The timestamp of the time a pin was most recently made.
74 ///
75 /// **Note**: This is only available for text channels.
76 pub last_pin_timestamp: Option<Timestamp>,
77 /// The name of the channel.
78 pub name: String,
79 /// Permission overwrites for [`Member`]s and for [`Role`]s.
80 #[serde(default)]
81 pub permission_overwrites: Vec<PermissionOverwrite>,
82 /// The position of the channel.
83 ///
84 /// The default text channel will _almost always_ have a position of `0`.
85 #[serde(default)]
86 pub position: u16,
87 /// The topic of the channel.
88 ///
89 /// **Note**: This is only available for text, forum and stage channels.
90 pub topic: Option<String>,
91 /// The maximum number of members allowed in the channel.
92 ///
93 /// **Note**: This is only available for voice channels.
94 pub user_limit: Option<u32>,
95 /// Used to tell if the channel is not safe for work.
96 // This field can or can not be present sometimes, but if it isn't default to `false`.
97 #[serde(default)]
98 pub nsfw: bool,
99 /// A rate limit that applies per user and excludes bots.
100 ///
101 /// **Note**: This is only available for text channels excluding news channels.
102 #[doc(alias = "slowmode")]
103 #[serde(default)]
104 pub rate_limit_per_user: Option<u16>,
105 /// The region override.
106 ///
107 /// **Note**: This is only available for voice and stage channels. [`None`] for voice and stage
108 /// channels means automatic region selection.
109 pub rtc_region: Option<String>,
110 /// The video quality mode for a voice channel.
111 pub video_quality_mode: Option<VideoQualityMode>,
112 /// An approximate count of messages in the thread.
113 ///
114 /// This is currently saturated at 255 to prevent breaking.
115 ///
116 /// **Note**: This is only available on thread channels.
117 pub message_count: Option<u32>,
118 /// An approximate count of users in a thread, stops counting at 50.
119 ///
120 /// **Note**: This is only available on thread channels.
121 pub member_count: Option<u8>,
122 /// The thread metadata.
123 ///
124 /// **Note**: This is only available on thread channels.
125 pub thread_metadata: Option<ThreadMetadata>,
126 /// Thread member object for the current user, if they have joined the thread, only included on
127 /// certain API endpoints.
128 pub member: Option<PartialThreadMember>,
129 /// Default duration for newly created threads, in minutes, to automatically archive the thread
130 /// after recent activity.
131 pub default_auto_archive_duration: Option<AutoArchiveDuration>,
132 /// Computed permissions for the invoking user in the channel, including overwrites.
133 ///
134 /// Only included inside [`CommandDataResolved`].
135 pub permissions: Option<Permissions>,
136 /// Extra information about the channel
137 ///
138 /// **Note**: This is only available in forum channels.
139 #[serde(default)]
140 pub flags: ChannelFlags,
141 /// The number of messages ever sent in a thread, it's similar to `message_count` on message
142 /// creation, but will not decrement the number when a message is deleted.
143 pub total_message_sent: Option<u64>,
144 /// The set of available tags.
145 ///
146 /// **Note**: This is only available in forum channels.
147 #[serde(default)]
148 pub available_tags: Vec<ForumTag>,
149 /// The set of applied tags.
150 ///
151 /// **Note**: This is only available in a thread in a forum.
152 #[serde(default)]
153 pub applied_tags: Vec<ForumTagId>,
154 /// The emoji to show in the add reaction button
155 ///
156 /// **Note**: This is only available in a forum.
157 pub default_reaction_emoji: Option<ForumEmoji>,
158 /// The initial `rate_limit_per_user` to set on newly created threads in a channel. This field
159 /// is copied to the thread at creation time and does not live update.
160 ///
161 /// **Note**: This is only available in a forum or text channel.
162 pub default_thread_rate_limit_per_user: Option<u16>,
163 /// The status of a voice channel.
164 ///
165 /// **Note**: This is only available in voice channels.
166 pub status: Option<String>,
167 /// The default sort order type used to order posts
168 ///
169 /// **Note**: This is only available in a forum.
170 pub default_sort_order: Option<SortOrder>,
171 /// The default forum layout view used to display posts in a forum. Defaults to 0, which
172 /// indicates a layout view has not been set by a channel admin.
173 ///
174 /// **Note**: This is only available in a forum.
175 pub default_forum_layout: Option<ForumLayoutType>,
176}
177
178enum_number! {
179 /// See [`GuildChannel::default_forum_layout`].
180 ///
181 /// [Discord docs](https://discord.com/developers/docs/resources/channel#channel-object-forum-layout-types).
182 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
183 #[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
184 #[serde(from = "u8", into = "u8")]
185 #[non_exhaustive]
186 pub enum ForumLayoutType {
187 /// No default has been set for forum channel.
188 #[default]
189 NotSet = 0,
190 /// Display posts as a list.
191 ListView = 1,
192 /// Display posts as a collection of tiles.
193 GalleryView = 2,
194 _ => Unknown(u8),
195 }
196}
197
198#[cfg(feature = "model")]
199impl GuildChannel {
200 /// Whether or not this channel is text-based, meaning that it is possible to send messages.
201 #[must_use]
202 pub fn is_text_based(&self) -> bool {
203 matches!(
204 self.kind,
205 ChannelType::Text
206 | ChannelType::News
207 | ChannelType::Voice
208 | ChannelType::Stage
209 | ChannelType::PublicThread
210 | ChannelType::PrivateThread
211 | ChannelType::NewsThread
212 )
213 }
214
215 /// Broadcasts to the channel that the current user is typing.
216 ///
217 /// For bots, this is a good indicator for long-running commands.
218 ///
219 /// **Note**: Requires the [Send Messages] permission.
220 ///
221 /// # Errors
222 ///
223 /// Returns [`Error::Http`] if the current user does not have the required permissions.
224 ///
225 /// [Send Messages]: Permissions::SEND_MESSAGES
226 #[inline]
227 pub async fn broadcast_typing(&self, http: impl AsRef<Http>) -> Result<()> {
228 self.id.broadcast_typing(http).await
229 }
230
231 /// Creates an invite for the given channel.
232 ///
233 /// **Note**: Requires the [Create Instant Invite] permission.
234 ///
235 /// # Examples
236 ///
237 /// Create an invite that can only be used 5 times:
238 ///
239 /// ```rust,ignore
240 /// let builder = CreateBuilder::default().max_uses(5);
241 /// let invite = channel.create_invite(&context, builder).await;
242 /// ```
243 ///
244 /// # Errors
245 ///
246 /// If the `cache` is enabled, returns [`ModelError::InvalidPermissions`] if the current user
247 /// lacks permission. Otherwise returns [`Error::Http`], as well as if invalid data is given.
248 ///
249 /// [Create Instant Invite]: Permissions::CREATE_INSTANT_INVITE
250 #[inline]
251 #[cfg(feature = "utils")]
252 pub async fn create_invite(
253 &self,
254 cache_http: impl CacheHttp,
255 builder: CreateInvite<'_>,
256 ) -> Result<RichInvite> {
257 builder.execute(cache_http, self.id).await
258 }
259
260 /// Creates a [permission overwrite][`PermissionOverwrite`] for either a single [`Member`] or
261 /// [`Role`] within a [`Channel`].
262 ///
263 /// Refer to the documentation for [`PermissionOverwrite`]s for more information.
264 ///
265 /// Requires the [Manage Channels] permission.
266 ///
267 /// # Examples
268 ///
269 /// Creating a permission overwrite for a member by specifying the
270 /// [`PermissionOverwriteType::Member`] variant, allowing it the [Send Messages] permission,
271 /// but denying the [Send TTS Messages] and [Attach Files] permissions:
272 ///
273 /// ```rust,no_run
274 /// # #[cfg(feature = "cache")]
275 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
276 /// # use serenity::{cache::Cache, http::Http, model::id::{ChannelId, UserId}};
277 /// # use std::sync::Arc;
278 /// #
279 /// # let http: Arc<Http> = unimplemented!();
280 /// # let cache = Cache::default();
281 /// # let (channel_id, user_id) = (ChannelId::new(1), UserId::new(1));
282 /// use serenity::model::channel::{PermissionOverwrite, PermissionOverwriteType};
283 /// use serenity::model::{ModelError, Permissions};
284 /// let allow = Permissions::SEND_MESSAGES;
285 /// let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
286 /// let overwrite = PermissionOverwrite {
287 /// allow,
288 /// deny,
289 /// kind: PermissionOverwriteType::Member(user_id),
290 /// };
291 /// // assuming the cache has been unlocked
292 /// let channel = cache.channel(channel_id).ok_or(ModelError::ItemMissing)?;
293 ///
294 /// channel.create_permission(&http, overwrite).await?;
295 /// # Ok(())
296 /// # }
297 /// ```
298 ///
299 /// Creating a permission overwrite for a role by specifying the
300 /// [`PermissionOverwriteType::Role`] variant, allowing it the [Manage Webhooks]
301 /// permission, but denying the [Send TTS Messages] and [Attach Files]
302 /// permissions:
303 ///
304 /// ```rust,no_run
305 /// # #[cfg(feature = "cache")]
306 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
307 /// # use serenity::{cache::Cache, http::Http, model::id::{ChannelId, UserId, RoleId}};
308 /// # use std::sync::Arc;
309 /// #
310 /// # let http: Arc<Http> = unimplemented!();
311 /// # let cache = Cache::default();
312 /// # let (channel_id, user_id, role_id) = (ChannelId::new(1), UserId::new(1), RoleId::new(1));
313 /// use serenity::model::channel::{Channel, PermissionOverwrite, PermissionOverwriteType};
314 /// use serenity::model::{ModelError, Permissions};
315 ///
316 /// let allow = Permissions::SEND_MESSAGES;
317 /// let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
318 /// let overwrite = PermissionOverwrite {
319 /// allow,
320 /// deny,
321 /// kind: PermissionOverwriteType::Role(role_id),
322 /// };
323 ///
324 /// let channel = cache.channel(channel_id).ok_or(ModelError::ItemMissing)?;
325 ///
326 /// channel.create_permission(&http, overwrite).await?;
327 /// # Ok(())
328 /// # }
329 /// ```
330 ///
331 /// # Errors
332 ///
333 /// Returns [`Error::Http`] if the current user lacks permission.
334 ///
335 /// [Attach Files]: Permissions::ATTACH_FILES
336 /// [Manage Channels]: Permissions::MANAGE_CHANNELS
337 /// [Manage Webhooks]: Permissions::MANAGE_WEBHOOKS
338 /// [Send Messages]: Permissions::SEND_MESSAGES
339 /// [Send TTS Messages]: Permissions::SEND_TTS_MESSAGES
340 #[inline]
341 pub async fn create_permission(
342 &self,
343 http: impl AsRef<Http>,
344 target: PermissionOverwrite,
345 ) -> Result<()> {
346 self.id.create_permission(http, target).await
347 }
348
349 /// Deletes this channel, returning the channel on a successful deletion.
350 ///
351 /// **Note**: Requires the [Manage Channels] permission.
352 ///
353 /// # Errors
354 ///
355 /// If the `cache` is enabled, returns [`ModelError::InvalidPermissions`] if the current user
356 /// does not have permission.
357 ///
358 /// Otherwise returns [`Error::Http`] if the current user lacks permission.
359 ///
360 /// [Manage Channels]: Permissions::MANAGE_CHANNELS
361 pub async fn delete(&self, cache_http: impl CacheHttp) -> Result<GuildChannel> {
362 #[cfg(feature = "cache")]
363 {
364 if let Some(cache) = cache_http.cache() {
365 crate::utils::user_has_perms_cache(cache, self.id, Permissions::MANAGE_CHANNELS)?;
366 }
367 }
368
369 let channel = self.id.delete(cache_http.http()).await?;
370 channel.guild().ok_or(Error::Model(ModelError::InvalidChannelType))
371 }
372
373 /// Deletes all messages by Ids from the given vector in the channel.
374 ///
375 /// The minimum amount of messages is 2 and the maximum amount is 100.
376 ///
377 /// Requires the [Manage Messages] permission.
378 ///
379 /// **Note**: Messages that are older than 2 weeks can't be deleted using this method.
380 ///
381 /// # Errors
382 ///
383 /// Returns [`ModelError::BulkDeleteAmount`] if an attempt was made to delete either 0 or more
384 /// than 100 messages.
385 ///
386 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
387 #[inline]
388 pub async fn delete_messages<T: AsRef<MessageId>>(
389 &self,
390 http: impl AsRef<Http>,
391 message_ids: impl IntoIterator<Item = T>,
392 ) -> Result<()> {
393 self.id.delete_messages(http, message_ids).await
394 }
395
396 /// Deletes all permission overrides in the channel from a member or role.
397 ///
398 /// **Note**: Requires the [Manage Channel] permission.
399 ///
400 /// # Errors
401 ///
402 /// Returns [`Error::Http`] if the current user lacks permission.
403 ///
404 /// [Manage Channel]: Permissions::MANAGE_CHANNELS
405 #[inline]
406 pub async fn delete_permission(
407 &self,
408 http: impl AsRef<Http>,
409 permission_type: PermissionOverwriteType,
410 ) -> Result<()> {
411 self.id.delete_permission(http, permission_type).await
412 }
413
414 /// Deletes the given [`Reaction`] from the channel.
415 ///
416 /// **Note**: Requires the [Manage Messages] permission, _if_ the current user did not perform
417 /// the reaction.
418 ///
419 /// # Errors
420 ///
421 /// Returns [`Error::Http`] if the current user lacks permission. [Manage Messages]:
422 /// Permissions::MANAGE_MESSAGES
423 #[inline]
424 pub async fn delete_reaction(
425 &self,
426 http: impl AsRef<Http>,
427 message_id: impl Into<MessageId>,
428 user_id: Option<UserId>,
429 reaction_type: impl Into<ReactionType>,
430 ) -> Result<()> {
431 self.id.delete_reaction(http, message_id, user_id, reaction_type).await
432 }
433
434 /// Deletes all of the [`Reaction`]s associated with the provided message id.
435 ///
436 /// **Note**: Requires the [Manage Messages] permission.
437 ///
438 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
439 ///
440 /// # Errors
441 ///
442 /// Returns [`Error::Http`] if the current user lacks permission
443 ///
444 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
445 #[inline]
446 pub async fn delete_reactions(
447 &self,
448 http: impl AsRef<Http>,
449 message_id: impl Into<MessageId>,
450 ) -> Result<()> {
451 self.id.delete_reactions(http, message_id).await
452 }
453
454 /// Edits the channel's settings.
455 ///
456 /// Refer to the documentation for [`EditChannel`] for a full list of methods.
457 ///
458 /// **Note**: Requires the [Manage Channels] permission. Modifying permissions via
459 /// [`EditChannel::permissions`] also requires the [Manage Roles] permission.
460 ///
461 /// # Examples
462 ///
463 /// Change a voice channels name and bitrate:
464 ///
465 /// ```rust,no_run
466 /// # use serenity::builder::EditChannel;
467 /// # use serenity::http::Http;
468 /// # use serenity::model::id::ChannelId;
469 /// # async fn run() {
470 /// # let http: Http = unimplemented!();
471 /// # let channel = ChannelId::new(1234);
472 /// let builder = EditChannel::new().name("test").bitrate(86400);
473 /// channel.edit(&http, builder).await;
474 /// # }
475 /// ```
476 ///
477 /// # Errors
478 ///
479 /// If the `cache` is enabled, returns a [`ModelError::InvalidPermissions`] if the current user
480 /// lacks permission. Otherwise returns [`Error::Http`], as well as if invalid data is given.
481 ///
482 /// [Manage Channels]: Permissions::MANAGE_CHANNELS
483 /// [Manage Roles]: Permissions::MANAGE_ROLES
484 pub async fn edit(
485 &mut self,
486 cache_http: impl CacheHttp,
487 builder: EditChannel<'_>,
488 ) -> Result<()> {
489 let channel = builder.execute(cache_http, self.id).await?;
490 *self = channel;
491 Ok(())
492 }
493
494 /// Edits a [`Message`] in the channel given its Id.
495 ///
496 /// Message editing preserves all unchanged message data, with some exceptions for embeds and
497 /// attachments.
498 ///
499 /// **Note**: In most cases requires that the current user be the author of the message.
500 ///
501 /// Refer to the documentation for [`EditMessage`] for information regarding content
502 /// restrictions and requirements.
503 ///
504 /// # Errors
505 ///
506 /// See [`EditMessage::execute`] for a list of possible errors, and their corresponding
507 /// reasons.
508 #[inline]
509 pub async fn edit_message(
510 &self,
511 cache_http: impl CacheHttp,
512 message_id: impl Into<MessageId>,
513 builder: EditMessage,
514 ) -> Result<Message> {
515 self.id.edit_message(cache_http, message_id, builder).await
516 }
517
518 /// Edits a thread.
519 ///
520 /// # Errors
521 ///
522 /// Returns [`Error::Http`] if the current user lacks permission.
523 pub async fn edit_thread(
524 &mut self,
525 cache_http: impl CacheHttp,
526 builder: EditThread<'_>,
527 ) -> Result<()> {
528 *self = self.id.edit_thread(cache_http, builder).await?;
529 Ok(())
530 }
531
532 /// Edits the voice state of a given user in a stage channel.
533 ///
534 /// **Note**: Requires the [Request to Speak] permission. Also requires the [Mute Members]
535 /// permission to suppress another user or unsuppress the current user. This is not required if
536 /// suppressing the current user.
537 ///
538 /// # Example
539 ///
540 /// Invite a user to speak.
541 ///
542 /// ```rust
543 /// # #[cfg(feature = "cache")]
544 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
545 /// # use std::sync::Arc;
546 /// # use serenity::{cache::Cache, http::Http, model::id::{ChannelId, UserId}};
547 /// #
548 /// # let http: Http = unimplemented!();
549 /// # let cache = Cache::default();
550 /// # let (channel_id, user_id) = (ChannelId::new(1), UserId::new(1));
551 /// use serenity::builder::EditVoiceState;
552 /// use serenity::model::ModelError;
553 ///
554 /// // assuming the cache has been unlocked
555 /// let channel = cache.channel(channel_id).ok_or(ModelError::ItemMissing)?;
556 ///
557 /// let builder = EditVoiceState::new().suppress(false);
558 /// channel.edit_voice_state(&http, user_id, builder).await?;
559 /// # Ok(())
560 /// # }
561 /// ```
562 ///
563 /// # Errors
564 ///
565 /// Returns a [`ModelError::InvalidChannelType`] if the channel is not a stage channel.
566 ///
567 /// Returns [`Error::Http`] if the user lacks permission, or if invalid data is given.
568 ///
569 /// [Request to Speak]: Permissions::REQUEST_TO_SPEAK
570 /// [Mute Members]: Permissions::MUTE_MEMBERS
571 pub async fn edit_voice_state(
572 &self,
573 cache_http: impl CacheHttp,
574 user_id: impl Into<UserId>,
575 builder: EditVoiceState,
576 ) -> Result<()> {
577 if self.kind != ChannelType::Stage {
578 return Err(Error::from(ModelError::InvalidChannelType));
579 }
580
581 builder.execute(cache_http, (self.guild_id, self.id, Some(user_id.into()))).await
582 }
583
584 /// Edits the current user's voice state in a stage channel.
585 ///
586 /// **Note**: Requires the [Request to Speak] permission. The [Mute Members] permission is
587 /// **not** required.
588 ///
589 /// # Example
590 ///
591 /// Send a request to speak, then clear the request.
592 ///
593 /// ```rust
594 /// # #[cfg(feature = "cache")]
595 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
596 /// # use std::sync::Arc;
597 /// # use serenity::{cache::Cache, http::Http, model::id::ChannelId};
598 /// #
599 /// # let http: Http = unimplemented!();
600 /// # let cache = Cache::default();
601 /// # let channel_id = ChannelId::new(1);
602 /// use serenity::builder::EditVoiceState;
603 /// use serenity::model::ModelError;
604 ///
605 /// // assuming the cache has been unlocked
606 /// let channel = cache.channel(channel_id).ok_or(ModelError::ItemMissing)?;
607 ///
608 /// // Send a request to speak
609 /// let builder = EditVoiceState::new().request_to_speak(true);
610 /// channel.edit_own_voice_state(&http, builder.clone()).await?;
611 ///
612 /// // Clear own request to speak
613 /// let builder = builder.request_to_speak(false);
614 /// channel.edit_own_voice_state(&http, builder).await?;
615 /// # Ok(())
616 /// # }
617 /// ```
618 ///
619 /// # Errors
620 ///
621 /// If the `cache` is enabled, returns a [`ModelError::InvalidChannelType`] if the channel is
622 /// not a stage channel.
623 ///
624 /// Returns [`Error::Http`] if the user lacks permission, or if invalid data is given.
625 ///
626 /// [Request to Speak]: Permissions::REQUEST_TO_SPEAK
627 /// [Mute Members]: Permissions::MUTE_MEMBERS
628 pub async fn edit_own_voice_state(
629 &self,
630 cache_http: impl CacheHttp,
631 builder: EditVoiceState,
632 ) -> Result<()> {
633 builder.execute(cache_http, (self.guild_id, self.id, None)).await
634 }
635
636 /// Follows the News Channel
637 ///
638 /// Requires [Manage Webhook] permissions on the target channel.
639 ///
640 /// **Note**: Only available on news channels.
641 ///
642 /// # Errors
643 ///
644 /// Returns [`Error::Http`] if the current user lacks permission.
645 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
646 #[inline]
647 pub async fn follow(
648 &self,
649 http: impl AsRef<Http>,
650 target_channel_id: impl Into<ChannelId>,
651 ) -> Result<FollowedChannel> {
652 self.id.follow(http, target_channel_id).await
653 }
654
655 /// Attempts to find this channel's guild in the Cache.
656 #[cfg(feature = "cache")]
657 #[inline]
658 pub fn guild<'a>(&self, cache: &'a impl AsRef<Cache>) -> Option<cache::GuildRef<'a>> {
659 cache.as_ref().guild(self.guild_id)
660 }
661
662 /// Gets all of the channel's invites.
663 ///
664 /// Requires the [Manage Channels] permission.
665 ///
666 /// # Errors
667 ///
668 /// Returns [`Error::Http`] if the current user lacks permission.
669 ///
670 /// [Manage Channels]: Permissions::MANAGE_CHANNELS
671 #[inline]
672 pub async fn invites(&self, http: impl AsRef<Http>) -> Result<Vec<RichInvite>> {
673 self.id.invites(http).await
674 }
675
676 /// Determines if the channel is NSFW.
677 #[inline]
678 #[must_use]
679 #[deprecated = "Use the GuildChannel::nsfw field"]
680 pub fn is_nsfw(&self) -> bool {
681 self.nsfw
682 }
683
684 /// Gets a message from the channel.
685 ///
686 /// Requires the [Read Message History] permission.
687 ///
688 /// # Errors
689 ///
690 /// Returns [`Error::Http`] if the current user lacks permission, or if a message with the
691 /// given Id does not exist in the channel.
692 ///
693 /// [Read Message History]: Permissions::READ_MESSAGE_HISTORY
694 #[inline]
695 pub async fn message(
696 &self,
697 cache_http: impl CacheHttp,
698 message_id: impl Into<MessageId>,
699 ) -> Result<Message> {
700 self.id.message(cache_http, message_id).await
701 }
702
703 /// Gets messages from the channel.
704 ///
705 /// **Note**: If the user does not have the [Read Message History] permission, returns an empty
706 /// [`Vec`].
707 ///
708 /// # Errors
709 ///
710 /// Returns [`Error::Http`] if the current user lacks permission.
711 ///
712 /// [Read Message History]: Permissions::READ_MESSAGE_HISTORY
713 #[inline]
714 pub async fn messages(
715 &self,
716 cache_http: impl CacheHttp,
717 builder: GetMessages,
718 ) -> Result<Vec<Message>> {
719 self.id.messages(cache_http, builder).await
720 }
721
722 /// Returns the name of the guild channel.
723 #[must_use]
724 pub fn name(&self) -> &str {
725 &self.name
726 }
727
728 /// Calculates the permissions of a member.
729 ///
730 /// The Id of the argument must be a [`Member`] of the [`Guild`] that the channel is in.
731 ///
732 /// # Examples
733 ///
734 /// Calculate the permissions of a [`User`] who posted a [`Message`] in a channel:
735 ///
736 /// ```rust,no_run
737 /// # use serenity::model::prelude::*;
738 /// # use serenity::prelude::*;
739 /// # struct Handler;
740 ///
741 /// #[serenity::async_trait]
742 /// impl EventHandler for Handler {
743 /// async fn message(&self, context: Context, msg: Message) {
744 /// let channel = match context.cache.channel(msg.channel_id) {
745 /// Some(channel) => channel,
746 /// None => return,
747 /// };
748 ///
749 /// if let Ok(permissions) = channel.permissions_for_user(&context.cache, &msg.author) {
750 /// println!("The user's permissions: {:?}", permissions);
751 /// }
752 /// }
753 /// }
754 /// ```
755 ///
756 /// # Errors
757 ///
758 /// Returns a [`ModelError::GuildNotFound`] if the channel's guild could not be found in the
759 /// [`Cache`].
760 ///
761 /// [Attach Files]: Permissions::ATTACH_FILES
762 /// [Send Messages]: Permissions::SEND_MESSAGES
763 #[cfg(feature = "cache")]
764 #[deprecated = "Use `Guild::user_permissions_in`"]
765 #[inline]
766 pub fn permissions_for_user(
767 &self,
768 cache: impl AsRef<Cache>,
769 user_id: impl Into<UserId>,
770 ) -> Result<Permissions> {
771 let guild = self.guild(&cache).ok_or(Error::Model(ModelError::GuildNotFound))?;
772 let member =
773 guild.members.get(&user_id.into()).ok_or(Error::Model(ModelError::MemberNotFound))?;
774 Ok(guild.user_permissions_in(self, member))
775 }
776
777 /// Calculates the permissions of a role.
778 ///
779 /// The Id of the argument must be a [`Role`] of the [`Guild`] that the channel is in.
780 ///
781 /// # Errors
782 ///
783 /// Returns a [`ModelError::GuildNotFound`] if the channel's guild could not be found in the
784 /// [`Cache`].
785 ///
786 /// Returns a [`ModelError::RoleNotFound`] if the given role could not be found in the
787 /// [`Cache`].
788 #[cfg(feature = "cache")]
789 #[inline]
790 #[deprecated = "this function ignores other roles the user may have as well as user-specific permissions; use Guild::user_permissions_in instead"]
791 #[allow(deprecated)]
792 pub fn permissions_for_role(
793 &self,
794 cache: impl AsRef<Cache>,
795 role_id: impl Into<RoleId>,
796 ) -> Result<Permissions> {
797 let guild = self.guild(&cache).ok_or(Error::Model(ModelError::GuildNotFound))?;
798 let role =
799 guild.roles.get(&role_id.into()).ok_or(Error::Model(ModelError::RoleNotFound))?;
800 guild.role_permissions_in(self, role)
801 }
802
803 /// Pins a [`Message`] to the channel.
804 ///
805 /// **Note**: Requires the [Manage Messages] permission.
806 ///
807 /// # Errors
808 ///
809 /// Returns [`Error::Http`] if the current user lacks permission, or if the channel already has
810 /// too many pinned messages.
811 ///
812 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
813 #[inline]
814 pub async fn pin(
815 &self,
816 http: impl AsRef<Http>,
817 message_id: impl Into<MessageId>,
818 ) -> Result<()> {
819 self.id.pin(http, message_id).await
820 }
821
822 /// Gets all channel's pins.
823 ///
824 /// **Note**: If the current user lacks the [Read Message History] permission an empty [`Vec`]
825 /// will be returned.
826 ///
827 /// # Errors
828 ///
829 /// Returns [`Error::Http`] if the current user lacks permission to view the channel.
830 ///
831 /// [Read Message History]: Permissions::READ_MESSAGE_HISTORY
832 #[inline]
833 pub async fn pins(&self, http: impl AsRef<Http>) -> Result<Vec<Message>> {
834 self.id.pins(http).await
835 }
836
837 /// Gets the list of [`User`]s who have reacted to a [`Message`] with a certain [`Emoji`].
838 ///
839 /// The default `limit` is `50` - specify otherwise to receive a different maximum number of
840 /// users. The maximum that may be retrieve at a time is `100`, if a greater number is provided
841 /// then it is automatically reduced.
842 ///
843 /// The optional `after` attribute is to retrieve the users after a certain user. This is
844 /// useful for pagination.
845 ///
846 /// **Note**: Requires the [Read Message History] permission.
847 ///
848 /// **Note**: If the passed reaction_type is a custom guild emoji, it must contain the name.
849 /// So, [`Emoji`] or [`EmojiIdentifier`] will always work, [`ReactionType`] only if
850 /// [`ReactionType::Custom::name`] is Some, and **[`EmojiId`] will never work**.
851 ///
852 /// # Errors
853 ///
854 /// Returns [`Error::Http`] if the current user lacks permission.
855 ///
856 /// [Read Message History]: Permissions::READ_MESSAGE_HISTORY
857 pub async fn reaction_users(
858 &self,
859 http: impl AsRef<Http>,
860 message_id: impl Into<MessageId>,
861 reaction_type: impl Into<ReactionType>,
862 limit: Option<u8>,
863 after: impl Into<Option<UserId>>,
864 ) -> Result<Vec<User>> {
865 self.id.reaction_users(http, message_id, reaction_type, limit, after).await
866 }
867
868 /// Sends a message with just the given message content in the channel.
869 ///
870 /// **Note**: Message content must be under 2000 unicode code points.
871 ///
872 /// # Errors
873 ///
874 /// Returns a [`ModelError::MessageTooLong`] if the content length is over the above limit. See
875 /// [`CreateMessage::execute`] for more details.
876 #[inline]
877 pub async fn say(
878 &self,
879 cache_http: impl CacheHttp,
880 content: impl Into<String>,
881 ) -> Result<Message> {
882 self.id.say(cache_http, content).await
883 }
884
885 /// Sends file(s) along with optional message contents.
886 ///
887 /// Refer to [`ChannelId::send_files`] for examples and more information.
888 ///
889 /// # Errors
890 ///
891 /// See [`CreateMessage::execute`] for a list of possible errors, and their corresponding
892 /// reasons.
893 #[inline]
894 pub async fn send_files(
895 self,
896 cache_http: impl CacheHttp,
897 files: impl IntoIterator<Item = CreateAttachment>,
898 builder: CreateMessage,
899 ) -> Result<Message> {
900 self.send_message(cache_http, builder.files(files)).await
901 }
902
903 /// Sends a message to the channel.
904 ///
905 /// Refer to the documentation for [`CreateMessage`] for information regarding content
906 /// restrictions and requirements.
907 ///
908 /// # Errors
909 ///
910 /// See [`CreateMessage::execute`] for a list of possible errors, and their corresponding
911 /// reasons.
912 pub async fn send_message(
913 &self,
914 cache_http: impl CacheHttp,
915 builder: CreateMessage,
916 ) -> Result<Message> {
917 builder.execute(cache_http, (self.id, Some(self.guild_id))).await
918 }
919
920 /// Starts typing in the channel for an indefinite period of time.
921 ///
922 /// Returns [`Typing`] that is used to trigger the typing. [`Typing::stop`] must be called on
923 /// the returned struct to stop typing. Note that on some clients, typing may persist for a few
924 /// seconds after [`Typing::stop`] is called. Typing is also stopped when the struct is
925 /// dropped.
926 ///
927 /// If a message is sent while typing is triggered, the user will stop typing for a brief
928 /// period of time and then resume again until either [`Typing::stop`] is called or the struct
929 /// is dropped.
930 ///
931 /// This should rarely be used for bots, although it is a good indicator that a long-running
932 /// command is still being processed.
933 ///
934 /// ## Examples
935 ///
936 /// ```rust,no_run
937 /// # #[cfg(feature = "cache")]
938 /// # async fn run() {
939 /// # use serenity::{cache::Cache, http::Http, model::channel::GuildChannel, Result};
940 /// # use std::sync::Arc;
941 /// #
942 /// # fn long_process() {}
943 /// # let http: Arc<Http> = unimplemented!();
944 /// # let cache = Cache::default();
945 /// # let channel: GuildChannel = unimplemented!();
946 /// // Initiate typing (assuming http is `Arc<Http>` and `channel` is bound)
947 /// let typing = channel.start_typing(&http);
948 ///
949 /// // Run some long-running process
950 /// long_process();
951 ///
952 /// // Stop typing
953 /// typing.stop();
954 /// # }
955 /// ```
956 #[allow(clippy::missing_errors_doc)]
957 pub fn start_typing(&self, http: &Arc<Http>) -> Typing {
958 http.start_typing(self.id)
959 }
960
961 /// Unpins a [`Message`] in the channel given by its Id.
962 ///
963 /// Requires the [Manage Messages] permission.
964 ///
965 /// # Errors
966 ///
967 /// Returns [`Error::Http`] if the current user lacks permission.
968 ///
969 /// [Manage Messages]: Permissions::MANAGE_MESSAGES
970 #[inline]
971 pub async fn unpin(
972 &self,
973 http: impl AsRef<Http>,
974 message_id: impl Into<MessageId>,
975 ) -> Result<()> {
976 self.id.unpin(http, message_id).await
977 }
978
979 /// Retrieves the channel's webhooks.
980 ///
981 /// **Note**: Requires the [Manage Webhooks] permission.
982 ///
983 /// # Errors
984 ///
985 /// Returns [`Error::Http`] if the current user lacks permission.
986 ///
987 /// [Manage Webhooks]: Permissions::MANAGE_WEBHOOKS
988 #[inline]
989 pub async fn webhooks(&self, http: impl AsRef<Http>) -> Result<Vec<Webhook>> {
990 self.id.webhooks(http).await
991 }
992
993 /// Retrieves [`Member`]s from the current channel.
994 ///
995 /// [`ChannelType::Voice`] and [`ChannelType::Stage`] returns [`Member`]s using the channel.
996 ///
997 /// [`ChannelType::Text`] and [`ChannelType::News`] return [`Member`]s that can read the
998 /// channel.
999 ///
1000 /// # Errors
1001 ///
1002 /// Other [`ChannelType`]s lack the concept of [`Member`]s and will return:
1003 /// [`ModelError::InvalidChannelType`].
1004 #[cfg(feature = "cache")]
1005 #[inline]
1006 pub fn members(&self, cache: impl AsRef<Cache>) -> Result<Vec<Member>> {
1007 let cache = cache.as_ref();
1008 let guild = cache.guild(self.guild_id).ok_or(ModelError::GuildNotFound)?;
1009
1010 match self.kind {
1011 ChannelType::Voice | ChannelType::Stage => Ok(guild
1012 .voice_states
1013 .values()
1014 .filter_map(|v| {
1015 v.channel_id.and_then(|c| {
1016 if c == self.id {
1017 guild.members.get(&v.user_id).cloned()
1018 } else {
1019 None
1020 }
1021 })
1022 })
1023 .collect()),
1024 ChannelType::News | ChannelType::Text => Ok(guild
1025 .members
1026 .values()
1027 .filter(|member| {
1028 guild.user_permissions_in(self, member).contains(Permissions::VIEW_CHANNEL)
1029 })
1030 .cloned()
1031 .collect::<Vec<Member>>()),
1032 _ => Err(Error::from(ModelError::InvalidChannelType)),
1033 }
1034 }
1035
1036 /// Returns a builder which can be awaited to obtain a message or stream of messages sent in
1037 /// this guild channel.
1038 #[cfg(feature = "collector")]
1039 pub fn await_reply(&self, shard_messenger: impl AsRef<ShardMessenger>) -> MessageCollector {
1040 MessageCollector::new(shard_messenger).channel_id(self.id)
1041 }
1042
1043 /// Same as [`Self::await_reply`].
1044 #[cfg(feature = "collector")]
1045 pub fn await_replies(&self, shard_messenger: impl AsRef<ShardMessenger>) -> MessageCollector {
1046 self.await_reply(shard_messenger)
1047 }
1048
1049 /// Returns a stream builder which can be awaited to obtain a reaction or stream of reactions
1050 /// sent by this guild channel.
1051 #[cfg(feature = "collector")]
1052 pub fn await_reaction(&self, shard_messenger: impl AsRef<ShardMessenger>) -> ReactionCollector {
1053 ReactionCollector::new(shard_messenger).channel_id(self.id)
1054 }
1055
1056 /// Same as [`Self::await_reaction`].
1057 #[cfg(feature = "collector")]
1058 pub fn await_reactions(
1059 &self,
1060 shard_messenger: impl AsRef<ShardMessenger>,
1061 ) -> ReactionCollector {
1062 self.await_reaction(shard_messenger)
1063 }
1064
1065 /// Creates a webhook in the channel.
1066 ///
1067 /// # Errors
1068 ///
1069 /// Returns [`ModelError::InvalidChannelType`] if the corresponding channel is not of type
1070 /// [`ChannelType::Text`] or [`ChannelType::News`].
1071 ///
1072 /// See [`CreateWebhook::execute`] for a detailed list of other
1073 /// possible errors,
1074 pub async fn create_webhook(
1075 &self,
1076 cache_http: impl CacheHttp,
1077 builder: CreateWebhook<'_>,
1078 ) -> Result<Webhook> {
1079 // forum channels are not text-based, but webhooks can be created in them
1080 // and used to send messages in their posts
1081 if !self.is_text_based() && self.kind != ChannelType::Forum {
1082 return Err(Error::Model(ModelError::InvalidChannelType));
1083 }
1084
1085 self.id.create_webhook(cache_http, builder).await
1086 }
1087
1088 /// Gets a stage instance.
1089 ///
1090 /// # Errors
1091 ///
1092 /// Returns [`ModelError::InvalidChannelType`] if the channel is not a stage channel.
1093 ///
1094 /// Returns [`Error::Http`] if there is no stage instance currently.
1095 pub async fn get_stage_instance(&self, http: impl AsRef<Http>) -> Result<StageInstance> {
1096 if self.kind != ChannelType::Stage {
1097 return Err(Error::Model(ModelError::InvalidChannelType));
1098 }
1099
1100 self.id.get_stage_instance(http).await
1101 }
1102
1103 /// Creates a stage instance.
1104 ///
1105 /// # Errors
1106 ///
1107 /// Returns [`ModelError::InvalidChannelType`] if the channel is not a stage channel.
1108 ///
1109 /// Returns [`Error::Http`] if there is already a stage instance currently.
1110 pub async fn create_stage_instance(
1111 &self,
1112 cache_http: impl CacheHttp,
1113 builder: CreateStageInstance<'_>,
1114 ) -> Result<StageInstance> {
1115 if self.kind != ChannelType::Stage {
1116 return Err(Error::Model(ModelError::InvalidChannelType));
1117 }
1118
1119 self.id.create_stage_instance(cache_http, builder).await
1120 }
1121
1122 /// Edits the stage instance
1123 ///
1124 /// # Errors
1125 ///
1126 /// Returns [`ModelError::InvalidChannelType`] if the channel is not a stage channel.
1127 ///
1128 /// Returns [`Error::Http`] if the channel is not a stage channel, or there is no stage
1129 /// instance currently.
1130 pub async fn edit_stage_instance(
1131 &self,
1132 cache_http: impl CacheHttp,
1133 builder: EditStageInstance<'_>,
1134 ) -> Result<StageInstance> {
1135 if self.kind != ChannelType::Stage {
1136 return Err(Error::Model(ModelError::InvalidChannelType));
1137 }
1138
1139 self.id.edit_stage_instance(cache_http, builder).await
1140 }
1141
1142 /// Deletes a stage instance.
1143 ///
1144 /// # Errors
1145 ///
1146 /// Returns [`ModelError::InvalidChannelType`] if the channel is not a stage channel.
1147 ///
1148 /// Returns [`Error::Http`] if there is no stage instance currently.
1149 pub async fn delete_stage_instance(&self, http: impl AsRef<Http>) -> Result<()> {
1150 if self.kind != ChannelType::Stage {
1151 return Err(Error::Model(ModelError::InvalidChannelType));
1152 }
1153
1154 self.id.delete_stage_instance(http).await
1155 }
1156
1157 /// Creates a public thread that is connected to a message.
1158 ///
1159 /// # Errors
1160 ///
1161 /// Returns [`Error::Http`] if the current user lacks permission, or if invalid data is given.
1162 pub async fn create_thread_from_message(
1163 &self,
1164 cache_http: impl CacheHttp,
1165 message_id: impl Into<MessageId>,
1166 builder: CreateThread<'_>,
1167 ) -> Result<GuildChannel> {
1168 self.id.create_thread_from_message(cache_http, message_id, builder).await
1169 }
1170
1171 /// Creates a thread that is not connected to a message.
1172 ///
1173 /// # Errors
1174 ///
1175 /// Returns [`Error::Http`] if the current user lacks permission, or if invalid data is given.
1176 pub async fn create_thread(
1177 &self,
1178 cache_http: impl CacheHttp,
1179 builder: CreateThread<'_>,
1180 ) -> Result<GuildChannel> {
1181 self.id.create_thread(cache_http, builder).await
1182 }
1183
1184 /// Creates a post in a forum channel.
1185 ///
1186 /// # Errors
1187 ///
1188 /// Returns [`Error::Http`] if the current user lacks permission, or if invalid data is given.
1189 pub async fn create_forum_post(
1190 &self,
1191 cache_http: impl CacheHttp,
1192 builder: CreateForumPost<'_>,
1193 ) -> Result<GuildChannel> {
1194 self.id.create_forum_post(cache_http, builder).await
1195 }
1196}
1197
1198impl fmt::Display for GuildChannel {
1199 /// Formats the channel, creating a mention of it.
1200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1201 fmt::Display::fmt(&self.id.mention(), f)
1202 }
1203}
1204
1205/// A partial guild channel.
1206///
1207/// [Discord docs](https://discord.com/developers/docs/resources/channel#channel-object),
1208/// [subset description](https://discord.com/developers/docs/topics/gateway#thread-delete)
1209#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
1210#[derive(Clone, Debug, Deserialize, Serialize)]
1211#[non_exhaustive]
1212pub struct PartialGuildChannel {
1213 /// The channel Id.
1214 pub id: ChannelId,
1215 /// The channel guild Id.
1216 pub guild_id: GuildId,
1217 /// The channel category Id, or the parent text channel Id for a thread.
1218 pub parent_id: ChannelId,
1219 /// The channel type.
1220 #[serde(rename = "type")]
1221 pub kind: ChannelType,
1222}