twitch_api/helix/endpoints/moderation/
update_automod_settings.rs

1//! Updates the broadcaster’s AutoMod settings.
2//!
3//! [`update-automod-settings`](https://dev.twitch.tv/docs/api/reference#update-automod-settings)
4//! The settings are used to automatically block inappropriate or harassing messages from appearing in the broadcaster’s chat room.
5//!
6//! # Accessing the endpoint
7//!
8//! ## Request: [UpdateAutoModSettingsRequest]
9//!
10//! To use this endpoint, construct an [`UpdateAutoModSettingsRequest`] with the [`UpdateAutoModSettingsRequest::new()`] method.
11//!
12//! ```rust
13//! use twitch_api::helix::moderation::update_automod_settings;
14//! let request = update_automod_settings::UpdateAutoModSettingsRequest::new(
15//!     "123", "456",
16//! );
17//! ```
18//!
19//! ## Body: [UpdateAutoModSettingsBody]
20//!
21//! We also need to provide a body to the request.
22//!
23//! ```
24//! # use twitch_api::helix::moderation::update_automod_settings;
25//! // Set the overall level to 3
26//! let body = update_automod_settings::UpdateAutoModSettingsBody::overall(3);
27//! ```
28//!
29//!
30//! ## Response: [AutoModSettings]
31//!
32//! Send the request to receive the response with [`HelixClient::req_patch()`](helix::HelixClient::req_patch).
33//!
34//! ```rust, no_run
35//! use twitch_api::helix::{self, moderation::update_automod_settings};
36//! # use twitch_api::client;
37//! # #[tokio::main]
38//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
39//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
40//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
41//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
42//! let request = update_automod_settings::UpdateAutoModSettingsRequest::new(
43//!     "123",
44//!     "456"
45//! );
46//! let body =
47//!     update_automod_settings::UpdateAutoModSettingsBody::overall(3);
48//! let response: helix::moderation::AutoModSettings = client.req_put(request, body, &token).await?.data;
49//! # Ok(())
50//! # }
51//! ```
52//!
53//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestPut::create_request)
54//! and parse the [`http::Response`] with [`UpdateAutoModSettingsRequest::parse_response(None, &request.get_uri(), response)`](UpdateAutoModSettingsRequest::parse_response)
55
56use super::*;
57use helix::RequestPut;
58
59pub use super::AutoModSettings;
60
61/// Query Parameters for [Update AutoMod Settings](super::update_automod_settings)
62///
63/// [`update-automod-settings`](https://dev.twitch.tv/docs/api/reference#update-automod-settings)
64#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
65#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
66#[non_exhaustive]
67pub struct UpdateAutoModSettingsRequest<'a> {
68    /// The ID of the broadcaster whose AutoMod settings you want to update.
69    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
70    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
71    #[cfg_attr(not(feature = "deser_borrow"), serde(bound(deserialize = "'de: 'a")))]
72    pub broadcaster_id: Cow<'a, types::UserIdRef>,
73    /// The ID of the broadcaster or a user that has permission to moderate the broadcaster’s chat room. This ID must match the user ID in the user access token.
74    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
75    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
76    #[cfg_attr(not(feature = "deser_borrow"), serde(bound(deserialize = "'de: 'a")))]
77    pub moderator_id: Cow<'a, types::UserIdRef>,
78}
79
80impl<'a> UpdateAutoModSettingsRequest<'a> {
81    /// Update the AutoMod settings on the specified channel as the specified moderator
82    pub fn new(
83        broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
84        moderator_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
85    ) -> Self {
86        Self {
87            broadcaster_id: broadcaster_id.into_cow(),
88            moderator_id: moderator_id.into_cow(),
89        }
90    }
91}
92
93/// Body Parameters for [Update AutoMod Settings](super::update_automod_settings)
94///
95/// [`update-automod-settings`](https://dev.twitch.tv/docs/api/reference#update-automod-settings)
96///
97/// Because PUT is an overwrite operation, you must include all the fields that you want set after the operation completes.
98/// Typically, you’ll send a GET request, update the fields you want to change, and pass that object in the PUT request.
99///
100/// You may set either `overall_level` (`Overall`) or the individual settings like `aggression` (`Individual`), but not both.
101#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
102#[serde(untagged)]
103#[non_exhaustive]
104pub enum UpdateAutoModSettingsBody {
105    /// Set the `overall_level`
106    ///
107    /// Setting `overall_level` applies default values to the individual settings.
108    /// However, setting `overall_level` to 4 does not necessarily mean that it applies 4 to all the individual settings.
109    /// Instead, it applies a set of recommended defaults to the rest of the settings.
110    #[non_exhaustive]
111    Overall {
112        /// The default AutoMod level for the broadcaster.
113        overall_level: u8,
114    },
115    /// Set the individual levels for each setting
116    Individual(UpdateAutoModSettingsIndividual),
117}
118
119/// Set the individual levels for each setting
120///
121/// Note that because PUT is an overwrite operation, you must include all the fields that you want set after the operation completes.
122/// Use [from_settings](Self::from_settings) to initialize this struct to previously returned [AutoModSettings].
123#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug, Default)]
124#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
125#[non_exhaustive]
126pub struct UpdateAutoModSettingsIndividual {
127    /// The Automod level for hostility involving aggression.
128    #[cfg_attr(feature = "typed-builder", builder(default))]
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub aggression: Option<u8>,
131    /// The Automod level for hostility involving name calling or insults.
132    #[cfg_attr(feature = "typed-builder", builder(default))]
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub bullying: Option<u8>,
135    /// The Automod level for discrimination against disability.
136    #[cfg_attr(feature = "typed-builder", builder(default))]
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub disability: Option<u8>,
139    /// The Automod level for discrimination against women.
140    #[cfg_attr(feature = "typed-builder", builder(default))]
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub misogyny: Option<u8>,
143    /// The Automod level for racial discrimination.
144    #[cfg_attr(feature = "typed-builder", builder(default))]
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub race_ethnicity_or_religion: Option<u8>,
147    /// The Automod level for sexual content.
148    #[cfg_attr(feature = "typed-builder", builder(default))]
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub sex_based_terms: Option<u8>,
151    /// The AutoMod level for discrimination based on sexuality, sex, or gender.
152    #[cfg_attr(feature = "typed-builder", builder(default))]
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub sexuality_sex_or_gender: Option<u8>,
155    /// The Automod level for profanity.
156    #[cfg_attr(feature = "typed-builder", builder(default))]
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub swearing: Option<u8>,
159}
160
161impl helix::private::SealedSerialize for UpdateAutoModSettingsBody {}
162
163impl UpdateAutoModSettingsBody {
164    /// Set the `overall_level`
165    pub const fn overall(overall_level: u8) -> Self { Self::Overall { overall_level } }
166
167    /// Constructs an `Individual` from [AutoModSettings]
168    pub const fn from_settings(settings: &AutoModSettings) -> Self {
169        Self::Individual(UpdateAutoModSettingsIndividual::from_settings(settings))
170    }
171}
172
173impl UpdateAutoModSettingsIndividual {
174    /// Constructs an update on individual settings from [AutoModSettings]
175    pub const fn from_settings(settings: &AutoModSettings) -> Self {
176        Self {
177            aggression: Some(settings.aggression),
178            bullying: Some(settings.bullying),
179            disability: Some(settings.disability),
180            misogyny: Some(settings.misogyny),
181            race_ethnicity_or_religion: Some(settings.race_ethnicity_or_religion),
182            sex_based_terms: Some(settings.sex_based_terms),
183            sexuality_sex_or_gender: Some(settings.sexuality_sex_or_gender),
184            swearing: Some(settings.swearing),
185        }
186    }
187}
188
189impl Request for UpdateAutoModSettingsRequest<'_> {
190    type Response = super::AutoModSettings;
191
192    const PATH: &'static str = "moderation/automod/settings";
193    #[cfg(feature = "twitch_oauth2")]
194    const SCOPE: twitch_oauth2::Validator =
195        twitch_oauth2::validator![twitch_oauth2::Scope::ModeratorManageAutomodSettings];
196}
197
198impl RequestPut for UpdateAutoModSettingsRequest<'_> {
199    type Body = UpdateAutoModSettingsBody;
200
201    fn parse_inner_response(
202        request: Option<Self>,
203        uri: &http::Uri,
204        response: &str,
205        status: http::StatusCode,
206    ) -> Result<helix::Response<Self, <Self as Request>::Response>, helix::HelixRequestPutError>
207    where
208        Self: Sized,
209    {
210        helix::parse_single_return(request, uri, response, status)
211    }
212}
213
214#[cfg(test)]
215#[test]
216fn test_request_overall() {
217    use helix::*;
218    let req = UpdateAutoModSettingsRequest::new("1234", "5678");
219    let body = UpdateAutoModSettingsBody::overall(3);
220
221    assert_eq!(
222        std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
223        r#"{"overall_level":3}"#
224    );
225
226    req.create_request(body, "token", "clientid").unwrap();
227
228    // From twitch docs
229    let data = br#"
230    {
231        "data": [
232            {
233                "broadcaster_id": "1234",
234                "moderator_id": "5678",
235                "overall_level": 3,
236                "disability": 3,
237                "aggression": 3,
238                "sexuality_sex_or_gender": 3,
239                "misogyny": 3,
240                "bullying": 2,
241                "swearing": 0,
242                "race_ethnicity_or_religion": 3,
243                "sex_based_terms": 3
244            }
245        ]
246    }
247    "#
248    .to_vec();
249
250    let http_response = http::Response::builder().status(200).body(data).unwrap();
251
252    let uri = req.get_uri().unwrap();
253    assert_eq!(
254        uri.to_string(),
255        "https://api.twitch.tv/helix/moderation/automod/settings?broadcaster_id=1234&moderator_id=5678"
256    );
257
258    let res = UpdateAutoModSettingsRequest::parse_response(Some(req), &uri, http_response)
259        .unwrap()
260        .data;
261    assert_eq!(res.overall_level, Some(3));
262    assert_eq!(res.disability, 3);
263}
264
265#[cfg(test)]
266#[test]
267fn test_request_individual() {
268    use helix::*;
269    let req = UpdateAutoModSettingsRequest::new("1234", "5678");
270    let body = UpdateAutoModSettingsBody::Individual(UpdateAutoModSettingsIndividual {
271        aggression: Some(0),
272        bullying: Some(1),
273        disability: None,
274        misogyny: None,
275        race_ethnicity_or_religion: None,
276        sex_based_terms: None,
277        sexuality_sex_or_gender: None,
278        swearing: Some(2),
279    });
280
281    assert_eq!(
282        std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
283        r#"{"aggression":0,"bullying":1,"swearing":2}"#
284    );
285
286    req.create_request(body, "token", "clientid").unwrap();
287
288    let data = br#"
289    {
290        "data": [
291            {
292                "aggression": 0,
293                "broadcaster_id": "1234",
294                "bullying": 1,
295                "disability": 0,
296                "misogyny": 0,
297                "moderator_id": "5678",
298                "overall_level": null,
299                "race_ethnicity_or_religion": 0,
300                "sex_based_terms": 0,
301                "sexuality_sex_or_gender": 0,
302                "swearing": 2
303            }
304        ]
305    }
306    "#
307    .to_vec();
308
309    let http_response = http::Response::builder().status(200).body(data).unwrap();
310
311    let uri = req.get_uri().unwrap();
312    assert_eq!(
313        uri.to_string(),
314        "https://api.twitch.tv/helix/moderation/automod/settings?broadcaster_id=1234&moderator_id=5678"
315    );
316
317    let res = UpdateAutoModSettingsRequest::parse_response(Some(req), &uri, http_response)
318        .unwrap()
319        .data;
320    assert_eq!(res.overall_level, None);
321    assert_eq!(res.swearing, 2);
322}