zynko 0.1.0

Biblioteca oficial para bots do Zynko: API, gateway e voz.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! The HTTP API with a bot's token.

use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use reqwest::Method;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::error::{Error, Result};
use crate::types::*;

/// Where the API is unless told otherwise.
pub const DEFAULT_API: &str = "https://zynko.org/api";

/// A file to send with a message.
#[derive(Debug, Clone)]
pub struct FileInput {
    pub name: String,
    pub data: Vec<u8>,
    /// Worked out by the server from the name when absent.
    pub content_type: Option<String>,
}

impl FileInput {
    pub fn new(name: impl Into<String>, data: impl Into<Vec<u8>>) -> Self {
        Self {
            name: name.into(),
            data: data.into(),
            content_type: None,
        }
    }

    /// Reads a file from disk; the name is the file's own.
    pub async fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let data = tokio::fs::read(path).await?;
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("arquivo")
            .to_string();
        Ok(Self::new(name, data))
    }

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

/// A message to send: text, files, cards and buttons. A `&str` or `String` converts into one.
///
/// ```
/// use zynko::{Button, Card, SendOptions};
/// let msg = SendOptions::new("Votação")
///     .card(Card::new().title("Pizza ou hambúrguer?"))
///     .row(vec![Button::primary("Pizza", "voto:pizza")]);
/// ```
#[derive(Debug, Clone, Default)]
pub struct SendOptions {
    pub content: String,
    /// Answer this message (from the same channel).
    pub reply_to: Option<Id>,
    /// Uploaded first (up to 10).
    pub files: Vec<FileInput>,
    pub nonce: Option<String>,
    /// Up to 5.
    pub cards: Vec<Card>,
    /// Rows of buttons.
    pub components: Components,
}

impl SendOptions {
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            ..Default::default()
        }
    }
    pub fn reply_to(mut self, id: impl Into<Id>) -> Self {
        self.reply_to = Some(id.into());
        self
    }
    pub fn file(mut self, file: FileInput) -> Self {
        self.files.push(file);
        self
    }
    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
        self.nonce = Some(nonce.into());
        self
    }
    pub fn card(mut self, card: Card) -> Self {
        self.cards.push(card);
        self
    }
    /// Adds a row of buttons.
    pub fn row(mut self, row: Vec<Button>) -> Self {
        self.components.push(row);
        self
    }
}

impl From<&str> for SendOptions {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}
impl From<String> for SendOptions {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}
impl From<&String> for SendOptions {
    fn from(s: &String) -> Self {
        Self::new(s.clone())
    }
}

/// What an interaction's answer carries. A `&str` or `String` converts into one.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ReplyOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cards: Option<Vec<Card>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
    /// Only the person who used the command sees it (and it is not kept). No buttons.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub ephemeral: bool,
}

impl ReplyOptions {
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: Some(content.into()),
            ..Default::default()
        }
    }
    pub fn ephemeral(mut self) -> Self {
        self.ephemeral = true;
        self
    }
    pub fn card(mut self, card: Card) -> Self {
        self.cards.get_or_insert_with(Vec::new).push(card);
        self
    }
    pub fn row(mut self, row: Vec<Button>) -> Self {
        self.components.get_or_insert_with(Vec::new).push(row);
        self
    }
}

impl From<&str> for ReplyOptions {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}
impl From<String> for ReplyOptions {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

/// A change to a message: only what is set changes. `components: Some(vec![])` takes the
/// buttons away. A `&str` or `String` converts into a text-only edit.
#[derive(Debug, Clone, Default, Serialize)]
pub struct EditOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cards: Option<Vec<Card>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
}

impl EditOptions {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }
    pub fn cards(mut self, cards: Vec<Card>) -> Self {
        self.cards = Some(cards);
        self
    }
    pub fn components(mut self, components: Components) -> Self {
        self.components = Some(components);
        self
    }
}

impl From<&str> for EditOptions {
    fn from(s: &str) -> Self {
        Self::new().content(s)
    }
}
impl From<String> for EditOptions {
    fn from(s: String) -> Self {
        Self::new().content(s)
    }
}

/// Which messages to list (`Rest::messages`).
#[derive(Debug, Clone, Default)]
pub struct MessagesQuery {
    pub before: Option<Id>,
    pub after: Option<Id>,
    /// Up to 100.
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct NewRole {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permissions: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hoist: Option<bool>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct NewChannel {
    pub name: String,
    /// See [`ChannelType`]; text by default.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub kind: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<Id>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
}

/// What to change in a channel; `Some(None)` clears a field.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ChannelEdit {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<Option<Id>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate_limit_per_user: Option<u64>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct InviteOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_age_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_uses: Option<u64>,
}

/// An interaction answer's kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CallbackType {
    /// A new message in the channel.
    Message,
    /// Changes the clicked message (buttons only).
    Update,
}

