discordipc 0.1.1

A Rust crate that enables connection and interaction with Discord's IPC, allowing you to set custom activities for your project.
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use serde::Serialize;
use serde_with::skip_serializing_none;
use std::time::{SystemTime, UNIX_EPOCH};

#[skip_serializing_none]
#[derive(Clone, Debug, Default, Serialize)]
pub struct Activity {
    #[serde(rename = "type")]
    pub kind: ActivityType,
    pub details: Option<String>,
    pub state: Option<String>,

    pub timestamps: Option<Timestamps>,
    pub assets: Assets,
    pub buttons: Option<Vec<Button>>,

    pub party: Option<Party>,
    pub secrets: Option<Secrets>,

    pub instance: bool,
}
impl Activity {
    /// Creates a new instance of an `Activity`.
    ///
    /// This method initializes a default `Activity` object, which can be further customized
    /// using chained methods. It is the starting point for building an activity.
    ///
    /// ## Examples
    ///
    /// Basic usage:
    ///
    /// ```rust
    /// use discordipc::activity::{Activity, ActivityType};
    ///
    /// let activity = Activity::new()
    ///     .kind(ActivityType::Playing)
    ///     .details("Ranked")
    ///     .state("In Lobby");
    /// ```
    ///
    /// Or:
    /// ```rust
    /// use discordipc::activity::{Activity, ActivityType, Button, Party, Timestamps};
    ///
    /// let activity = Activity::new()
    ///     .kind(ActivityType::Watching)
    ///     .details("song_name")
    ///     .state("In a Watch Party")
    ///     .timestamps(Timestamps::new().start_now())
    ///     .button(Button::new("Join", "https://example.com/join"))
    ///     .party(Party::new().id("party_id").size([5, 8])); // 5/8 members
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the activity type.
    ///
    /// ## Options
    /// - `ActivityType::Playing`
    /// - `ActivityType::Listening`
    /// - `ActivityType::Watching`
    /// - `ActivityType::Competing`
    pub fn kind(mut self, kind: ActivityType) -> Self {
        self.kind = kind;
        self
    }

