Merge branch 'main' into feature/permissions-and-roles

This commit is contained in:
Flori Weber 2023-06-11 15:34:43 +02:00
commit ebe8a054e0
No known key found for this signature in database
GPG Key ID: 0ACD574FCF5226CF
74 changed files with 1807 additions and 1268 deletions

View File

@ -30,7 +30,7 @@
</div> </div>
## Roadmap ## Progress Tracker/Roadmap:
### Core Functionality ### Core Functionality
- [x] Rate Limiter (hint: couldn't be fully tested due to [an Issue with the Spacebar Server](https://github.com/spacebarchat/server/issues/1022)) - [x] Rate Limiter (hint: couldn't be fully tested due to [an Issue with the Spacebar Server](https://github.com/spacebarchat/server/issues/1022))
- [x] [Login (the conventional way)](https://github.com/polyphony-chat/chorus/issues/1) - [x] [Login (the conventional way)](https://github.com/polyphony-chat/chorus/issues/1)

View File

@ -17,7 +17,7 @@ pub struct ExampleObserver {}
// One struct can be an observer of multiple websocketevents, if needed // One struct can be an observer of multiple websocketevents, if needed
impl Observer<GatewayReady> for ExampleObserver { impl Observer<GatewayReady> for ExampleObserver {
// After we subscribe to an event this function is called every time we receive it // After we subscribe to an event this function is called every time we receive it
fn update(&self, _data: &GatewayReady) { fn update(&mut self, _data: &GatewayReady) {
println!("Observed Ready!"); println!("Observed Ready!");
} }
} }

View File

@ -1,5 +1,4 @@
use chorus::{self, gateway::Gateway, types::GatewayIdentifyPayload}; use chorus::{self, gateway::Gateway, types::GatewayIdentifyPayload};
use tokio;
/// This example creates a simple gateway connection and a session with an Identify event /// This example creates a simple gateway connection and a session with an Identify event
#[tokio::main] #[tokio::main]

View File

@ -1,72 +1,70 @@
pub mod login { use std::cell::RefCell;
use std::cell::RefCell; use std::rc::Rc;
use std::rc::Rc;
use reqwest::Client; use reqwest::Client;
use serde_json::{from_str, json}; use serde_json::{from_str, json};
use crate::api::limits::LimitType; use crate::api::limits::LimitType;
use crate::errors::ChorusLibError; use crate::errors::ChorusLibError;
use crate::instance::{Instance, UserMeta}; use crate::instance::{Instance, UserMeta};
use crate::limit::LimitedRequester; use crate::limit::LimitedRequester;
use crate::types::{ErrorResponse, LoginResult, LoginSchema}; use crate::types::{ErrorResponse, LoginResult, LoginSchema};
impl Instance { impl Instance {
pub async fn login_account( pub async fn login_account(
&mut self, &mut self,
login_schema: &LoginSchema, login_schema: &LoginSchema,
) -> Result<UserMeta, ChorusLibError> { ) -> Result<UserMeta, ChorusLibError> {
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
let json_schema = json!(login_schema); let json_schema = json!(login_schema);
let client = Client::new(); let client = Client::new();
let endpoint_url = self.urls.get_api().to_string() + "/auth/login"; let endpoint_url = self.urls.get_api().to_string() + "/auth/login";
let request_builder = client.post(endpoint_url).body(json_schema.to_string()); let request_builder = client.post(endpoint_url).body(json_schema.to_string());
// We do not have a user yet, and the UserRateLimits will not be affected by a login // We do not have a user yet, and the UserRateLimits will not be affected by a login
// request (since login is an instance wide limit), which is why we are just cloning the // request (since login is an instance wide limit), which is why we are just cloning the
// instances' limits to pass them on as user_rate_limits later. // instances' limits to pass them on as user_rate_limits later.
let mut cloned_limits = self.limits.clone(); let mut cloned_limits = self.limits.clone();
let response = requester let response = requester
.send_request( .send_request(
request_builder, request_builder,
LimitType::AuthRegister, LimitType::AuthRegister,
&mut self.limits, &mut self.limits,
&mut cloned_limits, &mut cloned_limits,
) )
.await; .await;
if response.is_err() { if response.is_err() {
return Err(ChorusLibError::NoResponse); return Err(ChorusLibError::NoResponse);
}
let response_unwrap = response.unwrap();
let status = response_unwrap.status();
let response_text_string = response_unwrap.text().await.unwrap();
if status.is_client_error() {
let json: ErrorResponse = serde_json::from_str(&response_text_string).unwrap();
let error_type = json.errors.errors.iter().next().unwrap().0.to_owned();
let mut error = "".to_string();
for (_, value) in json.errors.errors.iter() {
for error_item in value._errors.iter() {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
}
}
return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
}
let cloned_limits = self.limits.clone();
let login_result: LoginResult = from_str(&response_text_string).unwrap();
let object = self
.get_user(login_result.token.clone(), None)
.await
.unwrap();
let user = UserMeta::new(
Rc::new(RefCell::new(self.clone())),
login_result.token,
cloned_limits,
login_result.settings,
object,
);
Ok(user)
} }
let response_unwrap = response.unwrap();
let status = response_unwrap.status();
let response_text_string = response_unwrap.text().await.unwrap();
if status.is_client_error() {
let json: ErrorResponse = serde_json::from_str(&response_text_string).unwrap();
let error_type = json.errors.errors.iter().next().unwrap().0.to_owned();
let mut error = "".to_string();
for (_, value) in json.errors.errors.iter() {
for error_item in value._errors.iter() {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
}
}
return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
}
let cloned_limits = self.limits.clone();
let login_result: LoginResult = from_str(&response_text_string).unwrap();
let object = self
.get_user(login_result.token.clone(), None)
.await
.unwrap();
let user = UserMeta::new(
Rc::new(RefCell::new(self.clone())),
login_result.token,
cloned_limits,
login_result.settings,
object,
);
Ok(user)
} }
} }

View File

@ -1,5 +1,5 @@
pub mod login;
pub mod register;
pub use login::*; pub use login::*;
pub use register::*; pub use register::*;
pub mod login;
pub mod register;

View File

@ -1,79 +1,77 @@
pub mod register { use std::{cell::RefCell, rc::Rc};
use std::{cell::RefCell, rc::Rc};
use reqwest::Client; use reqwest::Client;
use serde_json::{from_str, json}; use serde_json::{from_str, json};
use crate::{ use crate::{
api::limits::LimitType, api::limits::LimitType,
errors::ChorusLibError, errors::ChorusLibError,
instance::{Instance, Token, UserMeta}, instance::{Instance, Token, UserMeta},
limit::LimitedRequester, limit::LimitedRequester,
types::{ErrorResponse, RegisterSchema}, types::{ErrorResponse, RegisterSchema},
}; };
impl Instance { impl Instance {
/** /**
Registers a new user on the Spacebar server. Registers a new user on the Spacebar server.
# Arguments # Arguments
* `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user. * `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user.
# Errors # Errors
* [`ChorusLibError`] - If the server does not respond. * [`ChorusLibError`] - If the server does not respond.
*/ */
pub async fn register_account( pub async fn register_account(
&mut self, &mut self,
register_schema: &RegisterSchema, register_schema: &RegisterSchema,
) -> Result<UserMeta, ChorusLibError> { ) -> Result<UserMeta, ChorusLibError> {
let json_schema = json!(register_schema); let json_schema = json!(register_schema);
let mut limited_requester = LimitedRequester::new().await; let mut limited_requester = LimitedRequester::new().await;
let client = Client::new(); let client = Client::new();
let endpoint_url = self.urls.get_api().to_string() + "/auth/register"; let endpoint_url = self.urls.get_api().to_string() + "/auth/register";
let request_builder = client.post(endpoint_url).body(json_schema.to_string()); let request_builder = client.post(endpoint_url).body(json_schema.to_string());
// We do not have a user yet, and the UserRateLimits will not be affected by a login // We do not have a user yet, and the UserRateLimits will not be affected by a login
// request (since register is an instance wide limit), which is why we are just cloning // request (since register is an instance wide limit), which is why we are just cloning
// the instances' limits to pass them on as user_rate_limits later. // the instances' limits to pass them on as user_rate_limits later.
let mut cloned_limits = self.limits.clone(); let mut cloned_limits = self.limits.clone();
let response = limited_requester let response = limited_requester
.send_request( .send_request(
request_builder, request_builder,
LimitType::AuthRegister, LimitType::AuthRegister,
&mut self.limits, &mut self.limits,
&mut cloned_limits, &mut cloned_limits,
) )
.await; .await;
if response.is_err() { if response.is_err() {
return Err(ChorusLibError::NoResponse); return Err(ChorusLibError::NoResponse);
}
let response_unwrap = response.unwrap();
let status = response_unwrap.status();
let response_unwrap_text = response_unwrap.text().await.unwrap();
let token = from_str::<Token>(&response_unwrap_text).unwrap();
let token = token.token;
if status.is_client_error() {
let json: ErrorResponse = serde_json::from_str(&token).unwrap();
let error_type = json.errors.errors.iter().next().unwrap().0.to_owned();
let mut error = "".to_string();
for (_, value) in json.errors.errors.iter() {
for error_item in value._errors.iter() {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
}
}
return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
}
let user_object = self.get_user(token.clone(), None).await.unwrap();
let settings =
UserMeta::get_settings(&token, &self.urls.get_api().to_string(), &mut self.limits)
.await
.unwrap();
let user: UserMeta = UserMeta::new(
Rc::new(RefCell::new(self.clone())),
token.clone(),
cloned_limits,
settings,
user_object,
);
Ok(user)
} }
let response_unwrap = response.unwrap();
let status = response_unwrap.status();
let response_unwrap_text = response_unwrap.text().await.unwrap();
let token = from_str::<Token>(&response_unwrap_text).unwrap();
let token = token.token;
if status.is_client_error() {
let json: ErrorResponse = serde_json::from_str(&token).unwrap();
let error_type = json.errors.errors.iter().next().unwrap().0.to_owned();
let mut error = "".to_string();
for (_, value) in json.errors.errors.iter() {
for error_item in value._errors.iter() {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
}
}
return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
}
let user_object = self.get_user(token.clone(), None).await.unwrap();
let settings =
UserMeta::get_settings(&token, &self.urls.get_api().to_string(), &mut self.limits)
.await
.unwrap();
let user: UserMeta = UserMeta::new(
Rc::new(RefCell::new(self.clone())),
token.clone(),
cloned_limits,
settings,
user_object,
);
Ok(user)
} }
} }

View File

@ -1,9 +1,9 @@
pub mod channels;
pub mod messages;
pub mod permissions;
pub mod reactions;
pub use channels::*; pub use channels::*;
pub use messages::*; pub use messages::*;
pub use permissions::*; pub use permissions::*;
pub use reactions::*; pub use reactions::*;
pub mod channels;
pub mod messages;
pub mod permissions;
pub mod reactions;

View File

@ -28,7 +28,7 @@ impl ReactionMeta {
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#delete-all-reactions](https://discord.com/developers/docs/resources/channel#delete-all-reactions) See [https://discord.com/developers/docs/resources/channel#delete-all-reactions](https://discord.com/developers/docs/resources/channel#delete-all-reactions)
*/ */
pub async fn delete_all( pub async fn delete_all(
&self, &self,
user: &mut UserMeta, user: &mut UserMeta,
@ -66,7 +66,7 @@ impl ReactionMeta {
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions) See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions)
*/ */
pub async fn get( pub async fn get(
&self, &self,
emoji: &str, emoji: &str,
@ -108,7 +108,7 @@ impl ReactionMeta {
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji](https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji) See [https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji](https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji)
*/ */
pub async fn delete_emoji( pub async fn delete_emoji(
&self, &self,
emoji: &str, emoji: &str,
@ -154,7 +154,7 @@ impl ReactionMeta {
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#create-reaction](https://discord.com/developers/docs/resources/channel#create-reaction) See [https://discord.com/developers/docs/resources/channel#create-reaction](https://discord.com/developers/docs/resources/channel#create-reaction)
*/ */
pub async fn create( pub async fn create(
&self, &self,
emoji: &str, emoji: &str,
@ -241,7 +241,7 @@ impl ReactionMeta {
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#delete-own-reaction](https://discord.com/developers/docs/resources/channel#delete-own-reaction) See [https://discord.com/developers/docs/resources/channel#delete-own-reaction](https://discord.com/developers/docs/resources/channel#delete-own-reaction)
*/ */
pub async fn delete_user( pub async fn delete_user(
&self, &self,
user_id: &str, user_id: &str,

View File

@ -173,7 +173,7 @@ impl Guild {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let _: Vec<Channel> = match from_str(&stringed_response) { let _: Vec<Channel> = match from_str(&stringed_response) {
@ -181,7 +181,7 @@ impl Guild {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
} }

View File

@ -43,7 +43,7 @@ impl types::GuildMember {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let member = from_str::<types::GuildMember>(&response_text); let member = from_str::<types::GuildMember>(&response_text);

View File

@ -1,7 +1,7 @@
pub mod guilds;
pub mod member;
pub mod roles;
pub use guilds::*; pub use guilds::*;
pub use roles::*; pub use roles::*;
pub use roles::*; pub use roles::*;
pub mod guilds;
pub mod member;
pub mod roles;

View File

@ -48,7 +48,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
@ -105,7 +105,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
@ -139,7 +139,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::FormCreationError { return Err(ChorusLibError::FormCreationError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let request = Client::new().post(url).bearer_auth(user.token()).body(body); let request = Client::new().post(url).bearer_auth(user.token()).body(body);
@ -161,7 +161,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
Ok(role) Ok(role)
@ -194,7 +194,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::FormCreationError { return Err(ChorusLibError::FormCreationError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let request = Client::new() let request = Client::new()
@ -216,7 +216,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
Ok(role) Ok(role)
@ -256,7 +256,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::FormCreationError { return Err(ChorusLibError::FormCreationError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let request = Client::new() let request = Client::new()
@ -281,7 +281,7 @@ impl types::RoleObject {
Err(e) => { Err(e) => {
return Err(ChorusLibError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
Ok(role) Ok(role)

View File

@ -10,7 +10,7 @@ impl Instance {
Gets the instance policies schema. Gets the instance policies schema.
# Errors # Errors
[`ChorusLibError`] - If the request fails. [`ChorusLibError`] - If the request fails.
*/ */
pub async fn general_configuration_schema( pub async fn general_configuration_schema(
&self, &self,
) -> Result<GeneralConfiguration, ChorusLibError> { ) -> Result<GeneralConfiguration, ChorusLibError> {

View File

@ -47,7 +47,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct Guild { pub struct Guild {
pub maxRoles: u64, pub maxRoles: u64,
pub maxEmojis: u64, pub maxEmojis: u64,
@ -58,7 +57,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct Message { pub struct Message {
pub maxCharacters: u64, pub maxCharacters: u64,
pub maxTTSCharacters: u64, pub maxTTSCharacters: u64,
@ -70,7 +68,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct Channel { pub struct Channel {
pub maxPins: u64, pub maxPins: u64,
pub maxTopic: u64, pub maxTopic: u64,
@ -102,7 +99,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct AuthRoutes { pub struct AuthRoutes {
pub login: Window, pub login: Window,
pub register: Window, pub register: Window,
@ -110,7 +106,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct AbsoluteRate { pub struct AbsoluteRate {
pub register: AbsoluteWindow, pub register: AbsoluteWindow,
pub sendMessage: AbsoluteWindow, pub sendMessage: AbsoluteWindow,
@ -125,7 +120,6 @@ pub mod limits {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub struct Config { pub struct Config {
pub user: User, pub user: User,
pub guild: Guild, pub guild: Guild,

View File

@ -1,5 +1,5 @@
pub mod instance;
pub mod limits;
pub use instance::*; pub use instance::*;
pub use limits::*; pub use limits::*;
pub mod instance;
pub mod limits;

View File

@ -1,3 +1,3 @@
pub mod instance;
pub use instance::limits::*; pub use instance::limits::*;
pub mod instance;

View File

@ -1,3 +1,3 @@
pub mod users;
pub use users::*; pub use users::*;
pub mod users;

View File

@ -32,3 +32,35 @@ custom_error! {
pub ObserverError pub ObserverError
AlreadySubscribedError = "Each event can only be subscribed to once." AlreadySubscribedError = "Each event can only be subscribed to once."
} }
custom_error! {
/// For errors we receive from the gateway, see https://discord-userdoccers.vercel.app/topics/opcodes-and-status-codes#gateway-close-event-codes;
///
/// Supposed to be sent as numbers, though they are sent as string most of the time?
///
/// Also includes errors when initiating a connection and unexpected opcodes
#[derive(PartialEq, Eq)]
pub GatewayError
// Errors we have received from the gateway
UnknownError = "We're not sure what went wrong. Try reconnecting?",
UnknownOpcodeError = "You sent an invalid Gateway opcode or an invalid payload for an opcode",
DecodeError = "Gateway server couldn't decode payload",
NotAuthenticatedError = "You sent a payload prior to identifying",
AuthenticationFailedError = "The account token sent with your identify payload is invalid",
AlreadyAuthenticatedError = "You've already identified, no need to reauthenticate",
InvalidSequenceNumberError = "The sequence number sent when resuming the session was invalid. Reconnect and start a new session",
RateLimitedError = "You are being rate limited!",
SessionTimedOutError = "Your session timed out. Reconnect and start a new one",
InvalidShardError = "You sent us an invalid shard when identifying",
ShardingRequiredError = "The session would have handled too many guilds - you are required to shard your connection in order to connect",
InvalidAPIVersionError = "You sent an invalid Gateway version",
InvalidIntentsError = "You sent an invalid intent",
DisallowedIntentsError = "You sent a disallowed intent. You may have tried to specify an intent that you have not enabled or are not approved for",
// Errors when initiating a gateway connection
CannotConnectError{error: String} = "Cannot connect due to a tungstenite error: {error}",
NonHelloOnInitiateError{opcode: u8} = "Received non hello on initial gateway connection ({opcode}), something is definitely wrong",
// Other misc errors
UnexpectedOpcodeReceivedError{opcode: u8} = "Received an opcode we weren't expecting to receive: {opcode}",
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,7 @@
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::api::limits::Limits; use crate::api::limits::Limits;
@ -5,10 +9,6 @@ use crate::errors::{ChorusLibError, FieldFormatError};
use crate::types::{GeneralConfiguration, User, UserSettings}; use crate::types::{GeneralConfiguration, User, UserSettings};
use crate::URLBundle; use crate::URLBundle;
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
/** /**
The [`Instance`] what you will be using to perform all sorts of actions on the Spacebar server. The [`Instance`] what you will be using to perform all sorts of actions on the Spacebar server.
@ -47,7 +47,7 @@ impl Instance {
Err(e) => { Err(e) => {
return Err(ChorusLibError::CantGetInfoError { return Err(ChorusLibError::CantGetInfoError {
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
Ok(instance) Ok(instance)

View File

@ -1,3 +1,5 @@
use url::{ParseError, Url};
#[cfg(feature = "client")] #[cfg(feature = "client")]
pub mod api; pub mod api;
pub mod errors; pub mod errors;
@ -11,9 +13,7 @@ pub mod types;
#[cfg(feature = "client")] #[cfg(feature = "client")]
pub mod voice; pub mod voice;
use url::{ParseError, Url};
#[derive(Clone, Default, Debug, PartialEq, Eq)] #[derive(Clone, Default, Debug, PartialEq, Eq)]
/// A URLBundle is a struct which bundles together the API-, Gateway- and CDN-URLs of a Spacebar /// A URLBundle is a struct which bundles together the API-, Gateway- and CDN-URLs of a Spacebar
/// instance. /// instance.
pub struct URLBundle { pub struct URLBundle {

View File

@ -1,11 +1,12 @@
use std::collections::VecDeque;
use reqwest::{Client, RequestBuilder, Response};
use crate::{ use crate::{
api::limits::{Limit, LimitType, Limits, LimitsMutRef}, api::limits::{Limit, LimitType, Limits, LimitsMutRef},
errors::ChorusLibError, errors::ChorusLibError,
}; };
use reqwest::{Client, RequestBuilder, Response};
use std::collections::VecDeque;
// Note: There seem to be some overlapping request limiters. We need to make sure that sending a // Note: There seem to be some overlapping request limiters. We need to make sure that sending a
// request checks for all the request limiters that apply, and blocks if any of the limiters are 0 // request checks for all the request limiters that apply, and blocks if any of the limiters are 0
@ -64,7 +65,7 @@ impl LimitedRequester {
- There has been an error with processing (unwrapping) the [`Response`](`reqwest::Response`) - There has been an error with processing (unwrapping) the [`Response`](`reqwest::Response`)
- The call to [`update_limits`](`crate::limits::update_limits`) yielded errors. Read the - The call to [`update_limits`](`crate::limits::update_limits`) yielded errors. Read the
methods' Errors section for more information. methods' Errors section for more information.
*/ */
pub async fn send_request( pub async fn send_request(
&mut self, &mut self,
request: RequestBuilder, request: RequestBuilder,
@ -79,7 +80,7 @@ impl LimitedRequester {
return Err(ChorusLibError::RequestErrorError { return Err(ChorusLibError::RequestErrorError {
url: "".to_string(), url: "".to_string(),
error: e.to_string(), error: e.to_string(),
}) });
} }
}; };
let result = self.http.execute(built_request).await; let result = self.http.execute(built_request).await;
@ -88,7 +89,7 @@ impl LimitedRequester {
Err(e) => { Err(e) => {
return Err(ChorusLibError::ReceivedErrorCodeError { return Err(ChorusLibError::ReceivedErrorCodeError {
error_code: e.to_string(), error_code: e.to_string(),
}) });
} }
}; };
self.update_limits( self.update_limits(
@ -104,7 +105,7 @@ impl LimitedRequester {
_ => { _ => {
return Err(ChorusLibError::ReceivedErrorCodeError { return Err(ChorusLibError::ReceivedErrorCodeError {
error_code: response.status().as_str().to_string(), error_code: response.status().as_str().to_string(),
}) });
} }
} }
} else { } else {
@ -281,10 +282,11 @@ impl LimitedRequester {
mod rate_limit { mod rate_limit {
use serde_json::from_str; use serde_json::from_str;
use super::*;
use crate::{api::limits::Config, URLBundle}; use crate::{api::limits::Config, URLBundle};
#[tokio::test]
use super::*;
#[tokio::test]
async fn create_limited_requester() { async fn create_limited_requester() {
let _urls = URLBundle::new( let _urls = URLBundle::new(
String::from("http://localhost:3001/api/"), String::from("http://localhost:3001/api/"),

View File

@ -1,3 +1,8 @@
use std::fmt::{Display, Formatter};
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(feature = "sqlx")] #[cfg(feature = "sqlx")]
use sqlx::{ use sqlx::{
@ -6,10 +11,6 @@ use sqlx::{
error::BoxDynError, error::BoxDynError,
Decode, Encode, MySql, Decode, Encode, MySql,
}; };
use std::fmt::{Display, Formatter};
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use crate::types::config::types::subconfigs::guild::{ use crate::types::config::types::subconfigs::guild::{
autojoin::AutoJoinConfiguration, discovery::DiscoverConfiguration, autojoin::AutoJoinConfiguration, discovery::DiscoverConfiguration,

View File

@ -9,6 +9,7 @@ pub struct RegistrationEmailConfiguration {
#[serde(default)] #[serde(default)]
pub domains: Vec<String>, pub domains: Vec<String>,
} }
impl Default for RegistrationEmailConfiguration { impl Default for RegistrationEmailConfiguration {
fn default() -> Self { fn default() -> Self {
Self { Self {

View File

@ -1,7 +1,7 @@
mod date_of_birth;
mod email;
mod password;
pub use date_of_birth::DateOfBirthConfiguration; pub use date_of_birth::DateOfBirthConfiguration;
pub use email::RegistrationEmailConfiguration; pub use email::RegistrationEmailConfiguration;
pub use password::PasswordConfiguration; pub use password::PasswordConfiguration;
mod date_of_birth;
mod email;
mod password;

View File

@ -1,5 +1,5 @@
mod captcha;
mod twofactor;
pub use captcha::{CaptchaConfiguration, CaptchaService}; pub use captcha::{CaptchaConfiguration, CaptchaService};
pub use twofactor::TwoFactorConfiguration; pub use twofactor::TwoFactorConfiguration;
mod captcha;
mod twofactor;

View File

@ -1,10 +1,11 @@
use crate::types::utils::Snowflake;
use crate::types::{Team, User};
use bitflags::{bitflags, Flags}; use bitflags::{bitflags, Flags};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use serde_repr::{Deserialize_repr, Serialize_repr}; use serde_repr::{Deserialize_repr, Serialize_repr};
use crate::types::utils::Snowflake;
use crate::types::{Team, User};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))]
pub struct Application { pub struct Application {

View File

@ -23,7 +23,6 @@ pub struct Attachment {
} }
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PartialDiscordFileAttachment { pub struct PartialDiscordFileAttachment {
pub id: Option<i16>, pub id: Option<i16>,
pub filename: String, pub filename: String,

View File

@ -34,7 +34,7 @@ pub struct Guild {
pub emojis: Vec<Emoji>, pub emojis: Vec<Emoji>,
pub explicit_content_filter: Option<i32>, pub explicit_content_filter: Option<i32>,
//#[cfg_attr(feature = "sqlx", sqlx(try_from = "String"))] //#[cfg_attr(feature = "sqlx", sqlx(try_from = "String"))]
pub features: GuildFeaturesList, pub features: Option<GuildFeaturesList>,
pub icon: Option<String>, pub icon: Option<String>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub icon_hash: Option<String>, pub icon_hash: Option<String>,

View File

@ -170,7 +170,6 @@ pub struct EmbedAuthor {
} }
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct EmbedField { pub struct EmbedField {
name: String, name: String,
value: String, value: String,

View File

@ -1,26 +1,3 @@
mod application;
mod attachment;
mod audit_log;
mod auto_moderation;
mod channel;
mod config;
mod emoji;
mod guild;
mod guild_member;
mod integration;
mod message;
mod relationship;
mod role;
mod security_key;
mod stage_instance;
mod sticker;
mod team;
mod template;
mod user;
mod user_settings;
mod voice_state;
mod webhook;
pub use application::*; pub use application::*;
pub use attachment::*; pub use attachment::*;
pub use audit_log::*; pub use audit_log::*;
@ -43,3 +20,26 @@ pub use user::*;
pub use user_settings::*; pub use user_settings::*;
pub use voice_state::*; pub use voice_state::*;
pub use webhook::*; pub use webhook::*;
mod application;
mod attachment;
mod audit_log;
mod auto_moderation;
mod channel;
mod config;
mod emoji;
mod guild;
mod guild_member;
mod integration;
mod message;
mod relationship;
mod role;
mod security_key;
mod stage_instance;
mod sticker;
mod team;
mod template;
mod user;
mod user_settings;
mod voice_state;
mod webhook;

View File

@ -1,6 +1,6 @@
use bitflags::bitflags; use bitflags::bitflags;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_aux::prelude::deserialize_option_number_from_string; use serde_aux::prelude::{deserialize_option_number_from_string, deserialize_string_from_number};
use crate::types::utils::Snowflake; use crate::types::utils::Snowflake;
@ -16,6 +16,7 @@ pub struct RoleObject {
pub unicode_emoji: Option<String>, pub unicode_emoji: Option<String>,
pub position: u16, pub position: u16,
#[serde(default)] #[serde(default)]
#[serde(deserialize_with = "deserialize_string_from_number")]
pub permissions: String, pub permissions: String,
pub managed: bool, pub managed: bool,
pub mentionable: bool, pub mentionable: bool,

View File

@ -21,7 +21,8 @@ pub struct GuildTemplate {
pub updated_at: DateTime<Utc>, pub updated_at: DateTime<Utc>,
pub source_guild_id: String, pub source_guild_id: String,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub source_guild: Vec<Guild>, // Unsure how a {recursive: Guild} looks like, might be a Vec? pub source_guild: Vec<Guild>,
// Unsure how a {recursive: Guild} looks like, might be a Vec?
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub serialized_source_guild: Vec<Guild>, pub serialized_source_guild: Vec<Guild>,
} }

View File

@ -13,6 +13,12 @@ pub enum UserStatus {
Invisible, Invisible,
} }
impl std::fmt::Display for UserStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "sqlx", derive(sqlx::Type))] #[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{GuildApplicationCommandPermissions, WebSocketEvent}; use crate::types::{GuildApplicationCommandPermissions, WebSocketEvent};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update /// See https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update
pub struct ApplicationCommandPermissionsUpdate { pub struct ApplicationCommandPermissionsUpdate {
#[serde(flatten)] #[serde(flatten)]

View File

@ -5,7 +5,7 @@ use crate::types::{
WebSocketEvent, WebSocketEvent,
}; };
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create /// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create
pub struct AutoModerationRuleCreate { pub struct AutoModerationRuleCreate {
#[serde(flatten)] #[serde(flatten)]
@ -14,7 +14,7 @@ pub struct AutoModerationRuleCreate {
impl WebSocketEvent for AutoModerationRuleCreate {} impl WebSocketEvent for AutoModerationRuleCreate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update /// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update
pub struct AutoModerationRuleUpdate { pub struct AutoModerationRuleUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -23,7 +23,7 @@ pub struct AutoModerationRuleUpdate {
impl WebSocketEvent for AutoModerationRuleUpdate {} impl WebSocketEvent for AutoModerationRuleUpdate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete /// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete
pub struct AutoModerationRuleDelete { pub struct AutoModerationRuleDelete {
#[serde(flatten)] #[serde(flatten)]
@ -32,7 +32,7 @@ pub struct AutoModerationRuleDelete {
impl WebSocketEvent for AutoModerationRuleDelete {} impl WebSocketEvent for AutoModerationRuleDelete {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution /// See https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution
pub struct AutoModerationActionExecution { pub struct AutoModerationActionExecution {
pub guild_id: Snowflake, pub guild_id: Snowflake,

View File

@ -2,50 +2,59 @@ use serde::{Deserialize, Serialize};
use crate::types::{VoiceState, WebSocketEvent}; use crate::types::{VoiceState, WebSocketEvent};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented;
/// Is sent to a client by the server to signify a new being created /// Is sent to a client by the server to signify a new call being created;
/// {"t":"CALL_CREATE","s":2,"op":0,"d":{"voice_states":[],"ringing":[],"region":"milan","message_id":"1107187514906775613","embedded_activities":[],"channel_id":"837609115475771392"}} ///
/// Ex: {"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 struct CallCreate {
pub voice_states: Vec<VoiceState>, pub voice_states: Vec<VoiceState>,
/// Seems like a vec of channel ids /// Seems like a vec of channel ids
pub ringing: Vec<String>, pub ringing: Vec<String>,
pub region: String, // milan pub region: String,
// milan
pub message_id: String, pub message_id: String,
/// What is this? /// What is this?
pub embedded_activities: Vec<serde_json::Value>, pub embedded_activities: Vec<serde_json::Value>,
pub channel_id: String, pub channel_id: String,
} }
impl WebSocketEvent for CallCreate {} impl WebSocketEvent for CallCreate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented;
/// Updates the status of calls /// Updates the client on which calls are ringing, along with a specific call?;
/// {"t":"CALL_UPDATE","s":5,"op":0,"d":{"ringing":["837606544539254834"],"region":"milan","message_id":"1107191540234846308","guild_id":null,"channel_id":"837609115475771392"}} ///
/// Ex: {"t":"CALL_UPDATE","s":5,"op":0,"d":{"ringing":["837606544539254834"],"region":"milan","message_id":"1107191540234846308","guild_id":null,"channel_id":"837609115475771392"}}
pub struct CallUpdate { pub struct CallUpdate {
/// Seems like a vec of channel ids /// Seems like a vec of channel ids
pub ringing: Vec<String>, pub ringing: Vec<String>,
pub region: String, // milan pub region: String,
// milan
pub message_id: String, pub message_id: String,
pub guild_id: Option<String>, pub guild_id: Option<String>,
pub channel_id: String, pub channel_id: String,
} }
impl WebSocketEvent for CallUpdate {} impl WebSocketEvent for CallUpdate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented;
/// Deletes a ringing call /// Deletes a ringing call;
/// {"t":"CALL_DELETE","s":8,"op":0,"d":{"channel_id":"837609115475771392"}} /// Ex: {"t":"CALL_DELETE","s":8,"op":0,"d":{"channel_id":"837609115475771392"}}
pub struct CallDelete { pub struct CallDelete {
pub channel_id: String, pub channel_id: String,
} }
impl WebSocketEvent for CallDelete {} impl WebSocketEvent for CallDelete {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented;
/// See https://unofficial-discord-docs.vercel.app/gateway/op13 /// See https://unofficial-discord-docs.vercel.app/gateway/op13;
/// {"op":13,"d":{"channel_id":"837609115475771392"}} ///
/// Ex: {"op":13,"d":{"channel_id":"837609115475771392"}}
pub struct CallSync { pub struct CallSync {
pub channel_id: String, pub channel_id: String,
} }
impl WebSocketEvent for CallSync {} impl WebSocketEvent for CallSync {}

View File

@ -13,7 +13,7 @@ pub struct ChannelPinsUpdate {
impl WebSocketEvent for ChannelPinsUpdate {} impl WebSocketEvent for ChannelPinsUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#channel-create /// See https://discord.com/developers/docs/topics/gateway-events#channel-create
pub struct ChannelCreate { pub struct ChannelCreate {
#[serde(flatten)] #[serde(flatten)]
@ -22,7 +22,7 @@ pub struct ChannelCreate {
impl WebSocketEvent for ChannelCreate {} impl WebSocketEvent for ChannelCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#channel-update /// See https://discord.com/developers/docs/topics/gateway-events#channel-update
pub struct ChannelUpdate { pub struct ChannelUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -31,7 +31,7 @@ pub struct ChannelUpdate {
impl WebSocketEvent for ChannelUpdate {} impl WebSocketEvent for ChannelUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// Officially undocumented. /// Officially undocumented.
/// Sends updates to client about a new message with its id /// Sends updates to client about a new message with its id
/// {"channel_unread_updates": [{"id": "816412869766938648", "last_message_id": "1085892012085104680"}} /// {"channel_unread_updates": [{"id": "816412869766938648", "last_message_id": "1085892012085104680"}}
@ -40,7 +40,7 @@ pub struct ChannelUnreadUpdate {
pub guild_id: String, pub guild_id: String,
} }
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// Contains very few fields from [Channel] /// Contains very few fields from [Channel]
/// See also [ChannelUnreadUpdates] /// See also [ChannelUnreadUpdates]
pub struct ChannelUnreadUpdateObject { pub struct ChannelUnreadUpdateObject {
@ -51,7 +51,7 @@ pub struct ChannelUnreadUpdateObject {
impl WebSocketEvent for ChannelUnreadUpdate {} impl WebSocketEvent for ChannelUnreadUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#channel-delete /// See https://discord.com/developers/docs/topics/gateway-events#channel-delete
pub struct ChannelDelete { pub struct ChannelDelete {
#[serde(flatten)] #[serde(flatten)]

View File

@ -1,20 +1,22 @@
use crate::types::entities::{Guild, PublicUser, UnavailableGuild};
use crate::types::events::WebSocketEvent;
use crate::types::{AuditLogEntry, Emoji, GuildMember, GuildScheduledEvent, RoleObject, Sticker};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::entities::{Guild, PublicUser, UnavailableGuild};
use crate::types::events::WebSocketEvent;
use crate::types::{AuditLogEntry, Emoji, GuildMember, GuildScheduledEvent, RoleObject, Sticker};
use super::PresenceUpdate; use super::PresenceUpdate;
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-create /// See https://discord.com/developers/docs/topics/gateway-events#guild-create;
/// This one is particularly painful, it can be a Guild object with an extra field or an unavailable guild object /// Received to give data about a guild;
// This one is particularly painful, it can be a Guild object with an extra field or an unavailable guild object
pub struct GuildCreate { pub struct GuildCreate {
#[serde(flatten)] #[serde(flatten)]
pub d: GuildCreateDataOption, pub d: GuildCreateDataOption,
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)] #[serde(untagged)]
pub enum GuildCreateDataOption { pub enum GuildCreateDataOption {
UnavailableGuild(UnavailableGuild), UnavailableGuild(UnavailableGuild),
@ -26,10 +28,12 @@ impl Default for GuildCreateDataOption {
GuildCreateDataOption::UnavailableGuild(UnavailableGuild::default()) GuildCreateDataOption::UnavailableGuild(UnavailableGuild::default())
} }
} }
impl WebSocketEvent for GuildCreate {} impl WebSocketEvent for GuildCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-ban-add-guild-ban-add-event-fields /// See https://discord.com/developers/docs/topics/gateway-events#guild-ban-add-guild-ban-add-event-fields;
/// Received to give info about a user being banned from a guild;
pub struct GuildBanAdd { pub struct GuildBanAdd {
pub guild_id: String, pub guild_id: String,
pub user: PublicUser, pub user: PublicUser,
@ -37,8 +41,9 @@ pub struct GuildBanAdd {
impl WebSocketEvent for GuildBanAdd {} impl WebSocketEvent for GuildBanAdd {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove /// See https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove;
/// Received to give info about a user being unbanned from a guild;
pub struct GuildBanRemove { pub struct GuildBanRemove {
pub guild_id: String, pub guild_id: String,
pub user: PublicUser, pub user: PublicUser,
@ -46,8 +51,9 @@ pub struct GuildBanRemove {
impl WebSocketEvent for GuildBanRemove {} impl WebSocketEvent for GuildBanRemove {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-update;
/// Received to give info about a guild being updated;
pub struct GuildUpdate { pub struct GuildUpdate {
#[serde(flatten)] #[serde(flatten)]
pub guild: Guild, pub guild: Guild,
@ -55,8 +61,9 @@ pub struct GuildUpdate {
impl WebSocketEvent for GuildUpdate {} impl WebSocketEvent for GuildUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-delete /// See https://discord.com/developers/docs/topics/gateway-events#guild-delete;
/// Received to tell the client about a guild being deleted;
pub struct GuildDelete { pub struct GuildDelete {
#[serde(flatten)] #[serde(flatten)]
pub guild: UnavailableGuild, pub guild: UnavailableGuild,
@ -64,8 +71,9 @@ pub struct GuildDelete {
impl WebSocketEvent for GuildDelete {} impl WebSocketEvent for GuildDelete {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create /// See https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create;
/// Received to the client about an audit log entry being added;
pub struct GuildAuditLogEntryCreate { pub struct GuildAuditLogEntryCreate {
#[serde(flatten)] #[serde(flatten)]
pub entry: AuditLogEntry, pub entry: AuditLogEntry,
@ -73,8 +81,9 @@ pub struct GuildAuditLogEntryCreate {
impl WebSocketEvent for GuildAuditLogEntryCreate {} impl WebSocketEvent for GuildAuditLogEntryCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update;
/// Received to tell the client about a change to a guild's emoji list;
pub struct GuildEmojisUpdate { pub struct GuildEmojisUpdate {
pub guild_id: String, pub guild_id: String,
pub emojis: Vec<Emoji>, pub emojis: Vec<Emoji>,
@ -82,8 +91,9 @@ pub struct GuildEmojisUpdate {
impl WebSocketEvent for GuildEmojisUpdate {} impl WebSocketEvent for GuildEmojisUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update;
/// Received to tell the client about a change to a guild's sticker list;
pub struct GuildStickersUpdate { pub struct GuildStickersUpdate {
pub guild_id: String, pub guild_id: String,
pub stickers: Vec<Sticker>, pub stickers: Vec<Sticker>,
@ -91,7 +101,7 @@ pub struct GuildStickersUpdate {
impl WebSocketEvent for GuildStickersUpdate {} impl WebSocketEvent for GuildStickersUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update
pub struct GuildIntegrationsUpdate { pub struct GuildIntegrationsUpdate {
pub guild_id: String, pub guild_id: String,
@ -99,8 +109,9 @@ pub struct GuildIntegrationsUpdate {
impl WebSocketEvent for GuildIntegrationsUpdate {} impl WebSocketEvent for GuildIntegrationsUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-add /// See https://discord.com/developers/docs/topics/gateway-events#guild-member-add;
/// Received to tell the client about a user joining a guild;
pub struct GuildMemberAdd { pub struct GuildMemberAdd {
#[serde(flatten)] #[serde(flatten)]
pub member: GuildMember, pub member: GuildMember,
@ -109,8 +120,9 @@ pub struct GuildMemberAdd {
impl WebSocketEvent for GuildMemberAdd {} impl WebSocketEvent for GuildMemberAdd {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-remove /// See https://discord.com/developers/docs/topics/gateway-events#guild-member-remove;
/// Received to tell the client about a user leaving a guild;
pub struct GuildMemberRemove { pub struct GuildMemberRemove {
pub guild_id: String, pub guild_id: String,
pub user: PublicUser, pub user: PublicUser,
@ -118,7 +130,7 @@ pub struct GuildMemberRemove {
impl WebSocketEvent for GuildMemberRemove {} impl WebSocketEvent for GuildMemberRemove {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-member-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-member-update
pub struct GuildMemberUpdate { pub struct GuildMemberUpdate {
pub guild_id: String, pub guild_id: String,
@ -136,7 +148,7 @@ pub struct GuildMemberUpdate {
impl WebSocketEvent for GuildMemberUpdate {} impl WebSocketEvent for GuildMemberUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-members-chunk /// See https://discord.com/developers/docs/topics/gateway-events#guild-members-chunk
pub struct GuildMembersChunk { pub struct GuildMembersChunk {
pub guild_id: String, pub guild_id: String,
@ -150,7 +162,7 @@ pub struct GuildMembersChunk {
impl WebSocketEvent for GuildMembersChunk {} impl WebSocketEvent for GuildMembersChunk {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-create /// See https://discord.com/developers/docs/topics/gateway-events#guild-role-create
pub struct GuildRoleCreate { pub struct GuildRoleCreate {
pub guild_id: String, pub guild_id: String,
@ -159,7 +171,7 @@ pub struct GuildRoleCreate {
impl WebSocketEvent for GuildRoleCreate {} impl WebSocketEvent for GuildRoleCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-role-update
pub struct GuildRoleUpdate { pub struct GuildRoleUpdate {
pub guild_id: String, pub guild_id: String,
@ -168,7 +180,7 @@ pub struct GuildRoleUpdate {
impl WebSocketEvent for GuildRoleUpdate {} impl WebSocketEvent for GuildRoleUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-role-delete /// See https://discord.com/developers/docs/topics/gateway-events#guild-role-delete
pub struct GuildRoleDelete { pub struct GuildRoleDelete {
pub guild_id: String, pub guild_id: String,
@ -177,7 +189,7 @@ pub struct GuildRoleDelete {
impl WebSocketEvent for GuildRoleDelete {} impl WebSocketEvent for GuildRoleDelete {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-create /// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-create
pub struct GuildScheduledEventCreate { pub struct GuildScheduledEventCreate {
#[serde(flatten)] #[serde(flatten)]
@ -186,7 +198,7 @@ pub struct GuildScheduledEventCreate {
impl WebSocketEvent for GuildScheduledEventCreate {} impl WebSocketEvent for GuildScheduledEventCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-update /// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-update
pub struct GuildScheduledEventUpdate { pub struct GuildScheduledEventUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -195,7 +207,7 @@ pub struct GuildScheduledEventUpdate {
impl WebSocketEvent for GuildScheduledEventUpdate {} impl WebSocketEvent for GuildScheduledEventUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-delete /// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-delete
pub struct GuildScheduledEventDelete { pub struct GuildScheduledEventDelete {
#[serde(flatten)] #[serde(flatten)]
@ -204,7 +216,7 @@ pub struct GuildScheduledEventDelete {
impl WebSocketEvent for GuildScheduledEventDelete {} impl WebSocketEvent for GuildScheduledEventDelete {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-add /// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-add
pub struct GuildScheduledEventUserAdd { pub struct GuildScheduledEventUserAdd {
pub guild_scheduled_event_id: String, pub guild_scheduled_event_id: String,
@ -214,7 +226,7 @@ pub struct GuildScheduledEventUserAdd {
impl WebSocketEvent for GuildScheduledEventUserAdd {} impl WebSocketEvent for GuildScheduledEventUserAdd {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-remove /// See https://discord.com/developers/docs/topics/gateway-events#guild-scheduled-event-user-remove
pub struct GuildScheduledEventUserRemove { pub struct GuildScheduledEventUserRemove {
pub guild_scheduled_event_id: String, pub guild_scheduled_event_id: String,

View File

@ -9,7 +9,7 @@ pub struct GatewayHeartbeat {
impl WebSocketEvent for GatewayHeartbeat {} impl WebSocketEvent for GatewayHeartbeat {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
pub struct GatewayHeartbeatAck { pub struct GatewayHeartbeatAck {
pub op: i32, pub op: i32,
} }

View File

@ -1,6 +1,7 @@
use crate::types::events::WebSocketEvent; use crate::types::WebSocketEvent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Received on gateway init, tells the client how often to send heartbeats;
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize)]
pub struct GatewayHello { pub struct GatewayHello {
pub op: i32, pub op: i32,
@ -9,8 +10,11 @@ pub struct GatewayHello {
impl WebSocketEvent for GatewayHello {} impl WebSocketEvent for GatewayHello {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// Contains info on how often the client should send heartbeats to the server;
pub struct HelloData { pub struct HelloData {
/// How often a client should send heartbeats, in milliseconds
// u128 because std used u128s for milliseconds
pub heartbeat_interval: u128, pub heartbeat_interval: u128,
} }

View File

@ -9,7 +9,8 @@ pub struct GatewayIdentifyPayload {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub compress: Option<bool>, pub compress: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub large_threshold: Option<i16>, //default: 50 pub large_threshold: Option<i16>,
//default: 50
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub shard: Option<Vec<(i32, i32)>>, pub shard: Option<Vec<(i32, i32)>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -65,7 +66,7 @@ impl GatewayIdentifyPayload {
impl WebSocketEvent for GatewayIdentifyPayload {} impl WebSocketEvent for GatewayIdentifyPayload {}
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize, Clone)]
#[serde_as] #[serde_as]
pub struct GatewayIdentifyConnectionProps { pub struct GatewayIdentifyConnectionProps {
/// Almost always sent /// Almost always sent

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{Integration, WebSocketEvent}; use crate::types::{Integration, WebSocketEvent};
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#integration-create /// See https://discord.com/developers/docs/topics/gateway-events#integration-create
pub struct IntegrationCreate { pub struct IntegrationCreate {
#[serde(flatten)] #[serde(flatten)]
@ -12,7 +12,7 @@ pub struct IntegrationCreate {
impl WebSocketEvent for IntegrationCreate {} impl WebSocketEvent for IntegrationCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#integration-update /// See https://discord.com/developers/docs/topics/gateway-events#integration-update
pub struct IntegrationUpdate { pub struct IntegrationUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -22,7 +22,7 @@ pub struct IntegrationUpdate {
impl WebSocketEvent for IntegrationUpdate {} impl WebSocketEvent for IntegrationUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#integration-delete /// See https://discord.com/developers/docs/topics/gateway-events#integration-delete
pub struct IntegrationDelete { pub struct IntegrationDelete {
pub id: String, pub id: String,

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{Interaction, WebSocketEvent}; use crate::types::{Interaction, WebSocketEvent};
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#interaction-create /// See https://discord.com/developers/docs/topics/gateway-events#interaction-create
pub struct InteractionCreate { pub struct InteractionCreate {
#[serde(flatten)] #[serde(flatten)]

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{GuildInvite, WebSocketEvent}; use crate::types::{GuildInvite, WebSocketEvent};
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#invite-create /// See https://discord.com/developers/docs/topics/gateway-events#invite-create
pub struct InviteCreate { pub struct InviteCreate {
#[serde(flatten)] #[serde(flatten)]
@ -11,7 +11,7 @@ pub struct InviteCreate {
impl WebSocketEvent for InviteCreate {} impl WebSocketEvent for InviteCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#invite-delete /// See https://discord.com/developers/docs/topics/gateway-events#invite-delete
pub struct InviteDelete { pub struct InviteDelete {
pub channel_id: String, pub channel_id: String,

View File

@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use super::WebSocketEvent; use super::WebSocketEvent;
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented
/// ///
/// Sent to the server to signify lazy loading of a guild; /// Sent to the server to signify lazy loading of a guild;
@ -24,4 +24,5 @@ pub struct LazyRequest {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub channels: Option<HashMap<String, Vec<Vec<u64>>>>, pub channels: Option<HashMap<String, Vec<Vec<u64>>>>,
} }
impl WebSocketEvent for LazyRequest {} impl WebSocketEvent for LazyRequest {}

View File

@ -4,7 +4,7 @@ use crate::types::entities::{Emoji, GuildMember, Message, PublicUser};
use super::WebSocketEvent; use super::WebSocketEvent;
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct TypingStartEvent { pub struct TypingStartEvent {
pub channel_id: String, pub channel_id: String,
pub guild_id: Option<String>, pub guild_id: Option<String>,
@ -15,7 +15,7 @@ pub struct TypingStartEvent {
impl WebSocketEvent for TypingStartEvent {} impl WebSocketEvent for TypingStartEvent {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#message-create /// See https://discord.com/developers/docs/topics/gateway-events#message-create
pub struct MessageCreate { pub struct MessageCreate {
#[serde(flatten)] #[serde(flatten)]
@ -25,7 +25,7 @@ pub struct MessageCreate {
mentions: Option<Vec<MessageCreateUser>>, mentions: Option<Vec<MessageCreateUser>>,
} }
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#message-create-message-create-extra-fields /// See https://discord.com/developers/docs/topics/gateway-events#message-create-message-create-extra-fields
pub struct MessageCreateUser { pub struct MessageCreateUser {
#[serde(flatten)] #[serde(flatten)]
@ -35,7 +35,7 @@ pub struct MessageCreateUser {
impl WebSocketEvent for MessageCreate {} impl WebSocketEvent for MessageCreate {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageUpdate { pub struct MessageUpdate {
#[serde(flatten)] #[serde(flatten)]
message: Message, message: Message,
@ -46,7 +46,7 @@ pub struct MessageUpdate {
impl WebSocketEvent for MessageUpdate {} impl WebSocketEvent for MessageUpdate {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageDelete { pub struct MessageDelete {
id: String, id: String,
channel_id: String, channel_id: String,
@ -55,7 +55,7 @@ pub struct MessageDelete {
impl WebSocketEvent for MessageDelete {} impl WebSocketEvent for MessageDelete {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageDeleteBulk { pub struct MessageDeleteBulk {
ids: Vec<String>, ids: Vec<String>,
channel_id: String, channel_id: String,
@ -64,7 +64,7 @@ pub struct MessageDeleteBulk {
impl WebSocketEvent for MessageDeleteBulk {} impl WebSocketEvent for MessageDeleteBulk {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageReactionAdd { pub struct MessageReactionAdd {
user_id: String, user_id: String,
channel_id: String, channel_id: String,
@ -76,7 +76,7 @@ pub struct MessageReactionAdd {
impl WebSocketEvent for MessageReactionAdd {} impl WebSocketEvent for MessageReactionAdd {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageReactionRemove { pub struct MessageReactionRemove {
user_id: String, user_id: String,
channel_id: String, channel_id: String,
@ -87,7 +87,7 @@ pub struct MessageReactionRemove {
impl WebSocketEvent for MessageReactionRemove {} impl WebSocketEvent for MessageReactionRemove {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageReactionRemoveAll { pub struct MessageReactionRemoveAll {
channel_id: String, channel_id: String,
message_id: String, message_id: String,
@ -96,7 +96,7 @@ pub struct MessageReactionRemoveAll {
impl WebSocketEvent for MessageReactionRemoveAll {} impl WebSocketEvent for MessageReactionRemoveAll {}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct MessageReactionRemoveEmoji { pub struct MessageReactionRemoveEmoji {
channel_id: String, channel_id: String,
message_id: String, message_id: String,
@ -106,7 +106,7 @@ pub struct MessageReactionRemoveEmoji {
impl WebSocketEvent for MessageReactionRemoveEmoji {} impl WebSocketEvent for MessageReactionRemoveEmoji {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented
/// ///
/// Not documented anywhere unofficially /// Not documented anywhere unofficially
@ -126,4 +126,5 @@ pub struct MessageACK {
pub flags: Option<serde_json::Value>, pub flags: Option<serde_json::Value>,
pub channel_id: String, pub channel_id: String,
} }
impl WebSocketEvent for MessageACK {} impl WebSocketEvent for MessageACK {}

View File

@ -1,31 +1,5 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
mod application;
mod auto_moderation;
mod call;
mod channel;
mod guild;
mod heartbeat;
mod hello;
mod identify;
mod integration;
mod interaction;
mod invite;
mod lazy_request;
mod message;
mod passive_update;
mod presence;
mod ready;
mod relationship;
mod request_members;
mod resume;
mod session;
mod stage_instance;
mod thread;
mod user;
mod voice;
mod webhooks;
pub use application::*; pub use application::*;
pub use auto_moderation::*; pub use auto_moderation::*;
pub use call::*; pub use call::*;
@ -52,6 +26,32 @@ pub use user::*;
pub use voice::*; pub use voice::*;
pub use webhooks::*; pub use webhooks::*;
mod application;
mod auto_moderation;
mod call;
mod channel;
mod guild;
mod heartbeat;
mod hello;
mod identify;
mod integration;
mod interaction;
mod invite;
mod lazy_request;
mod message;
mod passive_update;
mod presence;
mod ready;
mod relationship;
mod request_members;
mod resume;
mod session;
mod stage_instance;
mod thread;
mod user;
mod voice;
mod webhooks;
pub trait WebSocketEvent {} pub trait WebSocketEvent {}
#[derive(Debug, Default, Serialize, Clone)] #[derive(Debug, Default, Serialize, Clone)]
@ -79,7 +79,6 @@ impl WebSocketEvent for GatewaySendPayload {}
/// ///
/// Similar to [GatewaySendPayload], except we send a [Value] for d whilst we receive a [serde_json::value::RawValue] /// 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 /// Also, we never need to sent the event name
pub struct GatewayReceivePayload<'a> { pub struct GatewayReceivePayload<'a> {
#[serde(rename = "op")] #[serde(rename = "op")]
pub op_code: u8, pub op_code: u8,

View File

@ -1,14 +1,27 @@
use crate::types::events::WebSocketEvent; use crate::types::{events::WebSocketEvent, UserStatus};
use crate::types::interfaces::Activity; use crate::types::{Activity, PublicUser, Snowflake};
use crate::types::PublicUser;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, Default, Clone)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Sent by the client to update its status and presence;
/// See https://discord.com/developers/docs/topics/gateway-events#update-presence
pub struct UpdatePresence {
/// unix time of when the client went idle, or none if client is not idle
pub since: Option<u128>,
/// the client's status (online, invisible, offline, dnd, idle..)
pub status: UserStatus,
pub activities: Vec<Activity>,
pub afk: bool,
}
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Received to tell the client that a user updated their presence / status
/// See https://discord.com/developers/docs/topics/gateway-events#presence-update-presence-update-event-fields /// See https://discord.com/developers/docs/topics/gateway-events#presence-update-presence-update-event-fields
pub struct PresenceUpdate { pub struct PresenceUpdate {
pub user: PublicUser, pub user: PublicUser,
pub guild_id: Option<String>, #[serde(default)]
pub status: String, pub guild_id: Option<Snowflake>,
pub status: UserStatus,
pub activities: Vec<Activity>, pub activities: Vec<Activity>,
pub client_status: ClientStatusObject, pub client_status: ClientStatusObject,
} }

View File

@ -1,13 +1,14 @@
use serde::{Deserialize, Serialize};
use crate::types::entities::{Guild, User}; use crate::types::entities::{Guild, User};
use crate::types::events::{Session, WebSocketEvent}; use crate::types::events::{Session, WebSocketEvent};
use crate::types::interfaces::ClientStatusObject; use crate::types::interfaces::ClientStatusObject;
use crate::types::{Activity, GuildMember, PresenceUpdate, VoiceState}; use crate::types::{Activity, GuildMember, PresenceUpdate, VoiceState};
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Sort of documented, though most fields are left out /// 1/2 half documented;
/// For a full example see https://gist.github.com/kozabrada123/a347002b1fb8825a5727e40746d4e199 /// Received after identifying, provides initial user info;
/// to:do add all undocumented fields /// See https://discord.com/developers/docs/topics/gateway-events#ready;
pub struct GatewayReady { pub struct GatewayReady {
pub analytics_token: Option<String>, pub analytics_token: Option<String>,
pub auth_session_id_hash: Option<String>, pub auth_session_id_hash: Option<String>,
@ -27,10 +28,9 @@ pub struct GatewayReady {
impl WebSocketEvent for GatewayReady {} impl WebSocketEvent for GatewayReady {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented;
/// Sent after the READY event when a client is a user /// Sent after the READY event when a client is a user, seems to somehow add onto the ready event;
/// {"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 struct GatewayReadySupplemental {
pub merged_presences: MergedPresences, pub merged_presences: MergedPresences,
pub merged_members: Vec<Vec<GuildMember>>, pub merged_members: Vec<Vec<GuildMember>>,
@ -43,13 +43,13 @@ pub struct GatewayReadySupplemental {
impl WebSocketEvent for GatewayReadySupplemental {} impl WebSocketEvent for GatewayReadySupplemental {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct MergedPresences { pub struct MergedPresences {
pub guilds: Vec<Vec<MergedPresenceGuild>>, pub guilds: Vec<Vec<MergedPresenceGuild>>,
pub friends: Vec<MergedPresenceFriend>, pub friends: Vec<MergedPresenceFriend>,
} }
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct MergedPresenceFriend { pub struct MergedPresenceFriend {
pub user_id: String, pub user_id: String,
pub status: String, pub status: String,
@ -59,7 +59,7 @@ pub struct MergedPresenceFriend {
pub activities: Vec<Activity>, pub activities: Vec<Activity>,
} }
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct MergedPresenceGuild { pub struct MergedPresenceGuild {
pub user_id: String, pub user_id: String,
pub status: String, pub status: String,
@ -69,7 +69,7 @@ pub struct MergedPresenceGuild {
pub activities: Vec<Activity>, pub activities: Vec<Activity>,
} }
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct SupplementalGuild { pub struct SupplementalGuild {
pub voice_states: Option<Vec<VoiceState>>, pub voice_states: Option<Vec<VoiceState>>,
pub id: String, pub id: String,

View File

@ -11,7 +11,7 @@ pub struct RelationshipAdd {
impl WebSocketEvent for RelationshipAdd {} impl WebSocketEvent for RelationshipAdd {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://github.com/spacebarchat/server/issues/203 /// See https://github.com/spacebarchat/server/issues/203
pub struct RelationshipRemove { pub struct RelationshipRemove {
pub id: Snowflake, pub id: Snowflake,

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{Activity, WebSocketEvent}; use crate::types::{Activity, WebSocketEvent};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Officially Undocumented /// Officially Undocumented
/// Seems like it sends active session info to users on connect /// 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"}] /// [{"activities":[],"client_info":{"client":"web","os":"other","version":0},"session_id":"ab5941b50d818b1f8d93b4b1b581b192","status":"online"}]
@ -10,7 +10,7 @@ pub struct SessionsReplace {
pub sessions: Vec<Session>, pub sessions: Vec<Session>,
} }
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Session info for the current user /// Session info for the current user
pub struct Session { pub struct Session {
pub activities: Vec<Activity>, pub activities: Vec<Activity>,
@ -19,7 +19,7 @@ pub struct Session {
pub status: String, pub status: String,
} }
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// Another Client info object /// Another Client info object
/// {"client":"web","os":"other","version":0} /// {"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 // Note: I don't think this one exists yet? Though I might've made a mistake and this might be a duplicate

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::types::{StageInstance, WebSocketEvent}; use crate::types::{StageInstance, WebSocketEvent};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-create /// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-create
pub struct StageInstanceCreate { pub struct StageInstanceCreate {
#[serde(flatten)] #[serde(flatten)]
@ -11,7 +11,7 @@ pub struct StageInstanceCreate {
impl WebSocketEvent for StageInstanceCreate {} impl WebSocketEvent for StageInstanceCreate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-update /// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-update
pub struct StageInstanceUpdate { pub struct StageInstanceUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -20,7 +20,7 @@ pub struct StageInstanceUpdate {
impl WebSocketEvent for StageInstanceUpdate {} impl WebSocketEvent for StageInstanceUpdate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete /// See https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete
pub struct StageInstanceDelete { pub struct StageInstanceDelete {
#[serde(flatten)] #[serde(flatten)]

View File

@ -1,8 +1,9 @@
use crate::types::entities::{Channel, ThreadMember};
use crate::types::events::WebSocketEvent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize)] use crate::types::entities::{Channel, ThreadMember};
use crate::types::events::WebSocketEvent;
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-create /// See https://discord.com/developers/docs/topics/gateway-events#thread-create
pub struct ThreadCreate { pub struct ThreadCreate {
#[serde(flatten)] #[serde(flatten)]
@ -11,7 +12,7 @@ pub struct ThreadCreate {
impl WebSocketEvent for ThreadCreate {} impl WebSocketEvent for ThreadCreate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-update /// See https://discord.com/developers/docs/topics/gateway-events#thread-update
pub struct ThreadUpdate { pub struct ThreadUpdate {
#[serde(flatten)] #[serde(flatten)]
@ -20,7 +21,7 @@ pub struct ThreadUpdate {
impl WebSocketEvent for ThreadUpdate {} impl WebSocketEvent for ThreadUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-delete /// See https://discord.com/developers/docs/topics/gateway-events#thread-delete
pub struct ThreadDelete { pub struct ThreadDelete {
#[serde(flatten)] #[serde(flatten)]
@ -29,7 +30,7 @@ pub struct ThreadDelete {
impl WebSocketEvent for ThreadDelete {} impl WebSocketEvent for ThreadDelete {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-list-sync /// See https://discord.com/developers/docs/topics/gateway-events#thread-list-sync
pub struct ThreadListSync { pub struct ThreadListSync {
pub guild_id: String, pub guild_id: String,
@ -40,7 +41,7 @@ pub struct ThreadListSync {
impl WebSocketEvent for ThreadListSync {} impl WebSocketEvent for ThreadListSync {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-member-update /// 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 inner payload is a thread member object with an extra field.
pub struct ThreadMemberUpdate { pub struct ThreadMemberUpdate {
@ -51,7 +52,7 @@ pub struct ThreadMemberUpdate {
impl WebSocketEvent for ThreadMemberUpdate {} impl WebSocketEvent for ThreadMemberUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#thread-members-update /// See https://discord.com/developers/docs/topics/gateway-events#thread-members-update
pub struct ThreadMembersUpdate { pub struct ThreadMembersUpdate {
pub id: String, pub id: String,

View File

@ -1,10 +1,12 @@
use serde::{Deserialize, Serialize};
use crate::types::entities::PublicUser; use crate::types::entities::PublicUser;
use crate::types::events::WebSocketEvent; use crate::types::events::WebSocketEvent;
use crate::types::utils::Snowflake; use crate::types::utils::Snowflake;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#user-update /// See https://discord.com/developers/docs/topics/gateway-events#user-update;
/// Sent to indicate updates to a user object; (name changes, discriminator changes, etc);
pub struct UserUpdate { pub struct UserUpdate {
#[serde(flatten)] #[serde(flatten)]
pub user: PublicUser, pub user: PublicUser,
@ -12,12 +14,12 @@ pub struct UserUpdate {
impl WebSocketEvent for UserUpdate {} impl WebSocketEvent for UserUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// Undocumented /// Undocumented;
/// ///
/// Possibly an update for muted guild / channel settings for the current user /// Possibly an update for muted guild / channel settings for the current user;
/// ///
/// {"version":2,"suppress_roles":false,"suppress_everyone":false,"notify_highlights":0,"muted":false,"mute_scheduled_events":false,"mute_config":null,"mobile_push":true,"message_notifications":1,"hide_muted_channels":false,"guild_id":"848582562217590824","flags":0,"channel_overrides":[{"muted":false,"mute_config":null,"message_notifications":3,"flags":4096,"collapsed":false,"channel_id":"1042689182893604885"}]} /// Ex: {"version":2,"suppress_roles":false,"suppress_everyone":false,"notify_highlights":0,"muted":false,"mute_scheduled_events":false,"mute_config":null,"mobile_push":true,"message_notifications":1,"hide_muted_channels":false,"guild_id":"848582562217590824","flags":0,"channel_overrides":[{"muted":false,"mute_config":null,"message_notifications":3,"flags":4096,"collapsed":false,"channel_id":"1042689182893604885"}]}
pub struct UserGuildSettingsUpdate { pub struct UserGuildSettingsUpdate {
pub version: u8, pub version: u8,
pub suppress_roles: bool, pub suppress_roles: bool,
@ -37,12 +39,12 @@ pub struct UserGuildSettingsUpdate {
impl WebSocketEvent for UserGuildSettingsUpdate {} impl WebSocketEvent for UserGuildSettingsUpdate {}
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize, Clone)]
/// Undocumented /// Undocumented;
/// ///
/// Received in [UserGuildSettingsUpdate] /// Received in [UserGuildSettingsUpdate];
/// ///
/// {"muted":false,"mute_config":null,"message_notifications":3,"flags":4096,"collapsed":false,"channel_id":"1042689182893604885"} /// Ex: {"muted":false,"mute_config":null,"message_notifications":3,"flags":4096,"collapsed":false,"channel_id":"1042689182893604885"}
pub struct UserGuildSettingsChannelOverride { pub struct UserGuildSettingsChannelOverride {
pub muted: bool, pub muted: bool,
/// ?? /// ??

View File

@ -2,11 +2,10 @@ use crate::types::{events::WebSocketEvent, VoiceState};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default)]
/// See https://discord.com/developers/docs/topics/gateway-events#update-voice-state
/// ///
/// Sent to the server /// Sent to the server to indicate an update of the voice state (leave voice channel, join voice channel, mute, deafen);
/// ///
/// Not to be confused with [VoiceStateUpdate] /// Not to be confused with [VoiceStateUpdate];
pub struct UpdateVoiceState { pub struct UpdateVoiceState {
pub guild_id: Option<String>, pub guild_id: Option<String>,
pub channel_id: Option<String>, pub channel_id: Option<String>,
@ -16,12 +15,12 @@ pub struct UpdateVoiceState {
impl WebSocketEvent for UpdateVoiceState {} impl WebSocketEvent for UpdateVoiceState {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#voice-state-update /// See https://discord.com/developers/docs/topics/gateway-events#voice-state-update;
/// ///
/// Received from the server /// Received from the server to indicate an update in a user's voice state (leave voice channel, join voice channel, mute, deafen, etc);
/// ///
/// Not to be confused with [UpdateVoiceState] /// Not to be confused with [UpdateVoiceState];
pub struct VoiceStateUpdate { pub struct VoiceStateUpdate {
#[serde(flatten)] #[serde(flatten)]
pub state: VoiceState, pub state: VoiceState,
@ -29,8 +28,10 @@ pub struct VoiceStateUpdate {
impl WebSocketEvent for VoiceStateUpdate {} impl WebSocketEvent for VoiceStateUpdate {}
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#voice-server-update /// See https://discord.com/developers/docs/topics/gateway-events#voice-server-update;
///
/// Received to indicate which voice endpoint, token and guild_id to use;
pub struct VoiceServerUpdate { pub struct VoiceServerUpdate {
pub token: String, pub token: String,
pub guild_id: String, pub guild_id: String,

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use super::WebSocketEvent; use super::WebSocketEvent;
#[derive(Debug, Deserialize, Serialize, Default)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
/// See https://discord.com/developers/docs/topics/gateway-events#webhooks-update /// See https://discord.com/developers/docs/topics/gateway-events#webhooks-update
pub struct WebhooksUpdate { pub struct WebhooksUpdate {
pub guild_id: String, pub guild_id: String,

View File

@ -1,6 +1,7 @@
use crate::types::entities::Emoji;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::entities::Emoji;
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Activity { pub struct Activity {
name: String, name: String,

View File

@ -1,6 +1,7 @@
use crate::types::utils::Snowflake;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::utils::Snowflake;
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct WelcomeScreenObject { pub struct WelcomeScreenObject {
pub enabled: bool, pub enabled: bool,

View File

@ -1,8 +1,9 @@
use crate::types::entities::{AllowedMention, Embed};
use crate::types::utils::Snowflake;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use crate::types::entities::{AllowedMention, Embed};
use crate::types::utils::Snowflake;
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct Interaction { pub struct Interaction {
pub id: Snowflake, pub id: Snowflake,

View File

@ -1,11 +1,11 @@
mod activity;
mod connected_account;
mod guild_welcome_screen;
mod interaction;
mod status;
pub use activity::*; pub use activity::*;
pub use connected_account::*; pub use connected_account::*;
pub use guild_welcome_screen::*; pub use guild_welcome_screen::*;
pub use interaction::*; pub use interaction::*;
pub use status::*; pub use status::*;
mod activity;
mod connected_account;
mod guild_welcome_screen;
mod interaction;
mod status;

View File

@ -1,7 +1,8 @@
use crate::errors::FieldFormatError;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::errors::FieldFormatError;
/** /**
A struct that represents a well-formed email address. A struct that represents a well-formed email address.
*/ */
@ -100,7 +101,6 @@ You will receive a [`FieldFormatError`], if:
- The username is not between 2 and 32 characters. - The username is not between 2 and 32 characters.
- The password is not between 1 and 72 characters. - The password is not between 1 and 72 characters.
*/ */
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub struct RegisterSchema { pub struct RegisterSchema {

View File

@ -1,6 +1,7 @@
use crate::types::entities::Channel;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::entities::Channel;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
/// Represents the schema which needs to be sent to create a Guild. /// Represents the schema which needs to be sent to create a Guild.

View File

@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
use crate::types::entities::{ use crate::types::entities::{
AllowedMention, Component, Embed, MessageReference, PartialDiscordFileAttachment, AllowedMention, Component, Embed, MessageReference, PartialDiscordFileAttachment,
}; };
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]

View File

@ -1,11 +1,3 @@
mod apierror;
mod auth;
mod channel;
mod guild;
mod message;
mod role;
mod user;
pub use apierror::*; pub use apierror::*;
pub use auth::*; pub use auth::*;
pub use channel::*; pub use channel::*;
@ -14,11 +6,20 @@ pub use message::*;
pub use role::*; pub use role::*;
pub use user::*; pub use user::*;
mod apierror;
mod auth;
mod channel;
mod guild;
mod message;
mod role;
mod user;
#[cfg(test)] #[cfg(test)]
mod schemas_tests { mod schemas_tests {
use super::*;
use crate::errors::FieldFormatError; use crate::errors::FieldFormatError;
use super::*;
#[test] #[test]
fn password_too_short() { fn password_too_short() {
assert_eq!( assert_eq!(

View File

@ -1,4 +1,3 @@
use crate::types::Snowflake;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]

View File

@ -1,8 +1,8 @@
pub use regexes::*;
pub use rights::Rights;
pub use snowflake::{DeconstructedSnowflake, Snowflake};
pub mod jwt; pub mod jwt;
mod regexes; mod regexes;
mod rights; mod rights;
mod snowflake; mod snowflake;
pub use regexes::*;
pub use rights::Rights;
pub use snowflake::{DeconstructedSnowflake, Snowflake};

View File

@ -1,6 +1,7 @@
mod common;
use chorus::types; use chorus::types;
mod common;
#[tokio::test] #[tokio::test]
async fn test_registration() { async fn test_registration() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;

View File

@ -1,15 +1,16 @@
mod common;
use chorus::types::{self, Channel, PermissionFlags, PermissionOverwrite}; use chorus::types::{self, Channel, PermissionFlags, PermissionOverwrite};
mod common;
#[tokio::test] #[tokio::test]
async fn get_channel() { async fn get_channel() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;
let bundle_channel = bundle.channel.clone(); let bundle_channel = bundle.channel.clone();
let mut bundle_user = &mut bundle.user; let bundle_user = &mut bundle.user;
assert_eq!( assert_eq!(
bundle_channel, bundle_channel,
Channel::get(&mut bundle_user, &bundle_channel.id.to_string(),) Channel::get(bundle_user, &bundle_channel.id.to_string())
.await .await
.unwrap() .unwrap()
); );

24
tests/gateway.rs Normal file
View File

@ -0,0 +1,24 @@
mod common;
use chorus::gateway::*;
use chorus::types;
#[tokio::test]
/// Tests establishing a connection (hello and heartbeats) on the local gateway;
async fn test_gateway_establish() {
let bundle = common::setup().await;
Gateway::new(bundle.urls.wss).await.unwrap();
}
#[tokio::test]
/// Tests establishing a connection and authenticating
async fn test_gateway_authenticate() {
let bundle = common::setup().await;
let gateway = Gateway::new(bundle.urls.wss).await.unwrap();
let mut identify = types::GatewayIdentifyPayload::common();
identify.token = bundle.user.token;
gateway.send_identify(identify).await;
}

View File

@ -1,6 +1,7 @@
mod common;
use chorus::types::{Guild, GuildCreateSchema}; use chorus::types::{Guild, GuildCreateSchema};
mod common;
#[tokio::test] #[tokio::test]
async fn guild_creation_deletion() { async fn guild_creation_deletion() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;

View File

@ -7,7 +7,7 @@ async fn add_remove_role() {
let role_id = &bundle.role.id.to_string(); let role_id = &bundle.role.id.to_string();
let user_id = &bundle.user.object.id.to_string(); let user_id = &bundle.user.object.id.to_string();
chorus::types::GuildMember::add_role(&mut bundle.user, guild_id, user_id, role_id).await; chorus::types::GuildMember::add_role(&mut bundle.user, guild_id, user_id, role_id).await;
let member = chorus::types::GuildMember::get(&mut bundle.user, &guild_id, &user_id) let member = chorus::types::GuildMember::get(&mut bundle.user, guild_id, user_id)
.await .await
.unwrap(); .unwrap();
let mut role_found = false; let mut role_found = false;
@ -21,7 +21,7 @@ async fn add_remove_role() {
assert!(false) assert!(false)
} }
chorus::types::GuildMember::remove_role(&mut bundle.user, guild_id, user_id, role_id).await; chorus::types::GuildMember::remove_role(&mut bundle.user, guild_id, user_id, role_id).await;
let member = chorus::types::GuildMember::get(&mut bundle.user, &guild_id, &user_id) let member = chorus::types::GuildMember::get(&mut bundle.user, guild_id, user_id)
.await .await
.unwrap(); .unwrap();
for role in member.roles.iter() { for role in member.roles.iter() {

View File

@ -1,9 +1,10 @@
mod common;
use chorus::types;
use std::fs::File; use std::fs::File;
use std::io::{BufReader, Read}; use std::io::{BufReader, Read};
use chorus::types;
mod common;
#[tokio::test] #[tokio::test]
async fn send_message() { async fn send_message() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;

View File

@ -1,7 +1,7 @@
mod common;
use chorus::types::{self, RoleCreateModifySchema}; use chorus::types::{self, RoleCreateModifySchema};
mod common;
#[tokio::test] #[tokio::test]
async fn create_and_get_roles() { async fn create_and_get_roles() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;