enum Body<'a> {
    None,
    Json(&'a Value),
    File(&'a FileInput),
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct ApiErrorBody {
    code: Option<String>,
    message: Option<String>,
    retry_after_ms: Option<u64>,
}

/// The HTTP API with a bot's token. Every route is reachable through [`Rest::request`]; the
/// common ones have their own method. Cheap to clone.
#[derive(Clone)]
pub struct Rest {
    inner: Arc<RestInner>,
}

struct RestInner {
    api: String,
    auth: String,
    retries: u32,
    http: reqwest::Client,
}

impl std::fmt::Debug for Rest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Rest")
            .field("api", &self.inner.api)
            .finish_non_exhaustive()
    }
}

fn enc(s: &str) -> String {
    // Percent-encodes a path segment (emoji names, `name:id`).
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

impl Rest {
    /// `api`: https://zynko.org/api unless you run your own server. `retries`: how many times a
    /// 429 is waited out and tried again (0: never).
    pub fn new(token: &str, api: Option<&str>, retries: u32) -> Self {
        crate::install_crypto();
        let api = api.unwrap_or(DEFAULT_API).trim_end_matches('/').to_string();
        let http = reqwest::Client::builder()
            .user_agent(concat!("zynko-rust/", env!("CARGO_PKG_VERSION")))
            .build()
            .expect("cliente HTTP");
        Self {
            inner: Arc::new(RestInner {
                api,
                auth: format!("Bot {token}"),
                retries,
                http,
            }),
        }
    }

    /// The API's address, without the trailing slash.
    pub fn api(&self) -> &str {
        &self.inner.api
    }

    /// The server's address without /api, to turn `/api/media/...` paths into links.
    pub fn base(&self) -> &str {
        self.inner
            .api
            .strip_suffix("/api")
            .unwrap_or(&self.inner.api)
    }

    /// Any route: `request::<Value>(Method::PATCH, "/guilds/1/members/2", Some(json!({...})))`.
    /// An empty answer reads as `null` (use `()` or `Value`).
    pub async fn request<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        body: Option<Value>,
    ) -> Result<T> {
        match &body {
            Some(v) => self.send_req(method, path, Body::Json(v)).await,
            None => self.send_req(method, path, Body::None).await,
        }
    }

    async fn send_req<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        body: Body<'_>,
    ) -> Result<T> {
        let url = format!("{}{}", self.inner.api, path);
        let mut attempt = 0;
        loop {
            let mut req = self
                .inner
                .http
                .request(method.clone(), &url)
                .header("Authorization", &self.inner.auth);
            req = match &body {
                Body::None => req,
                Body::Json(v) => req.json(v),
                Body::File(f) => {
                    let mut part =
                        reqwest::multipart::Part::bytes(f.data.clone()).file_name(f.name.clone());
                    if let Some(ct) = &f.content_type {
                        part = part.mime_str(ct)?;
                    }
                    req.multipart(reqwest::multipart::Form::new().part("file", part))
                }
            };
            let res = req.send().await?;
            let status = res.status();
            if status.is_success() {
                let text = res.text().await?;
                let value = if text.trim().is_empty() {
                    Value::Null
                } else {
                    serde_json::from_str(&text)?
                };
                return Ok(serde_json::from_value(value)?);
            }
            let header_wait = res
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<f64>().ok());
            let reason = status.canonical_reason().unwrap_or("").to_string();
            let text = res.text().await.unwrap_or_default();
            let err: ApiErrorBody = serde_json::from_str(&text).unwrap_or_default();
            if status.as_u16() == 429
                && attempt < self.inner.retries
                && err.code.as_deref() == Some("rate_limited")
            {
                let ms = err
                    .retry_after_ms
                    .unwrap_or_else(|| (header_wait.unwrap_or(1.0) * 1000.0) as u64);
                tokio::time::sleep(Duration::from_millis(ms + 50)).await;
                attempt += 1;
                continue;
            }
            return Err(Error::Api {
                status: status.as_u16(),
                code: err
                    .code
                    .unwrap_or_else(|| format!("http_{}", status.as_u16())),
                message: err.message.unwrap_or(reason),
            });
        }
    }

    pub async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.request(Method::GET, path, None).await
    }
    /// POST with a body (`{}` when none).
    pub async fn post<T: DeserializeOwned>(&self, path: &str, body: Option<Value>) -> Result<T> {
        self.request(Method::POST, path, Some(body.unwrap_or_else(|| json!({}))))
            .await
    }
    pub async fn patch<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T> {
        self.request(Method::PATCH, path, Some(body)).await
    }
    pub async fn put<T: DeserializeOwned>(&self, path: &str, body: Option<Value>) -> Result<T> {
        self.request(Method::PUT, path, body).await
    }
    pub async fn delete<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.request(Method::DELETE, path, None).await
    }

    // ---------- messages ----------

    /// Sends a message; files are uploaded first.
    pub async fn send(
        &self,
        channel_id: &str,
        message: impl Into<SendOptions>,
    ) -> Result<MessageData> {
        let opts = message.into();
        let mut attachment_ids = Vec::new();
        for f in &opts.files {
            attachment_ids.push(self.upload(channel_id, f).await?.id);
        }
        let mut body = json!({ "content": opts.content });
        if let Some(r) = &opts.reply_to {
            body["reply_to"] = json!(r);
        }
        if let Some(n) = &opts.nonce {
            body["nonce"] = json!(n);
        }
        if !attachment_ids.is_empty() {
            body["attachment_ids"] = json!(attachment_ids);
        }
        if !opts.cards.is_empty() {
            body["cards"] = serde_json::to_value(&opts.cards)?;
        }
        if !opts.components.is_empty() {
            body["components"] = serde_json::to_value(&opts.components)?;
        }
        self.post(&format!("/channels/{channel_id}/messages"), Some(body))
            .await
    }

    /// Uploads a file to a channel, to be sent in a message (see [`Rest::send`]).
    pub async fn upload(&self, channel_id: &str, file: &FileInput) -> Result<Attachment> {
        self.send_req(
            Method::POST,
            &format!("/channels/{channel_id}/attachments"),
            Body::File(file),
        )
        .await
    }

    /// Changes the bot's own message: whatever is given (text, cards, buttons).
    pub async fn edit_message(
        &self,
        channel_id: &str,
        message_id: &str,
        edit: impl Into<EditOptions>,
    ) -> Result<MessageData> {
        let body = serde_json::to_value(edit.into())?;
        self.patch(
            &format!("/channels/{channel_id}/messages/{message_id}"),
            body,
        )
        .await
    }

    pub async fn delete_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
        self.delete::<Value>(&format!("/channels/{channel_id}/messages/{message_id}"))
            .await
            .map(drop)
    }

    /// Messages, newest first; `before`/`after` an id, up to `limit` (100).
    pub async fn messages(&self, channel_id: &str, q: MessagesQuery) -> Result<Vec<MessageData>> {
        let mut params = Vec::new();
        if let Some(b) = &q.before {
            params.push(format!("before={}", enc(b)));
        }
        if let Some(a) = &q.after {
            params.push(format!("after={}", enc(a)));
        }
        if let Some(l) = q.limit {
            params.push(format!("limit={l}"));
        }
        let qs = if params.is_empty() {
            String::new()
        } else {
            format!("?{}", params.join("&"))
        };
        self.get(&format!("/channels/{channel_id}/messages{qs}"))
            .await
    }

    pub async fn react(&self, channel_id: &str, message_id: &str, emoji: &str) -> Result<()> {
        self.put::<Value>(
            &format!(
                "/channels/{channel_id}/messages/{message_id}/reactions/{}",
                enc(emoji)
            ),
            None,
        )
        .await
        .map(drop)
    }

    pub async fn unreact(&self, channel_id: &str, message_id: &str, emoji: &str) -> Result<()> {
        self.delete::<Value>(&format!(
            "/channels/{channel_id}/messages/{message_id}/reactions/{}",
            enc(emoji)
        ))
        .await
        .map(drop)
    }

    /// "Digitando..." for a few seconds.
    pub async fn typing(&self, channel_id: &str) -> Result<()> {
        self.post::<Value>(&format!("/channels/{channel_id}/typing"), None)
            .await
            .map(drop)
    }

    // ---------- people, servers, channels ----------

    pub async fn me(&self) -> Result<User> {
        self.get("/users/@me").await
    }

    pub async fn profile(&self, user_id: &str) -> Result<Profile> {
        self.get(&format!("/users/{user_id}/profile")).await
    }

    /// The DM with someone (opened if needed).
    pub async fn dm(&self, user_id: &str) -> Result<Channel> {
        self.post(
            "/users/@me/channels",
            Some(json!({ "recipient_id": user_id })),
        )
        .await
    }

    pub async fn members(&self, guild_id: &str) -> Result<Vec<Member>> {
        self.get(&format!("/guilds/{guild_id}/members")).await
    }

    pub async fn kick(&self, guild_id: &str, user_id: &str) -> Result<()> {
        self.delete::<Value>(&format!("/guilds/{guild_id}/members/{user_id}"))
            .await
            .map(drop)
    }

    pub async fn ban(&self, guild_id: &str, user_id: &str) -> Result<()> {
        self.put::<Value>(&format!("/guilds/{guild_id}/bans/{user_id}"), None)
            .await
            .map(drop)
    }

    pub async fn unban(&self, guild_id: &str, user_id: &str) -> Result<()> {
        self.delete::<Value>(&format!("/guilds/{guild_id}/bans/{user_id}"))
            .await
            .map(drop)
    }

    pub async fn add_role(&self, guild_id: &str, user_id: &str, role_id: &str) -> Result<()> {
        self.put::<Value>(
            &format!("/guilds/{guild_id}/members/{user_id}/roles/{role_id}"),
            None,
        )
        .await
        .map(drop)
    }

    pub async fn remove_role(&self, guild_id: &str, user_id: &str, role_id: &str) -> Result<()> {
        self.delete::<Value>(&format!(
            "/guilds/{guild_id}/members/{user_id}/roles/{role_id}"
        ))
        .await
        .map(drop)
    }

    pub async fn create_role(&self, guild_id: &str, role: &NewRole) -> Result<Role> {
        self.post(
            &format!("/guilds/{guild_id}/roles"),
            Some(serde_json::to_value(role)?),
        )
        .await
    }

    pub async fn create_channel(&self, guild_id: &str, channel: &NewChannel) -> Result<Channel> {
        self.post(
            &format!("/guilds/{guild_id}/channels"),
            Some(serde_json::to_value(channel)?),
        )
        .await
    }

    pub async fn edit_channel(&self, channel_id: &str, edit: &ChannelEdit) -> Result<Channel> {
        self.patch(
            &format!("/channels/{channel_id}"),
            serde_json::to_value(edit)?,
        )
        .await
    }

    pub async fn delete_channel(&self, channel_id: &str) -> Result<()> {
        self.delete::<Value>(&format!("/channels/{channel_id}"))
            .await
            .map(drop)
    }

    pub async fn create_invite(&self, guild_id: &str, opts: &InviteOptions) -> Result<Invite> {
        self.post(
            &format!("/guilds/{guild_id}/invites"),
            Some(serde_json::to_value(opts)?),
        )
        .await
    }

    // ---------- commands ----------

    /// Replaces all of the bot's "/" commands.
    pub async fn set_commands(&self, commands: &[Command]) -> Result<Vec<Command>> {
        self.put("/users/@me/commands", Some(serde_json::to_value(commands)?))
            .await
    }

    pub async fn commands(&self) -> Result<Vec<Command>> {
        self.get("/users/@me/commands").await
    }

    /// Answers an interaction (see `Interaction`). `body` is a [`ReplyOptions`] or
    /// [`EditOptions`], serialized.
    pub async fn interaction_callback(
        &self,
        id: &str,
        token: &str,
        kind: CallbackType,
        body: impl Serialize,
    ) -> Result<MessageData> {
        let mut v = serde_json::to_value(body)?;
        if !v.is_object() {
            v = json!({});
        }
        v["type"] = json!(kind);
        self.post(&format!("/interactions/{id}/{token}/callback"), Some(v))
            .await
    }

    // ---------- voice ----------

    /// A media token for a voice room (the voice connection uses it; see `Client::join_voice`).
    pub async fn voice_token(&self, channel_id: &str) -> Result<VoiceJoin> {
        self.post(&format!("/channels/{channel_id}/voice"), None)
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encodes_emoji_segments() {
        assert_eq!(enc("abc_1"), "abc_1");
        assert_eq!(enc("👍"), "%F0%9F%91%8D");
        assert_eq!(enc("gato:123"), "gato%3A123");
    }

    #[test]
    fn base_strips_api() {
        let r = Rest::new("x", Some("http://127.0.0.1:8080/api/"), 3);
        assert_eq!(r.api(), "http://127.0.0.1:8080/api");
        assert_eq!(r.base(), "http://127.0.0.1:8080");
    }

    #[test]
    fn edit_options_send_only_what_is_set() {
        let v = serde_json::to_value(EditOptions::new().components(vec![])).unwrap();
        assert_eq!(v, json!({ "components": [] }));
        let v = serde_json::to_value(ReplyOptions::new("oi").ephemeral()).unwrap();
        assert_eq!(v, json!({ "content": "oi", "ephemeral": true }));
    }
}