1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
//! Thread operations for DiscordUser
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use crate::{context::DiscordContext, error::Result, route::Route, types::*};
impl<T: DiscordContext + Send + Sync> ThreadOps for T {}
/// A thread member entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadMember {
pub id: Option<String>,
pub user_id: Option<String>,
pub join_timestamp: String,
pub flags: u64,
}
/// Response from GET /guilds/{id}/threads/active
#[derive(Debug, Clone, Deserialize)]
pub struct ActiveThreads {
pub threads: Vec<Channel>,
pub members: Vec<ThreadMember>,
}
/// Response from the archived-threads listing endpoints.
///
/// Used by:
/// - `GET /channels/{channel.id}/threads/archived/public`
/// - `GET /channels/{channel.id}/threads/archived/private`
/// - `GET /channels/{channel.id}/users/@me/threads/archived/private`
#[derive(Debug, Clone, Deserialize)]
pub struct ArchivedThreadsResponse {
/// The archived threads returned for this page.
#[serde(default)]
pub threads: Vec<Channel>,
/// Thread-member entries for the calling user, one per thread the user
/// has joined. Empty when the user is not a member of any returned
/// thread.
#[serde(default)]
pub members: Vec<ThreadMember>,
/// Whether more archived threads exist beyond this page. Use the
/// earliest `archive_timestamp`/`id` from `threads` as the next `before`
/// cursor.
#[serde(default)]
pub has_more: bool,
}
/// Response from `POST /channels/{channel.id}/threads` when the channel is a
/// forum or media channel.
///
/// Discord returns a [`Channel`] object for the new thread plus the seed
/// [`Message`] sent into it. The seed-message field is left as
/// [`serde_json::Value`] for forward compatibility with Discord's evolving
/// message schema.
#[derive(Debug, Clone, Deserialize)]
pub struct ForumThreadResponse {
/// The newly created forum/media thread channel.
#[serde(flatten)]
pub channel: Channel,
/// The first message posted to the thread, if returned by the API.
#[serde(default)]
pub message: Option<serde_json::Value>,
}
/// Extension trait providing thread management operations
#[allow(async_fn_in_trait)]
pub trait ThreadOps: DiscordContext {
/// Create a thread not attached to a message.
///
/// Set `req.channel_type` to 11 (PUBLIC_THREAD) or 12 (PRIVATE_THREAD).
/// Use [`CreateThreadRequest::public`] / [`CreateThreadRequest::private`]
/// helpers.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires CREATE_PUBLIC_THREADS or CREATE_PRIVATE_THREADS as appropriate.
async fn create_thread(&self, channel_id: &ChannelId, req: CreateThreadRequest) -> Result<Channel> {
self.http().post(Route::CreateThread { channel_id: channel_id.get() }, req).await
}
/// Create a thread attached to an existing message.
///
/// The thread type is PUBLIC_THREAD by default (no `type` field needed).
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires CREATE_PUBLIC_THREADS permission.
async fn create_thread_from_message(&self, channel_id: &ChannelId, message_id: &MessageId, req: CreateThreadRequest) -> Result<Channel> {
self.http().post(Route::CreateThreadFromMessage { channel_id: channel_id.get(), message_id: message_id.get() }, req).await
}
/// Edit a thread's settings (name, archived state, locked, auto-archive
/// duration, slowmode).
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires MANAGE_THREADS permission (or be the thread creator for private
/// threads).
async fn edit_thread(&self, channel_id: &ChannelId, req: EditThreadRequest) -> Result<Channel> {
self.http().patch(Route::EditChannel { channel_id: channel_id.get() }, req).await
}
/// Join a thread as the current user.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
async fn join_thread(&self, channel_id: &ChannelId) -> Result<()> {
self.http().put(Route::JoinThread { channel_id: channel_id.get() }, EMPTY_REQUEST).await
}
/// Leave a thread as the current user.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
async fn leave_thread(&self, channel_id: &ChannelId) -> Result<()> {
self.http().delete(Route::LeaveThread { channel_id: channel_id.get() }).await
}
/// Add a member to a thread.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires MANAGE_THREADS or be the thread creator.
async fn add_thread_member(&self, channel_id: &ChannelId, user_id: &UserId) -> Result<()> {
self.http().put(Route::AddThreadMember { channel_id: channel_id.get(), user_id: user_id.get() }, EMPTY_REQUEST).await
}
/// Remove a member from a thread.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires MANAGE_THREADS or be the thread creator.
async fn remove_thread_member(&self, channel_id: &ChannelId, user_id: &UserId) -> Result<()> {
self.http().delete(Route::RemoveThreadMember { channel_id: channel_id.get(), user_id: user_id.get() }).await
}
/// Get all members of a thread.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
async fn get_thread_members(&self, channel_id: &ChannelId) -> Result<Vec<ThreadMember>> {
self.http().get(Route::GetThreadMembers { channel_id: channel_id.get() }).await
}
/// Get all active (non-archived) threads in a guild.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
async fn get_active_threads(&self, guild_id: &GuildId) -> Result<ActiveThreads> {
self.http().get(Route::GetActiveThreads { guild_id: guild_id.get() }).await
}
/// Archive a thread by setting `archived: true`.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires MANAGE_THREADS or be the thread creator.
async fn archive_thread(&self, channel_id: &ChannelId) -> Result<Channel> {
self.edit_thread(channel_id, EditThreadRequest { archived: Some(true), ..Default::default() }).await
}
/// Unarchive a thread by setting `archived: false`.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires MANAGE_THREADS or be the thread creator.
async fn unarchive_thread(&self, channel_id: &ChannelId) -> Result<Channel> {
self.edit_thread(channel_id, EditThreadRequest { archived: Some(false), ..Default::default() }).await
}
/// Get a single thread member.
///
/// `GET /channels/{channel.id}/thread-members/{user.id}?with_member=true`
///
/// When `with_member` is `true`, Discord includes the corresponding
/// guild-member object on the response so callers can render a name and
/// avatar without a follow-up request.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure (e.g. 404 if the user is
/// not a member of the thread).
async fn get_thread_member(&self, channel_id: &ChannelId, user_id: &UserId, with_member: bool) -> Result<ThreadMember> {
self.http().get(Route::GetThreadMember { channel_id: channel_id.get(), user_id: user_id.get(), with_member }).await
}
/// List members of a thread (single page).
///
/// `GET /channels/{channel.id}/thread-members?with_member={bool}&after={snowflake}&limit={1-100}`
///
/// Returns up to `limit` (max 100) thread-member entries ordered by
/// `user_id` ascending. Use the last returned member's `user_id` as the
/// `after` cursor on the next call. Pass `limit: None` to use Discord's
/// default (100).
///
/// For automatic pagination across all pages, use
/// [`list_all_thread_members`](Self::list_all_thread_members).
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
async fn list_thread_members(&self, channel_id: &ChannelId, with_member: bool, after: Option<u64>, limit: Option<u32>) -> Result<Vec<ThreadMember>> {
self.http().get(Route::ListThreadMembers { channel_id: channel_id.get(), with_member, after, limit }).await
}
/// List every member of a thread, automatically paginating.
///
/// Repeatedly calls [`list_thread_members`](Self::list_thread_members)
/// with `limit=100`, advancing the `after` cursor by the highest returned
/// `user_id` until Discord returns fewer than 100 members (signaling the
/// final page).
///
/// `with_member` is forwarded to each underlying call. Members lacking a
/// `user_id` (which would otherwise be unable to advance the cursor) are
/// kept in the result but do not influence pagination — pagination stops
/// either when a short page is returned or when no member on the page
/// carries a numeric `user_id`.
///
/// # Errors
/// Returns the first [`DiscordError::Http`] encountered while paging.
async fn list_all_thread_members(&self, channel_id: &ChannelId, with_member: bool) -> Result<Vec<ThreadMember>> {
let mut all: Vec<ThreadMember> = Vec::new();
let mut after: Option<u64> = None;
loop {
let page = self.list_thread_members(channel_id, with_member, after, Some(100)).await?;
let page_len = page.len();
// Find the largest numeric user_id on this page to use as the
// next cursor. Discord returns members ordered by user_id
// ascending, so the last entry usually carries the max — but we
// scan to be defensive against unordered responses.
let next_after: Option<u64> = page.iter().filter_map(|m| m.user_id.as_deref().and_then(|s| s.parse::<u64>().ok())).max();
all.extend(page);
// Termination conditions:
// 1. Fewer than 100 results → final page reached.
// 2. No advanceable cursor → would loop forever otherwise.
if page_len < 100 || next_after.is_none() {
break;
}
after = next_after;
}
Ok(all)
}
/// List public archived threads in a channel.
///
/// `GET /channels/{channel.id}/threads/archived/public?before={iso8601}&limit={n}`
///
/// Threads are returned in descending order by `archive_timestamp`. Use
/// the earliest archive timestamp from the response as the next `before`
/// cursor (ISO 8601 format).
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires READ_MESSAGE_HISTORY in the parent channel.
async fn list_public_archived_threads(&self, channel_id: &ChannelId, before: Option<&str>, limit: Option<u32>) -> Result<ArchivedThreadsResponse> {
self.http().get(Route::PublicArchivedThreads { channel_id: channel_id.get(), before: before.map(|s| Cow::Owned(s.to_string())), limit }).await
}
/// List private archived threads in a channel.
///
/// `GET /channels/{channel.id}/threads/archived/private?before={iso8601}&limit={n}`
///
/// Same response shape and pagination rules as
/// [`list_public_archived_threads`](Self::list_public_archived_threads).
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires READ_MESSAGE_HISTORY *and* MANAGE_THREADS on the parent
/// channel.
async fn list_private_archived_threads(&self, channel_id: &ChannelId, before: Option<&str>, limit: Option<u32>) -> Result<ArchivedThreadsResponse> {
self.http().get(Route::PrivateArchivedThreads { channel_id: channel_id.get(), before: before.map(|s| Cow::Owned(s.to_string())), limit }).await
}
/// List private archived threads the current user has joined.
///
/// `GET /channels/{channel.id}/users/@me/threads/archived/private?before={snowflake}&limit={n}`
///
/// Note: unlike the other archived-thread listings, the `before` cursor
/// here is a thread *snowflake ID*, not an ISO 8601 timestamp.
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires READ_MESSAGE_HISTORY on the parent channel. MANAGE_THREADS is
/// not required because the listing is scoped to the current user's
/// memberships.
async fn list_joined_private_archived_threads(&self, channel_id: &ChannelId, before: Option<u64>, limit: Option<u32>) -> Result<ArchivedThreadsResponse> {
self.http().get(Route::JoinedPrivateArchivedThreads { channel_id: channel_id.get(), before, limit }).await
}
/// Start a thread in a forum or media channel.
///
/// `POST /channels/{channel.id}/threads`
///
/// Forum/media-channel threads require an initial message; the `message`
/// argument carries that payload (content, embeds, components, etc.).
/// Tags from the forum's `available_tags` may be selected via
/// `applied_tags`.
///
/// Returns the new thread [`Channel`] together with the seed message
/// (when included by Discord) wrapped in [`ForumThreadResponse`].
///
/// # Errors
/// Returns [`DiscordError::Http`] on HTTP failure.
///
/// # Permissions
/// Requires SEND_MESSAGES in the parent forum/media channel.
async fn start_thread_in_forum_channel(&self, channel_id: &ChannelId, name: String, auto_archive_duration: Option<u32>, rate_limit_per_user: Option<u32>, message: ForumThreadMessage, applied_tags: Option<Vec<String>>) -> Result<ForumThreadResponse> {
// We build an inline JSON body rather than reusing CreateThreadRequest
// so the typed `message: ForumThreadMessage` survives serialization
// (CreateThreadRequest declares `message` as `serde_json::Value`,
// which would force an extra round-trip through serde_json::to_value
// to use here).
#[derive(Serialize)]
struct StartForumThreadBody<'a> {
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
auto_archive_duration: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
rate_limit_per_user: Option<u32>,
message: &'a ForumThreadMessage,
#[serde(skip_serializing_if = "Option::is_none")]
applied_tags: Option<Vec<String>>,
}
let body = StartForumThreadBody {
name,
auto_archive_duration,
rate_limit_per_user,
message: &message,
applied_tags,
};
self.http().post(Route::StartThreadInForumChannel { channel_id: channel_id.get() }, body).await
}
}