Skip to main content

02_activity/
02_activity.rs

1use discordipc::{
2    activity::{Activity, Button, Timestamps},
3    packet::Packet,
4    Client, Result,
5};
6
7fn main() -> Result<()> {
8    let client = Client::new("<application_id>");
9
10    client.on("READY", |client, _packet| {
11        println!("Connected");
12
13        // === Create an activity ===
14
15        // You can create activities this way... (recommended)
16        let activity = Activity::new()
17            .details("In Workspace: test")
18            .state("Dealing with proc-macros")
19            .timestamps(Timestamps::new().start_now())
20            .button(Button::new("Get started!", "https://rustup.rs/"));
21
22        // Or this way...
23        let _activity = Activity {
24            details: Some("In Workspace: test".to_string()),
25            state: Some("Dealing with proc-macros".to_string()),
26            timestamps: Some(Timestamps::new().start_now()),
27            buttons: Some(vec![Button {
28                label: "Get started!".to_string(),
29                url: "https://rustup.rs/".to_string(),
30            }]),
31            ..Activity::default()
32        };
33        // Note that this method is more susceptible to errors as it skips structural checks.
34
35        // === Build the packet ===
36        let nonce = Packet::generate_nonce(); // Unique nonce for identifying the packet exchange
37
38        // You can manually build the activity packet with Packet::new()
39        // or you can use Packet::new_activity()
40        let activity_packet = Packet::new_activity(Some(&activity), Some(&nonce));
41
42        // === Listen for a response ===
43        client.once(nonce, |client, packet| {
44            // Setting up an activity is an operation that could fail,
45            // so the packet payload may contain a success or an error.
46            // You can use packet.filter() to automatically search for errors in its payload.
47            match packet.filter() {
48                Ok(_packet) => {
49                    println!("Activity has been set!");
50
51                    std::thread::sleep(std::time::Duration::from_secs(10));
52
53                    if let Err(e) = client.send(Packet::new_activity(None, None)) {
54                        eprintln!("Couldn't send packet: {}", e)
55                    };
56                    println!("Activity cleared!");
57                }
58                Err(e) => println!("Couldn't set activity: {}", e),
59            }
60        });
61
62        // Once you set up the listener, you can now send the activity packet.
63        if let Err(e) = client.send(activity_packet) {
64            eprintln!("Couldn't send packet: {}", e)
65        };
66    });
67
68    // Try to connect
69    client.connect()?;
70    std::io::stdin().read_line(&mut String::new()).unwrap();
71    client.disconnect()?;
72    println!("Disconnected");
73
74    Ok(())
75}