twilight_model/http/attachment.rs
1//! Models used when sending attachments to Discord.
2
3use serde::{Deserialize, Serialize};
4
5/// Attachments used in messages.
6///
7/// # Examples
8///
9/// Create an attachment of a short JSON blob describing a cat with a
10/// description for screen readers:
11///
12/// ```
13/// use twilight_model::http::attachment::Attachment;
14///
15/// let filename = "twilight_sparkle.json".to_owned();
16/// let file_content = br#"{
17/// "best_friend": "Spike",
18/// "cutie_mark": "sparkles",
19/// "name": "Twilight Sparkle"
20/// }"#
21/// .to_vec();
22/// let id = 1;
23///
24/// let mut attachment = Attachment::from_bytes(filename, file_content, id);
25/// attachment.description("Raw data about Twilight Sparkle".to_owned());
26/// ```
27#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
28pub struct Attachment {
29 /// Description of the attachment, useful for screen readers and users
30 /// requiring alt text.
31 #[serde(skip_serializing_if = "Option::is_none")]
32 pub description: Option<String>,
33 /// Content of the file.
34 #[serde(skip)]
35 pub file: Vec<u8>,
36 /// Name of the file.
37 ///
38 /// Examples may be `twilight_sparkle.png`, `cat.jpg`, or `logs.txt`.
39 pub filename: String,
40 /// Unique ID of the attachment in the message.
41 ///
42 /// While attachment IDs can be the same as attachments in other messages,
43 /// they must be unique within the same message. Attachment IDs don't need
44 /// to be in any particular format; for example, IDs of 0, 100, the current
45 /// timestamp, and so on are all valid.
46 pub id: u64,
47}
48
49impl Attachment {
50 /// Create an attachment from a filename and bytes.
51 ///
52 /// # Examples
53 ///
54 /// Create an attachment with a grocery list named "grocerylist.txt":
55 ///
56 /// ```
57 /// use twilight_model::http::attachment::Attachment;
58 ///
59 /// let filename = "grocerylist.txt".to_owned();
60 /// let file_content = b"Apples\nGrapes\nLemonade".to_vec();
61 /// let id = 1;
62 ///
63 /// let attachment = Attachment::from_bytes(filename, file_content, id);
64 /// ```
65 pub const fn from_bytes(filename: String, file: Vec<u8>, id: u64) -> Self {
66 Self {
67 description: None,
68 file,
69 filename,
70 id,
71 }
72 }
73
74 /// Set the description of the attachment.
75 ///
76 /// Attachment descriptions are useful for those requiring screen readers
77 /// and are displayed as alt text.
78 pub fn description(&mut self, description: String) {
79 self.description = Some(description);
80 }
81}