twilight_http/request/application/interaction/
create_response_with_response.rs1use crate::{
2 client::Client,
3 error::Error,
4 request::{Request, TryIntoRequest, attachment::AttachmentManager},
5 response::{Response, ResponseFuture},
6 routing::Route,
7};
8use std::future::IntoFuture;
9use twilight_model::{
10 http::interaction::InteractionResponse,
11 id::{Id, marker::InteractionMarker},
12};
13
14#[must_use = "requests must be configured and executed"]
18pub struct CreateResponseWithResponse<'a> {
19 interaction_id: Id<InteractionMarker>,
20 interaction_token: &'a str,
21 response: &'a InteractionResponse,
22 http: &'a Client,
23}
24
25impl<'a> CreateResponseWithResponse<'a> {
26 pub(crate) const fn new(
27 http: &'a Client,
28 interaction_id: Id<InteractionMarker>,
29 interaction_token: &'a str,
30 response: &'a InteractionResponse,
31 ) -> Self {
32 Self {
33 interaction_id,
34 interaction_token,
35 response,
36 http,
37 }
38 }
39}
40
41impl IntoFuture for CreateResponseWithResponse<'_> {
42 type Output = Result<Response<InteractionResponse>, Error>;
43
44 type IntoFuture = ResponseFuture<InteractionResponse>;
45
46 fn into_future(self) -> Self::IntoFuture {
47 let http = self.http;
48
49 match self.try_into_request() {
50 Ok(request) => http.request(request),
51 Err(source) => ResponseFuture::error(source),
52 }
53 }
54}
55
56impl TryIntoRequest for CreateResponseWithResponse<'_> {
57 fn try_into_request(self) -> Result<Request, Error> {
58 let mut request = Request::builder(&Route::InteractionCallback {
59 interaction_id: self.interaction_id.get(),
60 interaction_token: self.interaction_token,
61 with_response: true,
62 });
63
64 request = request.use_authorization_token(false);
67
68 if let Some(attachments) = self
71 .response
72 .data
73 .as_ref()
74 .and_then(|data| data.attachments.as_ref())
75 {
76 let fields = crate::json::to_vec(&self.response).map_err(Error::json)?;
77
78 let form = AttachmentManager::new()
79 .set_files(attachments.iter().collect())
80 .build_form(&fields);
81
82 request = request.form(form);
83 } else {
84 request = request.json(&self.response);
85 }
86
87 request.build()
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use crate::{client::Client, request::TryIntoRequest};
94 use std::error::Error;
95 use twilight_model::{
96 http::interaction::{InteractionResponse, InteractionResponseType},
97 id::Id,
98 };
99
100 #[test]
101 fn interaction_callback() -> Result<(), Box<dyn Error>> {
102 let application_id = Id::new(1);
103 let interaction_id = Id::new(2);
104 let token = "foo".to_owned().into_boxed_str();
105
106 let client = Client::new(String::new());
107
108 let response = InteractionResponse {
109 kind: InteractionResponseType::DeferredUpdateMessage,
110 data: None,
111 };
112
113 let req = client
114 .interaction(application_id)
115 .create_response(interaction_id, &token, &response)
116 .with_response()
117 .try_into_request()?;
118
119 assert!(!req.use_authorization_token());
120
121 Ok(())
122 }
123}