01_basics/01_basics.rs
1use discordipc::{
2 packet::{Opcode, Packet},
3 Client,
4};
5use serde_json::json;
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8 // === Build a client ===
9
10 // Build your client instance (with your own application ID)
11 // You can create one in https://discord.com/developers/applications
12 let client = Client::new("<application_id>");
13
14 // Listen to "READY" event
15 // The "READY" event is triggered when the client has successfully connected to Discord
16 // and is ready to receive and send packets.
17 client.on("READY", |client, _packet| {
18 println!("Connected");
19 // You will receive as arguments a reference to the client instance you created and the incoming Discord packet.
20 // Once the client is connected, you can start interacting with Discord's IPC.
21
22 // === Build a packet ===
23 // A packet is built from an opcode and a payload.
24 // The opcode establishes the kind of operation to be performed
25 // The most common opcodes are Opcode::Frame (1) and Opcode::Ping (3).
26 // Frame is used for most operations, while Ping is only used to ping Discord.
27 let opcode = Opcode::Ping;
28 // The payload contains the command data in JSON format in addition to a
29 // unique nonce for identifying the packet exchange.
30 // The payload of a ping packet is optional; you can send an empty value if you prefer.
31 // You can listen to the opcode (4)Pong to handle the response
32 // or you can include a "nonce" field in the payload.
33 let nonce = Packet::generate_nonce();
34 let payload = json!({
35 "nonce": nonce,
36 "example_field": "ping"
37 });
38
39 let ping = Packet::new(opcode, payload);
40
41 // === Listen for a response ===
42 client.once(nonce, |_client, packet| {
43 // If you receive this, the ping was successful.
44 println!("Pong!");
45 // The received packet has the opcode (4)Pong and has the same payload as the one sent before.
46 println!("{}", packet);
47 });
48
49 // === Send the packet ===
50 // Once you set up the listener, you can now send your packet
51 if let Err(e) = client.send(ping) {
52 eprintln!("Couldn't send packet: {}", e)
53 };
54 // When a response is received, the listener will be triggered.
55 });
56
57 // Try to connect
58 client.connect()?;
59 std::io::stdin().read_line(&mut String::new()).unwrap();
60 client.disconnect()?;
61 println!("Disconnected");
62
63 Ok(())
64}