twitch_api/helix/endpoints/moderation/
manage_held_automod_messages.rs

1//! Allow or deny a message that was held for review by AutoMod.
2//! [`manage-held-automod-messages`](https://dev.twitch.tv/docs/api/reference#manage-held-automod-messages)
3//!
4//! # Accessing the endpoint
5//!
6//! ## Request: [ManageHeldAutoModMessagesRequest]
7//!
8//! To use this endpoint, construct a [`ManageHeldAutoModMessagesRequest`] with the [`ManageHeldAutoModMessagesRequest::new()`] method.
9//!
10//! ```rust
11//! use twitch_api::helix::moderation::manage_held_automod_messages;
12//! let request =
13//!     manage_held_automod_messages::ManageHeldAutoModMessagesRequest::new();
14//! ```
15//!
16//! ## Body: [ManageHeldAutoModMessagesBody]
17//!
18//! We also need to provide a body to the request containing what we want to change.
19//!
20//! ```
21//! # use twitch_api::helix::moderation::manage_held_automod_messages;
22//! let body = manage_held_automod_messages::ManageHeldAutoModMessagesBody::new(
23//!     "9327994",
24//!     "836013710",
25//!     true,
26//! );
27//! ```
28//!
29//! ## Response: [ManageHeldAutoModMessages]
30//!
31//!
32//! Send the request to receive the response with [`HelixClient::req_post()`](helix::HelixClient::req_post).
33//!
34//!
35//! ```rust, no_run
36//! use twitch_api::helix::{self, moderation::manage_held_automod_messages};
37//! # use twitch_api::client;
38//! # #[tokio::main]
39//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
40//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
41//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
42//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
43//! let request = manage_held_automod_messages::ManageHeldAutoModMessagesRequest::new();
44//! let body = manage_held_automod_messages::ManageHeldAutoModMessagesBody::new(
45//!     "9327994",
46//!     "836013710",
47//!     true,
48//! );
49//! let response: manage_held_automod_messages::ManageHeldAutoModMessages = client.req_post(request, body, &token).await?.data;
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestPost::create_request)
55//! and parse the [`http::Response`] with [`ManageHeldAutoModMessagesRequest::parse_response(None, &request.get_uri(), response)`](ManageHeldAutoModMessagesRequest::parse_response)
56
57use std::marker::PhantomData;
58
59use super::*;
60use helix::RequestPost;
61/// Query Parameters for [Manage Held AutoMod Messages](super::manage_held_automod_messages)
62///
63/// [`manage-held-automod-messages`](https://dev.twitch.tv/docs/api/reference#manage-held-automod-messages)
64#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug, Default)]
65#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
66#[must_use]
67#[non_exhaustive]
68pub struct ManageHeldAutoModMessagesRequest<'a> {
69    #[serde(skip)]
70    _marker: PhantomData<&'a ()>,
71}
72
73impl ManageHeldAutoModMessagesRequest<'_> {
74    /// Create a new [`ManageHeldAutoModMessagesRequest`]
75    pub fn new() -> Self { Self::default() }
76}
77
78/// Body Parameters for [Manage Held AutoMod Messages](super::manage_held_automod_messages)
79///
80/// [`manage-held-automod-messages`](https://dev.twitch.tv/docs/api/reference#manage-held-automod-messages)
81#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
82#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
83#[non_exhaustive]
84pub struct ManageHeldAutoModMessagesBody<'a> {
85    /// The moderator who is approving or rejecting the held message. Must match the user_id in the user OAuth token.
86    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
87    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
88    pub user_id: Cow<'a, types::UserIdRef>,
89    /// ID of the message to be allowed or denied. These message IDs are retrieved from IRC or PubSub. Only one message ID can be provided.
90    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
91    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
92    pub msg_id: Cow<'a, types::MsgIdRef>,
93    /// The action to take for the message. Must be "ALLOW" or "DENY".
94    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
95    pub action: AutoModAction,
96}
97
98impl<'a> ManageHeldAutoModMessagesBody<'a> {
99    /// Create a new [`ManageHeldAutoModMessagesBody`]
100    ///
101    /// # Examples
102    ///
103    /// ```rust
104    /// use twitch_api::helix::moderation::ManageHeldAutoModMessagesBody;
105    ///
106    /// let body = ManageHeldAutoModMessagesBody::new("1234", "5678", true);
107    /// ```
108    pub fn new(
109        user_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
110        msg_id: impl types::IntoCow<'a, types::MsgIdRef> + 'a,
111        action: impl Into<AutoModAction>,
112    ) -> Self {
113        Self {
114            user_id: user_id.into_cow(),
115            msg_id: msg_id.into_cow(),
116            action: action.into(),
117        }
118    }
119}
120
121/// Action to take for a message.
122#[derive(PartialEq, Eq, Deserialize, Serialize, Copy, Clone, Debug)]
123#[serde(rename_all = "UPPERCASE")]
124#[non_exhaustive]
125pub enum AutoModAction {
126    /// Allow the message
127    Allow,
128    /// Deny the message
129    Deny,
130}
131
132impl From<bool> for AutoModAction {
133    fn from(b: bool) -> Self {
134        match b {
135            true => Self::Allow,
136            false => Self::Deny,
137        }
138    }
139}
140
141impl helix::private::SealedSerialize for ManageHeldAutoModMessagesBody<'_> {}
142
143/// Return Values for [Manage Held AutoMod Messages](super::manage_held_automod_messages)
144///
145/// [`manage-held-automod-messages`](https://dev.twitch.tv/docs/api/reference#manage-held-automod-messages)
146#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
147#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
148#[non_exhaustive]
149pub enum ManageHeldAutoModMessages {
150    /// Successfully approved or denied the message
151    Success,
152}
153
154impl Request for ManageHeldAutoModMessagesRequest<'_> {
155    type Response = ManageHeldAutoModMessages;
156
157    const PATH: &'static str = "moderation/automod/message";
158    #[cfg(feature = "twitch_oauth2")]
159    const SCOPE: twitch_oauth2::Validator =
160        twitch_oauth2::validator![twitch_oauth2::Scope::ModeratorManageAutoMod];
161}
162
163impl<'a> RequestPost for ManageHeldAutoModMessagesRequest<'a> {
164    type Body = ManageHeldAutoModMessagesBody<'a>;
165
166    fn parse_inner_response<'d>(
167        request: Option<Self>,
168        uri: &http::Uri,
169        response: &str,
170        status: http::StatusCode,
171    ) -> Result<helix::Response<Self, Self::Response>, helix::HelixRequestPostError>
172    where
173        Self: Sized,
174    {
175        match status {
176            http::StatusCode::NO_CONTENT => Ok(helix::Response::with_data(
177                ManageHeldAutoModMessages::Success,
178                request,
179            )),
180            _ => Err(helix::HelixRequestPostError::InvalidResponse {
181                reason: "unexpected status",
182                response: response.to_string(),
183                status,
184                uri: uri.clone(),
185            }),
186        }
187    }
188}
189
190#[cfg(test)]
191#[test]
192fn test_request() {
193    use helix::*;
194    let req = ManageHeldAutoModMessagesRequest::new();
195
196    let body = ManageHeldAutoModMessagesBody::new("9327994", "836013710", true);
197
198    assert_eq!(
199        std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
200        r#"{"user_id":"9327994","msg_id":"836013710","action":"ALLOW"}"#
201    );
202
203    dbg!(req.create_request(body, "token", "clientid").unwrap());
204
205    // From twitch docs
206    let data = br#""#.to_vec();
207
208    let http_response = http::Response::builder().status(204).body(data).unwrap();
209
210    let uri = req.get_uri().unwrap();
211    assert_eq!(
212        uri.to_string(),
213        "https://api.twitch.tv/helix/moderation/automod/message?"
214    );
215
216    dbg!(ManageHeldAutoModMessagesRequest::parse_response(Some(req), &uri, http_response).unwrap());
217}