00_simple/00_simple.rs
1//! This is the simplest way to use the crate with `Client::new_simple()`.
2//! It does not rely on event listeners and provides a straightforward usage example.
3//! If you need more advanced usage with event listeners, check out the other examples.
4
5use discordipc::{activity::Activity, packet::Packet, Client};
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8 // Build your client instance (with your own application ID)
9 // You can create one in https://discord.com/developers/applications
10 let client = Client::new_simple("<application_id>");
11
12 // `connect_and_wait()` is a blocking method that sends a connection request,
13 // waits for a direct response, and returns the response packet.
14 let connection_response = client.connect_and_wait()?;
15
16 // You can use `filter()` in any packet to search for an error response.
17 match connection_response.filter() {
18 Ok(_packet) => println!("Connected"),
19 Err(e) => {
20 eprintln!("Couldn't connect to Discord: {}", e);
21 return Ok(());
22 }
23 }
24
25 // === Set an activity ===
26 let activity = Activity::new().details("Simple activity");
27
28 // Build an activity packet.
29 // Pass Some(&activity) to set an activity or None to clear it.
30 // The second argument is a nonce used to identify a packet exchange, but it's not needed here,
31 // since `send_and_wait()` already waits for a direct response.
32 let packet = Packet::new_activity(Some(&activity), None);
33
34 // You can use `filter()` in `send_and_wait()` as it returns a packet
35 match client.send_and_wait(packet)?.filter() {
36 Ok(_packet) => println!("Activity has been set!"),
37 Err(e) => eprintln!("Couldn't set activity: {}", e),
38 };
39
40 std::thread::sleep(std::time::Duration::from_secs(10));
41
42 // === Clear the activity ===
43 let packet = Packet::new_activity(None, None);
44 match client.send_and_wait(packet)?.filter() {
45 Ok(_packet) => println!("Activity has been cleared!"),
46 Err(e) => eprintln!("Couldn't clear activity: {}", e),
47 };
48
49 std::thread::sleep(std::time::Duration::from_secs(3));
50 client.disconnect()?;
51 println!("Disconnected");
52
53 Ok(())
54}