### Client Initialization and Event Handling Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/struct.Client.html?search=u32+-%3E+bool This example demonstrates how to create a Client instance, set up an event handler to respond to messages, and start the client to connect to Discord. ```APIDOC ## Example: Ping-Pong Bot This example shows how to create a `Client` instance and add an event handler that responds to "!ping" messages with "Pong!". ```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!"); } } } // In your main function or wherever you initialize the client: // let mut client = Client::builder("my token here", GatewayIntents::default()).event_handler(Handler).await?; // client.start().await?; ``` ``` -------------------------------- ### Poise Framework Quickstart Example Source: https://docs.rs/poise/latest/poise/index.html?search= A basic example demonstrating how to set up and run a Poise Discord bot with a simple command. It includes user data definition, error handling, command registration, and client startup. ```Rust use poise::serenity_prelude as serenity; struct Data {} // User data, which is stored and accessible in all command invocations type Error = Box; type Context<'a> = poise::Context<'a, Data, Error>; /// Displays your or another user's account creation date #[poise::command(slash_command, prefix_command)] async fn age( ctx: Context<'_>, #[description = "Selected user"] user: Option, ) -> Result<(), Error> { let u = user.as_ref().unwrap_or_else(|| ctx.author()); let response = format!("{}'s account was created at {}", u.name, u.created_at()); ctx.say(response).await?; Ok(()) } #[tokio::main] async fn main() { let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN"); let intents = serenity::GatewayIntents::non_privileged(); let framework = poise::Framework::builder() .options(poise::FrameworkOptions { commands: vec![age()], ..Default::default() }) .setup(|ctx, _ready, framework| { Box::pin(async move { poise::builtins::register_globally(ctx, &framework.options().commands).await?; Ok(Data {{}}) }) }) .build(); let client = serenity::ClientBuilder::new(token, intents) .framework(framework) .await; client.unwrap().start().await.unwrap(); } ``` -------------------------------- ### Client Initialization and Event Handling Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/struct.Client.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to create a new Client instance, configure it with a token and gateway intents, attach an event handler, and start the bot. It also shows how to use the `data` field for custom state management. ```APIDOC ## Client Initialization and Event Handling This example shows how to create a `Client` instance, set up an `EventHandler`, and start the bot. It also includes an example of using the `data` field for custom state. ### Method `Client::builder()` followed by `event_handler()` and `start()` ### Example Usage ```rust use serenity::model::prelude::*; use serenity::prelude::*; use serenity::Client; use std::collections::HashMap; // Define a custom type for the TypeMap struct MessageEventCounter; impl TypeMapKey for MessageEventCounter { type Value = HashMap; } // Define the event handler struct struct Handler; #[serenity::async_trait] impl EventHandler for Handler { async fn message(&self, ctx: Context, msg: Message) { if msg.content == "!ping" { let _ = msg.channel_id.say(&context, "Pong!"); } // Example of updating custom data let mut data = ctx.data.write().await; let counter = data.entry("message_count".to_string()).or_insert(0); *counter += 1; } // Other event handlers can be implemented here } #[tokio::main] async fn main() -> Result<(), Box> { // Replace with your actual token let token = "YOUR_BOT_TOKEN".to_string(); let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT; // Create a new client builder let mut client = Client::builder(&token, intents) .event_handler(Handler) .await?; // Initialize custom data in the TypeMap { let mut data = client.data.write().await; data.insert::(HashMap::new()); data.insert("message_count".to_string(), 0u64); } // Start the client client.start().await?; Ok(()) } ``` ### Fields * **`data: Arc>`**: A shared, mutable map for storing custom data across different contexts. Useful for counters, database connections, etc. * **`shard_manager: Arc`**: Manages all active shards for the client. * **`ws_url: Arc>`**: The WebSocket URL for the gateway connection. * **`cache: Arc`**: Access to the Discord cache. * **`http: Arc`**: An HTTP client for making REST API requests. ``` -------------------------------- ### Client Initialization and Event Handling Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/prelude/struct.Client.html?search= This example demonstrates how to create a `Client` instance, configure an event handler, and start the client to connect to Discord. It showcases a simple "ping-pong" bot. ```APIDOC ## Examples ### Creating a Client instance and adding a handler on every message receive, acting as a “ping-pong” bot is simple: ```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? ``` ``` -------------------------------- ### Basic Ping-Pong Bot Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/struct.Client.html Demonstrates how to create a Serenity Client, set up an event handler for message creation, and start the bot. This example requires the 'client' and 'gateway' features. ```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?; ``` -------------------------------- ### Client Initialization and Event Handling Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/struct.Client.html Demonstrates how to create a Client instance, configure event handlers, and start the bot. This example shows a basic "ping-pong" bot that responds to the "!ping" command. ```APIDOC ## Client Initialization and Event Handling ### Description This example shows how to create a Serenity `Client` instance, set up an `EventHandler` to respond to messages, and then start the client to connect to Discord. It implements a simple "ping-pong" bot. ### Method ``` Client::builder(...).event_handler(...).await?; client.start().await?; ``` ### Endpoint N/A (SDK Method) ### Parameters #### Client Builder Parameters - **token** (string) - Required - The authentication token for your Discord bot. - **intents** (GatewayIntents) - Required - The gateway intents to subscribe to. #### Event Handler - **event_handler** (struct implementing `EventHandler`) - Required - A struct that defines how to handle various Discord events. ### Request Example ```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!"); } } } // In your main function or similar: let mut client = Client::builder("my token here", GatewayIntents::default()).event_handler(Handler).await?; client.start().await?; ``` ### Response #### Success Response - **Client**: A successfully built `Client` instance. - **Start**: The client connects to Discord and begins processing events. #### Response Example N/A (Asynchronous execution) ``` -------------------------------- ### Example Searches Source: https://docs.rs/poise/latest/poise/serenity_prelude/enum.InstallationContext.html?search= Provides examples of search queries that can be used with InstallationContext. ```APIDOC ## Example Searches ### Description Provides examples of search queries that can be used with InstallationContext. ### Example Queries - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### CreateCommandOption Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/builder/struct.CreateCommandOption.html?search= Provides examples of how to search for CreateCommandOption. These examples demonstrate different search patterns and types. ```APIDOC ## Search Examples ### Description This section provides example searches for CreateCommandOption. These examples illustrate common search queries and patterns. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### CreateSelectMenuOption Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/struct.CreateSelectMenuOption.html?search= Provides example searches for finding CreateSelectMenuOption. These examples demonstrate common search patterns and can be adapted for specific needs. ```APIDOC ## CreateSelectMenuOption Search Examples ### Description Provides example searches for finding CreateSelectMenuOption. These examples demonstrate common search patterns and can be adapted for specific needs. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Basic Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/prelude/enum.EntitlementKind.html?search= These examples demonstrate basic search patterns for EntitlementKind. ```rust * std::vec ``` ```rust u32 -> bool ``` ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Getting the Start Index of the Window Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.Window.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the starting index of the current window within the underlying buffer. ```rust pub fn start(&self) -> usize ``` -------------------------------- ### Framework::new Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html?search=u32+-%3E+bool Sets up a new Framework instance. It takes framework options and a setup callback for user data initialization. ```APIDOC ## Framework::new ### Description Sets up a new `Framework`. For more ergonomic setup, please see `FrameworkBuilder`. The user data callback is invoked as soon as the bot is logged in. The user data setup is not allowed to return Result because there would be no reasonable course of action on error. ### Method `new(options: FrameworkOptions, setup: F)` ### Endpoint N/A (SDK method) ### Parameters - **options** (`FrameworkOptions`): The framework configuration options. - **setup** (`F`): A callback function to initialize user data. It must be `Send + Sync + 'static` and implement `FnOnce(&'a Context, &'a Ready, &'a Self) -> BoxFuture<'a, Result>`. ### Request Example N/A ### Response Returns a `Self` (Framework) instance. ``` -------------------------------- ### AtomicWaker::new() Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/task/struct.AtomicWaker.html Creates a new AtomicWaker instance. This is the starting point for using AtomicWaker. ```rust pub const fn new() -> AtomicWaker ``` -------------------------------- ### InstallationContext Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/prelude/enum.InstallationContext.html?search= Demonstrates various ways to search within InstallationContext, including searching for types, type conversions, and generic function applications. ```APIDOC ## InstallationContext Search ### Description Provides examples of search queries for InstallationContext. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Create Empty Permissions Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/permissions/struct.Permissions.html?search= Get a `Permissions` value with all bits unset. Useful for starting with no permissions. ```rust pub const fn empty() -> Permissions ``` -------------------------------- ### Framework::new Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a new Framework instance with provided options and a setup function for user data. The setup function is called once the bot is logged in. ```APIDOC ## Framework::new ### Description Setup a new `Framework`. For more ergonomic setup, please see `FrameworkBuilder`. The user data callback is invoked as soon as the bot is logged in. That way, bot data like user ID or connected guilds can be made available to the user data setup function. The user data setup is not allowed to return Result because there would be no reasonable course of action on error. ### Method `pub fn new(options: FrameworkOptions, setup: F) -> Self` ### Type Parameters - `U`: The type of the user data. - `E`: The type of the error. - `F`: The type of the setup function, which must be `Send + Sync + 'static` and implement `FnOnce(&'a Context, &'a Ready, &'a Self) -> BoxFuture<'a, Result>`. ### Parameters - **options**: `FrameworkOptions` - The framework options. - **setup**: `F` - The user data setup function. ``` -------------------------------- ### AsyncBufReadExt: fill_buf Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/trait.AsyncBufReadExt.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use fill_buf to get a non-empty buffer or EOF. Requires Unpin. ```rust use futures::{io::AsyncBufReadExt as _, stream::{iter, TryStreamExt as _}}; let mut stream = iter(vec![Ok(vec![1, 2, 3]), Ok(vec![4, 5, 6])]).into_async_read(); assert_eq!(stream.fill_buf().await?, vec![1, 2, 3]); stream.consume_unpin(2); assert_eq!(stream.fill_buf().await?, vec![3]); stream.consume_unpin(1); assert_eq!(stream.fill_buf().await?, vec![4, 5, 6]); stream.consume_unpin(3); assert_eq!(stream.fill_buf().await?, vec![]); ``` -------------------------------- ### STARTED_HOME_ACTIONS Flag Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/guild/struct.GuildMemberFlags.html Indicates that a member has started Server Guide new member actions. This flag is not editable. ```rust pub const STARTED_HOME_ACTIONS: GuildMemberFlags ``` -------------------------------- ### Example Help Command Implementation Source: https://docs.rs/poise/latest/poise/builtins/fn.help.html?search= An example of how to implement a help command using `poise::builtins::help`. This includes setting up custom help text and default configurations. ```rust /// Show this menu #[poise::command(prefix_command, track_edits, slash_command)] pub async fn help( ctx: Context<'_>, #[description = "Specific command to show help about"] command: Option, ) -> Result<(), Error> { let config = poise::builtins::HelpConfiguration { extra_text_at_bottom: "\"Type ?help command for more info on a command.\nYou can edit your message to the bot and the bot will edit its response.", ..Default::default() }; poise::builtins::help(ctx, command.as_deref(), config).await?; Ok(()) } ``` -------------------------------- ### Client::start Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/struct.Client.html Establishes the connection and starts listening for events. This method is suitable for bots in less than 2500 guilds. ```APIDOC ## Client::start ### Description Establish the connection and start listening for events. This will start receiving events in a loop and start dispatching the events to your registered handlers. Note that this should be used only for users and for bots which are in less than 2500 guilds. If you have a reason for sharding and/or are in more than 2500 guilds, use one of these depending on your use case: Refer to the Gateway documentation for more information on effectively using sharding. ### Method `async fn start(&mut self) -> Result<(), Error>` ### Errors Returns a `ClientError::Shutdown` when all shards have shutdown due to an error. ### Example ```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); } ``` ``` -------------------------------- ### Getting Window Bounds Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.Window.html Retrieves the current start and end indices that define the window's view into the underlying buffer. ```rust pub fn start(&self) -> usize ``` ```rust pub fn end(&self) -> usize ``` -------------------------------- ### Client Initialization and Event Handling Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/struct.Client.html?search=std%3A%3Avec Demonstrates how to create a new Client instance, configure it with a bot token and gateway intents, assign an event handler, and start the client to connect to Discord. ```APIDOC ## Client::builder ### Description Initializes a new `Client` builder with the provided token and gateway intents. This builder can then be used to configure event handlers and other client options before creating the `Client` instance. ### Method Associated function (constructor-like) ### Parameters - **token** (`&str`) - Required - The authentication token for your Discord bot. - **intents** (`GatewayIntents`) - Required - The gateway intents to subscribe to for receiving events. ### Endpoint N/A (SDK method) ### Request Body N/A ### Response #### Success Response Returns a `ClientBuilder` which can be further configured. ### Example ```rust use serenity::prelude::*; use serenity::Client; // Define your event handler struct 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!"); } } } // Inside an async function or block: let token = "your_bot_token_here"; let intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES; let mut client = Client::builder(token, intents) .event_handler(Handler) .await?; // To start the client: client.start().await?; ``` ## Client::start ### Description Starts the client, establishing the WebSocket connection and beginning to process events. ### Method Instance method ### Endpoint N/A (SDK method) ### Parameters N/A ### Request Body N/A ### Response #### Success Response This method runs indefinitely until the client disconnects or an error occurs. ### Example (See Client::builder example above) ``` -------------------------------- ### StreamExt::next() Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.Lines.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `next()` method from the `StreamExt` trait to get the next item from a stream. This requires the stream to be `Unpin`. ```rust async fn example(stream: &mut S) -> Option { stream.next().await } ``` -------------------------------- ### Get current cursor position Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.Cursor.html Returns the current byte position within the cursor's buffer. This example demonstrates seeking and checking the position. ```rust use futures::io::{AsyncSeekExt, Cursor, SeekFrom}; let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); assert_eq!(buff.position(), 0); buff.seek(SeekFrom::Current(2)).await?; assert_eq!(buff.position(), 2); buff.seek(SeekFrom::Current(-1)).await?; assert_eq!(buff.position(), 1); ``` -------------------------------- ### Initialize New Framework Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html?search=u32+-%3E+bool Sets up a new `Framework` instance. The user data callback is invoked upon bot login to make data like user ID or guild information available. This setup function cannot return a `Result` due to the lack of a reasonable error handling course. ```rust pub fn new(options: FrameworkOptions, setup: F) -> Self where F: Send + Sync + 'static + for<'a> FnOnce(&'a Context, &'a Ready, &'a Self) -> BoxFuture<'a, Result>, U: Send + Sync + 'static, E: Send + 'static, ``` -------------------------------- ### Get Role by Name Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/guild/struct.Guild.html?search=std%3A%3Avec Demonstrates how to obtain a reference to a Role by its name within a cached guild. If multiple roles share the same name, one of them will be returned. ```rust impl EventHandler for Handler { async fn message(&self, ctx: Context, msg: Message) { if let Some(guild_id) = msg.guild_id { if let Some(guild) = guild_id.to_guild_cached(&ctx) { if let Some(role) = guild.role_by_name("role_name") { println!("{:?}", role); } } } } } ``` -------------------------------- ### Setup New Framework Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a new Framework instance. The user data callback is invoked upon bot login to make bot data available. This method is less ergonomic than using `FrameworkBuilder`. ```rust pub fn new(options: FrameworkOptions, setup: F) -> Self where F: Send + Sync + 'static + for<'a> FnOnce(&'a Context, &'a Ready, &'a Self) -> BoxFuture<'a, Result>, U: Send + Sync + 'static, E: Send + 'static, ``` -------------------------------- ### FrameworkBuilder::setup Source: https://docs.rs/poise/latest/poise/framework/struct.FrameworkBuilder.html Sets the setup callback for the framework. This callback is executed during framework initialization and can return user data. ```APIDOC ## pub fn setup(self, setup: F) -> Self ### Description Sets the setup callback which also returns the user data struct. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Not applicable (method on a builder) ### Endpoint Not applicable (method on a builder) ### Request Example Not applicable (method on a builder) ### Response #### Success Response Returns `Self` (the builder instance) with the setup callback configured. #### Response Example Not applicable (method on a builder) ``` -------------------------------- ### Rust unfold Example: Creating a Stream Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/prelude/stream/fn.unfold.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to use the 'unfold' function to create a stream of numbers. It starts with a state of 0 and generates values by doubling the state, incrementing the state, and stopping when the state exceeds 2. The collected stream is then asserted to match the expected output. ```rust use futures::stream::{self, StreamExt}; let stream = stream::unfold(0, |state| async move { if state <= 2 { let next_state = state + 1; let yielded = state * 2; Some((yielded, next_state)) } else { None } }); let result = stream.collect::>().await; assert_eq!(result, vec![0, 2, 4]); ``` -------------------------------- ### Get Role by Name Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/guild/struct.Guild.html?search=u32+-%3E+bool Obtains a reference to a role by its name. If multiple roles share the same name, one of them is returned. This example demonstrates usage within an event handler. ```rust #[serenity::async_trait] #[cfg(all(feature = "cache", feature = "client"))] impl EventHandler for Handler { async fn message(&self, ctx: Context, msg: Message) { if let Some(guild_id) = msg.guild_id { if let Some(guild) = guild_id.to_guild_cached(&ctx) { if let Some(role) = guild.role_by_name("role_name") { println!("{:?}", role); } } } } } ``` -------------------------------- ### Framework Command Prefix Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/framework/index.html Illustrates how commands are invoked based on a prefix and potential whitespace options. ```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 ``` -------------------------------- ### Get User's Tag Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/prelude/struct.User.html Returns the user's tag in the format 'username#discriminator'. This example demonstrates how to use it within a command. Requires the 'model' crate feature. ```rust pub fn tag(&self) -> String ``` ```rust #[serenity::async_trait] impl EventHandler for Handler { async fn message(&self, context: Context, msg: Message) { if msg.content == "!mytag" { let content = format!("Your tag is: {}", msg.author.tag()); let _ = msg.channel_id.say(&context.http, &content).await; } } } ``` -------------------------------- ### Framework::new Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html?search= Sets up a new Framework instance. The user data callback is invoked as soon as the bot is logged in to set up bot data. For more ergonomic setup, use `FrameworkBuilder`. ```APIDOC ## Framework::new ### Description Setup a new `Framework`. For more ergonomic setup, please see `FrameworkBuilder` The user data callback is invoked as soon as the bot is logged in. That way, bot data like user ID or connected guilds can be made available to the user data setup function. The user data setup is not allowed to return Result because there would be no reasonable course of action on error. ### Method `pub fn new(options: FrameworkOptions, setup: F) -> Self` ### Type Parameters - `U`: Type of the user data. - `E`: Type of the error. - `F`: Type of the setup function. ### Parameters - **options** (`FrameworkOptions`): The framework options. - **setup** (`F`): A function that takes context, ready event, and the framework, and returns user data or an error. ``` -------------------------------- ### Setting the Setup Callback Source: https://docs.rs/poise/latest/poise/framework/struct.FrameworkBuilder.html?search=u32+-%3E+bool Configures the setup callback for the framework. This callback is essential and runs during framework initialization, returning user data. ```rust pub fn setup(self, setup: F) -> Self where F: Send + Sync + 'static + for<'a> FnOnce(&'a Context, &'a Ready, &'a Framework) -> BoxFuture<'a, Result> ``` -------------------------------- ### Example: Get Reset Time for a Route Source: https://docs.rs/poise/latest/poise/serenity_prelude/http/struct.Ratelimiter.html?search= Demonstrates how to access the ratelimiter's routes and retrieve the reset time for a specific channel ID route. Requires the 'http' feature. ```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); } } ``` -------------------------------- ### Get Full Invocation String Source: https://docs.rs/poise/latest/poise/structs/struct.ApplicationContext.html?search=std%3A%3Avec Returns the complete string used to invoke the command, including arguments. Example: `"/slash_command subcommand arg1:value1 arg2:value2"`. ```rust pub fn invocation_string(self) -> String ``` -------------------------------- ### Framework::new Source: https://docs.rs/poise/latest/poise/framework/struct.Framework.html Sets up a new Framework instance. The user data callback is invoked as soon as the bot is logged in to provide access to bot data. ```APIDOC ## Framework::new ### Description Setup a new `Framework`. For more ergonomic setup, please see `FrameworkBuilder` The user data callback is invoked as soon as the bot is logged in. That way, bot data like user ID or connected guilds can be made available to the user data setup function. The user data setup is not allowed to return Result because there would be no reasonable course of action on error. ### Method `pub fn new(options: FrameworkOptions, setup: F) -> Self` ### Type Parameters * `U`: The type of the user data. * `E`: The type of the error. * `F`: The type of the setup function. ### Parameters * **options** (`FrameworkOptions`): The framework options. * **setup** (`F`): A function that takes context, ready event, and the framework, and returns user data. ``` -------------------------------- ### Example Searches for CreateChannel Source: https://docs.rs/poise/latest/poise/serenity_prelude/builder/struct.CreateChannel.html?search= Demonstrates common search patterns for the CreateChannel builder, including searching for standard library types, type conversions, and generic type transformations. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Iterating Over Reverse Chunks Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSliceMut.html?search= Use `rchunks` to get an iterator over slices of a specified `chunk_size`, starting from the end of the slice. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = [0, 1, 2, 3, 4, 5]; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &[4, 5]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert_eq!(iter.next().unwrap(), &[0, 1]); assert!(iter.next().is_none()); ``` -------------------------------- ### OptionFuture Usage Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/prelude/future/struct.OptionFuture.html?search=std%3A%3Avec Demonstrates how to create and await an OptionFuture. It shows initialization from Some and None, and verifies the awaited output. ```rust use futures::future::OptionFuture; let mut a: OptionFuture<_> = Some(async { 123 }).into(); assert_eq!(a.await, Some(123)); a = None.into(); assert_eq!(a.await, None); ``` -------------------------------- ### Mutably iterating over chunks from the end of a slice Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSliceMut.html?search= Use `rchunks_mut` to get an iterator over mutable chunks of a specified size, starting from the end of the slice. This allows in-place modification of slice elements within each chunk. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### TakeUntil Example: Retrieving the Stopping Future's Result Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/prelude/stream/struct.TakeUntil.html Demonstrates how to use the `take_result` method to get the output of the future that stops the stream. This is useful for obtaining reasons or data associated with the stream's termination. ```Rust use futures::future; use futures::stream::{self, StreamExt}; use futures::task::Poll; let stream = stream::iter(1..=10); let mut i = 0; let stop_fut = future::poll_fn(|_cx| { i += 1; if i <= 5 { Poll::Pending } else { Poll::Ready("reason") } }); let mut stream = stream.take_until(stop_fut); let _ = stream.by_ref().collect::>().await; let result = stream.take_result().unwrap(); assert_eq!(result, "reason"); ``` -------------------------------- ### Configuring a Serenity Client with a Standard Framework Source: https://docs.rs/poise/latest/poise/serenity_prelude/framework/index.html?search=std%3A%3Avec This example demonstrates how to set up a Serenity client with a standard command framework. It includes defining commands, grouping them, and configuring the framework with a prefix and event handler. ```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() // The `#[group]` (and similarly, `#[command]`) macro generates static instances // containing any options you gave it. For instance, the group `name` and its `commands`. // Their identifiers, names you can use to refer to these instances in code, are an // all-uppercased version of the `name` with a `_GROUP` suffix appended at the end. .group(&GENERAL_GROUP); framework.configure(Configuration::new().prefix("~")); let mut client = Client::builder(&token, GatewayIntents::default()) .event_handler(Handler) .framework(framework) .await?; ``` -------------------------------- ### Example Usage for ~register Command Source: https://docs.rs/poise/latest/poise/builtins/fn.register_application_commands.html This example shows how to implement a `~register` command in your bot using `register_application_commands`. It explains how to register commands in the current guild or globally based on arguments. ```rust Registers application commands in this guild or globally Run with no arguments to register in guild, run with argument "global" to register globally. ``` -------------------------------- ### CreateChannel Builder Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/builder/struct.CreateChannel.html Demonstrates how to create a new channel builder with a specified name. This is the initial step for configuring a new channel. ```rust pub struct CreateChannel<'a> { /* private fields */ } ``` -------------------------------- ### Unsafe access to disjoint mutable slices with RangeInclusive indices Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSliceMut.html?search= This example demonstrates using `get_disjoint_unchecked_mut` with `RangeInclusive` indices to get mutable references to sub-slices. It's crucial to ensure indices are within bounds and do not overlap, as this is an unsafe operation. ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]); a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(x, &[1, 11, 111]); ``` -------------------------------- ### Iterating over exact chunks from the end of a slice Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSlice.html Use `rchunks_exact` to get an iterator over non-overlapping chunks of a specified size, starting from the end. Elements that do not form a full chunk are available via the `remainder` method. Panics if `chunk_size` is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### Example Searches for CreateStageInstance Source: https://docs.rs/poise/latest/poise/serenity_prelude/builder/struct.CreateStageInstance.html?search= Demonstrates common search patterns for the CreateStageInstance builder. These examples illustrate how to query for standard library types, type conversions, and generic type operations. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Iterating over chunks from the end of a slice Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSlice.html Use `rchunks` to get an iterator over non-overlapping chunks of a specified size, starting from the end of the slice. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. Panics if `chunk_size` is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Async Task System Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/index.html Demonstrates how to build and use the task system context within macros and keywords like async and await. This example shows the creation of futures, sending data through an asynchronous channel, collecting results, and executing the main future. ```Rust fn main() { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); // Create a future by an async block, where async is responsible for an // implementation of Future. At this point no executor has been provided // to this future, so it will not be running. let fut_values = async { // Create another async block, again where the Future implementation // is generated by async. Since this is inside of a parent async block, // it will be provided with the executor of the parent block when the parent // block is executed. // // This executor chaining is done by Future::poll whose second argument // is a std::task::Context. This represents our executor, and the Future // implemented by this async block can be polled using the parent async // block's executor. let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; // Use the provided thread pool to spawn the generated future // responsible for transmission pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); // Use the executor provided to this async block to wait for the // future to complete. fut_values.await }; // Actually execute the above future, which will invoke Future::poll and // subsequently chain appropriate Future::poll and methods needing executors // to drive all futures. Eventually fut_values will be driven to completion. let values: Vec = executor::block_on(fut_values); println!("Values={{:?}}", values); } ``` -------------------------------- ### Safe access to disjoint mutable slices with Range indices Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/io/struct.IoSliceMut.html?search= This example shows how to safely get mutable references to sub-slices using `get_disjoint_mut` with `Range` indices. The method returns a `Result`, ensuring that errors from invalid or overlapping ranges are handled. ```rust let v = &mut [1, 2, 3]; if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) { a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(v, &[8, 88, 888]); ``` -------------------------------- ### Create Echo Command Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/application/struct.Command.html?search=u32+-%3E+bool Example demonstrating how to create a command that echoes user input. ```APIDOC ## Example: Echo Command ### Description Creates a command named "echo" that takes a string argument and makes the bot send that message back. ### Code Example ```rust use serenity::builder::{CreateCommand, CreateCommandOption as CreateOption}; use serenity::model::application::{Command, CommandOptionType}; 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_integration_sync Source: https://docs.rs/poise/latest/poise/serenity_prelude/http/struct.Http.html?search=std%3A%3Avec Starts syncing an integration with a guild. ```APIDOC ## start_integration_sync ### Description Starts syncing an integration with a guild. ### Method POST ### Endpoint /guilds/{guild_id}/integrations/{integration_id}/sync ### Parameters #### Path Parameters - **guild_id** (GuildId) - Required - The ID of the guild. - **integration_id** (IntegrationId) - Required - The ID of the integration to sync. ``` -------------------------------- ### Get Column Number from JsonError Source: https://docs.rs/poise/latest/poise/serenity_prelude/json/struct.JsonError.html?search=u32+-%3E+bool Returns the one-based column number at which the error was detected. The first character in the input and any characters immediately following a newline character are in column 1. Note that errors may occur in column 0, for example if a read from an I/O stream fails immediately following a previously read newline character. ```rust pub fn column(&self) -> usize ``` -------------------------------- ### VideoQualityMode Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/enum.VideoQualityMode.html?search= Provides examples of how to search for VideoQualityMode. These examples demonstrate different search patterns and types. ```APIDOC ## VideoQualityMode Search ### Description Provides examples of how to search for VideoQualityMode. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Example: Sending a Welcome Message with Mentions Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/mention/trait.Mentionable.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `mention` method on `Member` and `ChannelId` to create a formatted welcome message. ```rust use serenity::model::mention::Mentionable; async fn greet( ctx: Context, member: Member, to_channel: GuildChannel, rules_channel: ChannelId, ) -> Result<(), Error> { let builder = CreateMessage::new().content(format!( "Hi {member}, welcome to the server! \ Please refer to {rules} for our code of conduct, \ and enjoy your stay.", member = member.mention(), rules = rules_channel.mention(), )); to_channel.id.send_message(ctx, builder).await?; Ok(()) } ``` -------------------------------- ### Typing Start Event Handler Source: https://docs.rs/poise/latest/poise/serenity_prelude/client/trait.EventHandler.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Handles the 'Typing Start' event, which is sent when a user starts typing in a channel. ```rust fn typing_start<'life0, 'async_trait>( &'life0 self, ctx: Context, event: TypingStartEvent, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, Self: 'async_trait { // Implementation details for handling typing start events unimplemented!() } ``` -------------------------------- ### Mention All Users and Specific Roles Source: https://docs.rs/poise/latest/poise/serenity_prelude/struct.CreateAllowedMentions.html?search= Example demonstrating how to allow mentions for all users and specific roles. ```rust // Mention all users and the role 182894738100322304 m.allowed_mentions(Am::new().all_users(true).roles(vec![182894738100322304])); ``` -------------------------------- ### Model Error Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/enum.ModelError.html?search= Provides examples of how to search for model errors. These examples demonstrate common search patterns. ```APIDOC ## Model Error Search ### Description This section provides examples of how to search for model errors. These examples demonstrate common search patterns for identifying specific error types or error transformations. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Simple Example Source: https://docs.rs/poise/latest/poise/serenity_prelude/futures/prelude/future/fn.select.html A simple example demonstrating the usage of the `select` function to wait for one of two futures to complete. ```APIDOC ## Example: Simple Usage ### Description This example shows how to use `select` with two futures that have different types but produce the same output type. It demonstrates how to extract the resolved value using a `match` statement on the `Either` enum. ### Code ```rust use core::pin::pin; use futures::future; use futures::future::Either; // These two futures have different types even though their outputs have the same type. let future1 = async { future::pending::<()>().await; // will never finish 1 }; let future2 = async { future::ready(2).await }; // 'select' requires Future + Unpin bounds let future1 = pin!(future1); let future2 = pin!(future2); let value = match future::select(future1, future2).await { Either::Left((value1, _)) => value1, // `value1` is resolved from `future1` // `_` represents `future2` Either::Right((value2, _)) => value2, // `value2` is resolved from `future2` // `_` represents `future1` }; assert!(value == 2); ``` ``` -------------------------------- ### ScheduledEventPrivacyLevel Search Examples Source: https://docs.rs/poise/latest/poise/serenity_prelude/model/prelude/enum.ScheduledEventPrivacyLevel.html?search= Examples of how to search for ScheduledEventPrivacyLevel. These examples demonstrate searching by type, type conversion, and generic type mapping. ```APIDOC ## ScheduledEventPrivacyLevel Search ### Description Provides examples for searching ScheduledEventPrivacyLevel. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Create and Configure Poise Framework Source: https://docs.rs/poise/latest/poise/index.html?search= This snippet demonstrates how to build a Poise framework instance. It shows the use of `Framework::builder()` to supply basic data and `FrameworkOptions` for detailed configuration, including error handling, prefix options, and command definitions. It concludes with setting up a Serenity client and starting the bot. ```rust use poise::serenity_prelude as serenity; // Use `Framework::builder()` to create a framework builder and supply basic data to the framework: let framework = poise::Framework::builder() .setup(|_, _, _| Box::pin(async move { // construct user data here (invoked when bot connects to Discord) Ok(()) })) // Most configuration is done via the `FrameworkOptions` struct, which you can define with // a struct literal (hint: use `..Default::default()` to fill uninitialized // settings with their default value): .options(poise::FrameworkOptions { on_error: |err| Box::pin(my_error_function(err)), prefix_options: poise::PrefixFrameworkOptions { prefix: Some("~".into()), edit_tracker: Some(Arc::new(poise::EditTracker::for_timespan(std::time::Duration::from_secs(3600)))), case_insensitive_commands: true, ..Default::default() }, // This is also where commands go commands: vec![ command1(), command2(), // You can also modify a command by changing the fields of its Command instance poise::Command { // [override fields here] ..command3() } ], ..Default::default() }).build(); let client = serenity::ClientBuilder::new("...", serenity::GatewayIntents::non_privileged()) .framework(framework).await; client.unwrap().start().await.unwrap(); ```