xurl-rs 1.1.0

A fast, ergonomic CLI for the X (Twitter) API — OAuth1/2, Bearer, media upload, streaming
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/// API shortcut functions — high-level X API v2 operations.
///
/// Each function maps to one of the 29 shortcut commands, building the
/// appropriate endpoint URL and request body.
use serde::Serialize;

use super::request::{ApiClient, RequestOptions};
use super::response::types::{
    ApiResponse, BlockingResult, BookmarkedResult, DeletedResult, DmEvent, FollowingResult,
    LikedResult, MutingResult, RetweetedResult, Tweet, UsageData, User, deserialize_response,
};
use crate::error::Result;

// ── Request body types ───────────────────────────────────────────────

#[derive(Serialize)]
struct PostBody {
    text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    reply: Option<PostReply>,
    #[serde(rename = "quote_tweet_id", skip_serializing_if = "Option::is_none")]
    quote: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    media: Option<PostMedia>,
}

#[derive(Serialize)]
struct PostReply {
    #[serde(rename = "in_reply_to_tweet_id")]
    in_reply_to_post_id: String,
}

#[derive(Serialize)]
struct PostMedia {
    media_ids: Vec<String>,
}

// ── Helpers ──────────────────────────────────────────────────────────

/// Extracts a post ID from a full URL or returns the input as-is.
#[must_use]
pub fn resolve_post_id(input: &str) -> String {
    let input = input.trim();

    if (input.starts_with("http://") || input.starts_with("https://"))
        && let Ok(parsed) = url::Url::parse(input)
    {
        let parts: Vec<&str> = parsed.path().trim_matches('/').split('/').collect();
        for (i, p) in parts.iter().enumerate() {
            if *p == "status" && i + 1 < parts.len() {
                return parts[i + 1].to_string();
            }
        }
    }
    input.to_string()
}

/// Normalizes a username — strips a leading "@" if present.
#[must_use]
pub fn resolve_username(input: &str) -> String {
    input.trim().trim_start_matches('@').to_string()
}

// ── Shortcut executors ───────────────────────────────────────────────

/// Creates a new post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn create_post(
    client: &mut ApiClient,
    text: &str,
    media_ids: &[String],
    opts: &RequestOptions,
) -> Result<ApiResponse<Tweet>> {
    let mut body = PostBody {
        text: text.to_string(),
        reply: None,
        quote: None,
        media: None,
    };
    if !media_ids.is_empty() {
        body.media = Some(PostMedia {
            media_ids: media_ids.to_vec(),
        });
    }

    let data = serde_json::to_string(&body)?;
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = "/2/tweets".to_string();
    opts.data = data;

    deserialize_response(client.send_request(&opts)?)
}

/// Replies to an existing post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn reply_to_post(
    client: &mut ApiClient,
    post_id: &str,
    text: &str,
    media_ids: &[String],
    opts: &RequestOptions,
) -> Result<ApiResponse<Tweet>> {
    let post_id = resolve_post_id(post_id);
    let mut body = PostBody {
        text: text.to_string(),
        reply: Some(PostReply {
            in_reply_to_post_id: post_id,
        }),
        quote: None,
        media: None,
    };
    if !media_ids.is_empty() {
        body.media = Some(PostMedia {
            media_ids: media_ids.to_vec(),
        });
    }

    let data = serde_json::to_string(&body)?;
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = "/2/tweets".to_string();
    opts.data = data;

    deserialize_response(client.send_request(&opts)?)
}

/// Quotes an existing post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn quote_post(
    client: &mut ApiClient,
    post_id: &str,
    text: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<Tweet>> {
    let post_id = resolve_post_id(post_id);
    let body = PostBody {
        text: text.to_string(),
        reply: None,
        quote: Some(post_id),
        media: None,
    };

    let data = serde_json::to_string(&body)?;
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = "/2/tweets".to_string();
    opts.data = data;

    deserialize_response(client.send_request(&opts)?)
}

