### Client Initialization and Event Handling Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html Demonstrates how to create a Serenity Client instance, configure event handlers, and start the client. This example shows a basic 'ping-pong' bot. ```APIDOC ## POST /client/create ### Description Initializes a new Serenity Client instance with a given token, gateway intents, and an event handler. ### Method POST ### Endpoint /client/create ### Parameters #### Query Parameters - **token** (string) - Required - The authentication token for the Discord bot. - **gateway_intents** (GatewayIntents) - Required - Specifies the gateway intents to subscribe to. #### Request Body - **event_handler** (EventHandler) - Required - An implementation of the `EventHandler` trait to handle Discord events. ### Request Example ```json { "token": "my token here", "gateway_intents": "GUILDS | GUILD_MESSAGES", "event_handler": { "message": "async fn message(&self, context: Context, msg: Message) { if msg.content == \"!ping\" { let _ = msg.channel_id.say(&context, \"Pong!\"); } }" } } ``` ### Response #### Success Response (200) - **client_id** (string) - A unique identifier for the created client instance. #### Response Example ```json { "client_id": "client_abc123" } ``` ## POST /client/{client_id}/start ### Description Starts the WebSocket connection for the specified Serenity Client. ### Method POST ### Endpoint /client/{client_id}/start ### Parameters #### Path Parameters - **client_id** (string) - Required - The unique identifier of the client to start. ### Response #### Success Response (200) - **status** (string) - Indicates the client has started successfully. #### Response Example ```json { "status": "started" } ``` ``` -------------------------------- ### Command Creation Examples Source: https://docs.rs/serenity/latest/serenity/model/application/struct.Command.html?search= Examples demonstrating how to create simple and interactive commands. ```APIDOC ## Command Creation Examples ### Description Examples demonstrating how to create simple and interactive commands. ### Code Examples #### Simple Ping Command ```rust use serenity::builder::CreateCommand; use serenity::model::application::Command; use serenity::model::id::ApplicationId; let builder = CreateCommand::new("ping").description("A simple ping command"); let _ = Command::create_global_command(&http, builder).await; ``` #### Echo Command ```rust use serenity::builder::{CreateCommand, CreateCommandOption as CreateOption}; use serenity::model::application::{Command, CommandOptionType}; use serenity::model::id::ApplicationId; let builder = CreateCommand::new("echo").description("Makes the bot send a message").add_option( CreateOption::new(CommandOptionType::String, "message", "The message to send") .required(true), ); let _ = Command::create_global_command(&http, builder).await; ``` ``` -------------------------------- ### Start Serenity Client with Default Shard (Rust) Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html?search=u32+-%3E+bool This example demonstrates how to start a Serenity Discord client with default settings, suitable for users and bots in less than 2500 guilds. It requires a Discord bot token and default gateway intents. The function `client.start().await` establishes the connection and begins event processing. ```rust use serenity::client::Client; use serenity::prelude::GatewayIntents; // Replace with your actual token retrieval logic let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start().await { println!("Err with client: {:?}", why); } ``` -------------------------------- ### Start Serenity Client with Autosharding (Rust) Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html?search=std%3A%3Avec This example shows how to start a Serenity client using autosharding. The client automatically determines the optimal number of shards to use based on Discord's API recommendations. This is ideal for bots that may exceed the 2500 guild limit or require sharding for performance. ```rust use serenity::Client; use serenity::gateway::GatewayIntents; // Ensure you have the DISCORD_TOKEN environment variable set. let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start_autosharded().await { println!("Err with client: {:?}", why); } ``` -------------------------------- ### Define InstallationContextConfig struct Source: https://docs.rs/serenity/latest/serenity/model/application/struct.InstallationContextConfig.html The InstallationContextConfig struct holds optional OAuth2 installation parameters. It is used to represent the installation context of a Discord application. ```rust pub struct InstallationContextConfig { pub oauth2_install_params: Option, } ``` -------------------------------- ### Set Basic Prefix for Serenity Framework Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Configuration.html?search= This example demonstrates how to set a basic command prefix for the Serenity standard framework. It uses the `prefix` method on the `Configuration` struct to define the character or string that commands should start with. ```rust use serenity::framework::standard::{Configuration, StandardFramework}; let framework = StandardFramework::new(); framework.configure(Configuration::new().prefix("!")); ``` -------------------------------- ### Struct: InstallationContextConfig Source: https://docs.rs/serenity/latest/serenity/model/application/struct.InstallationContextConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Represents the configuration for an application's installation context, specifically holding OAuth2 installation parameters. ```APIDOC ## DATA STRUCTURE: InstallationContextConfig ### Description Contains information about how the `CurrentApplicationInfo` is installed. This structure is used to manage OAuth2 installation parameters as defined by Discord. ### Fields - **oauth2_install_params** (Option) - Optional - Configuration parameters for the OAuth2 installation process. ### Request Example { "oauth2_install_params": { "scopes": ["bot", "applications.commands"], "permissions": "2147483648" } } ### Response #### Success Response (200) - **oauth2_install_params** (Option) - The installation parameters associated with the application context. #### Response Example { "oauth2_install_params": { "scopes": ["bot"], "permissions": "0" } } ``` -------------------------------- ### Initialize and Configure CreateWebhook Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateWebhook.html?search=std%3A%3Avec Demonstrates how to instantiate a new CreateWebhook builder and configure its properties such as name, avatar, and audit log reason. ```rust use serenity::builder::CreateWebhook; // Create a new builder let builder = CreateWebhook::new("My Webhook"); // Configure properties let configured_builder = builder .name("New Name") .audit_log_reason("Setting up a new webhook"); ``` -------------------------------- ### Get Channel Webhooks Example (Rust) Source: https://docs.rs/serenity/latest/serenity/http/struct.Http.html An example demonstrating how to retrieve all webhooks for a given channel ID using the `get_channel_webhooks` function. This requires the `http` client instance. ```rust let channel_id = ChannelId::new(81384788765712384); let webhooks = http.get_channel_webhooks(channel_id).await?; ``` -------------------------------- ### GET /args/iter Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Args.html?search= Iterates over available arguments starting from the current offset. ```APIDOC ## GET /args/iter ### Description Iterate over any available arguments until there are none. Modifications like trimmed or quoted are applied if previously called. ### Method GET ### Endpoint /args/iter ### Parameters #### Query Parameters - **T** (Type) - Required - The type to parse each argument into. ### Response #### Success Response (200) - **Iter** (Iterator) - An iterator over the parsed arguments. ``` -------------------------------- ### Initialise Method - VoiceGatewayManager (Rust) Source: https://docs.rs/serenity/latest/serenity/gateway/trait.VoiceGatewayManager.html Performs initial setup for the voice gateway manager when a connection to Discord starts. It receives the bot's user ID and the total shard count, performing setup only once. ```rust fn initialise<'life0, 'async_trait>( &'life0 self, shard_count: u32, user_id: UserId, ) -> Pin + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait; ``` -------------------------------- ### Initialize and Configure CreateWebhook Builder Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateWebhook.html?search= Demonstrates how to instantiate the CreateWebhook builder and configure its properties such as name, avatar, and audit log reason before execution. ```rust use serenity::builder::CreateWebhook; // Create a new builder instance let builder = CreateWebhook::new("My Webhook"); // Configure properties let configured_builder = builder .name("Updated Webhook Name") .audit_log_reason("Administrative cleanup"); ``` -------------------------------- ### Example: Calculate User Permissions in Channel (Rust) Source: https://docs.rs/serenity/latest/serenity/model/channel/struct.GuildChannel.html?search=std%3A%3Avec An example demonstrating how to use `permissions_for_user` to get a user's permissions within a channel after receiving a message. This code snippet requires the 'serenity' crate and implements the `EventHandler` trait. ```rust #[serenity::async_trait] impl EventHandler for Handler { async fn message(&self, context: Context, msg: Message) { let channel = match context.cache.channel(msg.channel_id) { Some(channel) => channel, None => return, }; if let Ok(permissions) = channel.permissions_for_user(&context.cache, &msg.author) { println!("The user's permissions: {:?}", permissions); } } } ``` -------------------------------- ### GET /guilds/:guild_id/members/search Source: https://docs.rs/serenity/latest/serenity/http/struct.Http.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a list of `Member`s in a `Guild` whose username or nickname starts with a provided string. ```APIDOC ## GET /guilds/:guild_id/members/search ### Description Returns a list of `Member`s in a `Guild` whose username or nickname starts with a provided string. ### Method GET ### Endpoint /guilds/:guild_id/members/search ### Parameters #### Path Parameters - **guild_id** (Snowflake) - Required - The ID of the guild. #### Query Parameters - **query** (string) - Required - The query string to search for. - **limit** (integer) - Optional - The maximum number of members to return (default 25, max 1000). #### Request Body None ### Response #### Success Response (200) - **members** (array) - A list of member objects. #### Response Example { "members": [ { "user": { "id": "987654321098765432", "username": "TestUser", "discriminator": "1234", "avatar": "a_abcdef1234567890", "public_flags": 64 }, "nick": "Tester", "roles": [ "112233445566778899" ], "joined_at": "2023-01-01T12:00:00.000000+00:00", "deaf": false, "mute": false } ] } ``` -------------------------------- ### Initialize and Configure CreateEmbed Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateEmbed.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to instantiate a new CreateEmbed builder and apply configuration methods such as setting a title and a timestamp. ```rust let timestamp: Timestamp = "2004-06-08T16:04:23Z".parse().expect("Invalid timestamp!"); let embed = CreateEmbed::new().title("hello").timestamp(timestamp); ``` -------------------------------- ### GET /gateway/bot Source: https://docs.rs/serenity/latest/serenity/model/gateway/struct.BotGateway.html Retrieves the gateway information specifically for bot users, including recommended shard counts and session start limits. ```APIDOC ## GET /gateway/bot ### Description Retrieves the bot-specific gateway connection information. This endpoint provides the necessary data to initialize a connection to the Discord gateway, including the recommended number of shards for the bot. ### Method GET ### Endpoint /gateway/bot ### Parameters None ### Response #### Success Response (200) - **url** (String) - The gateway URL to connect to. - **shards** (u32) - The number of shards recommended for the bot user. - **session_start_limit** (Object) - Information regarding the gateway session start rate limits. #### Response Example { "url": "wss://gateway.discord.gg", "shards": 1, "session_start_limit": { "total": 1000, "remaining": 999, "reset_after": 3600000, "max_concurrency": 1 } } ``` -------------------------------- ### POST /start_shards Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html?search= Establishes all specified sharded connections and begins listening for events. ```APIDOC ## POST /start_shards ### Description Establishes sharded connections and starts listening for events. This will start receiving events and dispatch them to your registered handlers for all shards within the process. ### Method POST ### Endpoint /start_shards ### Parameters #### Request Body - **total_shards** (u32) - Required - The total number of shards to initialize. ### Request Example { "total_shards": 8 } ### Response #### Success Response (200) - **result** (Result<()>) - Returns success if shards start correctly. #### Error Handling - Returns `ClientError::Shutdown` when all shards have shutdown due to an error. ``` -------------------------------- ### Initialize and Configure CreateSelectMenu Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateSelectMenu.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to instantiate a new CreateSelectMenu builder and chain configuration methods to define its behavior and appearance. ```rust use serenity::builder::CreateSelectMenu; use serenity::model::application::component::CreateSelectMenuKind; let menu = CreateSelectMenu::new("my_custom_id", CreateSelectMenuKind::String { options: vec![] }) .placeholder("Select an option...") .min_values(1) .max_values(3) .disabled(false); ``` -------------------------------- ### Get Remaining Arguments as String (Rust) Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Args.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the remainder of available arguments as a single string slice, starting from the current offset. This function is deprecated. ```rust use serenity::framework::standard::{Args, Delimiter}; let mut args = Args::new("first second third", &[Delimiter::Single(' ')]); args.next(); // Consumes "first" assert_eq!(args.rest(), "second third"); ``` -------------------------------- ### Initialize a Serenity Client with Event Handler Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html Demonstrates how to instantiate a Client, define an EventHandler to respond to messages, and start the connection. ```rust use serenity::model::prelude::*; use serenity::prelude::*; use serenity::Client; struct Handler; #[serenity::async_trait] impl EventHandler for Handler { async fn message(&self, context: Context, msg: Message) { if msg.content == "!ping" { let _ = msg.channel_id.say(&context, "Pong!"); } } } let mut client = Client::builder("my token here", GatewayIntents::default()).event_handler(Handler).await?; client.start().await?; ``` -------------------------------- ### Example of Custom Help Command with `plain` in Serenity Source: https://docs.rs/serenity/latest/serenity/framework/standard/help_commands/fn.plain.html?search=std%3A%3Avec This example demonstrates how to create a custom help command using the `#[help]` macro and the `plain` function. It shows the necessary imports and how to configure the `StandardFramework` to use the custom help command. Note that the `plain` function is deprecated. ```rust use std::collections::HashSet; use std::hash::BuildHasher; use serenity::framework::standard::help_commands::* use serenity::framework::standard::macros::help; use serenity::framework::standard::{ Args, CommandGroup, CommandResult, HelpOptions, StandardFramework, }; use serenity::model::prelude::*; #[help] async fn my_help( context: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet, ) -> CommandResult { let _ = plain(context, msg, args, &help_options, groups, owners).await?; Ok(()) } let framework = StandardFramework::new().help(&MY_HELP); ``` -------------------------------- ### Initialize and Configure CreatePollAnswer Source: https://docs.rs/serenity/latest/serenity/builder/create_poll/struct.CreatePollAnswer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to instantiate the CreatePollAnswer builder and configure its properties using the fluent API. ```rust use serenity::builder::CreatePollAnswer; let poll_answer = CreatePollAnswer::new() .text("Option A") .emoji(emoji_data); ``` -------------------------------- ### Start a Specific Shard for Serenity Client (Rust) Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html?search=u32+-%3E+bool This example demonstrates how to start a specific shard for a Serenity Discord client. It's useful when manually managing sharding across multiple processes. You need to specify the shard ID and the total number of shards. This requires a Discord bot token and default gateway intents. ```rust use serenity::client::Client; use serenity::prelude::GatewayIntents; // Replace with your actual token retrieval logic let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; // Example: Start shard 3 out of 5 if let Err(why) = client.start_shard(3, 5).await { println!("Err with client: {:?}", why); } // Example: Start shard 0 out of 1 (equivalent to Self::start for a single shard) // if let Err(why) = client.start_shard(0, 1).await { // println!("Err with client: {:?}", why); // } ``` -------------------------------- ### Initialize CreateCommandOption Builder Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateCommandOption.html Demonstrates how to instantiate the builder with required fields including type, name, and description. ```rust let option = CreateCommandOption::new(CommandOptionType::String, "age", "Enter your age"); ``` -------------------------------- ### Configure and Execute Stage Instance Creation Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateStageInstance.html?search= Methods for initializing the builder, configuring parameters like topic and audit log reasons, and executing the request to the Discord API. ```Rust pub fn new(topic: impl Into) -> Self; pub fn topic(self, topic: impl Into) -> Self; pub fn send_start_notification(self, send_start_notification: bool) -> Self; pub fn audit_log_reason(self, reason: &'a str) -> Self; fn execute<'life0, 'async_trait>( self, cache_http: impl 'async_trait + CacheHttp, ctx: Self::Context<'life0>, ) -> Pin> + Send + 'async_trait>>; ``` -------------------------------- ### Start Serenity Client with Autosharding (Rust) Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html?search=u32+-%3E+bool This example shows how to start a Serenity Discord client using autosharding. The client automatically determines the optimal number of shards based on Discord's API recommendations. This is suitable for bots operating in more than 2500 guilds. It requires a Discord bot token and default gateway intents. ```rust use serenity::client::Client; use serenity::prelude::GatewayIntents; // Replace with your actual token retrieval logic let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start_autosharded().await { println!("Err with client: {:?}", why); } ``` -------------------------------- ### Initialize Serenity Client Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html Provides examples for initializing the client using standard, autosharded, and manual shard configurations. ```rust use serenity::Client; let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start().await { println!("Err with client: {:?}", why); } ``` ```rust use serenity::Client; let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start_autosharded().await { println!("Err with client: {:?}", why); } ``` ```rust use serenity::Client; let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()).await?; if let Err(why) = client.start_shard(3, 5).await { println!("Err with client: {:?}", why); } ``` -------------------------------- ### GET /guilds/{guild_id}/members Source: https://docs.rs/serenity/latest/serenity/model/id/struct.GuildId.html?search=u32+-%3E+bool Retrieves a list of members in a guild whose username or nickname starts with a provided string. An optional limit can be set for the number of results. ```APIDOC ## GET /guilds/{guild_id}/members ### Description Returns a list of `Member`s in a `Guild` whose username or nickname starts with a provided string. Optionally pass in the `limit` to limit the number of results. ### Method GET ### Endpoint `/guilds/{guild_id}/members` ### Parameters #### Path Parameters - **guild_id** (UserId) - Required - The ID of the guild. #### Query Parameters - **query** (string) - Required - The string to search for in usernames or nicknames. - **limit** (u64) - Optional - The maximum number of results to return. Minimum value is 1, maximum and default value is 1000. ### Response #### Success Response (200) - **members** (array) - A list of `Member` objects. #### Response Example ```json [ { "user": { "id": "222222222222222222", "username": "SearchUser", "discriminator": "5678", "avatar": null, "public_flags": 0 }, "nick": "SearchNick", "roles": [], "joined_at": "2023-02-15T10:30:00.000000+00:00", "deaf": false, "mute": false } ] ``` ### Errors - **Error::Http** - If the API returns an error. ``` -------------------------------- ### GET /guilds/{guild_id}/members/search Source: https://docs.rs/serenity/latest/serenity/model/id/struct.GuildId.html?search=std%3A%3Avec Searches for members within a guild whose username or nickname starts with a provided string. An optional limit can be set for the number of results. ```APIDOC ## GET /guilds/{guild_id}/members/search ### Description Returns a list of `Member`s in a `Guild` whose username or nickname starts with a provided string. ### Method GET ### Endpoint `/guilds/{guild_id}/members/search` ### Parameters #### Path Parameters - **guild_id** (Snowflake) - Required - The ID of the guild. #### Query Parameters - **query** (string) - Required - The string to search for in member usernames or nicknames. - **limit** (integer) - Optional - The maximum number of results to return. Minimum: 1, Maximum and Default: 1000. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **members** (array) - A list of `Member` objects matching the search query. #### Response Example ```json [ { "user": { "id": "112233445566778899", "username": "TestUser", "discriminator": "1234", "avatar": null, "public_flags": 0 }, "nick": "Tester", "roles": [], "joined_at": "2023-01-01T00:00:00.000000+00:00", "premium_since": null, "deaf": false, "mute": false, "guild_id": "123456789012345678" } ] ``` ##### §Errors Returns an `Error::Http` if the API returns an error. ``` -------------------------------- ### Initialize and Configure CreatePollAnswer Source: https://docs.rs/serenity/latest/serenity/builder/create_poll/struct.CreatePollAnswer.html?search=std%3A%3Avec Demonstrates how to instantiate the CreatePollAnswer builder and configure it using the available text and emoji methods. ```rust use serenity::builder::CreatePollAnswer; let poll_answer = CreatePollAnswer::new() .text("Option A") .emoji(some_poll_media_emoji); ``` -------------------------------- ### TryFrom and TryInto Conversions Source: https://docs.rs/serenity/latest/serenity/builder/struct.EditWebhook.html?search=std%3A%3Avec Documentation for the TryFrom and TryInto traits, which allow for fallible conversions between types. ```APIDOC ## TryFrom for T ### Description Provides a way to convert from type `U` to type `T`. ### Method `try_from(value: U) -> Result>::Error>` ### Parameters * `value` (U) - The value to convert from. ### Response #### Success Response (Ok) * `T` - The successfully converted value. #### Error Response (Err) * `>::Error` - The error encountered during conversion. ## TryInto for T ### Description Provides a way to convert from type `T` to type `U`. ### Method `try_into(self) -> Result>::Error>` ### Parameters * `self` (T) - The value to convert. ### Response #### Success Response (Ok) * `U` - The successfully converted value. #### Error Response (Err) * `>::Error` - The error encountered during conversion. ``` -------------------------------- ### GET /channels/{channel_id}/messages (Stream) Source: https://docs.rs/serenity/latest/serenity/model/channel/struct.MessagesIter.html?search=u32+-%3E+bool Streams over all messages in a specific channel. This helper uses a buffer of up to 100 messages to efficiently fetch message history starting from the newest. ```APIDOC ## GET /channels/{channel_id}/messages ### Description Streams over all the messages in a channel. This is equivalent to repeated calls to fetch message history, utilizing a buffer to reduce API call overhead. ### Method GET ### Endpoint /channels/{channel_id}/messages ### Parameters #### Path Parameters - **channel_id** (ChannelId) - Required - The ID of the channel to stream messages from. ### Request Example ```rust let mut messages = MessagesIter::::stream(&ctx, channel_id).boxed(); ``` ### Response #### Success Response (200) - **Message** (Object) - A message object containing author, content, and metadata. #### Response Example ```json { "author": { "name": "User" }, "content": "Hello world!" } ``` ``` -------------------------------- ### Constructing a ClientBuilder Source: https://docs.rs/serenity/latest/serenity/client/struct.ClientBuilder.html?search=std%3A%3Avec Demonstrates how to initialize a new ClientBuilder instance using either a token or an existing Http client instance. ```rust let builder = ClientBuilder::new("your_token_here", GatewayIntents::default()); // Or using an existing Http instance let builder = ClientBuilder::new_with_http(http_client, GatewayIntents::default()); ``` -------------------------------- ### Get Current Buffer Slice Source: https://docs.rs/serenity/latest/serenity/framework/standard/type.CommandError.html?search=std%3A%3Avec Returns a slice of the buffer starting at the current position. The length of the slice can be less than the remaining bytes, accommodating non-contiguous buffer representations. ```rust fn chunk(&self) -> &[u8]; ``` -------------------------------- ### Get Remaining Arguments (Rust) Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Args.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the remainder of available arguments as an `Option<&str>`, starting from the current offset. Returns `None` if no arguments remain. This function is deprecated. ```rust use serenity::framework::standard::{Args, Delimiter}; let mut args = Args::new("first second", &[Delimiter::Single(' ')]); args.next(); // Consumes "first" assert_eq!(args.remains(), Some("second")); args.next(); // Consumes "second" assert_eq!(args.remains(), None); ``` -------------------------------- ### Define and Configure StandardFramework Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.StandardFramework.html?search= Demonstrates how to instantiate a StandardFramework and apply configuration settings such as command prefixes and whitespace handling. ```rust use serenity::framework::standard::{Configuration, StandardFramework}; use serenity::Client; let framework = StandardFramework::new(); framework.configure(Configuration::new().with_whitespace(true).prefix("~")); let token = std::env::var("DISCORD_TOKEN")?; let mut client = Client::builder(&token, GatewayIntents::default()) .event_handler(Handler) .framework(framework) .await?; ``` -------------------------------- ### Rust: Initialize CreateSoundboard Builder Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateSoundboard.html?search= Provides the constructor `new` for the `CreateSoundboard` builder, initializing it with a required name and a sound file. The name must be between 2 and 32 characters. ```rust pub fn new(name: impl Into, sound: &CreateAttachment) -> Self ``` -------------------------------- ### Rust: Get mutable buffer slice Source: https://docs.rs/serenity/latest/serenity/framework/standard/type.CommandError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a mutable slice of the buffer starting from the current position. The slice length can be less than the total remaining space, allowing for non-contiguous buffer implementations. ```Rust impl BufMut for Box where T: BufMut + ?Sized, { fn chunk_mut(&mut self) -> &mut UninitSlice { // Implementation details... } } ``` -------------------------------- ### POST /client/start Source: https://docs.rs/serenity/latest/serenity/client/struct.Client.html Establishes a connection to the Discord gateway and begins event dispatching for a single-shard client. ```APIDOC ## POST /client/start ### Description Starts the client connection. This method is intended for bots in fewer than 2500 guilds. ### Method POST ### Endpoint /client/start ### Parameters #### Request Body - **token** (string) - Required - The Discord bot token. - **intents** (GatewayIntents) - Required - The gateway intents to subscribe to. ### Request Example { "token": "DISCORD_TOKEN", "intents": "default" } ### Response #### Success Response (200) - **status** (string) - Connection established successfully. #### Error Response (500) - **error** (ClientError) - Returns ClientError::Shutdown if shards fail. ``` -------------------------------- ### Get Guild Webhooks - Rust Source: https://docs.rs/serenity/latest/serenity/http/struct.Http.html?search=u32+-%3E+bool Retrieves the webhooks for a given guild ID. This method requires authentication and returns a list of Webhook objects. An example demonstrates how to fetch all webhooks for a guild. ```rust use serenity::model::id::GuildId; // Assuming 'http' is an instance of your HTTP client let guild_id = GuildId::new(81384788765712384); let webhooks = http.get_guild_webhooks(guild_id).await?; ``` -------------------------------- ### Retrieve Guild Object from Serenity Cache Source: https://docs.rs/serenity/latest/serenity/cache/struct.Cache.html?search=u32+-%3E+bool Provides an example of how to get a reference to a `Guild` object from the cache using its `GuildId`. The snippet shows how to access and print the guild's name once retrieved. ```rust // assuming the cache is in scope, e.g. via `Context` if let Some(guild) = cache.guild(7) { println!("Guild name: {}", guild.name); }; ``` -------------------------------- ### Initializing RwLock Instances Source: https://docs.rs/serenity/latest/serenity/prelude/struct.RwLock.html?search=u32+-%3E+bool Provides examples for creating RwLock instances using standard constructors and constant constructors for static initialization. It includes options for setting maximum reader limits. ```rust use tokio::sync::RwLock; // Standard initialization let lock1 = RwLock::new(5); // Initialization with reader limit let lock2 = RwLock::with_max_readers(5, 1024); // Static constant initialization static LOCK1: RwLock = RwLock::const_new(5); static LOCK2: RwLock = RwLock::const_with_max_readers(5, 1024); ``` -------------------------------- ### Get Remaining Arguments as a String Slice (Rust) Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Args.html?search=u32+-%3E+bool Returns a string slice representing the remainder of the arguments starting from the current offset. This is useful for capturing all remaining arguments as a single block of text. ```rust use serenity::framework::standard::Args; // Assuming 'args' is an instance of Args // let remaining_args_slice = args.rest(); ``` -------------------------------- ### Get JSON Value as f64 (Rust) Source: https://docs.rs/serenity/latest/serenity/json/type.Value.html?search= Provides an example of extracting a JSON Value as an `f64`. Returns Some(f64) if the value is a number, otherwise returns None. Handles both integers and floating-point numbers. ```rust let v = json!({ "a": 256.0, "b": 64, "c": -64 }); assert_eq!(v["a"].as_f64(), Some(256.0)); assert_eq!(v["b"].as_f64(), Some(64.0)); assert_eq!(v["c"].as_f64(), Some(-64.0)); ``` -------------------------------- ### Configure a Serenity Client with a Standard Framework Source: https://docs.rs/serenity/latest/serenity/framework/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to define commands and groups using macros, configure a command prefix, and attach the framework to a ClientBuilder instance. This setup enables automatic command routing for a Discord bot. ```rust use serenity::framework::standard::macros::{command, group}; use serenity::framework::standard::{CommandResult, Configuration, StandardFramework}; use serenity::model::channel::Message; use serenity::prelude::*; #[command] async fn about(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.say(&ctx.http, "A simple test bot").await?; Ok(()) } #[command] async fn ping(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.say(&ctx.http, "pong!").await?; Ok(()) } #[group] #[commands(about, ping)] struct General; struct Handler; impl EventHandler for Handler {} let token = std::env::var("DISCORD_TOKEN")?; let framework = StandardFramework::new() .group(&GENERAL_GROUP); framework.configure(Configuration::new().prefix("~")); let mut client = Client::builder(&token, GatewayIntents::default()) .event_handler(Handler) .framework(framework) .await?; ``` -------------------------------- ### Get Guild Webhooks - Rust Source: https://docs.rs/serenity/latest/serenity/http/struct.Http.html?search=std%3A%3Avec Retrieves all webhooks for a given guild. This method requires authentication and returns a list of Webhook objects. An example demonstrates how to fetch webhooks using an HTTP client. ```rust let guild_id = GuildId::new(81384788765712384); let webhooks = http.get_guild_webhooks(guild_id).await?; ``` -------------------------------- ### Initialize and Configure EditWebhook Source: https://docs.rs/serenity/latest/serenity/builder/struct.EditWebhook.html?search=std%3A%3Avec Demonstrates the initialization of the EditWebhook builder and the application of various configuration methods such as setting the name, channel, and avatar. ```rust use serenity::builder::EditWebhook; let webhook_builder = EditWebhook::new() .name("New Webhook Name") .channel_id(123456789012345678) .audit_log_reason("Updating webhook configuration"); ``` -------------------------------- ### ExecuteWebhook Usage Examples Source: https://docs.rs/serenity/latest/serenity/builder/struct.ExecuteWebhook.html?search= Demonstrates how to use the ExecuteWebhook builder to send messages to Discord webhooks, including adding embeds, overriding avatars, setting content, and executing within threads. ```Rust use serenity::builder::{CreateEmbed, ExecuteWebhook}; use serenity::http::Http; use serenity::model::webhook::Webhook; use serenity::model::Colour; let url = "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"; let webhook = Webhook::from_url(&http, url).await?; let website = CreateEmbed::new() .title("The Rust Language Website") .description("Rust is a systems programming language.") .colour(Colour::from_rgb(222, 165, 132)); let resources = CreateEmbed::new() .title("Rust Resources") .description("A few resources to help with learning Rust") .colour(0xDEA584) .field("The Rust Book", "A comprehensive resource for Rust.", false) .field("Rust by Example", "A collection of Rust examples", false); let builder = ExecuteWebhook::new() .content("Here's some information on Rust:") .embeds(vec![website, resources]); webhook.execute(&http, false, builder).await?; ``` ```Rust let builder = ExecuteWebhook::new() .avatar_url("https://i.imgur.com/KTs6whd.jpg") .content("Here's a webhook"); webhook.execute(&http, false, builder).await?; ``` ```Rust let builder = ExecuteWebhook::new().content("foo"); let execution = webhook.execute(&http, false, builder).await; if let Err(why) = execution { println!("Err sending webhook: {:?}", why); } ``` ```Rust let url = "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"; let mut webhook = Webhook::from_url(&http, url).await?; let builder = ExecuteWebhook::new().in_thread(12345678).content("test"); webhook.execute(&http, false, builder).await?; ``` -------------------------------- ### Constructing a Bot Invite URL with CreateBotAuthParameters Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateBotAuthParameters.html Demonstrates how to initialize the builder, configure application settings, and generate the final invite URL string. ```rust use serenity::builder::CreateBotAuthParameters; let params = CreateBotAuthParameters::new() .client_id(123456789012345678) .scopes(&[Scope::Bot, Scope::ApplicationsCommands]) .permissions(Permissions::SEND_MESSAGES) .guild_id(876543210987654321) .disable_guild_select(true); let url = params.build(); ``` -------------------------------- ### Get Cached Messages for a Channel in Serenity Source: https://docs.rs/serenity/latest/serenity/cache/struct.Cache.html?search=u32+-%3E+bool Demonstrates retrieving cached messages for a specific channel using `Cache::channel_messages`. The example shows how to filter these messages, for instance, to find messages sent by a particular user. ```rust let messages_in_channel = cache.channel_messages(7); let messages_by_user = messages_in_channel .as_ref() .map(|msgs| msgs.values().filter(|m| m.author.id == 8).collect::>()); ``` -------------------------------- ### Get Cache Settings Source: https://docs.rs/serenity/latest/serenity/cache/struct.Cache.html?search=std%3A%3Avec Retrieves the current cache settings, providing access to configuration parameters like the maximum number of messages to cache per channel. The example demonstrates how to access and print the `max_messages` setting. ```rust use serenity::cache::Cache; let mut cache = Cache::new(); println!("Max settings: {}", cache.settings().max_messages); ``` -------------------------------- ### Initialize CreateForumPost Builder Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateForumPost.html?search=u32+-%3E+bool Demonstrates the initialization of the CreateForumPost builder using the new constructor, which requires a name and message content. ```Rust use serenity::builder::CreateForumPost; use serenity::builder::CreateMessage; let message = CreateMessage::new().content("Hello world!"); let builder = CreateForumPost::new("My Forum Post", message); ``` -------------------------------- ### Initialize ShardManager Source: https://docs.rs/serenity/latest/serenity/gateway/struct.ShardManager.html?search=std%3A%3Avec Example of manually initializing a ShardManager with specific sharding configurations and event handlers. ```rust ShardManager::new(ShardManagerOptions { data, event_handlers: vec![event_handler], raw_event_handlers: vec![], framework: Arc::new(OnceLock::from(framework)), shard_index: 0, shard_init: 3, shard_total: 5, ws_url, intents: GatewayIntents::non_privileged(), presence: None, }); ``` -------------------------------- ### Get User Tag (Rust) Source: https://docs.rs/serenity/latest/serenity/model/user/struct.User.html?search=u32+-%3E+bool Returns the user's "tag", formatted as 'username#discriminator'. This function is available with the 'model' crate feature. An example demonstrates its use in a Discord bot command. ```rust pub fn tag(&self) -> String ``` -------------------------------- ### Retrieve Guild Member from Serenity Cache Source: https://docs.rs/serenity/latest/serenity/cache/struct.Cache.html?search=u32+-%3E+bool Illustrates fetching a `Member` object from the cache using both `GuildId` and `UserId`. The example demonstrates a practical scenario within an `EventHandler::message` context to get member role information. ```rust let roles_len = { let channel = match cache.channel(message.channel_id) { Some(channel) => channel, None => { if let Err(why) = message.channel_id.say(http, "Error finding channel data").await { println!("Error sending message: {:?}", why); } return; }, }; cache.member(channel.guild_id, message.author.id).map(|m| m.roles.len()) }; let message_res = if let Some(roles_len) = roles_len { let msg = format!("You have {} roles", roles_len); message.channel_id.say(&http, &msg).await } else { message.channel_id.say(&http, "Error finding member data").await }; if let Err(why) = message_res { println!("Error sending message: {:?}", why); } ``` -------------------------------- ### Serenity Framework Command Matching Example (Rust) Source: https://docs.rs/serenity/latest/serenity/framework/index.html?search=u32+-%3E+bool Illustrates how the Serenity framework matches message content to commands based on a prefix. It shows which inputs trigger commands and which do not, depending on whitespace and prefix characters. ```text ~ping // calls the ping command's function ~pin // does not ~ ping // _does_ call it _if_ the `allow_whitespace` option is enabled ~~ping // does not ``` -------------------------------- ### Initialize and Configure EditGuildWidget Source: https://docs.rs/serenity/latest/serenity/builder/struct.EditGuildWidget.html?search= Demonstrates how to instantiate the EditGuildWidget builder and use its fluent interface to set configuration options like enabled state, channel ID, and audit log reasons. ```rust use serenity::builder::EditGuildWidget; let widget = EditGuildWidget::new() .enabled(true) .channel_id(123456789012345678) .audit_log_reason("Updating widget settings"); ``` -------------------------------- ### Get Remaining Arguments as an Option (Rust) Source: https://docs.rs/serenity/latest/serenity/framework/standard/struct.Args.html?search=u32+-%3E+bool Returns an `Option<&str>` containing the remainder of the arguments starting from the current offset. Returns `None` if there are no arguments left. This is similar to `rest()` but explicitly handles the case of no remaining arguments. ```rust use serenity::framework::standard::Args; // Assuming 'args' is an instance of Args // let remaining_args_option = args.remains(); ``` -------------------------------- ### Initialize and Configure CreateWebhook Builder Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateWebhook.html?search=u32+-%3E+bool Demonstrates how to instantiate a new CreateWebhook builder and configure its properties like name and avatar. This builder is used to prepare data before executing the creation request. ```rust use serenity::builder::CreateWebhook; // Create a new builder instance let mut builder = CreateWebhook::new("My Webhook"); // Configure properties builder = builder.name("Updated Name"); builder = builder.audit_log_reason("Admin request"); ``` -------------------------------- ### Example: Get Green Component of a Role's Colour (Rust) Source: https://docs.rs/serenity/latest/serenity/model/colour/struct.Colour.html?search= Demonstrates how to retrieve the green component of a color associated with a role using the `serenity::model::Colour` struct. It assumes a `role` object with a `colour` field is available. ```rust use serenity::model::Colour; // assuming a `role` has already been bound let green = role.colour.g(); println!("The green component is: {}", green); ``` -------------------------------- ### Constructing an OAuth2 Invite Link with CreateBotAuthParameters Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateBotAuthParameters.html?search= Demonstrates how to initialize the builder, configure application settings such as client ID, scopes, and permissions, and finally generate the invite URL string. ```rust use serenity::builder::CreateBotAuthParameters; let params = CreateBotAuthParameters::new() .client_id(123456789012345678) .scopes(&[Scope::Bot, Scope::ApplicationsCommands]) .permissions(Permissions::SEND_MESSAGES) .build(); ``` -------------------------------- ### Example: Get Route Reset Time (Rust) Source: https://docs.rs/serenity/latest/serenity/http/struct.Ratelimiter.html Demonstrates how to access and print the reset time for a specific route using the `routes` method of the Ratelimiter. It involves acquiring read locks on the route map and the specific route's mutex. ```rust use serenity::http::Route; let routes = http.ratelimiter.unwrap().routes(); let reader = routes.read().await; let channel_id = ChannelId::new(7); let route = Route::Channel { channel_id, }; if let Some(route) = reader.get(&route.ratelimiting_bucket()) { if let Some(reset) = route.lock().await.reset() { println!("Reset time at: {:?}", reset); } } ``` -------------------------------- ### CreateCommand Builder Methods (Rust) Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateCommand.html?search= Demonstrates the usage of various methods available on the `CreateCommand` builder to configure Discord application commands. This includes setting names, localized names, descriptions, localized descriptions, options, permissions, and contexts. ```rust use serenity::builder::CreateCommand; use serenity::model::application::CommandType; use serenity::model::Permissions; use serenity::model::application::interaction::InteractionContext; // Example of creating a command with basic properties let mut command = CreateCommand::new("my_command"); command.description("A simple command"); // Example with localized names and descriptions command.name_localized("zh-CN", "我的命令"); command.description_localized("zh-CN", "一个简单的命令"); // Example setting other properties command.kind(CommandType::ChatInput); command.default_member_permissions(Permissions::ADMINISTRATOR); command.dm_permission(false); command.add_context(InteractionContext::Guild); command.nsfw(false); // Example adding an option (assuming CreateCommandOption is defined) // command.add_option(CreateCommandOption::default().name("input").description("User input").required(true).kind(ApplicationCommandOptionType::String)); // The command builder can then be executed to create the command on Discord. ``` -------------------------------- ### Initialise Method for VoiceGatewayManager (Rust) Source: https://docs.rs/serenity/latest/serenity/gateway/trait.VoiceGatewayManager.html?search=std%3A%3Avec The `initialise` method is called once at the start of a connection to Discord. It provides the bot's user ID and the total shard count, performing initial setup for the voice gateway manager. This method is part of the `VoiceGatewayManager` trait. ```rust fn initialise<'life0, 'async_trait>( &'life0 self, shard_count: u32, user_id: UserId, ) -> Pin + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait; ``` -------------------------------- ### Initialize and Configure CreateSelectMenuOption Source: https://docs.rs/serenity/latest/serenity/builder/struct.CreateSelectMenuOption.html?search=std%3A%3Avec Demonstrates how to instantiate a new select menu option and use the builder pattern methods to configure its properties such as label, value, description, emoji, and default selection status. ```rust use serenity::builder::CreateSelectMenuOption; let option = CreateSelectMenuOption::new("Option Label", "option_value") .description("This is a description") .emoji('😀') .default_selection(true); ``` -------------------------------- ### Handle Discord Typing Start Events (Rust) Source: https://docs.rs/serenity/latest/serenity/client/trait.EventHandler.html?search=u32+-%3E+bool Asynchronous function to handle the 'typing start' event on Discord, indicating a user has started typing a message. It receives the context and typing start event data. ```rust fn typing_start<'life0, 'async_trait>( &'life0 self, ctx: Context, event: TypingStartEvent, ) -> Pin + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait { // Implementation details } ```