djs_rest/endpoints/user.rs
1//! [User endpoints](https://docs.discord.com/developers/resources/user): the current user,
2//! other users, the current user's guilds, DMs, connections and role connections.
3//!
4//! Several of them act for a user through `OAuth2` and need a client built with
5//! [`RestBuilder::bearer_token`](crate::RestBuilder::bearer_token) (D-108); their docs say so.
6
7use djs_model::{
8 channel::Channel,
9 guild::Member,
10 id::{ApplicationId, GuildId, UserId},
11 rest::{CreateDm, CreateGroupDm, CurrentUserGuild, GetCurrentUserGuilds, ModifyCurrentUser},
12 user::{ApplicationRoleConnection, Connection, CurrentUser, User},
13};
14
15use crate::client::boxed;
16use crate::{Error, Request, Rest, Route};
17
18impl Rest {
19 /// [Get Current User](https://docs.discord.com/developers/resources/user#get-current-user):
20 /// returns the bot's own user (or, with a bearer token, the authorizing user's; the
21 /// email needs the `email` scope).
22 ///
23 /// discord.js counterpart: `Client#user` (from the `READY` event).
24 ///
25 /// # Errors
26 ///
27 /// See [`Rest::request`]; `401 Unauthorized` for an invalid token.
28 pub fn get_current_user(&self) -> impl Future<Output = Result<CurrentUser, Error>> + Send + '_ {
29 boxed(async move { self.call(Request::new(Route::GetCurrentUser)).await })
30 }
31
32 /// [Get User](https://docs.discord.com/developers/resources/user#get-user): returns any
33 /// user by ID.
34 ///
35 /// discord.js counterpart: `UserManager#fetch`.
36 ///
37 /// # Errors
38 ///
39 /// See [`Rest::request`]; `10013` Unknown User.
40 pub fn get_user(
41 &self,
42 user_id: UserId,
43 ) -> impl Future<Output = Result<User, Error>> + Send + '_ {
44 boxed(async move { self.call(Request::new(Route::GetUser { user_id })).await })
45 }
46
47 /// [Modify Current User](https://docs.discord.com/developers/resources/user#modify-current-user):
48 /// changes the bot's username, avatar or banner.
49 ///
50 /// discord.js counterpart: `ClientUser#edit`, `#setUsername`, `#setAvatar`.
51 ///
52 /// # Examples
53 ///
54 /// ```no_run
55 /// # async fn example(rest: djs_rest::Rest) -> Result<(), Box<dyn std::error::Error>> {
56 /// use djs_model::{rest::ModifyCurrentUser, util::{ImageData, Patch}};
57 ///
58 /// let mut body = ModifyCurrentUser::default();
59 /// body.avatar = Patch::Set(ImageData::new(std::fs::read("avatar.png")?)?);
60 /// rest.modify_current_user(&body).await?;
61 /// # Ok(())
62 /// # }
63 /// ```
64 ///
65 /// # Errors
66 ///
67 /// See [`Rest::request`]; `50035` when the username is taken or changed too often.
68 pub fn modify_current_user<'a>(
69 &'a self,
70 body: &'a ModifyCurrentUser,
71 ) -> impl Future<Output = Result<CurrentUser, Error>> + Send + 'a {
72 boxed(async move {
73 self.call(Request::new(Route::ModifyCurrentUser).json(body)?)
74 .await
75 })
76 }
77
78 /// [Get Current User Guilds](https://docs.discord.com/developers/resources/user#get-current-user-guilds):
79 /// returns a page of the current user's guilds (200 by default), sorted by ID. With a
80 /// bearer token, needs the `guilds` scope.
81 ///
82 /// Bots with large bot sharding must set [`shard`](GetCurrentUserGuilds::shard).
83 ///
84 /// discord.js counterpart: `GuildManager#fetch()`.
85 ///
86 /// # Errors
87 ///
88 /// See [`Rest::request`].
89 pub fn get_current_user_guilds<'a>(
90 &'a self,
91 query: &'a GetCurrentUserGuilds,
92 ) -> impl Future<Output = Result<Vec<CurrentUserGuild>, Error>> + Send + 'a {
93 boxed(async move {
94 self.call(Request::new(Route::GetCurrentUserGuilds).query(query))
95 .await
96 })
97 }
98
99 /// [Get Current User Guild Member](https://docs.discord.com/developers/resources/user#get-current-user-guild-member):
100 /// returns the authorizing user's membership of a guild. Needs a
101 /// [bearer token](crate::RestBuilder::bearer_token) with the `guilds.members.read` scope.
102 ///
103 /// discord.js counterpart: none (`REST#get(Routes.userGuildMember(guildId))`).
104 ///
105 /// # Errors
106 ///
107 /// See [`Rest::request`]; `10004` Unknown Guild when the user is not in it.
108 pub fn get_current_user_guild_member(
109 &self,
110 guild_id: GuildId,
111 ) -> impl Future<Output = Result<Member, Error>> + Send + '_ {
112 boxed(async move {
113 self.call(Request::new(Route::GetCurrentUserGuildMember { guild_id }))
114 .await
115 })
116 }
117
118 /// [Leave Guild](https://docs.discord.com/developers/resources/user#leave-guild): makes
119 /// the bot leave a guild.
120 ///
121 /// discord.js counterpart: `Guild#leave`.
122 ///
123 /// # Errors
124 ///
125 /// See [`Rest::request`]; `10004` Unknown Guild.
126 pub fn leave_guild(
127 &self,
128 guild_id: GuildId,
129 ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
130 boxed(async move {
131 self.call(Request::new(Route::LeaveGuild { guild_id }))
132 .await
133 })
134 }
135
136 /// [Create DM](https://docs.discord.com/developers/resources/user#create-dm): opens (or
137 /// returns the existing) DM channel with a user. Send messages to it with
138 /// [`create_message`](Self::create_message).
139 ///
140 /// DMs should follow a user action; opening many quickly gets the bot rate limited or
141 /// blocked from opening more.
142 ///
143 /// discord.js counterpart: `User#createDM`.
144 ///
145 /// # Examples
146 ///
147 /// ```no_run
148 /// # async fn example(rest: djs_rest::Rest, user_id: djs_model::id::UserId) -> Result<(), djs_rest::Error> {
149 /// use djs_model::rest::{CreateDm, CreateMessage};
150 ///
151 /// let dm = rest.create_dm(&CreateDm::new(user_id)).await?;
152 /// rest.create_message(dm.id(), &CreateMessage::from("Your report was received."))
153 /// .await?;
154 /// # Ok(())
155 /// # }
156 /// ```
157 ///
158 /// # Errors
159 ///
160 /// See [`Rest::request`]; `50007` when the user does not accept DMs from the bot (on
161 /// the message, not here).
162 pub fn create_dm<'a>(
163 &'a self,
164 body: &'a CreateDm,
165 ) -> impl Future<Output = Result<Channel, Error>> + Send + 'a {
166 boxed(async move { self.call(Request::new(Route::CreateDm).json(body)?).await })
167 }
168
169 /// [Create Group DM](https://docs.discord.com/developers/resources/user#create-group-dm):
170 /// creates a group DM with users who granted the application `gdm.join` (max 10 active
171 /// group DMs; meant for the deprecated `GameBridge` SDK).
172 ///
173 /// discord.js counterpart: none.
174 ///
175 /// # Errors
176 ///
177 /// See [`Rest::request`].
178 pub fn create_group_dm<'a>(
179 &'a self,
180 body: &'a CreateGroupDm,
181 ) -> impl Future<Output = Result<Channel, Error>> + Send + 'a {
182 boxed(async move {
183 self.call(Request::new(Route::CreateGroupDm).json(body)?)
184 .await
185 })
186 }
187
188 /// [Get Current User Connections](https://docs.discord.com/developers/resources/user#get-current-user-connections):
189 /// returns the accounts the authorizing user connected (Twitch, GitHub, …). Needs a
190 /// [bearer token](crate::RestBuilder::bearer_token) with the `connections` scope.
191 ///
192 /// discord.js counterpart: none (`REST#get(Routes.userConnections())`).
193 ///
194 /// # Errors
195 ///
196 /// See [`Rest::request`].
197 pub fn get_current_user_connections(
198 &self,
199 ) -> impl Future<Output = Result<Vec<Connection>, Error>> + Send + '_ {
200 boxed(async move {
201 self.call(Request::new(Route::GetCurrentUserConnections))
202 .await
203 })
204 }
205
206 /// [Get Current User Application Role Connection](https://docs.discord.com/developers/resources/user#get-current-user-application-role-connection):
207 /// returns the role connection (linked-roles data) the application stored for the
208 /// authorizing user. Needs a [bearer token](crate::RestBuilder::bearer_token) with the
209 /// `role_connections.write` scope.
210 ///
211 /// discord.js counterpart: none.
212 ///
213 /// # Errors
214 ///
215 /// See [`Rest::request`].
216 pub fn get_current_user_application_role_connection(
217 &self,
218 application_id: ApplicationId,
219 ) -> impl Future<Output = Result<ApplicationRoleConnection, Error>> + Send + '_ {
220 boxed(async move {
221 self.call(Request::new(
222 Route::GetCurrentUserApplicationRoleConnection { application_id },
223 ))
224 .await
225 })
226 }
227
228 /// [Update Current User Application Role Connection](https://docs.discord.com/developers/resources/user#update-current-user-application-role-connection):
229 /// replaces the role connection of the authorizing user and returns it. Needs a
230 /// [bearer token](crate::RestBuilder::bearer_token) with the `role_connections.write`
231 /// scope.
232 ///
233 /// The metadata values are stringified (`"1"` for true, ISO 8601 for dates), keyed by
234 /// the application's role connection metadata keys.
235 ///
236 /// discord.js counterpart: none.
237 ///
238 /// # Examples
239 ///
240 /// ```no_run
241 /// # async fn example(user: djs_rest::Rest, application_id: djs_model::id::ApplicationId) -> Result<(), djs_rest::Error> {
242 /// use djs_model::user::ApplicationRoleConnection;
243 ///
244 /// let mut connection = ApplicationRoleConnection::default();
245 /// connection.platform_name = Some("Chess Club".into());
246 /// connection.metadata.insert("rating".into(), "1850".into());
247 /// user.update_current_user_application_role_connection(application_id, &connection)
248 /// .await?;
249 /// # Ok(())
250 /// # }
251 /// ```
252 ///
253 /// # Errors
254 ///
255 /// See [`Rest::request`].
256 pub fn update_current_user_application_role_connection<'a>(
257 &'a self,
258 application_id: ApplicationId,
259 body: &'a ApplicationRoleConnection,
260 ) -> impl Future<Output = Result<ApplicationRoleConnection, Error>> + Send + 'a {
261 boxed(async move {
262 self.call(
263 Request::new(Route::UpdateCurrentUserApplicationRoleConnection { application_id })
264 .json(body)?,
265 )
266 .await
267 })
268 }
269
270 /// [Delete Current User Application Role Connection](https://docs.discord.com/developers/resources/user#delete-current-user-application-role-connection):
271 /// removes the role connection of the authorizing user. Needs a
272 /// [bearer token](crate::RestBuilder::bearer_token) with the `role_connections.write`
273 /// scope.
274 ///
275 /// discord.js counterpart: none.
276 ///
277 /// # Errors
278 ///
279 /// See [`Rest::request`].
280 pub fn delete_current_user_application_role_connection(
281 &self,
282 application_id: ApplicationId,
283 ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
284 boxed(async move {
285 self.request_ignoring_body(Request::new(
286 Route::DeleteCurrentUserApplicationRoleConnection { application_id },
287 ))
288 .await
289 })
290 }
291}