/// Deletes a post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn delete_post(
    client: &mut ApiClient,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<DeletedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/tweets/{post_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Reads a single post with expansions.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn read_post(
    client: &mut ApiClient,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<Tweet>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/tweets/{post_id}?tweet.fields=created_at,public_metrics,conversation_id,in_reply_to_user_id,referenced_tweets,entities,attachments&expansions=author_id,referenced_tweets.id&user.fields=username,name,verified"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Searches recent posts.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn search_posts(
    client: &mut ApiClient,
    query: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<Tweet>>> {
    let q = url::form_urlencoded::byte_serialize(query.as_bytes()).collect::<String>();
    let max_results = max_results.clamp(10, 100);

    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/tweets/search/recent?query={q}&max_results={max_results}&tweet.fields=created_at,public_metrics,conversation_id,entities&expansions=author_id&user.fields=username,name,verified"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches the authenticated user's profile.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_me(client: &mut ApiClient, opts: &RequestOptions) -> Result<ApiResponse<User>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint =
        "/2/users/me?user.fields=created_at,description,public_metrics,verified,profile_image_url"
            .to_string();
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Looks up a user by username.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn lookup_user(
    client: &mut ApiClient,
    username: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<User>> {
    let username = resolve_username(username);
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/by/username/{username}?user.fields=created_at,description,public_metrics,verified,profile_image_url"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches the home timeline.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_timeline(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<Tweet>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/timelines/reverse_chronological?max_results={max_results}&tweet.fields=created_at,public_metrics,conversation_id,entities&expansions=author_id&user.fields=username,name"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches recent mentions.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_mentions(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<Tweet>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/mentions?max_results={max_results}&tweet.fields=created_at,public_metrics,conversation_id,entities&expansions=author_id&user.fields=username,name"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Likes a post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn like_post(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<LikedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{user_id}/likes");
    opts.data = format!(r#"{{"tweet_id":"{post_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Unlikes a post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unlike_post(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<LikedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{user_id}/likes/{post_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Reposts a post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn repost(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<RetweetedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{user_id}/retweets");
    opts.data = format!(r#"{{"tweet_id":"{post_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Removes a repost.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unrepost(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<RetweetedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{user_id}/retweets/{post_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Bookmarks a post.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn bookmark(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<BookmarkedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{user_id}/bookmarks");
    opts.data = format!(r#"{{"tweet_id":"{post_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Removes a bookmark.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unbookmark(
    client: &mut ApiClient,
    user_id: &str,
    post_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<BookmarkedResult>> {
    let post_id = resolve_post_id(post_id);
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{user_id}/bookmarks/{post_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches bookmarks.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_bookmarks(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<Tweet>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/bookmarks?max_results={max_results}&tweet.fields=created_at,public_metrics,entities&expansions=author_id&user.fields=username,name"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Follows a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn follow_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<FollowingResult>> {
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/following");
    opts.data = format!(r#"{{"target_user_id":"{target_user_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Unfollows a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unfollow_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<FollowingResult>> {
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/following/{target_user_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches users that a given user follows.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_following(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<User>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/following?max_results={max_results}&user.fields=created_at,description,public_metrics,verified"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches followers of a given user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_followers(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<User>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/followers?max_results={max_results}&user.fields=created_at,description,public_metrics,verified"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Sends a direct message.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn send_dm(
    client: &mut ApiClient,
    participant_id: &str,
    text: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<DmEvent>> {
    let body = serde_json::json!({"text": text});
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/dm_conversations/with/{participant_id}/messages");
    opts.data = serde_json::to_string(&body)?;

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches recent DM events.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_dm_events(
    client: &mut ApiClient,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<DmEvent>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/dm_events?max_results={max_results}&dm_event.fields=created_at,dm_conversation_id,sender_id,text&expansions=sender_id&user.fields=username,name"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches posts liked by a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_liked_posts(
    client: &mut ApiClient,
    user_id: &str,
    max_results: i32,
    opts: &RequestOptions,
) -> Result<ApiResponse<Vec<Tweet>>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint = format!(
        "/2/users/{user_id}/liked_tweets?max_results={max_results}&tweet.fields=created_at,public_metrics,entities&expansions=author_id&user.fields=username,name"
    );
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Blocks a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn block_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<BlockingResult>> {
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/blocking");
    opts.data = format!(r#"{{"target_user_id":"{target_user_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Unblocks a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unblock_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<BlockingResult>> {
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/blocking/{target_user_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Mutes a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn mute_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<MutingResult>> {
    let mut opts = opts.clone();
    opts.method = "POST".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/muting");
    opts.data = format!(r#"{{"target_user_id":"{target_user_id}"}}"#);

    deserialize_response(client.send_request(&opts)?)
}

/// Fetches API usage data (tweet caps, daily breakdowns).
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn get_usage(client: &mut ApiClient, opts: &RequestOptions) -> Result<ApiResponse<UsageData>> {
    let mut opts = opts.clone();
    opts.method = "GET".to_string();
    opts.endpoint =
        "/2/usage/tweets?usage.fields=daily_project_usage,daily_client_app_usage".to_string();
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}

/// Unmutes a user.
///
/// # Errors
///
/// Returns an error if the request fails or the API returns an error.
pub fn unmute_user(
    client: &mut ApiClient,
    source_user_id: &str,
    target_user_id: &str,
    opts: &RequestOptions,
) -> Result<ApiResponse<MutingResult>> {
    let mut opts = opts.clone();
    opts.method = "DELETE".to_string();
    opts.endpoint = format!("/2/users/{source_user_id}/muting/{target_user_id}");
    opts.data.clear();

    deserialize_response(client.send_request(&opts)?)
}