Movatterモバイル変換


[0]ホーム

URL:


Docs.rs

StructShard

Source
pub struct Shard {    pub client:WsClient,    pub started:Instant,    pub token:String,    pub intents:GatewayIntents,/* private fields */}
Available oncrate featuregateway only.
Expand description

A Shard is a higher-level handler for a websocket connection to Discord’s gateway.

The shard allows for sending and receiving messages over the websocket, such as setting theactive activity, reconnecting, syncing guilds, and more.

Refer to themodule-level documentation for information on effectively usingmultiple shards, if you need to.

Note that there are additional methods available if you are manually managing a shard yourself,although they are hidden from the documentation since there are few use cases for doing such.

§Stand-alone shards

You may instantiate a shard yourself - decoupled from theClient - if you need to. For mostuse cases, you will not need to do this, and you can leave the client to do it.

This can be done by passing in the required parameters toSelf::new. You can then manuallyhandle the shard yourself.

Note: Youreally do not need to do this. Just call one of the appropriate methods on theClient.

§Examples

See the documentation forSelf::new on how to use this.

Fields§

§client:WsClient§started:Instant

Instant of when the shard was started.

§token:String§intents:GatewayIntents

Implementations§

Source§

implShard

Source

pub async fnnew( ws_url:Arc<Mutex<String>>, token: &str, shard_info:ShardInfo, intents:GatewayIntents, presence:Option<PresenceData>,) ->Result<Shard>

Instantiates a new instance of a Shard, bypassing the client.

Note: You should likely never need to do this yourself.

§Examples

Instantiating a new Shard manually for a bot with no shards, and then listening for events:

usestd::sync::Arc;useserenity::gateway::Shard;useserenity::model::gateway::{GatewayIntents, ShardInfo};useserenity::model::id::ShardId;usetokio::sync::Mutex;lettoken = std::env::var("DISCORD_BOT_TOKEN")?;letshard_info = ShardInfo {    id: ShardId(0),    total:1,};// retrieve the gateway response, which contains the URL to connect toletgateway = Arc::new(Mutex::new(http.get_gateway().await?.url));letshard = Shard::new(gateway,&token, shard_info, GatewayIntents::all(),None).await?;// at this point, you can create a `loop`, and receive events and match// their variants
§Errors

On Error, will return eitherError::Gateway,Error::Tungstenite or a Rustls/nativeTLS error.

Source

