Struct twilight_gateway::shard::Shard[][src]

pub struct Shard(_);
Expand description

Shard to run and manage a session with the gateway.

Shards are responsible for handling incoming events, process events relevant to the operation of shards - such as requests from the gateway to re-connect or invalidate a session - and then pass the events on to the user via an event stream.

Shards will go through a queue to initialize new ratelimited sessions with the ratelimit. Refer to Discord’s documentation on shards to have a better understanding of what they are.

Cloning

The shard internally wraps its data within an Arc. This means that the shard can be cloned and passed around tasks and threads cheaply.

Examples

Create and start a shard and print new and deleted messages:

use futures::stream::StreamExt;
use std::env;
use twilight_gateway::{EventTypeFlags, Event, Intents, Shard};

// Use the value of the "DISCORD_TOKEN" environment variable as the bot's
// token. Of course, you may pass this into your program however you want.
let token = env::var("DISCORD_TOKEN")?;
let event_types = EventTypeFlags::MESSAGE_CREATE | EventTypeFlags::MESSAGE_DELETE;

let (shard, mut events) = Shard::builder(token, Intents::GUILD_MESSAGES)
    .event_types(event_types)
    .build();

// Start the shard.
shard.start().await?;

// Create a loop of only new message and deleted message events.

while let Some(event) = events.next().await {
    match event {
        Event::MessageCreate(message) => {
            println!("message received with content: {}", message.content);
        },
        Event::MessageDelete(message) => {
            println!("message with ID {} deleted", message.id);
        },
        _ => {},
    }
}

Implementations

Create a new unconfigured shard.

Use start to initiate the gateway session.

Examples

Create a new shard and start it, wait a second, and then print its current connection stage:

use twilight_gateway::{Intents, Shard};
use std::{env, time::Duration};
use tokio::time as tokio_time;

let token = env::var("DISCORD_TOKEN")?;

let intents = Intents::GUILD_MESSAGES | Intents::GUILD_MESSAGE_TYPING;
let (shard, _) = Shard::new(token, intents);
shard.start().await?;

tokio_time::sleep(Duration::from_secs(1)).await;

let info = shard.info()?;
println!("Shard stage: {}", info.stage());

Create a builder to configure and construct a shard.

Refer to the builder for more information.

Return an immutable reference to the configuration used for this client.

Start the shard, connecting it to the gateway and starting the process of receiving and processing events.

Errors

Returns a ShardStartErrorType::Establishing error type if establishing a connection to the gateway failed.

Returns a ShardStartErrorType::ParsingGatewayUrl error type if the gateway URL couldn’t be parsed.

Returns a ShardStartErrorType::RetrievingGatewayUrl error type if the gateway URL couldn’t be retrieved from the HTTP API.

Retrieve information about the running of the shard, such as the current connection stage.

Errors

Returns a SessionInactiveError if the shard’s session is inactive.

Send a command over the gateway.

Errors

Returns a CommandErrorType::Sending error type if the message could not be sent over the websocket. This indicates the shard is currently restarting.

Returns a CommandErrorType::Serializing error type if the provided value failed to serialize into JSON.

Returns a CommandErrorType::SessionInactive error type if the shard has not been started.

Send a raw websocket message.

Examples

Send a ping message:

use std::env;
use twilight_gateway::{shard::{raw_message::Message, Shard}, Intents};

let token = env::var("DISCORD_TOKEN")?;
let (shard, _) = Shard::new(token, Intents::GUILDS);
shard.start().await?;

shard.send(Message::Ping(Vec::new())).await?;

Send a normal close (you may prefer to use shutdown):

use std::{borrow::Cow, env};
use twilight_gateway::{
    shard::{
        raw_message::{CloseFrame, Message},
        Shard,
    },
    Intents,
};

let token = env::var("DISCORD_TOKEN")?;
let (shard, _) = Shard::new(token, Intents::GUILDS);
shard.start().await?;

let close = CloseFrame::from((1000, ""));
let message = Message::Close(Some(close));
shard.send(message).await?;

Errors

Returns a SendErrorType::Sending error type if there is an issue with sending via the shard’s session. This may occur when the shard is between sessions.

Returns SendErrorType::SessionInactive error type when the shard has not been started.

👎 Deprecated since 0.3.0:

Use send which is more versatile

Send a raw command over the gateway.

This method should be used with caution, command should be preferred.

Errors

Returns a CommandErrorType::Sending error type if the message could not be sent over the websocket. This indicates the shard is currently restarting.

Returns a CommandErrorType::Serializing error type if the provided value failed to serialize into JSON.

Returns a CommandErrorType::SessionInactive error type if the shard has not been started.

Shut down the shard.

The shard will cleanly close the connection by sending a normal close code, causing Discord to show the bot as being offline. The session will not be resumable.

Shut down the shard in a resumable fashion.

The shard will cleanly close the connection by sending a restart close code, causing Discord to keep the bot as showing online. The connection will be resumable by using the provided session resume information to ClusterBuilder::resume_sessions.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.