    /// Sets the details of the activity.
    /// ## Parameters
    /// - `details`: The details to be shown.
    ///
    pub fn details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }

    /// Sets the state of the activity.
    ///
    /// ## Parameters
    /// - `state`: The state to be shown.
    ///
    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    /// Adds timestamps to the activity.
    ///
    /// ## Parameters
    /// - `timestamps`: The timestamps to be added.
    pub fn timestamps(mut self, timestamps: Timestamps) -> Self {
        self.timestamps = Some(timestamps);
        self
    }

    /// Adds assets (images) to the activity.
    ///
    /// You can set both a **large image** and a **small image**.  
    /// Each image can optionally have a tooltip text that appears when hovered.
    ///
    /// ## Parameters
    /// - `assets`: The [Assets] to be added to the activity.
    ///
    /// ## Examples
    ///  Small image:
    /// ```rust
    /// use discordipc::activity::{Activity, Assets};
    ///
    /// let activity = Activity::new()
    ///     .details("Assets example")
    ///     .assets(Assets::new()
    ///         // Without large image, it uses the app logo by default.
    ///         .small_image("small_image_key", Some("Small Image Tooltip")));
    /// ```
    ///
    /// Both:
    /// ```rust
    /// use discordipc::activity::{Activity, Assets};
    ///
    /// let activity = Activity::new()
    ///     .details("Assets example")
    ///     .assets(Assets::new()
    ///         .large_image("large_image_key", Some("Large Image Tooltip"))
    ///         .small_image("small_image_key", None));  // `None` for no tooltip.
    /// ```
    pub fn assets(mut self, assets: Assets) -> Self {
        self.assets = assets;
        self
    }

    /// Adds a button to the activity.
    ///
    /// ## Note
    /// Discord allows up to two buttons to show in the activity, adding a third button wouldn't do anything.
    ///
    /// Additionally, any existing secrets will be cleared, as secrets cannot currently be sent with buttons.
    ///
    /// ## Parameters
    /// - `button`: The [Button] to be added.
    ///
    /// ## Example
    /// ```rust
    /// use discordipc::activity::{Activity, Button};
    ///
    /// let activity = Activity::new()
    ///     .details("Click one of these!")
    ///     .button(Button::new("First Button", "https://example.com"))
    ///     .button(Button::new("Second Button", "https://example.com"));
    /// ```
    pub fn button(mut self, button: Button) -> Self {
        if let Some(ref mut buttons) = self.buttons {
            // there can only be up to 2 buttons
            if buttons.len() < 2 {
                buttons.push(button);
            }
        } else {
            self.buttons = Some(vec![button]);
        }

        self.secrets = None; // secrets cannot currently be sent with buttons
        self
    }

    /// Adds a party to the activity.
    ///
    /// An activity with a party can have multiple users participating in it.
    ///
    /// ### Note  
    /// When a party is added, the `state` field of the activity will be used as the party's title.  
    ///
    /// - If `state` is `None`, no title will be displayed.  
    /// - If **both** `state` and the party size are `None`, the party will not be shown at all.
    ///
    /// ## Parameters
    /// - `party`: The party to be added to the activity.
    ///
    /// ## Example:
    /// ```rust
    /// use discordipc::activity::{Activity, Party};
    ///
    /// let activity = Activity::new()
    ///     .details("Some details")
    ///     .state("In Game")
    ///     .party(Party::new().id("some_id").size([1, 5])); // 1 of 5 members
    /// ```
    pub fn party(mut self, party: Party) -> Self {
        self.party = Some(party);
        self
    }

    /// Adds secrets to the activity.  
    ///
    /// Secrets are unique, randomly generated strings used for **joining or spectating**  
    /// a multiplayer session through Discord Rich Presence.  
    ///
    /// - The **join secret** allows others to request to join the activity.  
    /// - The **spectate secret** lets users watch the session if the game supports it.  
    /// - The **match secret** identifies a specific game session.  
    ///
    ///
    /// ### Note  
    /// Any existing buttons will be **cleared**, as secrets cannot currently be sent with buttons.  
    ///
    /// ## Parameters  
    /// - `secrets`: The secrets to be added to the activity.   
    ///
    /// ## Example  
    /// ```rust
    /// use discordipc::activity::{Activity, Party, Secrets};
    ///
    /// let secrets = Secrets::new()
    ///     .join("join_secret123")
    ///     .spectate("spectate_secret456");
    ///
    /// let activity = Activity::new()
    ///     .instance(true)
    ///     .party(Party::new().size([1, 5]))
    ///     .secrets(secrets);
    /// ```
    pub fn secrets(mut self, secrets: Secrets) -> Self {
        self.secrets = Some(secrets);
        self.buttons = None; // secrets cannot currently be sent with buttons
        self
    }

    /// Sets whether the activity is an instance.  
    ///
    /// When an activity is marked as an **instance**, it means that it represents  
    /// a **specific session** rather than a general activity.  
    ///
    /// For example, a multiplayer game session would be considered an
    /// instance, whereas simply "Playing a Game" would not.  
    ///
    ///
    /// **Setting this to `true` allows features like:**  
    /// - Joining or spectating the session (if supported).  
    /// - Improved party-related features in Discord Rich Presence.  
    ///
    /// ## Parameters  
    /// - `instance`: `true` if this activity should be considered an instance, `false` otherwise.  
    ///
    /// ## Example  
    /// ```rust
    /// use discordipc::activity::{Activity, Party, Secrets};
    ///
    /// let activity = Activity::new()
    ///     .instance(true)
    ///     .party(Party::new().size([1, 5]))
    ///     .secrets(Secrets::new());
    /// ```
    pub fn instance(mut self, instance: bool) -> Self {
        self.instance = instance;
        self
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[serde(into = "u8")]
#[repr(u8)]
pub enum ActivityType {
    #[default]
    Playing = 0,
    Listening = 2,
    Watching = 3,
    Competing = 5,
}
impl From<ActivityType> for u8 {
    fn from(value: ActivityType) -> Self {
        value as u8
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Default, Serialize)]
pub struct Timestamps {
    pub start: Option<i64>,
    pub end: Option<i64>,
}
impl Timestamps {
    pub fn new() -> Self {
        Self::default()
    }

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

    pub fn start_now(mut self) -> Self {
        self.start = Some(Self::now());
        self
    }

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

    pub fn end_now(mut self) -> Self {
        self.end = Some(Self::now());
        self
    }

    fn now() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Default, Serialize)]
pub struct Assets {
    pub large_image: Option<String>,
    pub large_text: Option<String>,

    pub small_image: Option<String>,
    pub small_text: Option<String>,
}
impl Assets {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn large_image<S: Into<String>>(mut self, image_key: S, text: Option<S>) -> Self {
        self.large_image = Some(image_key.into());
        self.large_text = text.map(|text| text.into());
        self
    }

    pub fn small_image<S: Into<String>>(mut self, image_key: S, text: Option<S>) -> Self {
        self.small_image = Some(image_key.into());
        self.small_text = text.map(|text| text.into());
        self
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Serialize)]
pub struct Button {
    pub label: String,
    pub url: String,
}
impl Button {
    pub fn new(label: impl Into<String>, url: impl Into<String>) -> Self {
        Button {
            label: label.into(),
            url: url.into(),
        }
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Default, Serialize)]
pub struct Party {
    pub id: Option<String>,
    pub size: Option<[u32; 2]>,
}
impl Party {
    pub fn new() -> Self {
        Self::default()
    }

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

    pub fn size(mut self, size: [u32; 2]) -> Self {
        self.size = Some(size);
        self
    }

    pub fn current_size(mut self, current_size: u32) -> Self {
        if let Some(mut size) = self.size {
            size[0] = current_size.max(1);
        } else {
            self.size = Some([current_size.max(1), 0])
        }
        self
    }

    pub fn max_size(mut self, max_size: u32) -> Self {
        if let Some(mut size) = self.size {
            size[1] = max_size.max(1);
        } else {
            self.size = Some([0, max_size.max(1)])
        }
        self
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Default, Serialize)]
pub struct Secrets {
    pub join: Option<String>,
    pub spectate: Option<String>,
    #[serde(rename = "match")]
    pub match_: Option<String>,
}
impl Secrets {
    pub fn new() -> Self {
        Self::default()
    }

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

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

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