pub fnset_application_id_callback( &mut self, callback: implFnOnce(ApplicationId) +Send +Sync + 'static,)

Sets a callback to be called when the gateway receives the application’s ID from Discord.

Used internally by serenity to set the Http’s internal application ID automatically.

Source

pub fnpresence(&self) -> &PresenceData

Retrieves the current presence of the shard.

Source

pub fnlast_heartbeat_sent(&self) ->Option<Instant>

Retrieves the value of when the last heartbeat was sent.

Source

pub fnlast_heartbeat_ack(&self) ->Option<Instant>

Retrieves the value of when the last heartbeat ack was received.

Source

pub async fnheartbeat(&mut self) ->Result<()>

Sends a heartbeat to the gateway with the current sequence.

This sets the last heartbeat time to now, andSelf::last_heartbeat_acknowledged tofalse.

§Errors

ReturnsGatewayError::HeartbeatFailed if there was an error sending a heartbeat.

Source

pub fnheartbeat_interval(&self) ->Option<Duration>

Returns the heartbeat interval dictated by Discord, if the Hello packet has been received.

Source

pub fnlast_heartbeat_acknowledged(&self) ->bool

Source

pub fnseq(&self) ->u64

Source

pub fnsession_id(&self) ->Option<&String>

Source

pub fnset_activity(&mut self, activity:Option<ActivityData>)

Source

pub fnset_presence( &mut self, activity:Option<ActivityData>, status:OnlineStatus,)

Source

pub fnset_status(&mut self, status:OnlineStatus)

Source

pub fnshard_info(&self) ->ShardInfo

Retrieves a copy of the current shard information.

For example, if using 3 shards in total, and if this is shard 1, then it can be read as“the second of three shards”.

Source

pub fnstage(&self) ->ConnectionStage

Returns the current connection stage of the shard.

Source

pub fnhandle_event( &mut self, event: &Result<GatewayEvent>,) ->Result<Option<ShardAction>>

Handles an event from the gateway over the receiver, requiring the receiver to be passed ifa reconnect needs to occur.

The best case scenario is that one of two values is returned:

  • Ok(None): a heartbeat, late hello, or session invalidation was received;
  • Ok(Some((event, None))): an op0 dispatch was received, and the shard’s voice state willbe updated,if thevoice feature is enabled.
§Errors

Returns aGatewayError::InvalidAuthentication if invalid authentication was sent in theIDENTIFY.

Returns aGatewayError::InvalidShardData if invalid shard data was sent in theIDENTIFY.

Returns aGatewayError::NoAuthentication if no authentication was sent in the IDENTIFY.

Returns aGatewayError::OverloadedShard if the shard would have too many guildsassigned to it.

Source

pub async fndo_heartbeat(&mut self) ->bool

Does a heartbeat if needed. Returns false if something went wrong and the shard should berestarted.

true is returned under one of the following conditions:

  • the heartbeat interval has not elapsed
  • a heartbeat was successfully sent
  • there is no known heartbeat interval yet

false is returned under one of the following conditions:

  • a heartbeat acknowledgement was not received in time
  • an error occurred while heartbeating
Source

pub fnlatency(&self) ->Option<StdDuration>

Calculates the heartbeat latency between the shard and the gateway.

Source

pub fnshould_reconnect(&mut self) ->Option<ReconnectType>

Performs a deterministic reconnect.

The type of reconnect is deterministic on whether aSelf::session_id.

If thesession_id still exists, then a RESUME is sent. If not, then an IDENTIFY is sent.

Note that, if the shard is already in a stage ofConnectionStage::Connecting, then noaction will be performed.

Source

pub fnreconnection_type(&self) ->ReconnectType

Source

pub async fnchunk_guild( &mut self, guild_id:GuildId, limit:Option<u16>, presences:bool, filter:ChunkGuildFilter, nonce:Option<&str>,) ->Result<()>

Requests that one or multipleGuilds be chunked.

This will ask the gateway to start sending member chunks for large guilds (250 members+).If a guild is over 250 members, then a full member list will not be downloaded, and mustinstead be requested to be sent in “chunks” containing members.

Member chunks are sent as theEvent::GuildMembersChunk event. Each chunk only containsa partial amount of the total members.

If thecache feature is enabled, the cache will automatically be updated with memberchunks.

§Examples

Chunk a single guild by Id, limiting to 2000Members, and notspecifying a query parameter:

useserenity::model::id::GuildId;shard.chunk_guild(GuildId::new(81384788765712384),Some(2000),false, ChunkGuildFilter::None,None).await?;

Chunk a single guild by Id, limiting to 20 members, and specifying a query parameter of"do" and a nonce of"request":

useserenity::model::id::GuildId;shard    .chunk_guild(        GuildId::new(81384788765712384),Some(20),false,        ChunkGuildFilter::Query("do".to_owned()),Some("request"),    )    .await?;
Source

pub async fnidentify(&mut self) ->Result<()>

Sets the shard as going into identifying stage, which sets:

Source

pub async fninitialize(&mut self) ->Result<WsClient>

Initializes a new WebSocket client.

This will set the stage of the shard before and after instantiation of the client.

Source

pub async fnreset(&mut self)

Source

pub async fnresume(&mut self) ->Result<()>

Source

pub async fnreconnect(&mut self) ->Result<()>

Source

pub async fnupdate_presence(&mut self) ->Result<()>

Auto Trait Implementations§

§

impl !Freeze forShard

§

impl !RefUnwindSafe forShard

§

implSend forShard

§

implSync forShard

§

implUnpin forShard

§

impl !UnwindSafe forShard

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T>Instrument for T

Source§

fninstrument(self, span:Span) ->Instrumented<Self>

Instruments this type with the providedSpan, returning anInstrumented wrapper.Read more
Source§

fnin_current_span(self) ->Instrumented<Self>

Instruments this type with thecurrentSpan, returning anInstrumented wrapper.Read more
Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T>Same for T

Source§

typeOutput = T

Should always beSelf
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T>VZip<V> for T
where V:MultiLane<T>,

Source§

fnvzip(self) -> V

Source§

impl<T>WithSubscriber for T

Source§

fnwith_subscriber<S>(self, subscriber: S) ->WithDispatch<Self>
where S:Into<Dispatch>,

Attaches the providedSubscriber to this type, returning aWithDispatch wrapper.Read more
Source§

fnwith_current_subscriber(self) ->WithDispatch<Self>

Attaches the currentdefaultSubscriber to this type, returning aWithDispatch wrapper.Read more
Source§

impl<T>ErasedDestructor for T
where T: 'static,


[8]ページ先頭

©2009-2025 Movatter.jp