diff --git a/Cargo.toml b/Cargo.toml index cc0c4b7..d6c67ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,10 @@ client = [] [dependencies] tokio = {version = "1.28.1", features = ["rt", "macros", "rt-multi-thread", "full"]} -serde = {version = "1.0.162", features = ["derive"]} -serde_json = { version = "1.0.96", features = ["raw_value"] } +serde = {version = "1.0.163", features = ["derive"]} +serde_json = {version= "1.0.96", features = ["raw_value"]} +serde-aux = "4.2.0" +serde_with = "3.0.0" serde_repr = "0.1.12" reqwest = {version = "0.11.16", features = ["multipart"]} url = "2.3.1" @@ -20,7 +22,7 @@ chrono = {version = "0.4.24", features = ["serde"]} regex = "1.7.3" custom_error = "1.9.2" native-tls = "0.2.11" -tokio-tungstenite = {version = "0.18.0", features = ["native-tls"]} +tokio-tungstenite = {version = "0.19.0", features = ["native-tls"]} futures-util = "0.3.28" http = "0.2.9" openssl = "0.10.52" diff --git a/src/gateway.rs b/src/gateway.rs index a122d9b..90bcff5 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -40,11 +40,11 @@ pub struct GatewayHandle { impl GatewayHandle { /// Sends json to the gateway with an opcode async fn send_json_event(&self, op: u8, to_send: serde_json::Value) { - let gateway_payload = types::GatewayPayload { + + let gateway_payload = types::GatewaySendPayload { op, - d: Some(to_send), - s: None, - t: None, + d: Some(to_send), + s: None }; let payload_json = serde_json::to_string(&gateway_payload).unwrap(); @@ -81,7 +81,7 @@ impl GatewayHandle { self.send_json_event(3, to_send_value).await; } - /// Sends a Request Guild Members to the server + /// Sends a request guild members to the server pub async fn send_request_guild_members(&self, to_send: types::GatewayRequestGuildMembers) { let to_send_value = serde_json::to_value(&to_send).unwrap(); @@ -90,14 +90,35 @@ impl GatewayHandle { self.send_json_event(8, to_send_value).await; } - /// Sends a Request Guild Members to the server - pub async fn send_update_voice_state(&self, to_send: types::GatewayVoiceStateUpdate) { + /// Sends an update voice state to the server + pub async fn send_update_voice_state(&self, to_send: types::UpdateVoiceState) { + let to_send_value = serde_json::to_value(&to_send).unwrap(); - println!("GW: Sending Voice State Update.."); + println!("GW: Sending Update Voice State.."); self.send_json_event(4, to_send_value).await; } + + /// Sends a call sync to the server + pub async fn send_call_sync(&self, to_send: types::CallSync) { + + let to_send_value = serde_json::to_value(&to_send).unwrap(); + + println!("GW: Sending Call Sync.."); + + self.send_json_event(13, to_send_value).await; + } + + /// Sends a Lazy Request + pub async fn send_lazy_request(&self, to_send: types::LazyRequest) { + + let to_send_value = serde_json::to_value(&to_send).unwrap(); + + println!("GW: Sending Lazy Request.."); + + self.send_json_event(14, to_send_value).await; + } } pub struct Gateway { @@ -120,6 +141,7 @@ impl Gateway { let (ws_stream, _) = match connect_async_tls_with_config( &websocket_url, None, + false, Some(Connector::NativeTls( TlsConnector::builder().build().unwrap(), )), @@ -145,8 +167,7 @@ impl Gateway { // Wait for the first hello and then spawn both tasks so we avoid nested tasks // This automatically spawns the heartbeat task, but from the main thread let msg = ws_rx.next().await.unwrap().unwrap(); - let gateway_payload: types::GatewayPayload = - serde_json::from_str(msg.to_text().unwrap()).unwrap(); + let gateway_payload: types::GatewayReceivePayload = serde_json::from_str(msg.to_text().unwrap()).unwrap(); if gateway_payload.op != 10 { println!("Recieved non hello on gateway init, what is happening?"); @@ -159,12 +180,8 @@ impl Gateway { println!("GW: Received Hello"); - let gateway_hello: types::HelloData = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - gateway.heartbeat_handler = Some(HeartbeatHandler::new( - gateway_hello.heartbeat_interval, - shared_tx.clone(), - )); + let gateway_hello: types::HelloData = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + gateway.heartbeat_handler = Some(HeartbeatHandler::new(gateway_hello.heartbeat_interval, shared_tx.clone())); // Now we can continously check for messages in a different task, since we aren't going to receive another hello task::spawn(async move { @@ -190,325 +207,306 @@ impl Gateway { return; } - let msg_string = msg.to_string(); - - let gateway_payload: types::GatewayPayload = serde_json::from_str(&msg_string).unwrap(); + let gateway_payload: types::GatewayReceivePayload = serde_json::from_str(msg.to_text().unwrap()).unwrap(); // See https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes match gateway_payload.op { // Dispatch // An event was dispatched, we need to look at the gateway event name t 0 => { - let gateway_payload_t = gateway_payload.t.unwrap(); + let gateway_payload_t = gateway_payload.clone().t.unwrap(); println!("GW: Received {}..", gateway_payload_t); + //println!("Event data dump: {}", gateway_payload.d.clone().unwrap().get()); + // See https://discord.com/developers/docs/topics/gateway-events#receive-events + // "Some" of these are uncodumented match gateway_payload_t.as_str() { "READY" => { - let _data: types::GatewayReady = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); + let new_data: types::GatewayReady = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.session.ready.update_data(new_data).await; + }, + "READY_SUPPLEMENTAL" => { + let new_data: types::GatewayReadySupplemental = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.session.ready_supplimental.update_data(new_data).await; } "RESUMED" => {} - "APPLICATION_COMMAND_PERMISSIONS_UPDATE" => {} - "AUTO_MODERATION_RULE_CREATE" => {} - "AUTO_MODERATION_RULE_UPDATE" => {} - "AUTO_MODERATION_RULE_DELETE" => {} - "AUTO_MODERATION_ACTION_EXECUTION" => {} + "APPLICATION_COMMAND_PERMISSIONS_UPDATE" => { + let new_data: types::ApplicationCommandPermissionsUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.application.command_permissions_update.update_data(new_data).await; + } + "AUTO_MODERATION_RULE_CREATE" => { + let new_data: types::AutoModerationRuleCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.auto_moderation.rule_create.update_data(new_data).await; + } + "AUTO_MODERATION_RULE_UPDATE" => { + let new_data: types::AutoModerationRuleUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.auto_moderation.rule_update.update_data(new_data).await; + } + "AUTO_MODERATION_RULE_DELETE" => { + let new_data: types::AutoModerationRuleDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.auto_moderation.rule_delete.update_data(new_data).await; + } + "AUTO_MODERATION_ACTION_EXECUTION" => { + let new_data: types::AutoModerationActionExecution = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.auto_moderation.action_execution.update_data(new_data).await; + } "CHANNEL_CREATE" => { - let channel: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ChannelCreate { channel }; - self.events - .lock() - .await - .channel - .create - .update_data(new_data) - .await; + let new_data: types::ChannelCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.channel.create.update_data(new_data).await; } "CHANNEL_UPDATE" => { - let channel: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ChannelUpdate { channel }; - self.events - .lock() - .await - .channel - .update - .update_data(new_data) - .await; + let new_data: types::ChannelUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.channel.update.update_data(new_data).await; + } + "CHANNEL_UNREAD_UPDATE" => { + let new_data: types::ChannelUnreadUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.channel.unread_update.update_data(new_data).await; } "CHANNEL_DELETE" => { - let channel: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ChannelDelete { channel }; - self.events - .lock() - .await - .channel - .delete - .update_data(new_data) - .await; + let new_data: types::ChannelDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.channel.delete.update_data(new_data).await; } "CHANNEL_PINS_UPDATE" => { - let new_data: types::ChannelPinsUpdate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .channel - .pins_update - .update_data(new_data) - .await; + let new_data: types::ChannelPinsUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.channel.pins_update.update_data(new_data).await; + } + "CALL_CREATE" => { + let new_data: types::CallCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.call.create.update_data(new_data).await; + }, + "CALL_UPDATE" => { + let new_data: types::CallUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.call.update.update_data(new_data).await; + } + "CALL_DELETE" => { + let new_data: types::CallDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.call.delete.update_data(new_data).await; } "THREAD_CREATE" => { - let thread: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ThreadCreate { thread }; - self.events - .lock() - .await - .thread - .create - .update_data(new_data) - .await; + let new_data: types::ThreadCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.create.update_data(new_data).await; } "THREAD_UPDATE" => { - let thread: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ThreadUpdate { thread }; - self.events - .lock() - .await - .thread - .update - .update_data(new_data) - .await; + let new_data: types::ThreadUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.update.update_data(new_data).await; } "THREAD_DELETE" => { - let thread: types::Channel = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::ThreadDelete { thread }; - self.events - .lock() - .await - .thread - .delete - .update_data(new_data) - .await; + let new_data: types::ThreadDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.delete.update_data(new_data).await; } "THREAD_LIST_SYNC" => { - let new_data: types::ThreadListSync = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .thread - .list_sync - .update_data(new_data) - .await; + let new_data: types::ThreadListSync = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.list_sync.update_data(new_data).await; } "THREAD_MEMBER_UPDATE" => { - let new_data: types::ThreadMemberUpdate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .thread - .member_update - .update_data(new_data) - .await; + let new_data: types::ThreadMemberUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.member_update.update_data(new_data).await; } "THREAD_MEMBERS_UPDATE" => { - let new_data: types::ThreadMembersUpdate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .thread - .members_update - .update_data(new_data) - .await; + let new_data: types::ThreadMembersUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.thread.members_update.update_data(new_data).await; } "GUILD_CREATE" => { - let new_data: types::GuildCreate = - serde_json::from_str(&msg_string).unwrap(); - self.events - .lock() - .await - .guild - .create - .update_data(new_data) - .await; + let new_data: types::GuildCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.create.update_data(new_data).await; + } + "GUILD_UPDATE" => { + let new_data: types::GuildUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.update.update_data(new_data).await; } - "GUILD_UPDATE" => {} "GUILD_DELETE" => { - let _new_data: types::UnavailableGuild = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); + let new_data: types::GuildDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.delete.update_data(new_data).await; + } + "GUILD_AUDIT_LOG_ENTRY_CREATE" => { + let new_data: types::GuildAuditLogEntryCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.audit_log_entry_create.update_data(new_data).await; } - "GUILD_AUDIT_LOG_ENTRY_CREATE" => {} "GUILD_BAN_ADD" => { - let _new_data: types::GuildBanAdd = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); + let new_data: types::GuildBanAdd = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.ban_add.update_data(new_data).await; } "GUILD_BAN_REMOVE" => { - let _new_data: types::GuildBanRemove = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); + let new_data: types::GuildBanRemove = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.ban_remove.update_data(new_data).await; + } + "GUILD_EMOJIS_UPDATE" => { + let new_data: types::GuildEmojisUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.emojis_update.update_data(new_data).await; + } + "GUILD_STICKERS_UPDATE" => { + let new_data: types::GuildStickersUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.stickers_update.update_data(new_data).await; + } + "GUILD_INTEGRATIONS_UPDATE" => { + let new_data: types::GuildIntegrationsUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.integrations_update.update_data(new_data).await; + } + "GUILD_MEMBER_ADD" => { + let new_data: types::GuildMemberAdd = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.member_add.update_data(new_data).await; + } + "GUILD_MEMBER_REMOVE" => { + let new_data: types::GuildMemberRemove = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.member_remove.update_data(new_data).await; + } + "GUILD_MEMBER_UPDATE" => { + let new_data: types::GuildMemberUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.member_update.update_data(new_data).await; + } + "GUILD_MEMBERS_CHUNK" => { + let new_data: types::GuildMembersChunk = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.members_chunk.update_data(new_data).await; + } + "GUILD_ROLE_CREATE" => { + let new_data: types::GuildRoleCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_create.update_data(new_data).await; + } + "GUILD_ROLE_UPDATE" => { + let new_data: types::GuildRoleUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_update.update_data(new_data).await; + } + "GUILD_ROLE_DELETE" => { + let new_data: types::GuildRoleDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_delete.update_data(new_data).await; + } + "GUILD_SCHEDULED_EVENT_CREATE" => { + let new_data: types::GuildScheduledEventCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_scheduled_event_create.update_data(new_data).await; + } + "GUILD_SCHEDULED_EVENT_UPDATE" => { + let new_data: types::GuildScheduledEventUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_scheduled_event_update.update_data(new_data).await; + } + "GUILD_SCHEDULED_EVENT_DELETE" => { + let new_data: types::GuildScheduledEventDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_scheduled_event_delete.update_data(new_data).await; + } + "GUILD_SCHEDULED_EVENT_USER_ADD" => { + let new_data: types::GuildScheduledEventUserAdd = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_scheduled_event_user_add.update_data(new_data).await; + } + "GUILD_SCHEDULED_EVENT_USER_REMOVE" => { + let new_data: types::GuildScheduledEventUserRemove = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.role_scheduled_event_user_remove.update_data(new_data).await; + } + "PASSIVE_UPDATE_V1" => { + let new_data: types::PassiveUpdateV1 = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.guild.passive_update_v1.update_data(new_data).await; + } + "INTEGRATION_CREATE" => { + let new_data: types::IntegrationCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.integration.create.update_data(new_data).await; + } + "INTEGRATION_UPDATE" => { + let new_data: types::IntegrationUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.integration.update.update_data(new_data).await; + } + "INTEGRATION_DELETE" => { + let new_data: types::IntegrationDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.integration.delete.update_data(new_data).await; + } + "INTERACTION_CREATE" => { + let new_data: types::InteractionCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.interaction.create.update_data(new_data).await; + } + "INVITE_CREATE" => { + let new_data: types::InviteCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.invite.create.update_data(new_data).await; + } + "INVITE_DELETE" => { + let new_data: types::InviteDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.invite.delete.update_data(new_data).await; } - "GUILD_EMOJIS_UPDATE" => {} - "GUILD_STICKERS_UPDATE" => {} - "GUILD_INTEGRATIONS_UPDATE" => {} - "GUILD_MEMBER_ADD" => {} - "GUILD_MEMBER_REMOVE" => {} - "GUILD_MEMBER_UPDATE" => {} - "GUILD_MEMBERS_CHUNK" => {} - "GUILD_ROLE_CREATE" => {} - "GUILD_ROLE_UPDATE" => {} - "GUILD_ROLE_DELETE" => {} - "GUILD_SCHEDULED_EVENT_CREATE" => {} - "GUILD_SCHEDULED_EVENT_UPDATE" => {} - "GUILD_SCHEDULED_EVENT_DELETE" => {} - "GUILD_SCHEDULED_EVENT_USER_ADD" => {} - "GUILD_SCHEDULED_EVENT_USER_REMOVE" => {} - "INTEGRATION_CREATE" => {} - "INTEGRATION_UPDATE" => {} - "INTEGRATION_DELETE" => {} - "INTERACTION_CREATE" => {} - "INVITE_CREATE" => {} - "INVITE_DELETE" => {} "MESSAGE_CREATE" => { - let new_data: types::MessageCreate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .create - .update_data(new_data) - .await; + let new_data: types::MessageCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.create.update_data(new_data).await; } "MESSAGE_UPDATE" => { - let new_data: types::MessageUpdate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .update - .update_data(new_data) - .await; + let new_data: types::MessageUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.update.update_data(new_data).await; } "MESSAGE_DELETE" => { - let new_data: types::MessageDelete = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .delete - .update_data(new_data) - .await; + let new_data: types::MessageDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.delete.update_data(new_data).await; } "MESSAGE_DELETE_BULK" => { - let new_data: types::MessageDeleteBulk = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .delete_bulk - .update_data(new_data) - .await; + let new_data: types::MessageDeleteBulk = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.delete_bulk.update_data(new_data).await; } "MESSAGE_REACTION_ADD" => { - let new_data: types::MessageReactionAdd = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .reaction_add - .update_data(new_data) - .await; + let new_data: types::MessageReactionAdd = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.reaction_add.update_data(new_data).await; } "MESSAGE_REACTION_REMOVE" => { - let new_data: types::MessageReactionRemove = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .reaction_remove - .update_data(new_data) - .await; + let new_data: types::MessageReactionRemove = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.reaction_remove.update_data(new_data).await; } "MESSAGE_REACTION_REMOVE_ALL" => { - let new_data: types::MessageReactionRemoveAll = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .reaction_remove_all - .update_data(new_data) - .await; + let new_data: types::MessageReactionRemoveAll = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.reaction_remove_all.update_data(new_data).await; } "MESSAGE_REACTION_REMOVE_EMOJI" => { - let new_data: types::MessageReactionRemoveEmoji = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .message - .reaction_remove_emoji - .update_data(new_data) - .await; + let new_data: types::MessageReactionRemoveEmoji= serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.reaction_remove_emoji.update_data(new_data).await; + }, + "MESSAGE_ACK" => { + let new_data: types::MessageACK = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.message.ack.update_data(new_data).await; } "PRESENCE_UPDATE" => { - let new_data: types::PresenceUpdate = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .user - .presence_update - .update_data(new_data) - .await; + let new_data: types::PresenceUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.user.presence_update.update_data(new_data).await; + } + "RELATIONSHIP_ADD" => { + let new_data: types::RelationshipAdd = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.relationship.add.update_data(new_data).await; + } + "RELATIONSHIP_REMOVE" => { + let new_data: types::RelationshipRemove = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.relationship.remove.update_data(new_data).await; + } + "STAGE_INSTANCE_CREATE" => { + let new_data: types::StageInstanceCreate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.stage_instance.create.update_data(new_data).await; + } + "STAGE_INSTANCE_UPDATE" => { + let new_data: types::StageInstanceUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.stage_instance.update.update_data(new_data).await; + } + "STAGE_INSTANCE_DELETE" => { + let new_data: types::StageInstanceDelete = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.stage_instance.delete.update_data(new_data).await; + } + "SESSIONS_REPLACE" => { + let sessions: Vec = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + let new_data = types::SessionsReplace {sessions}; + self.events.lock().await.session.replace.update_data(new_data).await; } - "STAGE_INSTANCE_CREATE" => {} - "STAGE_INSTANCE_UPDATE" => {} - "STAGE_INSTANCE_DELETE" => {} - // Not documented in discord docs, I assume this isnt for bots / apps but is for users? - "SESSIONS_REPLACE" => {} "TYPING_START" => { - let new_data: types::TypingStartEvent = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - self.events - .lock() - .await - .user - .typing_start_event - .update_data(new_data) - .await; + let new_data: types::TypingStartEvent = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.user.typing_start_event.update_data(new_data).await; } "USER_UPDATE" => { - let user: types::User = - serde_json::from_value(gateway_payload.d.unwrap()).unwrap(); - let new_data = types::UserUpdate { user }; - self.events - .lock() - .await - .user - .update - .update_data(new_data) - .await; + let new_data: types::UserUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.user.update.update_data(new_data).await; + } + "VOICE_STATE_UPDATE" => { + let new_data: types::VoiceStateUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.voice.state_update.update_data(new_data).await; + } + "VOICE_SERVER_UPDATE" => { + let new_data: types::VoiceServerUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.voice.server_update.update_data(new_data).await; + } + "WEBHOOKS_UPDATE" => { + let new_data: types::WebhooksUpdate = serde_json::from_str(gateway_payload.d.unwrap().get()).unwrap(); + self.events.lock().await.webhooks.update.update_data(new_data).await; } - "VOICE_STATE_UPDATE" => {} - "VOICE_SERVER_UPDATE" => {} - "WEBHOOKS_UPDATE" => {} _ => { - panic!("Invalid gateway event ({})", &gateway_payload_t) + println!("Received unrecognised gateway event ({})! Please open an issue on the chorus github so we can implement it", &gateway_payload_t); } } } @@ -533,15 +531,8 @@ impl Gateway { 11 => { println!("GW: Received Heartbeat ACK"); } - 2 | 3 | 4 | 6 | 8 => { - panic!( - "Received Gateway op code that's meant to be sent, not received ({})", - gateway_payload.op - ) - } - _ => { - panic!("Received Invalid Gateway op code ({})", gateway_payload.op) - } + 2 | 3 | 4 | 6 | 8 => {panic!("Received gateway op code that's meant to be sent, not received ({})", gateway_payload.op)} + _ => {println!("Received unrecognised gateway op code ({})! Please open an issue on the chorus github so we can implement it", gateway_payload.op);} } // If we have an active heartbeat thread and we received a seq number we should let it know @@ -727,15 +718,53 @@ mod events { use super::*; #[derive(Default, Debug)] pub struct Events { + pub application: Application, + pub auto_moderation: AutoModeration, + pub session: Session, pub message: Message, pub user: User, + pub relationship: Relationship, pub channel: Channel, pub thread: Thread, pub guild: Guild, + pub invite: Invite, + pub integration: Integration, + pub interaction: Interaction, + pub stage_instance: StageInstance, + pub call: Call, + pub voice: Voice, + pub webhooks: Webhooks, pub gateway_identify_payload: GatewayEvent, pub gateway_resume: GatewayEvent, } + #[derive(Default, Debug)] + pub struct Application { + pub command_permissions_update: GatewayEvent, + } + + #[derive(Default, Debug)] + pub struct AutoModeration { + pub rule_create: GatewayEvent, + pub rule_update: GatewayEvent, + pub rule_delete: GatewayEvent, + pub action_execution: GatewayEvent, + } + + #[derive(Default, Debug)] + pub struct Session { + pub ready: GatewayEvent, + pub ready_supplimental: GatewayEvent, + pub replace: GatewayEvent + } + + #[derive(Default, Debug)] + pub struct StageInstance { + pub create: GatewayEvent, + pub update: GatewayEvent, + pub delete: GatewayEvent, + } + #[derive(Default, Debug)] pub struct Message { pub create: GatewayEvent, @@ -746,6 +775,7 @@ mod events { pub reaction_remove: GatewayEvent, pub reaction_remove_all: GatewayEvent, pub reaction_remove_emoji: GatewayEvent, + pub ack: GatewayEvent } #[derive(Default, Debug)] @@ -755,10 +785,17 @@ mod events { pub typing_start_event: GatewayEvent, } + #[derive(Default, Debug)] + pub struct Relationship { + pub add: GatewayEvent, + pub remove: GatewayEvent, + } + #[derive(Default, Debug)] pub struct Channel { pub create: GatewayEvent, pub update: GatewayEvent, + pub unread_update: GatewayEvent, pub delete: GatewayEvent, pub pins_update: GatewayEvent, } @@ -776,26 +813,63 @@ mod events { #[derive(Default, Debug)] pub struct Guild { pub create: GatewayEvent, - /*pub update: GatewayEvent, - pub delete: GatewayEvent, - pub audit_log_entry_create: GatewayEvent, - pub ban_add: GatewayEvent, - pub ban_remove: GatewayEvent, - pub emojis_update: GatewayEvent, - pub stickers_update: GatewayEvent, - pub integrations_update: GatewayEvent, - pub member_add: GatewayEvent, - pub member_remove: GatewayEvent, - pub member_update: GatewayEvent, - pub members_chunk: GatewayEvent, - pub role_create: GatewayEvent, - pub role_update: GatewayEvent, - pub role_delete: GatewayEvent, - pub role_scheduled_event_create: GatewayEvent, - pub role_scheduled_event_update: GatewayEvent, - pub role_scheduled_event_delete: GatewayEvent, - pub role_scheduled_event_user_add: GatewayEvent, - pub role_scheduled_event_user_remove: GatewayEvent,*/ + pub update: GatewayEvent, + pub delete: GatewayEvent, + pub audit_log_entry_create: GatewayEvent, + pub ban_add: GatewayEvent, + pub ban_remove: GatewayEvent, + pub emojis_update: GatewayEvent, + pub stickers_update: GatewayEvent, + pub integrations_update: GatewayEvent, + pub member_add: GatewayEvent, + pub member_remove: GatewayEvent, + pub member_update: GatewayEvent, + pub members_chunk: GatewayEvent, + pub role_create: GatewayEvent, + pub role_update: GatewayEvent, + pub role_delete: GatewayEvent, + pub role_scheduled_event_create: GatewayEvent, + pub role_scheduled_event_update: GatewayEvent, + pub role_scheduled_event_delete: GatewayEvent, + pub role_scheduled_event_user_add: GatewayEvent, + pub role_scheduled_event_user_remove: GatewayEvent, + pub passive_update_v1: GatewayEvent, + } + + #[derive(Default, Debug)] + pub struct Invite { + pub create: GatewayEvent, + pub delete: GatewayEvent + } + + #[derive(Default, Debug)] + pub struct Integration { + pub create: GatewayEvent, + pub update: GatewayEvent, + pub delete: GatewayEvent + } + + #[derive(Default, Debug)] + pub struct Interaction { + pub create: GatewayEvent, + } + + #[derive(Default, Debug)] + pub struct Call { + pub create: GatewayEvent, + pub update: GatewayEvent, + pub delete: GatewayEvent + } + + #[derive(Default, Debug)] + pub struct Voice { + pub state_update: GatewayEvent, + pub server_update: GatewayEvent + } + + #[derive(Default, Debug)] + pub struct Webhooks { + pub update: GatewayEvent, } } diff --git a/src/types/entities/application.rs b/src/types/entities/application.rs index 9844e6d..2aa0515 100644 --- a/src/types/entities/application.rs +++ b/src/types/entities/application.rs @@ -3,6 +3,9 @@ use crate::types::{Team, User}; use bitflags::{bitflags, Flags}; use serde::{Deserialize, Serialize}; use serde_json::Value; +use serde_repr::{Serialize_repr, Deserialize_repr}; +#[cfg(feature = "sqlx")] +use sqlx::FromRow; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] @@ -136,3 +139,33 @@ pub struct ApplicationCommandInteractionDataOption { pub value: Value, pub options: Vec, } + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +/// See https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure +pub struct GuildApplicationCommandPermissions { + pub id: Snowflake, + pub application_id: Snowflake, + pub guild_id: Snowflake, + pub permissions: Vec, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +/// See https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure +pub struct ApplicationCommandPermission { + pub id: Snowflake, + #[serde(rename = "type")] + pub permission_type: ApplicationCommandPermissionType, + /// true to allow, false, to disallow + pub permission: bool, +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Default, Clone, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[repr(u8)] +/// See https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permission-type +pub enum ApplicationCommandPermissionType { + #[default] + Role = 1, + User = 2, + Channel = 3 +} \ No newline at end of file diff --git a/src/types/entities/audit_log.rs b/src/types/entities/audit_log.rs new file mode 100644 index 0000000..4e5dba6 --- /dev/null +++ b/src/types/entities/audit_log.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::utils::Snowflake; + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object +pub struct AuditLogEntry { + pub target_id: Option, + pub changes: Option>, + pub user_id: Option, + pub id: Snowflake, + // to:do implement an enum for these types + pub action_type: u8, + // to:do add better options type + pub options: Option, + pub reason: Option +} + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/audit-log#audit-log-change-object +pub struct AuditLogChange { + pub new_value: Option, + pub old_value: Option, + pub key: String +} diff --git a/src/types/entities/auto_moderation.rs b/src/types/entities/auto_moderation.rs new file mode 100644 index 0000000..0b723c1 --- /dev/null +++ b/src/types/entities/auto_moderation.rs @@ -0,0 +1,135 @@ +use serde::{Deserialize, Serialize}; +use serde_repr::{Serialize_repr, Deserialize_repr}; + +use crate::types::utils::Snowflake; + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object +pub struct AutoModerationRule { + pub id: Snowflake, + pub guild_id: Snowflake, + pub name: String, + pub creator_id: Snowflake, + pub event_type: AutoModerationRuleEventType, + pub trigger_type: AutoModerationRuleTriggerType, + pub trigger_metadata: AutoModerationRuleTriggerMetadata, + pub actions: Vec, + pub enabled: bool, + pub exempt_roles: Vec, + pub exempt_channels: Vec, +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-event-types +pub enum AutoModerationRuleEventType { + #[default] + MessageSend = 1 +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-types +pub enum AutoModerationRuleTriggerType { + #[default] + Keyword = 1, + Spam = 3, + KeywordPreset = 4, + MentionSpam = 5 +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +#[serde(untagged)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata +pub enum AutoModerationRuleTriggerMetadata { + ForKeyword(AutoModerationRuleTriggerMetadataForKeyword), + ForKeywordPreset(AutoModerationRuleTriggerMetadataForKeywordPreset), + ForMentionSpam(AutoModerationRuleTriggerMetadataForMentionSpam), + #[default] + None +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata +pub struct AutoModerationRuleTriggerMetadataForKeyword { + pub keyword_filter: Vec, + pub regex_patterns: Vec, + pub allow_list: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata +pub struct AutoModerationRuleTriggerMetadataForKeywordPreset { + pub presets: Vec, + pub allow_list: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata +pub struct AutoModerationRuleTriggerMetadataForMentionSpam { + /// Max 50 + pub mention_total_limit: u8, + pub mention_raid_protection_enabled: bool +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-keyword-preset-types +pub enum AutoModerationRuleKeywordPresetType { + #[default] + Profanity = 1, + SexualContent = 2, + Slurs = 3 +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object +pub struct AutoModerationAction { + #[serde(rename = "type")] + pub action_type: AutoModerationActionType, + pub metadata: Option +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-types +pub enum AutoModerationActionType { + #[default] + BlockMessage = 1, + SendAlertMessage = 2, + Timeout = 3 +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +#[serde(untagged)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata +pub enum AutoModerationActionMetadata { + ForBlockMessage(AutoModerationActionMetadataForBlockMessage), + ForSendAlertMessage(AutoModerationActionMetadataForSendAlertMessage), + ForTimeout(AutoModerationActionMetadataForTimeout), + #[default] + None +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata +pub struct AutoModerationActionMetadataForBlockMessage { + pub custom_message: Option +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata +pub struct AutoModerationActionMetadataForSendAlertMessage { + pub channel_id: Snowflake +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +/// See https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata +pub struct AutoModerationActionMetadataForTimeout { + /// Max 2419200 + pub duration_seconds: u32, +} \ No newline at end of file diff --git a/src/types/entities/channel.rs b/src/types/entities/channel.rs index 596bdbf..a0c2bcb 100644 --- a/src/types/entities/channel.rs +++ b/src/types/entities/channel.rs @@ -1,5 +1,6 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; +use serde_aux::prelude::{deserialize_number_from_string, deserialize_option_number_from_string, deserialize_string_from_number}; use serde_repr::{Deserialize_repr, Serialize_repr}; use crate::types::{ @@ -66,9 +67,13 @@ pub struct Channel { #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)] pub struct Tag { + #[serde(default)] + #[serde(deserialize_with = "deserialize_number_from_string")] pub id: u64, pub name: String, pub moderated: bool, + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] pub emoji_id: Option, pub emoji_name: Option, } @@ -77,8 +82,13 @@ pub struct Tag { pub struct PermissionOverwrite { pub id: String, #[serde(rename = "type")] - pub overwrite_type: u8, + #[serde(deserialize_with = "deserialize_string_from_number")] + pub overwrite_type: String, + #[serde(default)] + #[serde(deserialize_with = "deserialize_string_from_number")] pub allow: String, + #[serde(default)] + #[serde(deserialize_with = "deserialize_string_from_number")] pub deny: String, } @@ -103,7 +113,9 @@ pub struct ThreadMember { #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)] pub struct DefaultReaction { - pub emoji_id: Option, + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] + pub emoji_id: Option, pub emoji_name: Option, } diff --git a/src/types/entities/emoji.rs b/src/types/entities/emoji.rs index 752d373..c9811af 100644 --- a/src/types/entities/emoji.rs +++ b/src/types/entities/emoji.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use serde_aux::prelude::deserialize_option_number_from_string; use crate::types::entities::User; use crate::types::{Guild, Snowflake}; diff --git a/src/types/entities/guild.rs b/src/types/entities/guild.rs index f3f03f7..c79ee1d 100644 --- a/src/types/entities/guild.rs +++ b/src/types/entities/guild.rs @@ -1,5 +1,6 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use serde_repr::{Serialize_repr, Deserialize_repr}; use crate::types::{ entities::{Channel, Emoji, GuildTemplate, RoleObject, Sticker, User, VoiceState, Webhook}, @@ -12,7 +13,7 @@ use crate::types::{ #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] pub struct Guild { pub id: Snowflake, - pub name: String, + pub name: Option, pub icon: Option, pub icon_hash: Option, pub splash: Option, @@ -33,7 +34,7 @@ pub struct Guild { #[cfg_attr(feature = "sqlx", sqlx(skip))] pub emojis: Vec, #[cfg_attr(feature = "sqlx", sqlx(skip))] - pub features: Vec, + pub features: Option>, pub application_id: Option, pub system_channel_id: Option, pub system_channel_flags: Option, @@ -56,7 +57,7 @@ pub struct Guild { pub welcome_screen: Option>, #[cfg(not(feature = "sqlx"))] pub welcome_screen: Option, - pub nsfw_level: u8, + pub nsfw_level: Option, #[cfg_attr(feature = "sqlx", sqlx(skip))] pub stickers: Option>, pub premium_progress_bar_enabled: Option, @@ -120,3 +121,59 @@ pub struct UnavailableGuild { pub struct GuildCreateResponse { pub id: String, } + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object +pub struct GuildScheduledEvent { + pub id: String, + pub guild_id: String, + pub channel_id: Option, + pub creator_id: Option, + pub name: String, + pub description: String, + pub scheduled_start_time: DateTime, + pub scheduled_end_time: Option>, + pub privacy_level: GuildScheduledEventPrivacyLevel, + pub status: GuildScheduledEventStatus, + pub entity_type: GuildScheduledEventEntityType, + pub entity_id: Option, + pub entity_metadata: Option, + pub creator: Option, + pub user_count: Option, + pub image: Option +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Default, Clone)] +#[repr(u8)] +/// See https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-privacy-level +pub enum GuildScheduledEventPrivacyLevel { + #[default] + GuildOnly = 2, +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Default, Clone)] +#[repr(u8)] +/// See https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-status +pub enum GuildScheduledEventStatus { + #[default] + Scheduled = 1, + Active = 2, + Completed = 3, + Canceled = 4 +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Default, Clone)] +#[repr(u8)] +/// See https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-types +pub enum GuildScheduledEventEntityType { + #[default] + StageInstance = 1, + Voice = 2, + External = 3, +} + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-metadata +pub struct GuildScheduledEventEntityMetadata { + pub location: Option +} \ No newline at end of file diff --git a/src/types/entities/guild_member.rs b/src/types/entities/guild_member.rs index 50d75e4..5e1ebfa 100644 --- a/src/types/entities/guild_member.rs +++ b/src/types/entities/guild_member.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; use crate::types::entities::User; -#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)] +#[derive(Debug, Deserialize, Default, Serialize, Clone, PartialEq, Eq)] pub struct GuildMember { pub user: Option, pub nick: Option, @@ -12,7 +12,7 @@ pub struct GuildMember { pub premium_since: Option, pub deaf: bool, pub mute: bool, - pub flags: i32, + pub flags: Option, pub pending: Option, pub permissions: Option, pub communication_disabled_until: Option, diff --git a/src/types/entities/message.rs b/src/types/entities/message.rs index 9efcad1..484a575 100644 --- a/src/types/entities/message.rs +++ b/src/types/entities/message.rs @@ -21,7 +21,7 @@ pub struct Message { pub tts: bool, pub mention_everyone: bool, #[cfg_attr(feature = "sqlx", sqlx(skip))] - pub mentions: Vec, + pub mentions: Option>, #[cfg_attr(feature = "sqlx", sqlx(skip))] pub mention_roles: Vec, #[cfg_attr(feature = "sqlx", sqlx(skip))] diff --git a/src/types/entities/mod.rs b/src/types/entities/mod.rs index 006aac1..5c8306b 100644 --- a/src/types/entities/mod.rs +++ b/src/types/entities/mod.rs @@ -16,6 +16,10 @@ mod user; mod user_settings; mod voice_state; mod webhook; +mod audit_log; +mod relationship; +mod auto_moderation; +mod stage_instance; pub use application::*; pub use attachment::*; @@ -35,3 +39,7 @@ pub use user::*; pub use user_settings::*; pub use voice_state::*; pub use webhook::*; +pub use audit_log::*; +pub use relationship::*; +pub use auto_moderation::*; +pub use stage_instance::*; \ No newline at end of file diff --git a/src/types/entities/relationship.rs b/src/types/entities/relationship.rs new file mode 100644 index 0000000..fc6d78d --- /dev/null +++ b/src/types/entities/relationship.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; +use serde_repr::{Serialize_repr, Deserialize_repr}; + +use crate::types::Snowflake; + +use super::PublicUser; + +#[derive(Debug, Deserialize, Serialize, Clone, Default)] +/// See https://docs.spacebar.chat/routes/#get-/users/@me/relationships/ +pub struct Relationship { + pub id: Snowflake, + #[serde(rename = "type")] + pub relationship_type: RelationshipType, + pub nickname: Option, + pub user: PublicUser +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +/// See https://github.com/spacebarchat/server/blob/60394d8c43904ff17935d6edbbfb09ecd479570a/src/util/entities/Relationship.ts#L30 +pub enum RelationshipType { + Outgoing = 4, + Incoming = 3, + Blocked = 2, + #[default] + Friends = 1, +} \ No newline at end of file diff --git a/src/types/entities/role.rs b/src/types/entities/role.rs index f427dc9..a9e479b 100644 --- a/src/types/entities/role.rs +++ b/src/types/entities/role.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use serde_aux::prelude::{deserialize_string_from_number, deserialize_option_number_from_string}; use crate::types::utils::Snowflake; @@ -13,11 +14,12 @@ pub struct RoleObject { pub icon: Option, pub unicode_emoji: Option, pub position: u16, + #[serde(default)] + #[serde(deserialize_with = "deserialize_string_from_number")] pub permissions: String, pub managed: bool, pub mentionable: bool, - // to:do add role tags https://discord.com/developers/docs/topics/permissions#role-object-role-tags-structure - //pub tags: Option + pub tags: Option } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -27,3 +29,21 @@ pub struct RoleSubscriptionData { pub total_months_subscribed: u32, pub is_renewal: bool, } + +#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)] +/// See https://discord.com/developers/docs/topics/permissions#role-object-role-tags-structure +pub struct RoleTags { + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] + pub bot_id: Option, + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] + pub integration_id: Option, + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] + pub subscription_listing_id: Option, + // These use the bad bool format, "Tags with type null represent booleans. They will be present and set to null if they are "true", and will be not present if they are "false"." + // premium_subscriber: bool, + // available_for_purchase: bool, + // guild_connections: bool, +} diff --git a/src/types/entities/stage_instance.rs b/src/types/entities/stage_instance.rs new file mode 100644 index 0000000..66376ef --- /dev/null +++ b/src/types/entities/stage_instance.rs @@ -0,0 +1,29 @@ +use serde::{Deserialize, Serialize}; +use serde_repr::{Serialize_repr, Deserialize_repr}; + +use crate::types::Snowflake; + +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// See https://discord.com/developers/docs/resources/stage-instance +pub struct StageInstance { + pub id: Snowflake, + pub guild_id: Snowflake, + pub channel_id: Snowflake, + /// 1 - 120 chars + pub topic: String, + pub privacy_level: StageInstancePrivacyLevel, + /// deprecated, apparently + pub discoverable_disabled: Option, + pub guild_scheduled_event_id: Option, +} + +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Default)] +#[repr(u8)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +/// See https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-privacy-level +pub enum StageInstancePrivacyLevel { + /// deprecated, apparently + Public = 1, + #[default] + GuildOnly = 2 +} \ No newline at end of file diff --git a/src/types/entities/sticker.rs b/src/types/entities/sticker.rs index 3c4a9d2..a3a79de 100644 --- a/src/types/entities/sticker.rs +++ b/src/types/entities/sticker.rs @@ -1,10 +1,12 @@ use serde::{Deserialize, Serialize}; +use serde_aux::prelude::{deserialize_option_number_from_string}; use crate::types::{entities::User, utils::Snowflake}; #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] pub struct Sticker { + #[serde(default)] pub id: Snowflake, pub pack_id: Option, pub name: String, diff --git a/src/types/entities/user.rs b/src/types/entities/user.rs index ee3702d..f6bf5c0 100644 --- a/src/types/entities/user.rs +++ b/src/types/entities/user.rs @@ -1,5 +1,6 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use serde_aux::prelude::deserialize_option_number_from_string; use serde_json::{Map, Value}; use crate::types::{ @@ -27,7 +28,7 @@ pub struct User { pub username: String, pub discriminator: String, pub avatar: Option, - pub bot: bool, + pub bot: Option, pub system: Option, pub mfa_enabled: Option, pub accent_color: Option, @@ -35,7 +36,11 @@ pub struct User { pub locale: Option, pub verified: Option, pub email: Option, - pub flags: String, + /// This field comes as either a string or a number as a string + /// So we need to account for that + #[serde(default)] + #[serde(deserialize_with = "deserialize_option_number_from_string")] + flags: Option, pub premium_since: Option>, pub premium_type: u8, pub pronouns: Option, @@ -47,11 +52,11 @@ pub struct User { pub nsfw_allowed: bool, pub premium: bool, pub purchased_flags: i32, - pub premium_usage_flags: i32, + pub premium_usage_flags: Option, pub disabled: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] pub struct PublicUser { pub id: Snowflake, pub username: String, @@ -61,7 +66,7 @@ pub struct PublicUser { pub banner: Option, pub theme_colors: Option>, pub pronouns: Option, - pub bot: bool, + pub bot: Option, pub bio: String, pub premium_type: u8, pub premium_since: Option>, diff --git a/src/types/entities/voice_state.rs b/src/types/entities/voice_state.rs index fd81ba8..dd0ab15 100644 --- a/src/types/entities/voice_state.rs +++ b/src/types/entities/voice_state.rs @@ -10,11 +10,13 @@ use crate::types::{ #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] pub struct VoiceState { - pub guild_id: Snowflake, + pub guild_id: Option, + pub guild: Option, pub channel_id: Snowflake, pub user_id: Snowflake, pub member: Option, pub session_id: Snowflake, + pub token: Option, pub deaf: bool, pub mute: bool, pub self_deaf: bool, @@ -23,4 +25,5 @@ pub struct VoiceState { pub self_video: bool, pub suppress: bool, pub request_to_speak_timestamp: Option>, + pub id: Option, } diff --git a/src/types/events/application.rs b/src/types/events/application.rs new file mode 100644 index 0000000..b2bd042 --- /dev/null +++ b/src/types/events/application.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{WebSocketEvent, GuildApplicationCommandPermissions}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update +pub struct ApplicationCommandPermissionsUpdate { + #[serde(flatten)] + pub permissions: GuildApplicationCommandPermissions, +} + +impl WebSocketEvent for ApplicationCommandPermissionsUpdate {} \ No newline at end of file diff --git a/src/types/events/auto_moderation.rs b/src/types/events/auto_moderation.rs new file mode 100644 index 0000000..3c6696d --- /dev/null +++ b/src/types/events/auto_moderation.rs @@ -0,0 +1,48 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{WebSocketEvent, AutoModerationRule, Snowflake, AutoModerationAction, AutoModerationRuleTriggerType}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create +pub struct AutoModerationRuleCreate { + #[serde(flatten)] + pub rule: AutoModerationRule, +} + +impl WebSocketEvent for AutoModerationRuleCreate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update +pub struct AutoModerationRuleUpdate { + #[serde(flatten)] + pub rule: AutoModerationRule, +} + +impl WebSocketEvent for AutoModerationRuleUpdate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete +pub struct AutoModerationRuleDelete { + #[serde(flatten)] + pub rule: AutoModerationRule, +} + +impl WebSocketEvent for AutoModerationRuleDelete {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution +pub struct AutoModerationActionExecution { + pub guild_id: Snowflake, + pub action: AutoModerationAction, + pub rule_id: Snowflake, + pub rule_trigger_type: AutoModerationRuleTriggerType, + pub user_id: Snowflake, + pub channel_id: Option, + pub message_id: Option, + pub alert_system_message_id: Option, + pub content: Option, + pub matched_keyword: Option, + pub matched_content: Option +} + +impl WebSocketEvent for AutoModerationActionExecution {} \ No newline at end of file diff --git a/src/types/events/call.rs b/src/types/events/call.rs new file mode 100644 index 0000000..dfea045 --- /dev/null +++ b/src/types/events/call.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{VoiceState, WebSocketEvent}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// Is sent to a client by the server to signify a new being created +/// {"t":"CALL_CREATE","s":2,"op":0,"d":{"voice_states":[],"ringing":[],"region":"milan","message_id":"1107187514906775613","embedded_activities":[],"channel_id":"837609115475771392"}} +pub struct CallCreate { + pub voice_states: Vec, + /// Seems like a vec of channel ids + pub ringing: Vec, + pub region: String, // milan + pub message_id: String, + /// What is this? + pub embedded_activities: Vec, + pub channel_id: String, +} +impl WebSocketEvent for CallCreate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// Updates the status of calls +/// {"t":"CALL_UPDATE","s":5,"op":0,"d":{"ringing":["837606544539254834"],"region":"milan","message_id":"1107191540234846308","guild_id":null,"channel_id":"837609115475771392"}} +pub struct CallUpdate { + /// Seems like a vec of channel ids + pub ringing: Vec, + pub region: String, // milan + pub message_id: String, + pub guild_id: Option, + pub channel_id: String, +} +impl WebSocketEvent for CallUpdate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// Deletes a ringing call +/// {"t":"CALL_DELETE","s":8,"op":0,"d":{"channel_id":"837609115475771392"}} +pub struct CallDelete { + pub channel_id: String, +} +impl WebSocketEvent for CallDelete {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// See https://unofficial-discord-docs.vercel.app/gateway/op13 +/// {"op":13,"d":{"channel_id":"837609115475771392"}} +pub struct CallSync { + pub channel_id: String, +} +impl WebSocketEvent for CallSync {} \ No newline at end of file diff --git a/src/types/events/channel.rs b/src/types/events/channel.rs index a5db906..d1ea864 100644 --- a/src/types/events/channel.rs +++ b/src/types/events/channel.rs @@ -15,8 +15,8 @@ impl WebSocketEvent for ChannelPinsUpdate {} #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#channel-create -/// Not directly serialized, as the inner payload is a channel object pub struct ChannelCreate { + #[serde(flatten)] pub channel: Channel, } @@ -24,17 +24,37 @@ impl WebSocketEvent for ChannelCreate {} #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#channel-update -/// Not directly serialized, as the inner payload is a channel object pub struct ChannelUpdate { + #[serde(flatten)] pub channel: Channel, } impl WebSocketEvent for ChannelUpdate {} +#[derive(Debug, Default, Deserialize, Serialize)] +/// Officially undocumented. +/// Sends updates to client about a new message with its id +/// {"channel_unread_updates": [{"id": "816412869766938648", "last_message_id": "1085892012085104680"}} +pub struct ChannelUnreadUpdate { + pub channel_unread_updates: Vec, + pub guild_id: String, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// Contains very few fields from [Channel] +/// See also [ChannelUnreadUpdates] +pub struct ChannelUnreadUpdateObject { + pub id: String, + pub last_message_id: String, + pub last_pin_timestamp: Option +} + +impl WebSocketEvent for ChannelUnreadUpdate {} + #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#channel-delete -/// Not directly serialized, as the inner payload is a channel object pub struct ChannelDelete { + #[serde(flatten)] pub channel: Channel, } diff --git a/src/types/events/guild.rs b/src/types/events/guild.rs index 840fb8e..6ddd95d 100644 --- a/src/types/events/guild.rs +++ b/src/types/events/guild.rs @@ -1,15 +1,21 @@ use crate::types::entities::{Guild, UnavailableGuild, User}; use crate::types::events::WebSocketEvent; +use crate::types::{AuditLogEntry, Emoji, GuildMember, GuildScheduledEvent, RoleObject, Sticker}; +use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use super::PresenceUpdate; + #[derive(Debug, Deserialize, Serialize, Default)] /// See https://discord.com/developers/docs/topics/gateway-events#guild-create -/// This one is particularly painful, it can be a Guild object with extra field or an unavailbile guild object +/// This one is particularly painful, it can be a Guild object with an extra field or an unavailable guild object pub struct GuildCreate { + #[serde(flatten)] pub d: GuildCreateDataOption, } #[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] pub enum GuildCreateDataOption { UnavailableGuild(UnavailableGuild), Guild(Guild), @@ -39,3 +45,181 @@ pub struct GuildBanRemove { } impl WebSocketEvent for GuildBanRemove {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-update +pub struct GuildUpdate { + #[serde(flatten)] + pub guild: Guild, +} + +impl WebSocketEvent for GuildUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-delete +pub struct GuildDelete { + #[serde(flatten)] + pub guild: UnavailableGuild, +} + +impl WebSocketEvent for GuildDelete {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create +pub struct GuildAuditLogEntryCreate { + #[serde(flatten)] + pub entry: AuditLogEntry, +} + +impl WebSocketEvent for GuildAuditLogEntryCreate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update +pub struct GuildEmojisUpdate { + pub guild_id: String, + pub emojis: Vec, +} + +impl WebSocketEvent for GuildEmojisUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update +pub struct GuildStickersUpdate { + pub guild_id: String, + pub stickers: Vec, +} + +impl WebSocketEvent for GuildStickersUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update +pub struct GuildIntegrationsUpdate { + pub guild_id: String, +} + +impl WebSocketEvent for GuildIntegrationsUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-add +pub struct GuildMemberAdd { + #[serde(flatten)] + pub member: GuildMember, + pub guild_id: String, +} + +impl WebSocketEvent for GuildMemberAdd {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-remove +pub struct GuildMemberRemove { + pub guild_id: String, + pub user: User, +} + +impl WebSocketEvent for GuildMemberRemove {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-update +pub struct GuildMemberUpdate { + pub guild_id: String, + pub roles: Vec, + pub user: User, + pub nick: Option, + pub avatar: Option, + pub joined_at: Option>, + pub premium_since: Option>, + pub deaf: Option, + pub mute: Option, + pub pending: Option, + pub communication_disabled_until: Option>, +} + +impl WebSocketEvent for GuildMemberUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-members-chunk +pub struct GuildMembersChunk { + pub guild_id: String, + pub members: Vec, + pub chunk_index: u16, + pub chunk_count: u16, + pub not_found: Option>, + pub presences: Option, + pub nonce: Option, +} + +impl WebSocketEvent for GuildMembersChunk {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-create +pub struct GuildRoleCreate { + pub guild_id: String, + pub role: RoleObject, +} + +impl WebSocketEvent for GuildRoleCreate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-update +pub struct GuildRoleUpdate { + pub guild_id: String, + pub role: RoleObject, +} + +impl WebSocketEvent for GuildRoleUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-delete +pub struct GuildRoleDelete { + pub guild_id: String, + pub role_id: String, +} + +impl WebSocketEvent for GuildRoleDelete {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-create +pub struct GuildScheduledEventCreate { + #[serde(flatten)] + pub event: GuildScheduledEvent, +} + +impl WebSocketEvent for GuildScheduledEventCreate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-update +pub struct GuildScheduledEventUpdate { + #[serde(flatten)] + pub event: GuildScheduledEvent, +} + +impl WebSocketEvent for GuildScheduledEventUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-delete +pub struct GuildScheduledEventDelete { + #[serde(flatten)] + pub event: GuildScheduledEvent, +} + +impl WebSocketEvent for GuildScheduledEventDelete {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-add +pub struct GuildScheduledEventUserAdd { + pub guild_scheduled_event_id: String, + pub user_id: String, + pub guild_id: String, +} + +impl WebSocketEvent for GuildScheduledEventUserAdd {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-remove +pub struct GuildScheduledEventUserRemove { + pub guild_scheduled_event_id: String, + pub user_id: String, + pub guild_id: String, +} + +impl WebSocketEvent for GuildScheduledEventUserRemove {} diff --git a/src/types/events/identify.rs b/src/types/events/identify.rs index b9cacee..c4b55f4 100644 --- a/src/types/events/identify.rs +++ b/src/types/events/identify.rs @@ -1,22 +1,168 @@ use crate::types::events::{PresenceUpdate, WebSocketEvent}; use serde::{Deserialize, Serialize}; +use serde_with::serde_as; -#[derive(Debug, Deserialize, Serialize, Default)] +#[derive(Debug, Deserialize, Serialize)] pub struct GatewayIdentifyPayload { pub token: String, pub properties: GatewayIdentifyConnectionProps, + #[serde(skip_serializing_if = "Option::is_none")] pub compress: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub large_threshold: Option, //default: 50 + #[serde(skip_serializing_if = "Option::is_none")] pub shard: Option>, + #[serde(skip_serializing_if = "Option::is_none")] pub presence: Option, - pub intents: i32, + // What is the difference between these two? + // Intents is documented, capabilities is used in users + // I wonder if these are interchangeable... + #[serde(skip_serializing_if = "Option::is_none")] + pub intents: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub capabilities: Option, +} + +impl Default for GatewayIdentifyPayload { + fn default() -> Self { + Self::common() + } +} + +impl GatewayIdentifyPayload { + /// Uses the most common, 25% data along with client capabilities + /// + /// Basically pretends to be an official client on Windows 10, with Chrome 113.0.0.0 + pub fn common() -> Self { + Self { + token: "".to_string(), + properties: GatewayIdentifyConnectionProps::default(), + compress: Some(false), + large_threshold: None, + shard: None, + presence: None, + intents: None, + capabilities: Some(8189), + } + } +} + +impl GatewayIdentifyPayload { + /// Creates an identify payload with the same default capabilities as the official client + pub fn default_w_client_capabilities() -> Self { + let mut def = Self::default(); + def.capabilities = Some(8189); // Default capabilities for a client + def + } + + /// Creates an identify payload with all possible capabilities + pub fn default_w_all_capabilities() -> Self { + let mut def = Self::default(); + def.capabilities = Some(i32::MAX); // Since discord uses bitwise for capabilities, this has almost every bit as 1, so all capabilities + def + } } impl WebSocketEvent for GatewayIdentifyPayload {} -#[derive(Debug, Deserialize, Serialize, Default)] +#[derive(Debug, Deserialize, Serialize)] +#[serde_as] pub struct GatewayIdentifyConnectionProps { + /// Almost always sent + /// + /// ex: "Linux", "Windows", "Mac OS X" + /// + /// ex (mobile): "Windows Mobile", "iOS", "Android", "BlackBerry" pub os: String, + /// Almost always sent + /// + /// ex: "Firefox", "Chrome", "Opera Mini", "Opera", "Blackberry", "Facebook Mobile", "Chrome iOS", "Mobile Safari", "Safari", "Android Chrome", "Android Mobile", "Edge", "Konqueror", "Internet Explorer", "Mozilla", "Discord Client" pub browser: String, - pub device: String, + /// Sometimes not sent, acceptable to be "" + /// + /// Speculation: + /// Only sent for mobile devices + /// + /// ex: "BlackBerry", "Windows Phone", "Android", "iPhone", "iPad", "" + #[serde_as(as = "NoneAsEmptyString")] + pub device: Option, + /// Almost always sent, most commonly en-US + /// + /// ex: "en-US" + pub system_locale: String, + /// Almost always sent + /// + /// ex: any user agent, most common is "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36" + pub browser_user_agent: String, + /// Almost always sent + /// + /// ex: "113.0.0.0" + pub browser_version: String, + /// Sometimes not sent, acceptable to be "" + /// + /// ex: "10" (For os = "Windows") + #[serde_as(as = "NoneAsEmptyString")] + pub os_version: Option, + /// Sometimes not sent, acceptable to be "" + #[serde_as(as = "NoneAsEmptyString")] + pub referrer: Option, + /// Sometimes not sent, acceptable to be "" + #[serde_as(as = "NoneAsEmptyString")] + pub referring_domain: Option, + /// Sometimes not sent, acceptable to be "" + #[serde_as(as = "NoneAsEmptyString")] + pub referrer_current: Option, + /// Almost always sent, most commonly "stable" + pub release_channel: String, + /// Almost always sent, identifiable if default is 0, should be around 199933 + pub client_build_number: u64, + //pub client_event_source: Option +} + +impl Default for GatewayIdentifyConnectionProps { + /// Uses the most common, 25% data + fn default() -> Self { + Self::common() + } +} + +impl GatewayIdentifyConnectionProps { + /// Returns a minimal, least data possible default + fn minimal() -> Self { + Self { + os: String::new(), + browser: String::new(), + device: None, + system_locale: String::from("en-US"), + browser_user_agent: String::new(), + browser_version: String::new(), + os_version: None, + referrer: None, + referring_domain: None, + referrer_current: None, + release_channel: String::from("stable"), + client_build_number: 199933, + } + } + + /// Returns the most common connection props so we can't be tracked + pub fn common() -> Self { + let mut default = Self::minimal(); + + // See https://www.useragents.me/#most-common-desktop-useragents + // 25% of the web + //default.browser_user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36".to_string(); + default.browser = String::from("Chrome"); + default.browser_version = String::from("113.0.0.0"); + + default.system_locale = String::from("en-US"); + + default.os = String::from("Windows"); + default.os_version = Some(String::from("10")); + + default.client_build_number = 199933; + default.release_channel = String::from("stable"); + + return default; + } } diff --git a/src/types/events/integration.rs b/src/types/events/integration.rs new file mode 100644 index 0000000..b7b49cc --- /dev/null +++ b/src/types/events/integration.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{Integration, WebSocketEvent}; + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#integration-create +pub struct IntegrationCreate { + #[serde(flatten)] + pub integration: Integration, + pub guild_id: String, +} + +impl WebSocketEvent for IntegrationCreate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#integration-update +pub struct IntegrationUpdate { + #[serde(flatten)] + pub integration: Integration, + pub guild_id: String, +} + +impl WebSocketEvent for IntegrationUpdate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#integration-delete +pub struct IntegrationDelete { + pub id: String, + pub guild_id: String, + pub application_id: Option, +} + +impl WebSocketEvent for IntegrationDelete {} \ No newline at end of file diff --git a/src/types/events/interaction.rs b/src/types/events/interaction.rs new file mode 100644 index 0000000..560ef55 --- /dev/null +++ b/src/types/events/interaction.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{Interaction, WebSocketEvent}; + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#interaction-create +pub struct InteractionCreate { + #[serde(flatten)] + pub interaction: Interaction, +} + +impl WebSocketEvent for InteractionCreate {} \ No newline at end of file diff --git a/src/types/events/invite.rs b/src/types/events/invite.rs new file mode 100644 index 0000000..e4693c8 --- /dev/null +++ b/src/types/events/invite.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{GuildInvite, WebSocketEvent}; + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#invite-create +pub struct InviteCreate { + #[serde(flatten)] + pub invite: GuildInvite +} + +impl WebSocketEvent for InviteCreate {} + +#[derive(Debug, Default, Deserialize, Serialize)] +/// See https://discord.com/developers/docs/topics/gateway-events#invite-delete +pub struct InviteDelete { + pub channel_id: String, + pub guild_id: Option, + pub code: String, +} + +impl WebSocketEvent for InviteDelete {} \ No newline at end of file diff --git a/src/types/events/lazy_request.rs b/src/types/events/lazy_request.rs new file mode 100644 index 0000000..d20fcf3 --- /dev/null +++ b/src/types/events/lazy_request.rs @@ -0,0 +1,27 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use super::WebSocketEvent; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// +/// Sent to the server to signify lazy loading of a guild; +/// Sent by the official client when switching to a guild or channel; +/// After this, you should recieve message updates +/// +/// See https://luna.gitlab.io/discord-unofficial-docs/lazy_guilds.html#op-14-lazy-request +/// +/// {"op":14,"d":{"guild_id":"848582562217590824","typing":true,"activities":true,"threads":true}} +pub struct LazyRequest { + pub guild_id: String, + pub typing: bool, + pub activities: bool, + pub threads: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub members: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub channels: Option>>> +} +impl WebSocketEvent for LazyRequest {} \ No newline at end of file diff --git a/src/types/events/message.rs b/src/types/events/message.rs index 8cd6429..758deff 100644 --- a/src/types/events/message.rs +++ b/src/types/events/message.rs @@ -1,3 +1,4 @@ +use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use crate::types::{ @@ -19,12 +20,43 @@ pub struct TypingStartEvent { impl WebSocketEvent for TypingStartEvent {} #[derive(Debug, Serialize, Deserialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#message-create pub struct MessageCreate { #[serde(flatten)] message: Message, - guild_id: Option, + guild_id: Option, member: Option, - mentions: Vec<(User, GuildMember)>, // Not sure if this is correct: https://discord.com/developers/docs/topics/gateway-events#message-create + mentions: Option>, +} + +#[derive(Debug, Serialize, Deserialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#message-create-message-create-extra-fields +pub struct MessageCreateUser { + pub id: String, + username: String, + discriminator: String, + avatar: Option, + bot: Option, + system: Option, + mfa_enabled: Option, + accent_color: Option, + locale: Option, + verified: Option, + email: Option, + premium_since: Option, + premium_type: Option, + pronouns: Option, + public_flags: Option, + banner: Option, + bio: Option, + theme_colors: Option>, + phone: Option, + nsfw_allowed: Option, + premium: Option, + purchased_flags: Option, + premium_usage_flags: Option, + disabled: Option, + member: GuildMember } impl WebSocketEvent for MessageCreate {} @@ -35,7 +67,7 @@ pub struct MessageUpdate { message: Message, guild_id: Option, member: Option, - mentions: Vec<(User, GuildMember)>, // Not sure if this is correct: https://discord.com/developers/docs/topics/gateway-events#message-create + mentions: Option>, // Not sure if this is correct: https://discord.com/developers/docs/topics/gateway-events#message-create } impl WebSocketEvent for MessageUpdate {} @@ -99,3 +131,23 @@ pub struct MessageReactionRemoveEmoji { } impl WebSocketEvent for MessageReactionRemoveEmoji {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// +/// Not documented anywhere unofficially +/// +/// Apparently "Message ACK refers to marking a message as read for Discord's API." (https://github.com/Rapptz/discord.py/issues/1851) +/// I suspect this is sent and recieved from the gateway to let clients on other devices know the user has read a message +/// +/// {"t":"MESSAGE_ACK","s":3,"op":0,"d":{"version":52,"message_id":"1107236673638633472","last_viewed":null,"flags":null,"channel_id":"967363950217936897"}} +pub struct MessageACK { + /// ? + pub version: u16, + pub message_id: String, + pub last_viewed: Option>, + /// What flags? + pub flags: Option, + pub channel_id: String, +} +impl WebSocketEvent for MessageACK {} \ No newline at end of file diff --git a/src/types/events/mod.rs b/src/types/events/mod.rs index 418cd31..3dbf5a6 100644 --- a/src/types/events/mod.rs +++ b/src/types/events/mod.rs @@ -12,7 +12,19 @@ mod request_members; mod resume; mod thread; mod user; -mod voice_status; +mod voice; +mod session; +mod webhooks; +mod passive_update; +mod integration; +mod invite; +mod call; +mod lazy_request; +mod relationship; +mod auto_moderation; +mod stage_instance; +mod interaction; +mod application; pub use channel::*; pub use guild::*; @@ -26,16 +38,49 @@ pub use request_members::*; pub use resume::*; pub use thread::*; pub use user::*; -pub use voice_status::*; +pub use voice::*; +pub use session::*; +pub use webhooks::*; +pub use passive_update::*; +pub use integration::*; +pub use invite::*; +pub use call::*; +pub use lazy_request::*; +pub use relationship::*; +pub use auto_moderation::*; +pub use stage_instance::*; +pub use interaction::*; +pub use application::*; pub trait WebSocketEvent {} -#[derive(Debug, Default, Deserialize, Serialize)] -pub struct GatewayPayload { +#[derive(Debug, Default, Serialize, Clone)] +/// The payload used for sending events to the gateway +/// +/// Similar to [GatewayReceivePayload], except we send a [Value] for d whilst we receive a [serde_json::value::RawValue] +/// Also, we never need to send the event name +pub struct GatewaySendPayload { pub op: u8, + #[serde(skip_serializing_if = "Option::is_none")] pub d: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub s: Option, +} + +impl WebSocketEvent for GatewaySendPayload {} + +#[derive(Debug, Default, Deserialize, Clone)] +/// The payload used for receiving events from the gateway +/// +/// Similar to [GatewaySendPayload], except we send a [Value] for d whilst we receive a [serde_json::value::RawValue] +/// Also, we never need to sent the event name + +pub struct GatewayReceivePayload<'a> { + pub op: u8, + #[serde(borrow)] + pub d: Option<&'a serde_json::value::RawValue>, pub s: Option, pub t: Option, } -impl WebSocketEvent for GatewayPayload {} +impl<'a> WebSocketEvent for GatewayReceivePayload<'a> {} diff --git a/src/types/events/passive_update.rs b/src/types/events/passive_update.rs new file mode 100644 index 0000000..43bed2a --- /dev/null +++ b/src/types/events/passive_update.rs @@ -0,0 +1,17 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{VoiceState, GuildMember}; +use super::{ChannelUnreadUpdateObject, WebSocketEvent}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// +/// Seems to be passively set to update the client on guild details (though, why not just send the update events?) +pub struct PassiveUpdateV1 { + pub voice_states: Vec, + pub members: Vec, + pub guild_id: String, + pub channels: Vec, +} + +impl WebSocketEvent for PassiveUpdateV1 {} \ No newline at end of file diff --git a/src/types/events/presence.rs b/src/types/events/presence.rs index f8fea4c..65c86e5 100644 --- a/src/types/events/presence.rs +++ b/src/types/events/presence.rs @@ -1,4 +1,4 @@ -use crate::types::entities::User; +use crate::types::PublicUser; use crate::types::events::WebSocketEvent; use crate::types::interfaces::Activity; use serde::{Deserialize, Serialize}; @@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, Default, Clone)] /// See https://discord.com/developers/docs/topics/gateway-events#presence-update-presence-update-event-fields pub struct PresenceUpdate { - pub user: User, - pub guild_id: String, + pub user: PublicUser, + pub guild_id: Option, pub status: String, pub activities: Vec, pub client_status: ClientStatusObject, diff --git a/src/types/events/ready.rs b/src/types/events/ready.rs index ff933c8..b82839e 100644 --- a/src/types/events/ready.rs +++ b/src/types/events/ready.rs @@ -1,15 +1,77 @@ -use crate::types::entities::{UnavailableGuild, User}; -use crate::types::events::WebSocketEvent; +use crate::types::entities::{UnavailableGuild, User, Guild}; +use crate::types::events::{WebSocketEvent, Session}; +use crate::types::interfaces::ClientStatusObject; +use crate::types::{PresenceUpdate, GuildMember, Activity, VoiceState}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, Default)] +/// Sort of documented, though most fields are left out +/// For a full example see https://gist.github.com/kozabrada123/a347002b1fb8825a5727e40746d4e199 +/// to:do add all undocumented fields pub struct GatewayReady { + pub analytics_token: Option, + pub auth_session_id_hash: Option, + pub country_code: Option, + pub v: u8, pub user: User, - pub guilds: Vec, + /// For bots these are [UnavailableGuild]s, for users they are [Guild] + pub guilds: Vec, + pub presences: Option>, + pub sessions: Option>, pub session_id: String, + pub session_type: Option, pub resume_gateway_url: Option, pub shard: Option<(u64, u64)>, } impl WebSocketEvent for GatewayReady {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// Sent after the READY event when a client is a user +/// {"t":"READY_SUPPLEMENTAL","s":2,"op":0,"d":{"merged_presences":{"guilds":[[{"user_id":"463640391196082177","status":"online","game":null,"client_status":{"web":"online"},"activities":[]}]],"friends":[{"user_id":"463640391196082177","status":"online","last_modified":1684053508443,"client_status":{"web":"online"},"activities":[]}]},"merged_members":[[{"user_id":"463640391196082177","roles":[],"premium_since":null,"pending":false,"nick":"pog","mute":false,"joined_at":"2021-05-30T15:24:08.763000+00:00","flags":0,"deaf":false,"communication_disabled_until":null,"avatar":null}]],"lazy_private_channels":[],"guilds":[{"voice_states":[],"id":"848582562217590824","embedded_activities":[]}],"disclose":["pomelo"]}} +pub struct GatewayReadySupplemental { + pub merged_presences: MergedPresences, + pub merged_members: Vec>, + // ? + pub lazy_private_channels: Vec, + pub guilds: Vec, + // ? pomelo + pub disclose: Vec, +} + +impl WebSocketEvent for GatewayReadySupplemental {} + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct MergedPresences { + pub guilds: Vec>, + pub friends: Vec +} + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct MergedPresenceFriend { + pub user_id: String, + pub status: String, + /// Looks like ms?? + pub last_modified: u128, + pub client_status: ClientStatusObject, + pub activities: Vec +} + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct MergedPresenceGuild { + pub user_id: String, + pub status: String, + // ? + pub game: Option, + pub client_status: ClientStatusObject, + pub activities: Vec +} + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct SupplimentalGuild { + pub voice_states: Option>, + pub id: String, + pub embedded_activities: Vec +} diff --git a/src/types/events/relationship.rs b/src/types/events/relationship.rs new file mode 100644 index 0000000..f8c0dff --- /dev/null +++ b/src/types/events/relationship.rs @@ -0,0 +1,22 @@ +use crate::types::{events::WebSocketEvent, Relationship, Snowflake, RelationshipType}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://github.com/spacebarchat/server/issues/204 +pub struct RelationshipAdd { + #[serde(flatten)] + pub relationship: Relationship, + pub should_notify: bool, +} + +impl WebSocketEvent for RelationshipAdd {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://github.com/spacebarchat/server/issues/203 +pub struct RelationshipRemove { + pub id: Snowflake, + #[serde(rename = "type")] + pub relationship_type: RelationshipType, +} + +impl WebSocketEvent for RelationshipRemove {} \ No newline at end of file diff --git a/src/types/events/request_members.rs b/src/types/events/request_members.rs index baf6d4a..67f37ce 100644 --- a/src/types/events/request_members.rs +++ b/src/types/events/request_members.rs @@ -7,7 +7,7 @@ pub struct GatewayRequestGuildMembers { pub guild_id: String, pub query: Option, pub limit: u64, - pub presence: Option, + pub presences: Option, pub user_ids: Option, pub nonce: Option, } diff --git a/src/types/events/session.rs b/src/types/events/session.rs new file mode 100644 index 0000000..e0206f5 --- /dev/null +++ b/src/types/events/session.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{Activity, WebSocketEvent}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Officially Undocumented +/// Seems like it sends active session info to users on connect +/// [{"activities":[],"client_info":{"client":"web","os":"other","version":0},"session_id":"ab5941b50d818b1f8d93b4b1b581b192","status":"online"}] +pub struct SessionsReplace { + pub sessions: Vec +} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Session info for the current user +pub struct Session { + pub activities: Vec, + pub client_info: ClientInfo, + pub session_id: String, + pub status: String, +} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// Another Client info object +/// {"client":"web","os":"other","version":0} +// Note: I don't think this one exists yet? Though I might've made a mistake and this might be a duplicate +pub struct ClientInfo { + pub client: String, + pub os: String, + pub version: u8 +} + +impl WebSocketEvent for SessionsReplace {} diff --git a/src/types/events/stage_instance.rs b/src/types/events/stage_instance.rs new file mode 100644 index 0000000..b308576 --- /dev/null +++ b/src/types/events/stage_instance.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{WebSocketEvent, StageInstance}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-create +pub struct StageInstanceCreate { + #[serde(flatten)] + pub stage_instance: StageInstance, +} + +impl WebSocketEvent for StageInstanceCreate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-update +pub struct StageInstanceUpdate { + #[serde(flatten)] + pub stage_instance: StageInstance, +} + +impl WebSocketEvent for StageInstanceUpdate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete +pub struct StageInstanceDelete { + #[serde(flatten)] + pub stage_instance: StageInstance, +} + +impl WebSocketEvent for StageInstanceDelete {} \ No newline at end of file diff --git a/src/types/events/thread.rs b/src/types/events/thread.rs index a9bf851..a02a148 100644 --- a/src/types/events/thread.rs +++ b/src/types/events/thread.rs @@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#thread-create -/// Not directly serialized, as the inner payload is a channel object pub struct ThreadCreate { + #[serde(flatten)] pub thread: Channel, } @@ -13,8 +13,8 @@ impl WebSocketEvent for ThreadCreate {} #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#thread-update -/// Not directly serialized, as the inner payload is a channel object pub struct ThreadUpdate { + #[serde(flatten)] pub thread: Channel, } @@ -22,8 +22,8 @@ impl WebSocketEvent for ThreadUpdate {} #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#thread-delete -/// Not directly serialized, as the inner payload is a channel object pub struct ThreadDelete { + #[serde(flatten)] pub thread: Channel, } @@ -43,29 +43,12 @@ impl WebSocketEvent for ThreadListSync {} #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#thread-member-update /// The inner payload is a thread member object with an extra field. -/// The extra field is a bit painful, because we can't just serialize a thread member object pub struct ThreadMemberUpdate { - pub id: Option, - pub user_id: Option, - pub join_timestamp: Option, - pub flags: Option, - pub member: Option, + #[serde(flatten)] + pub member: ThreadMember, pub guild_id: String, } -impl ThreadMemberUpdate { - /// Convert self to a thread member, losing the added guild_id field - pub fn to_thread_member(self) -> ThreadMember { - ThreadMember { - id: self.id, - user_id: self.user_id, - join_timestamp: self.join_timestamp.clone(), - flags: self.flags, - member: self.member, - } - } -} - impl WebSocketEvent for ThreadMemberUpdate {} #[derive(Debug, Default, Deserialize, Serialize)] diff --git a/src/types/events/user.rs b/src/types/events/user.rs index 4762121..bd90771 100644 --- a/src/types/events/user.rs +++ b/src/types/events/user.rs @@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#user-update -/// Not directly serialized, as the inner payload is the user object pub struct UserUpdate { + #[serde(flatten)] pub user: User, } diff --git a/src/types/events/voice.rs b/src/types/events/voice.rs new file mode 100644 index 0000000..2a102b5 --- /dev/null +++ b/src/types/events/voice.rs @@ -0,0 +1,40 @@ +use crate::types::{events::WebSocketEvent, VoiceState}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#update-voice-state +/// +/// Sent to the server +/// +/// Not to be confused with [VoiceStateUpdate] +pub struct UpdateVoiceState { + pub guild_id: Option, + pub channel_id: Option, + pub self_mute: bool, + pub self_deaf: bool, +} + +impl WebSocketEvent for UpdateVoiceState {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#voice-state-update +/// +/// Received from the server +/// +/// Not to be confused with [UpdateVoiceState] +pub struct VoiceStateUpdate { + #[serde(flatten)] + pub state: VoiceState +} + +impl WebSocketEvent for VoiceStateUpdate {} + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#voice-server-update +pub struct VoiceServerUpdate { + pub token: String, + pub guild_id: String, + pub endpoint: Option +} + +impl WebSocketEvent for VoiceServerUpdate {} \ No newline at end of file diff --git a/src/types/events/voice_status.rs b/src/types/events/voice_status.rs deleted file mode 100644 index aea7e0c..0000000 --- a/src/types/events/voice_status.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::types::events::WebSocketEvent; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Deserialize, Serialize, Default)] -/// See https://discord.com/developers/docs/topics/gateway-events#update-voice-state-gateway-voice-state-update-structure -pub struct GatewayVoiceStateUpdate { - pub guild_id: String, - pub channel_id: Option, - pub self_mute: bool, - pub self_deaf: bool, -} - -impl WebSocketEvent for GatewayVoiceStateUpdate {} diff --git a/src/types/events/webhooks.rs b/src/types/events/webhooks.rs new file mode 100644 index 0000000..e7711a7 --- /dev/null +++ b/src/types/events/webhooks.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +use super::WebSocketEvent; + +#[derive(Debug, Deserialize, Serialize, Default)] +/// See https://discord.com/developers/docs/topics/gateway-events#webhooks-update +pub struct WebhooksUpdate { + pub guild_id: String, + pub channel_id: String, +} + +impl WebSocketEvent for WebhooksUpdate {} \ No newline at end of file diff --git a/src/types/interfaces/interaction.rs b/src/types/interfaces/interaction.rs index 76b0361..0827078 100644 --- a/src/types/interfaces/interaction.rs +++ b/src/types/interfaces/interaction.rs @@ -3,7 +3,7 @@ use crate::types::utils::Snowflake; use serde::{Deserialize, Serialize}; use serde_json::Value; -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] pub struct Interaction { pub id: Snowflake, pub r#type: InteractionType, @@ -15,8 +15,9 @@ pub struct Interaction { pub version: i32, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] pub enum InteractionType { + #[default] SelfCommand = 0, Ping = 1, ApplicationCommand = 2,