sendly 3.30.0

Official Rust SDK for the Sendly SMS API
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::client::Sendly;
use crate::error::Result;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contact {
    pub id: String,
    #[serde(alias = "phoneNumber")]
    pub phone_number: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub email: Option<String>,
    #[serde(default)]
    pub metadata: Option<HashMap<String, serde_json::Value>>,
    #[serde(default, alias = "optedOut")]
    pub opted_out: Option<bool>,
    /// Carrier-reported line type: `mobile`, `voip`, `toll free`, `fixed line`,
    /// `fixed line or mobile`, `pager`, `voicemail`, `shared cost`, etc.
    /// Populated after a carrier lookup.
    #[serde(default, alias = "lineType")]
    pub line_type: Option<String>,
    #[serde(default, alias = "carrierName")]
    pub carrier_name: Option<String>,
    #[serde(default, alias = "lineTypeCheckedAt")]
    pub line_type_checked_at: Option<String>,
    /// Auto-exclusion reason: `landline`, `invalid_number`, `non_sms_capable`.
    /// Clear with `contacts.mark_valid()`.
    #[serde(default, alias = "invalidReason")]
    pub invalid_reason: Option<String>,
    #[serde(default, alias = "invalidatedAt")]
    pub invalidated_at: Option<String>,
    /// When a user manually cleared an auto-flag on this contact. Carrier
    /// re-checks that would re-flag the contact as invalid respect this
    /// timestamp and leave the contact clean, so your manual decisions
    /// survive future lookups.
    #[serde(default, alias = "userMarkedValidAt")]
    pub user_marked_valid_at: Option<String>,
    #[serde(default, alias = "createdAt")]
    pub created_at: Option<String>,
    #[serde(default, alias = "updatedAt")]
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct CheckNumbersRequest {
    #[serde(rename = "listId", skip_serializing_if = "Option::is_none")]
    pub list_id: Option<String>,
    #[serde(default)]
    pub force: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CheckNumbersResponse {
    #[serde(default)]
    pub success: bool,
    /// True if a carrier lookup for this scope was already running when you
    /// called this. Treat it as a soft no-op and wait for the
    /// `contacts.lookup_completed` webhook.
    #[serde(default, alias = "already_running")]
    pub already_running: bool,
    #[serde(default)]
    pub message: Option<String>,
}

/// Request body for `contacts.bulk_mark_valid`. Pass either an explicit id
/// array (up to 10,000 per call) OR a `list_id`, not both. Foreign ids
/// silently no-op via the per-organization filter.
#[derive(Debug, Clone, Serialize, Default)]
pub struct BulkMarkValidRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ids: Option<Vec<String>>,
    #[serde(rename = "listId", skip_serializing_if = "Option::is_none")]
    pub list_id: Option<String>,
}

impl BulkMarkValidRequest {
    /// Clear this explicit set of contact ids (up to 10,000).
    pub fn of_ids(ids: Vec<String>) -> Self {
        Self {
            ids: Some(ids),
            list_id: None,
        }
    }

    /// Clear every flagged member of this list.
    pub fn of_list_id(list_id: impl Into<String>) -> Self {
        Self {
            ids: None,
            list_id: Some(list_id.into()),
        }
    }
}

/// Response from `contacts.bulk_mark_valid`. Reports how many contacts
/// actually had their invalid flag cleared. Already-clean contacts and
/// foreign ids don't count.
#[derive(Debug, Clone, Deserialize)]
pub struct BulkMarkValidResponse {
    #[serde(default)]
    pub cleared: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContactList {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default, alias = "contactCount")]
    pub contact_count: i32,
    #[serde(default, alias = "createdAt")]
    pub created_at: Option<String>,
    #[serde(default, alias = "updatedAt")]
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContactListResponse {
    pub contacts: Vec<Contact>,
    #[serde(default)]
    pub total: i32,
    #[serde(default)]
    pub limit: i32,
    #[serde(default)]
    pub offset: i32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContactListsResponse {
    pub lists: Vec<ContactList>,
    #[serde(default)]
    pub total: i32,
    #[serde(default)]
    pub limit: i32,
    #[serde(default)]
    pub offset: i32,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateContactRequest {
    #[serde(rename = "phone_number")]
    pub phone_number: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

impl CreateContactRequest {
    pub fn new(phone_number: impl Into<String>) -> Self {
        Self {
            phone_number: phone_number.into(),
            name: None,
            email: None,
            metadata: None,
        }
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    pub fn metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateContactRequest {
    #[serde(skip_serializing_if = "Option::is_none", rename = "phone_number")]
    pub phone_number: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

impl UpdateContactRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn phone_number(mut self, phone_number: impl Into<String>) -> Self {
        self.phone_number = Some(phone_number.into());
        self
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    pub fn metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

#[derive(Debug, Clone, Default)]
pub struct ListContactsOptions {
    pub limit: Option<u32>,
    pub offset: Option<u32>,
    pub search: Option<String>,
    pub list_id: Option<String>,
}

impl ListContactsOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit.min(100));
        self
    }

    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    pub fn search(mut self, search: impl Into<String>) -> Self {
        self.search = Some(search.into());
        self
    }

    pub fn list_id(mut self, list_id: impl Into<String>) -> Self {
        self.list_id = Some(list_id.into());
        self
    }

    pub(crate) fn to_query_params(&self) -> Vec<(String, String)> {
        let mut params = Vec::new();
        if let Some(limit) = self.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }
        if let Some(offset) = self.offset {
            params.push(("offset".to_string(), offset.to_string()));
        }
        if let Some(ref search) = self.search {
            params.push(("search".to_string(), search.clone()));
        }
        if let Some(ref list_id) = self.list_id {
            params.push(("list_id".to_string(), list_id.clone()));
        }
        params
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateContactListRequest {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl CreateContactListRequest {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
        }
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateContactListRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl UpdateContactListRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct AddContactsRequest {
    #[serde(rename = "contact_ids")]
    pub contact_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ImportContactItem {
    pub phone: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "optedInAt")]
    pub opted_in_at: Option<String>,
}

impl ImportContactItem {
    pub fn new(phone: impl Into<String>) -> Self {
        Self {
            phone: phone.into(),
            name: None,
            email: None,
            opted_in_at: None,
        }
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ImportContactsRequest {
    pub contacts: Vec<ImportContactItem>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "listId")]
    pub list_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "optedInAt")]
    pub opted_in_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ImportContactsError {
    pub index: i32,
    pub phone: String,
    pub error: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ImportContactsResponse {
    pub imported: i32,
    #[serde(rename = "skippedDuplicates")]
    pub skipped_duplicates: i32,
    #[serde(default)]
    pub errors: Vec<ImportContactsError>,
    #[serde(default, rename = "totalErrors")]
    pub total_errors: i32,
}

pub struct ContactsResource<'a> {
    client: &'a Sendly,
}

impl<'a> ContactsResource<'a> {
    pub fn new(client: &'a Sendly) -> Self {
        Self { client }
    }

    pub fn lists(&self) -> ContactListsResource<'a> {
        ContactListsResource::new(self.client)
    }

    pub async fn list(&self, options: ListContactsOptions) -> Result<ContactListResponse> {
        let params = options.to_query_params();
        let response = self.client.get("/contacts", &params).await?;
        Ok(response.json().await?)
    }

    pub async fn get(&self, id: &str) -> Result<Contact> {
        let response = self.client.get(&format!("/contacts/{}", id), &[]).await?;
        Ok(response.json().await?)
    }

    pub async fn create(&self, request: CreateContactRequest) -> Result<Contact> {
        let response = self.client.post("/contacts", &request).await?;
        Ok(response.json().await?)
    }

    pub async fn update(&self, id: &str, request: UpdateContactRequest) -> Result<Contact> {
        let response = self
            .client
            .patch(&format!("/contacts/{}", id), &request)
            .await?;
        Ok(response.json().await?)
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client.delete(&format!("/contacts/{}", id)).await?;
        Ok(())
    }

    /// Clear the invalid flag on a contact so future campaigns include it again.
    ///
    /// Contacts get auto-flagged when a send fails with a terminal bad-number
    /// error (landline, invalid number) or when a carrier lookup reports they
    /// can't receive SMS.
    pub async fn mark_valid(&self, id: &str) -> Result<Contact> {
        let response = self
            .client
            .post(&format!("/contacts/{}/mark-valid", id), &serde_json::json!({}))
            .await?;
        Ok(response.json().await?)
    }

    /// Clear the invalid flag on many contacts at once — the escape hatch for
    /// when auto-flag misclassifies at scale. Pass either an explicit id array
    /// (up to 10,000 per call) OR a `list_id`, not both. Foreign ids silently
    /// no-op via the per-organization filter.
    ///
    /// Returns the number of contacts whose flag was actually cleared.
    /// Already-clean contacts and foreign ids don't count.
    pub async fn bulk_mark_valid(
        &self,
        request: BulkMarkValidRequest,
    ) -> Result<BulkMarkValidResponse> {
        let has_ids = request.ids.as_ref().map(|v| !v.is_empty()).unwrap_or(false);
        let has_list_id = request
            .list_id
            .as_ref()
            .map(|s| !s.is_empty())
            .unwrap_or(false);

        if !has_ids && !has_list_id {
            return Err(crate::error::Error::Validation {
                message: "bulk_mark_valid requires either ids or list_id".to_string(),
            });
        }
        if has_ids && has_list_id {
            return Err(crate::error::Error::Validation {
                message: "bulk_mark_valid accepts ids OR list_id, not both".to_string(),
            });
        }

        let response = self
            .client
            .post("/contacts/bulk-mark-valid", &request)
            .await?;
        Ok(response.json().await?)
    }

    /// Trigger a background carrier lookup across your contacts. Landlines
    /// and other non-SMS-capable numbers are auto-excluded from future
    /// campaigns. Idempotent: re-triggering while a lookup is running for the
    /// same scope is a no-op.
    pub async fn check_numbers(
        &self,
        request: CheckNumbersRequest,
    ) -> Result<CheckNumbersResponse> {
        let response = self.client.post("/contacts/lookup", &request).await?;
        Ok(response.json().await?)
    }

    pub async fn import(&self, request: ImportContactsRequest) -> Result<ImportContactsResponse> {
        let response = self.client.post("/contacts/import", &request).await?;
        Ok(response.json().await?)
    }
}

pub struct ContactListsResource<'a> {
    client: &'a Sendly,
}

impl<'a> ContactListsResource<'a> {
    pub fn new(client: &'a Sendly) -> Self {
        Self { client }
    }

    pub async fn list(&self) -> Result<ContactListsResponse> {
        let response = self.client.get("/contact-lists", &[]).await?;
        Ok(response.json().await?)
    }

    pub async fn get(&self, id: &str) -> Result<ContactList> {
        let response = self
            .client
            .get(&format!("/contact-lists/{}", id), &[])
            .await?;
        Ok(response.json().await?)
    }

    pub async fn create(&self, request: CreateContactListRequest) -> Result<ContactList> {
        let response = self.client.post("/contact-lists", &request).await?;
        Ok(response.json().await?)
    }

    pub async fn update(&self, id: &str, request: UpdateContactListRequest) -> Result<ContactList> {
        let response = self
            .client
            .patch(&format!("/contact-lists/{}", id), &request)
            .await?;
        Ok(response.json().await?)
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(&format!("/contact-lists/{}", id))
            .await?;
        Ok(())
    }

    pub async fn add_contacts(&self, list_id: &str, contact_ids: Vec<String>) -> Result<()> {
        let request = AddContactsRequest { contact_ids };
        self.client
            .post(&format!("/contact-lists/{}/contacts", list_id), &request)
            .await?;
        Ok(())
    }

    pub async fn remove_contact(&self, list_id: &str, contact_id: &str) -> Result<()> {
        self.client
            .delete(&format!(
                "/contact-lists/{}/contacts/{}",
                list_id, contact_id
            ))
            .await?;
        Ok(())
    }
}