code
stringlengths 40
729k
| docstring
stringlengths 22
46.3k
| func_name
stringlengths 1
97
| language
stringclasses 1
value | repo
stringlengths 6
48
| path
stringlengths 8
176
| url
stringlengths 47
228
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
pub fn time_remaining(&self) -> TimeRemaining {
let reset_after = self.reset_after();
let maybe_started_at = *self.started_at.lock().expect("bucket poisoned");
let Some(started_at) = maybe_started_at else {
return TimeRemaining::NotStarted;
};
let elapsed = started_at.elapsed();
if elapsed > Duration::from_millis(reset_after) {
return TimeRemaining::Finished;
}
TimeRemaining::Some(Duration::from_millis(reset_after) - elapsed)
}
|
Time remaining until this bucket will reset.
|
time_remaining
|
rust
|
twilight-rs/twilight
|
twilight-http-ratelimiting/src/in_memory/bucket.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-http-ratelimiting/src/in_memory/bucket.rs
|
ISC
|
pub fn try_reset(&self) -> bool {
if self.started_at.lock().expect("bucket poisoned").is_none() {
return false;
}
if let TimeRemaining::Finished = self.time_remaining() {
self.remaining.store(self.limit(), Ordering::Relaxed);
*self.started_at.lock().expect("bucket poisoned") = None;
true
} else {
false
}
}
|
Try to reset this bucket's [`started_at`] value if it has finished.
Returns whether resetting was possible.
[`started_at`]: Self::started_at
|
try_reset
|
rust
|
twilight-rs/twilight
|
twilight-http-ratelimiting/src/in_memory/bucket.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-http-ratelimiting/src/in_memory/bucket.rs
|
ISC
|
async fn next(&self) -> Option<TicketNotifier> {
tracing::debug!(path=?self.path, "starting to get next in queue");
self.wait_if_needed().await;
self.bucket.queue.pop(Self::WAIT).await
}
|
Get the next [`TicketNotifier`] in the queue.
|
next
|
rust
|
twilight-rs/twilight
|
twilight-http-ratelimiting/src/in_memory/bucket.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-http-ratelimiting/src/in_memory/bucket.rs
|
ISC
|
fn entry(&self, path: Path, tx: TicketNotifier) -> Option<Arc<Bucket>> {
let mut buckets = self.buckets.lock().expect("buckets poisoned");
match buckets.entry(path.clone()) {
Entry::Occupied(bucket) => {
tracing::debug!("got existing bucket: {path:?}");
bucket.get().queue.push(tx);
tracing::debug!("added request into bucket queue: {path:?}");
None
}
Entry::Vacant(entry) => {
tracing::debug!("making new bucket for path: {path:?}");
let bucket = Bucket::new(path);
bucket.queue.push(tx);
let bucket = Arc::new(bucket);
entry.insert(Arc::clone(&bucket));
Some(bucket)
}
}
}
|
Enqueue the [`TicketNotifier`] to the [`Path`]'s [`Bucket`].
Returns the new [`Bucket`] if none existed.
|
entry
|
rust
|
twilight-rs/twilight
|
twilight-http-ratelimiting/src/in_memory/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-http-ratelimiting/src/in_memory/mod.rs
|
ISC
|
pub fn new(user_id: Id<UserMarker>, shard_count: u32) -> Self {
Self::_new_with_resume(user_id, shard_count, None)
}
|
Create a new Lavalink client instance.
The user ID and number of shards provided may not be modified during
runtime, and the client must be re-created. These parameters are
automatically passed to new nodes created via [`add`].
See also [`new_with_resume`], which allows you to specify session resume
capability.
[`add`]: Self::add
[`new_with_resume`]: Self::new_with_resume
|
new
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub fn new_with_resume(
user_id: Id<UserMarker>,
shard_count: u32,
resume: impl Into<Option<Resume>>,
) -> Self {
Self::_new_with_resume(user_id, shard_count, resume.into())
}
|
Like [`new`], but allows you to specify resume capability (if any).
Provide `None` for the `resume` parameter to disable session resume
capability. See the [`Resume`] documentation for defaults.
[`Resume`]: crate::node::Resume
[`new`]: Self::new
|
new_with_resume
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub async fn process(&self, event: &Event) -> Result<(), ClientError> {
tracing::trace!("processing event: {event:?}");
let guild_id = match event {
Event::Ready(e) => {
let shard_id = e.shard.map_or(0, ShardId::number);
self.clear_shard_states(shard_id);
return Ok(());
}
Event::VoiceServerUpdate(e) => {
self.server_updates.insert(e.guild_id, e.clone());
e.guild_id
}
Event::VoiceStateUpdate(e) => {
if e.user_id != self.user_id {
tracing::trace!("got voice state update from another user");
return Ok(());
}
if let Some(guild_id) = e.guild_id {
// Update player if it exists and update the connected channel ID.
if let Some(player) = self.players.get(&guild_id) {
player.set_channel_id(e.channel_id);
}
if e.channel_id.is_none() {
self.sessions.remove(&guild_id);
self.server_updates.remove(&guild_id);
} else {
self.sessions
.insert(guild_id, e.session_id.clone().into_boxed_str());
}
guild_id
} else {
tracing::trace!("event has no guild ID: {e:?}");
return Ok(());
}
}
_ => return Ok(()),
};
tracing::debug!("got voice server/state update for {guild_id:?}: {event:?}");
let update = {
let server = self.server_updates.get(&guild_id);
let session = self.sessions.get(&guild_id);
match (server, session) {
(Some(server), Some(session)) => {
let server = server.value();
let session = session.value();
tracing::debug!(
"got both halves for {guild_id}: {server:?}; Session ID: {session:?}",
);
VoiceUpdate::new(guild_id, session.as_ref(), server.clone())
}
(Some(server), None) => {
tracing::debug!(
"guild {guild_id} is now waiting for other half; got: {:?}",
server.value()
);
return Ok(());
}
(None, Some(session)) => {
tracing::debug!(
"guild {guild_id} is now waiting for other half; got session ID: {:?}",
session.value()
);
return Ok(());
}
_ => return Ok(()),
}
};
tracing::debug!("getting player for guild {guild_id}");
let player = self.player(guild_id).await?;
tracing::debug!("sending voice update for guild {guild_id}: {update:?}");
player.send(update).map_err(|source| ClientError {
kind: ClientErrorType::SendingVoiceUpdate,
source: Some(Box::new(source)),
})?;
tracing::debug!("sent voice update for guild {guild_id}");
Ok(())
}
|
Process an event into the Lavalink client.
**Note**: calling this method in your event loop is required. See the
[crate documentation] for an example.
This requires the `VoiceServerUpdate` and `VoiceStateUpdate` events that
you receive from Discord over the gateway to send voice updates to
nodes. For simplicity in some applications' event loops, any event can
be provided, but they will just be ignored.
The Ready event can optionally be provided to do some cleaning of
stalled voice states that never received their voice server update half
or vice versa. It is recommended that you process Ready events.
# Errors
Returns a [`ClientErrorType::NodesUnconfigured`] error type if no nodes
have been added to the client when attempting to retrieve a guild's
player.
[crate documentation]: crate#examples
|
process
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub async fn add(
&self,
address: SocketAddr,
authorization: impl Into<String>,
) -> Result<(Arc<Node>, IncomingEvents), NodeError> {
let config = NodeConfig {
address,
authorization: authorization.into(),
resume: self.resume.clone(),
user_id: self.user_id,
};
let (node, rx) = Node::connect(config, self.players.clone()).await?;
let node = Arc::new(node);
self.nodes.insert(address, Arc::clone(&node));
Ok((node, rx))
}
|
Add a new node to be managed by the Lavalink client.
If a node already exists with the provided address, then it will be
replaced.
# Errors
See the errors section of [`Node::connect`].
|
add
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub async fn best(&self) -> Result<Arc<Node>, ClientError> {
let mut lowest = i32::MAX;
let mut best = None;
for node in &self.nodes {
if node.sender().is_closed() {
continue;
}
let penalty = node.value().penalty().await;
if penalty < lowest {
lowest = penalty;
best.replace(node.clone());
}
}
best.ok_or(ClientError {
kind: ClientErrorType::NodesUnconfigured,
source: None,
})
}
|
Determine the "best" node for new players according to available nodes'
penalty scores. Disconnected nodes will not be considered.
Refer to [`Node::penalty`] for how this is calculated.
# Errors
Returns a [`ClientErrorType::NodesUnconfigured`] error type if there are
no connected nodes available in the client.
[`Node::penalty`]: crate::node::Node::penalty
|
best
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub async fn player(&self, guild_id: Id<GuildMarker>) -> Result<Arc<Player>, ClientError> {
if let Some(player) = self.players().get(&guild_id) {
return Ok(player);
}
let node = self.best().await?;
Ok(self.players().get_or_insert(guild_id, node))
}
|
Retrieve a player for the guild.
Creates a player configured to use the best available node if a player
for the guild doesn't already exist. Use [`PlayerManager::get`] to only
retrieve and not create.
# Errors
Returns a [`ClientError`] with a [`ClientErrorType::NodesUnconfigured`]
type if no node has been configured via [`add`].
[`PlayerManager::get`]: crate::player::PlayerManager::get
[`add`]: Self::add
|
player
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
fn clear_shard_states(&self, shard_id: u32) {
let shard_count = u64::from(self.shard_count);
self.server_updates
.retain(|k, _| (k.get() >> 22) % shard_count != u64::from(shard_id));
self.sessions
.retain(|k, _| (k.get() >> 22) % shard_count != u64::from(shard_id));
}
|
Clear out the map of guild states/updates for a shard that are waiting
for their other half.
We can do this by iterating over the map and removing the ones that we
can calculate came from a shard.
This map should be small or empty, and if it isn't, then it needs to be
cleared out anyway.
|
clear_shard_states
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/client.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/client.rs
|
ISC
|
pub fn load_track(
address: SocketAddr,
identifier: impl AsRef<str>,
authorization: impl AsRef<str>,
) -> Result<Request<&'static [u8]>, HttpError> {
let identifier =
percent_encoding::percent_encode(identifier.as_ref().as_bytes(), NON_ALPHANUMERIC);
let url = format!("http://{address}/loadtracks?identifier={identifier}");
let mut req = Request::get(url);
let auth_value = HeaderValue::from_str(authorization.as_ref())?;
req = req.header(AUTHORIZATION, auth_value);
req.body(b"")
}
|
Get a list of tracks that match an identifier.
The response will include a body which can be deserialized into a
[`LoadedTracks`].
# Errors
See the documentation for [`http::Error`].
|
load_track
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/http.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/http.rs
|
ISC
|
pub fn get_route_planner(
address: SocketAddr,
authorization: impl AsRef<str>,
) -> Result<Request<&'static [u8]>, HttpError> {
let mut req = Request::get(format!("{address}/routeplanner/status"));
let auth_value = HeaderValue::from_str(authorization.as_ref())?;
req = req.header(AUTHORIZATION, auth_value);
req.body(b"")
}
|
Get the configured route planner for a node by address.
The response will include a body which can be deserialized into a
[`RoutePlanner`].
# Errors
See the documentation for [`http::Error`].
|
get_route_planner
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/http.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/http.rs
|
ISC
|
pub fn new(guild_id: Id<GuildMarker>, pause: bool) -> Self {
Self::from((guild_id, pause))
}
|
Create a new pause event.
Set to `true` to pause the player or `false` to resume it.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/model.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/model.rs
|
ISC
|
pub fn send(&self, msg: OutgoingEvent) -> Result<(), NodeSenderError> {
self.inner.send(msg).map_err(|source| NodeSenderError {
kind: NodeSenderErrorType::Sending,
source: Some(Box::new(source)),
})
}
|
Sends a message along this channel.
This is an unbounded sender, so this function differs from `Sink::send`
by ensuring the return type reflects that the channel is always ready to
receive messages.
# Errors
Returns a [`NodeSenderErrorType::Sending`] error type if node is no
longer connected.
|
send
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/node.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/node.rs
|
ISC
|
pub const fn new(seconds: u64) -> Self {
Self { timeout: seconds }
}
|
Configure resume capability, providing the number of seconds that the
Lavalink server should queue events for when the connection is resumed.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/node.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/node.rs
|
ISC
|
pub fn new(
user_id: Id<UserMarker>,
address: impl Into<SocketAddr>,
authorization: impl Into<String>,
resume: impl Into<Option<Resume>>,
) -> Self {
Self::_new(user_id, address.into(), authorization.into(), resume.into())
}
|
Create a new configuration for connecting to a node via
[`Node::connect`].
If adding a node through the [`Lavalink`] client then you don't need to
do this yourself.
[`Lavalink`]: crate::client::Lavalink
|
new
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/node.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/node.rs
|
ISC
|
pub async fn connect(
config: NodeConfig,
players: PlayerManager,
) -> Result<(Self, IncomingEvents), NodeError> {
let (bilock_left, bilock_right) = BiLock::new(Stats {
cpu: StatsCpu {
cores: 0,
lavalink_load: 0f64,
system_load: 0f64,
},
frames: None,
memory: StatsMemory {
allocated: 0,
free: 0,
used: 0,
reservable: 0,
},
players: 0,
playing_players: 0,
op: Opcode::Stats,
uptime: 0,
});
tracing::debug!("starting connection to {}", config.address);
let (conn_loop, lavalink_tx, lavalink_rx) =
Connection::connect(config.clone(), players.clone(), bilock_right).await?;
tracing::debug!("started connection to {}", config.address);
tokio::spawn(conn_loop.run());
Ok((
Self {
config,
lavalink_tx,
players,
stats: bilock_left,
},
IncomingEvents { inner: lavalink_rx },
))
}
|
Connect to a node, providing a player manager so that the node can
update player details.
Please refer to the [module] documentation for some additional
information about directly creating and using nodes. You are encouraged
to use the [`Lavalink`] client instead.
[`Lavalink`]: crate::client::Lavalink
[module]: crate
# Errors
Returns an error of type [`Connecting`] if the connection fails after
several backoff attempts.
Returns an error of type [`BuildingConnectionRequest`] if the request
failed to build.
Returns an error of type [`Unauthorized`] if the supplied authorization
is rejected by the node.
[`Connecting`]: crate::node::NodeErrorType::Connecting
[`BuildingConnectionRequest`]: crate::node::NodeErrorType::BuildingConnectionRequest
[`Unauthorized`]: crate::node::NodeErrorType::Unauthorized
|
connect
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/node.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/node.rs
|
ISC
|
pub fn sender(&self) -> NodeSender {
NodeSender {
inner: self.lavalink_tx.clone(),
}
}
|
Retrieve a unique sender to send events to the Lavalink server.
Note that sending player events through the node's sender won't update
player states, such as whether it's paused.
|
sender
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/node.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/node.rs
|
ISC
|
pub fn get(&self, guild_id: &Id<GuildMarker>) -> Option<Arc<Player>> {
self.players.get(guild_id).map(|r| Arc::clone(r.value()))
}
|
Return an immutable reference to a player by guild ID.
|
get
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/player.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/player.rs
|
ISC
|
pub fn get_or_insert(&self, guild_id: Id<GuildMarker>, node: Arc<Node>) -> Arc<Player> {
let player = self
.players
.entry(guild_id)
.or_insert_with(|| Arc::new(Player::new(guild_id, node)));
Arc::clone(&player)
}
|
Return a mutable reference to a player by guild ID or insert a new
player linked to a given node.
|
get_or_insert
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/player.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/player.rs
|
ISC
|
pub fn destroy(&self, guild_id: Id<GuildMarker>) -> Result<(), NodeSenderError> {
if let Some(player) = self.get(&guild_id) {
player
.node()
.send(OutgoingEvent::from(Destroy::new(guild_id)))?;
self.players.remove(&guild_id);
}
Ok(())
}
|
Destroy a player on the remote node and remove it from the [`PlayerManager`].
# Errors
Returns a [`NodeSenderErrorType::Sending`] error type if node is no
longer connected.
[`NodeSenderErrorType::Sending`]: crate::node::NodeSenderErrorType::Sending
|
destroy
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/player.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/player.rs
|
ISC
|
pub(crate) fn set_channel_id(&self, channel_id: Option<Id<ChannelMarker>>) {
self.channel_id
.store(channel_id.map_or(0_u64, Id::get), Ordering::Release);
}
|
Sets the channel ID the player is currently connected to.
|
set_channel_id
|
rust
|
twilight-rs/twilight
|
twilight-lavalink/src/player.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-lavalink/src/player.rs
|
ISC
|
fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
where
Self: Sized,
{
let (id, maybe_modifier, found) = parse_mention(buf, Self::SIGILS)?;
for sigil in Id::<ChannelMarker>::SIGILS {
if *sigil == found {
return Ok(MentionType::Channel(Id::from(id)));
}
}
for sigil in Id::<EmojiMarker>::SIGILS {
if *sigil == found {
return Ok(MentionType::Emoji(Id::from(id)));
}
}
for sigil in Id::<RoleMarker>::SIGILS {
if *sigil == found {
return Ok(MentionType::Role(Id::from(id)));
}
}
for sigil in Timestamp::SIGILS {
if *sigil == found {
let maybe_style = parse_maybe_style(maybe_modifier)?;
return Ok(MentionType::Timestamp(Timestamp::new(
id.get(),
maybe_style,
)));
}
}
for sigil in Id::<UserMarker>::SIGILS {
if *sigil == found {
return Ok(MentionType::User(Id::from(id)));
}
}
unreachable!("mention type must have been found");
}
|
Parse a mention from a string slice.
# Examples
Returns [`ParseMentionErrorType::TimestampStyleInvalid`] if a timestamp
style value is invalid.
[`ParseMentionError::TimestampStyleInvalid`]: super::error::ParseMentionErrorType::TimestampStyleInvalid
|
parse
|
rust
|
twilight-rs/twilight
|
twilight-mention/src/parse/impl.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-mention/src/parse/impl.rs
|
ISC
|
fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
where
Self: Sized,
{
let (unix, maybe_modifier, _) = parse_mention(buf, Self::SIGILS)?;
Ok(Timestamp::new(
unix.get(),
parse_maybe_style(maybe_modifier)?,
))
}
|
Parse a timestamp from a string slice.
# Examples
Returns [`ParseMentionErrorType::TimestampStyleInvalid`] if the
timestamp style value is invalid.
[`ParseMentionError::TimestampStyleInvalid`]: super::error::ParseMentionErrorType::TimestampStyleInvalid
|
parse
|
rust
|
twilight-rs/twilight
|
twilight-mention/src/parse/impl.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-mention/src/parse/impl.rs
|
ISC
|
fn parse_maybe_style(value: Option<&str>) -> Result<Option<TimestampStyle>, ParseMentionError<'_>> {
Ok(if let Some(modifier) = value {
Some(
TimestampStyle::try_from(modifier).map_err(|source| ParseMentionError {
kind: ParseMentionErrorType::TimestampStyleInvalid { found: modifier },
source: Some(Box::new(source)),
})?,
)
} else {
None
})
}
|
Parse a possible style value string slice into a [`TimestampStyle`].
# Errors
Returns [`ParseMentionErrorType::TimestampStyleInvalid`] if the timestamp
style value is invalid.
|
parse_maybe_style
|
rust
|
twilight-rs/twilight
|
twilight-mention/src/parse/impl.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-mention/src/parse/impl.rs
|
ISC
|
fn parse_mention<'a>(
buf: &'a str,
sigils: &'a [&'a str],
) -> Result<(NonZeroU64, Option<&'a str>, &'a str), ParseMentionError<'a>> {
let mut chars = buf.chars();
let c = chars.next();
if c != Some('<') {
return Err(ParseMentionError {
kind: ParseMentionErrorType::LeadingArrow { found: c },
source: None,
});
}
let maybe_sigil = sigils.iter().find(|sigil| {
if chars.as_str().starts_with(*sigil) {
for _ in 0..sigil.chars().count() {
chars.next();
}
return true;
}
false
});
let sigil = if let Some(sigil) = maybe_sigil {
*sigil
} else {
return Err(ParseMentionError {
kind: ParseMentionErrorType::Sigil {
expected: sigils,
found: chars.next(),
},
source: None,
});
};
if sigil == ":" && !separator_sigil_present(&mut chars) {
return Err(ParseMentionError {
kind: ParseMentionErrorType::PartMissing {
found: 1,
expected: 2,
},
source: None,
});
}
let end_position = chars
.as_str()
.find('>')
.ok_or_else(|| ParseMentionError::trailing_arrow(None))?;
let maybe_split_position = chars.as_str().find(':');
let end_of_id_position = maybe_split_position.unwrap_or(end_position);
let remaining = chars
.as_str()
.get(..end_of_id_position)
.ok_or_else(|| ParseMentionError::trailing_arrow(None))?;
let num = remaining.parse().map_err(|source| ParseMentionError {
kind: ParseMentionErrorType::IdNotU64 { found: remaining },
source: Some(Box::new(source)),
})?;
// If additional information - like a timestamp style - is present then we
// can just get a subslice of the string via the split and ending positions.
let style = maybe_split_position.and_then(|split_position| {
chars.next();
// We need to remove 1 so we don't catch the `>` in it.
let style_end_position = end_position - 1;
chars.as_str().get(split_position..style_end_position)
});
Ok((num, style, sigil))
}
|
# Errors
Returns [`ParseMentionErrorType::LeadingArrow`] if the leading arrow is not
present.
Returns [`ParseMentionErrorType::Sigil`] if the mention type's sigil is not
present after the leading arrow.
Returns [`ParseMentionErrorType::TrailingArrow`] if the trailing arrow is
not present after the ID.
|
parse_mention
|
rust
|
twilight-rs/twilight
|
twilight-mention/src/parse/impl.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-mention/src/parse/impl.rs
|
ISC
|
pub const fn is_guild(self) -> bool {
matches!(
self,
Self::GuildCategory
| Self::GuildDirectory
| Self::GuildAnnouncement
| Self::AnnouncementThread
| Self::PublicThread
| Self::PrivateThread
| Self::GuildStageVoice
| Self::GuildText
| Self::GuildVoice
| Self::GuildMedia
)
}
|
Whether the channel type is that of a guild.
The following channel types are considered guild channel types:
- [`AnnouncementThread`][`Self::AnnouncementThread`]
- [`GuildAnnouncement`][`Self::GuildAnnouncement`]
- [`GuildCategory`][`Self::GuildCategory`]
- [`GuildDirectory`][`Self::GuildDirectory`]
- [`GuildStageVoice`][`Self::GuildStageVoice`]
- [`GuildText`][`Self::GuildText`]
- [`GuildVoice`][`Self::GuildVoice`]
- [`PublicThread`][`Self::PublicThread`]
- [`PrivateThread`][`Self::PrivateThread`]
- [`GuildMedia`][`Self::GuildMedia`]
|
is_guild
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/channel_type.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/channel_type.rs
|
ISC
|
pub const fn is_thread(self) -> bool {
matches!(
self,
Self::AnnouncementThread | Self::PublicThread | Self::PrivateThread
)
}
|
Whether the channel type is a thread.
The following channel types are considered guild channel types:
- [`AnnouncementThread`][`Self::AnnouncementThread`]
- [`PrivateThread`][`Self::PrivateThread`]
- [`PublicThread`][`Self::PublicThread`]
|
is_thread
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/channel_type.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/channel_type.rs
|
ISC
|
pub const fn name(self) -> &'static str {
match self {
Self::AnnouncementThread => "AnnouncementThread",
Self::Group => "Group",
Self::GuildCategory => "GuildCategory",
Self::GuildDirectory => "GuildDirectory",
Self::GuildForum => "GuildForum",
Self::GuildAnnouncement => "GuildAnnouncement",
Self::GuildStageVoice => "GuildStageVoice",
Self::GuildText => "GuildText",
Self::GuildVoice => "GuildVoice",
Self::Private => "Private",
Self::PrivateThread => "PrivateThread",
Self::PublicThread => "PublicThread",
Self::GuildMedia => "GuildMedia",
Self::Unknown(_) => "Unknown",
}
}
|
Name of the variant as a string slice.
|
name
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/channel_type.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/channel_type.rs
|
ISC
|
pub const fn deletable(self) -> bool {
matches!(
self,
Self::Regular
| Self::ChannelMessagePinned
| Self::UserJoin
| Self::GuildBoost
| Self::GuildBoostTier1
| Self::GuildBoostTier2
| Self::GuildBoostTier3
| Self::ChannelFollowAdd
| Self::ThreadCreated
| Self::Reply
| Self::ChatInputCommand
| Self::GuildInviteReminder
| Self::ContextMenuCommand
| Self::AutoModerationAction
| Self::RoleSubscriptionPurchase
| Self::InteractionPremiumUpsell
| Self::StageStart
| Self::StageEnd
| Self::StageSpeaker
| Self::StageTopic
| Self::GuildApplicationPremiumSubscription
| Self::GuildIncidentAlertModeEnabled
| Self::GuildIncidentAlertModeDisabled
| Self::GuildIncidentReportRaid
| Self::GuildIncidentReportRaidFalseAlarm
)
}
|
Whether the message can be deleted, not taking permissions into account.
Some message types can't be deleted, even by server administrators.
Some message types can only be deleted with certain permissions. For
example, [`AutoModerationAction`][`Self::AutoModerationAction`] can only
be deleted if the user has the
[Manage Messages] permission.
To check whether a message can be deleted while taking permissions into
account, use
[`deletable_with_permissions`][`Self::deletable_with_permissions`].
[Manage Messages]: Permissions::MANAGE_MESSAGES
|
deletable
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/kind.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/kind.rs
|
ISC
|
pub const fn deletable_with_permissions(self, permissions: Permissions) -> bool {
let required_permissions = match self {
Self::AutoModerationAction => Permissions::MANAGE_MESSAGES,
_ => Permissions::empty(),
};
if !permissions.contains(required_permissions) {
return false;
}
self.deletable()
}
|
Whether the message can be deleted, taking permissions into account.
Some message types can't be deleted, even by server administrators.
Some message types can only be deleted with certain permissions. For
example, [`AutoModerationAction`][`Self::AutoModerationAction`] can only
be deleted if the user has the [Manage Messages] permission.
To check whether a message can be deleted *without* taking permissions
into account, use [`deletable`][`Self::deletable`].
[Manage Messages]: Permissions::MANAGE_MESSAGES
|
deletable_with_permissions
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/kind.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/kind.rs
|
ISC
|
pub const fn name(self) -> &'static str {
match self {
Self::Normal => "Normal",
Self::Burst => "Burst",
Self::Unknown(_) => "Unknown",
}
}
|
The name of the reaction type.
|
name
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/reaction_type.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/reaction_type.rs
|
ISC
|
pub const fn name(&self) -> &str {
match self {
Self::Default => "Default",
Self::Forward => "Forward",
Self::Unknown(_) => "Unknown",
}
}
|
Return a string representation of the type.
|
name
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/reference_type.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/reference_type.rs
|
ISC
|
pub const fn name(self) -> &'static str {
match self {
Self::ActionRow => "ActionRow",
Self::Button => "Button",
Self::TextSelectMenu
| Self::UserSelectMenu
| Self::RoleSelectMenu
| Self::MentionableSelectMenu
| Self::ChannelSelectMenu => "SelectMenu",
Self::TextInput => "TextInput",
Self::Unknown(_) => "Unknown",
}
}
|
Name of the component type.
Variants have a name equivalent to the variant name itself.
# Examples
Check the [`ActionRow`] variant's name:
```
use twilight_model::channel::message::component::ComponentType;
assert_eq!("ActionRow", ComponentType::ActionRow.name());
```
[`ActionRow`]: Self::ActionRow
|
name
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/component/kind.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/component/kind.rs
|
ISC
|
pub const fn kind(&self) -> ComponentType {
match self {
Self::ActionRow(_) => ComponentType::ActionRow,
Self::Button(_) => ComponentType::Button,
Self::SelectMenu(SelectMenu { kind, .. }) => match kind {
SelectMenuType::Text => ComponentType::TextSelectMenu,
SelectMenuType::User => ComponentType::UserSelectMenu,
SelectMenuType::Role => ComponentType::RoleSelectMenu,
SelectMenuType::Mentionable => ComponentType::MentionableSelectMenu,
SelectMenuType::Channel => ComponentType::ChannelSelectMenu,
},
Self::TextInput(_) => ComponentType::TextInput,
Component::Unknown(unknown) => ComponentType::Unknown(*unknown),
}
}
|
Type of component that this is.
```
use twilight_model::channel::message::component::{
Button, ButtonStyle, Component, ComponentType,
};
let component = Component::Button(Button {
custom_id: None,
disabled: false,
emoji: None,
label: Some("ping".to_owned()),
style: ButtonStyle::Primary,
url: None,
sku_id: None,
});
assert_eq!(ComponentType::Button, component.kind());
```
|
kind
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/message/component/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/message/component/mod.rs
|
ISC
|
pub const fn number(self) -> u16 {
match self {
Self::Hour => 60,
Self::Day => 1440,
Self::ThreeDays => 4320,
Self::Week => 10080,
Self::Unknown { value } => value,
}
}
|
Retrieve the length of the duration in minutes, used by the API
# Examples
```
use twilight_model::channel::thread::AutoArchiveDuration;
assert_eq!(60, AutoArchiveDuration::Hour.number());
```
|
number
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/thread/auto_archive_duration.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/thread/auto_archive_duration.rs
|
ISC
|
pub fn into_thread_member(self, guild_id: Id<GuildMarker>) -> ThreadMember {
let presence = self.presence.map(|p| p.into_presence(guild_id));
ThreadMember {
flags: self.flags,
id: self.id,
join_timestamp: self.join_timestamp,
member: self.member,
presence,
user_id: self.user_id,
}
}
|
Inject a guild ID into a thread member intermediary
|
into_thread_member
|
rust
|
twilight-rs/twilight
|
twilight-model/src/channel/thread/member.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/channel/thread/member.rs
|
ISC
|
pub const fn new(code: u16, reason: &'a str) -> Self {
Self {
code,
reason: Cow::Borrowed(reason),
}
}
|
Construct a close frame from a code and a reason why.
# Examples
```
use twilight_model::gateway::CloseFrame;
let frame = CloseFrame::new(1000, "reason here");
assert_eq!(1000, frame.code);
assert_eq!("reason here", frame.reason);
```
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/frame.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/frame.rs
|
ISC
|
pub const fn new(number: u32, total: u32) -> Self {
assert!(number < total, "number must be less than total");
if let Some(total) = NonZeroU32::new(total) {
Self { number, total }
} else {
panic!("unreachable: total is at least 1")
}
}
|
Create a new shard identifier.
The shard number is 0-indexed while the total number of shards is
1-indexed. A shard number of 7 with a total of 8 is therefore valid,
whilst a shard number of 8 out of 8 total shards is invalid.
# Examples
Create a new shard with a shard number of 13 out of a total of 24
shards:
```
use twilight_model::gateway::ShardId;
let id = ShardId::new(13, 24);
```
# Panics
Panics if the shard number is greater than or equal to the total number
of shards.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/id.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/id.rs
|
ISC
|
pub const fn from(code: u8) -> Option<Self> {
Some(match code {
0 => Self::Dispatch,
1 => Self::Heartbeat,
2 => Self::Identify,
3 => Self::PresenceUpdate,
4 => Self::VoiceStateUpdate,
6 => Self::Resume,
7 => Self::Reconnect,
8 => Self::RequestGuildMembers,
9 => Self::InvalidSession,
10 => Self::Hello,
11 => Self::HeartbeatAck,
_ => return None,
})
}
|
Try to match an integer value to an opcode, returning [`None`] if no
match is found.
|
from
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/opcode.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/opcode.rs
|
ISC
|
pub const fn is_received(self) -> bool {
matches!(
self,
Self::Dispatch
| Self::Heartbeat
| Self::HeartbeatAck
| Self::Hello
| Self::InvalidSession
| Self::Reconnect
)
}
|
Whether the opcode is received by the client.
This includes the following opcodes:
- [`Dispatch`]
- [`Heartbeat`]
- [`HeartbeatAck`]
- [`Hello`]
- [`InvalidSession`]
- [`Reconnect`]
[`Dispatch`]: Self::Dispatch
[`Heartbeat`]: Self::Heartbeat
[`HeartbeatAck`]: Self::HeartbeatAck
[`Hello`]: Self::Hello
[`InvalidSession`]: Self::InvalidSession
[`Reconnect`]: Self::Reconnect
|
is_received
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/opcode.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/opcode.rs
|
ISC
|
pub const fn is_sent(self) -> bool {
matches!(
self,
Self::Heartbeat
| Self::Identify
| Self::PresenceUpdate
| Self::Resume
| Self::RequestGuildMembers
| Self::VoiceStateUpdate
)
}
|
Whether the opcode is sent by the client.
This includes the following opcodes:
- [`Heartbeat`]
- [`Identify`]
- [`PresenceUpdate`]
- [`Resume`]
- [`RequestGuildMembers`]
- [`VoiceStateUpdate`]
[`Heartbeat`]: Self::Heartbeat
[`Identify`]: Self::Identify
[`PresenceUpdate`]: Self::PresenceUpdate
[`Resume`]: Self::Resume
[`RequestGuildMembers`]: Self::RequestGuildMembers
[`VoiceStateUpdate`]: Self::VoiceStateUpdate
|
is_sent
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/opcode.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/opcode.rs
|
ISC
|
pub const fn kind(&self) -> EventType {
match self {
Self::AutoModerationActionExecution(_) => EventType::AutoModerationActionExecution,
Self::AutoModerationRuleCreate(_) => EventType::AutoModerationRuleCreate,
Self::AutoModerationRuleDelete(_) => EventType::AutoModerationRuleDelete,
Self::AutoModerationRuleUpdate(_) => EventType::AutoModerationRuleUpdate,
Self::BanAdd(_) => EventType::BanAdd,
Self::BanRemove(_) => EventType::BanRemove,
Self::ChannelCreate(_) => EventType::ChannelCreate,
Self::ChannelDelete(_) => EventType::ChannelDelete,
Self::ChannelPinsUpdate(_) => EventType::ChannelPinsUpdate,
Self::ChannelUpdate(_) => EventType::ChannelUpdate,
Self::CommandPermissionsUpdate(_) => EventType::CommandPermissionsUpdate,
Self::EntitlementCreate(_) => EventType::EntitlementCreate,
Self::EntitlementDelete(_) => EventType::EntitlementDelete,
Self::EntitlementUpdate(_) => EventType::EntitlementUpdate,
Self::GuildAuditLogEntryCreate(_) => EventType::GuildAuditLogEntryCreate,
Self::GuildCreate(_) => EventType::GuildCreate,
Self::GuildDelete(_) => EventType::GuildDelete,
Self::GuildEmojisUpdate(_) => EventType::GuildEmojisUpdate,
Self::GuildIntegrationsUpdate(_) => EventType::GuildIntegrationsUpdate,
Self::GuildScheduledEventCreate(_) => EventType::GuildScheduledEventCreate,
Self::GuildScheduledEventDelete(_) => EventType::GuildScheduledEventDelete,
Self::GuildScheduledEventUpdate(_) => EventType::GuildScheduledEventUpdate,
Self::GuildScheduledEventUserAdd(_) => EventType::GuildScheduledEventUserAdd,
Self::GuildScheduledEventUserRemove(_) => EventType::GuildScheduledEventUserRemove,
Self::GuildStickersUpdate(_) => EventType::GuildStickersUpdate,
Self::GuildUpdate(_) => EventType::GuildUpdate,
Self::IntegrationCreate(_) => EventType::IntegrationCreate,
Self::IntegrationDelete(_) => EventType::IntegrationDelete,
Self::IntegrationUpdate(_) => EventType::IntegrationUpdate,
Self::InteractionCreate(_) => EventType::InteractionCreate,
Self::InviteCreate(_) => EventType::InviteCreate,
Self::InviteDelete(_) => EventType::InviteDelete,
Self::MemberAdd(_) => EventType::MemberAdd,
Self::MemberRemove(_) => EventType::MemberRemove,
Self::MemberUpdate(_) => EventType::MemberUpdate,
Self::MemberChunk(_) => EventType::MemberChunk,
Self::MessageCreate(_) => EventType::MessageCreate,
Self::MessageDelete(_) => EventType::MessageDelete,
Self::MessageDeleteBulk(_) => EventType::MessageDeleteBulk,
Self::MessagePollVoteAdd(_) => EventType::MessagePollVoteAdd,
Self::MessagePollVoteRemove(_) => EventType::MessagePollVoteRemove,
Self::MessageUpdate(_) => EventType::MessageUpdate,
Self::PresenceUpdate(_) => EventType::PresenceUpdate,
Self::ReactionAdd(_) => EventType::ReactionAdd,
Self::ReactionRemove(_) => EventType::ReactionRemove,
Self::ReactionRemoveAll(_) => EventType::ReactionRemoveAll,
Self::ReactionRemoveEmoji(_) => EventType::ReactionRemoveEmoji,
Self::Ready(_) => EventType::Ready,
Self::Resumed => EventType::Resumed,
Self::RoleCreate(_) => EventType::RoleCreate,
Self::RoleDelete(_) => EventType::RoleDelete,
Self::RoleUpdate(_) => EventType::RoleUpdate,
Self::StageInstanceCreate(_) => EventType::StageInstanceCreate,
Self::StageInstanceDelete(_) => EventType::StageInstanceDelete,
Self::StageInstanceUpdate(_) => EventType::StageInstanceUpdate,
Self::ThreadCreate(_) => EventType::ThreadCreate,
Self::ThreadDelete(_) => EventType::ThreadDelete,
Self::ThreadListSync(_) => EventType::ThreadListSync,
Self::ThreadMemberUpdate(_) => EventType::ThreadMemberUpdate,
Self::ThreadMembersUpdate(_) => EventType::ThreadMembersUpdate,
Self::ThreadUpdate(_) => EventType::ThreadUpdate,
Self::TypingStart(_) => EventType::TypingStart,
Self::UnavailableGuild(_) => EventType::UnavailableGuild,
Self::UserUpdate(_) => EventType::UserUpdate,
Self::VoiceServerUpdate(_) => EventType::VoiceServerUpdate,
Self::VoiceStateUpdate(_) => EventType::VoiceStateUpdate,
Self::WebhooksUpdate(_) => EventType::WebhooksUpdate,
}
}
|
Returns the type of event that this event is.
|
kind
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/event/dispatch.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/event/dispatch.rs
|
ISC
|
pub fn new(op: u8, event_type: Option<&'a str>) -> Self {
Self {
event_type: event_type.map(Into::into),
op,
sequence: None,
}
}
|
Create a new gateway event deserializer when you already know the opcode
and dispatch event type.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/event/gateway.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/event/gateway.rs
|
ISC
|
pub fn from_json(input: &'a str) -> Option<Self> {
let op = Self::find_opcode(input)?;
let event_type = Self::find_event_type(input).map(Into::into);
let sequence = Self::find_sequence(input);
Some(Self {
event_type,
op,
sequence,
})
}
|
Create a gateway event deserializer by scanning the JSON payload for its
opcode and dispatch event type.
|
from_json
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/event/gateway.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/event/gateway.rs
|
ISC
|
pub fn into_owned(self) -> GatewayEventDeserializer<'static> {
GatewayEventDeserializer {
event_type: self
.event_type
.map(|event_type| Cow::Owned(event_type.into_owned())),
op: self.op,
sequence: self.sequence,
}
}
|
Create a deserializer with an owned event type.
This is necessary when using a mutable deserialization library such as
`simd-json`.
|
into_owned
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/event/gateway.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/event/gateway.rs
|
ISC
|
pub const fn guild_id(&self) -> Option<Id<GuildMarker>> {
match self {
Event::AutoModerationActionExecution(e) => Some(e.guild_id),
Event::AutoModerationRuleCreate(e) => Some(e.0.guild_id),
Event::AutoModerationRuleDelete(e) => Some(e.0.guild_id),
Event::AutoModerationRuleUpdate(e) => Some(e.0.guild_id),
Event::BanAdd(e) => Some(e.guild_id),
Event::BanRemove(e) => Some(e.guild_id),
Event::ChannelCreate(e) => e.0.guild_id,
Event::ChannelDelete(e) => e.0.guild_id,
Event::ChannelPinsUpdate(e) => e.guild_id,
Event::ChannelUpdate(e) => e.0.guild_id,
Event::CommandPermissionsUpdate(e) => Some(e.0.guild_id),
Event::GuildAuditLogEntryCreate(e) => e.0.guild_id,
Event::GuildCreate(e) => Some(e.id()),
Event::GuildDelete(e) => Some(e.id),
Event::GuildEmojisUpdate(e) => Some(e.guild_id),
Event::GuildIntegrationsUpdate(e) => Some(e.guild_id),
Event::GuildScheduledEventCreate(e) => Some(e.0.guild_id),
Event::GuildScheduledEventDelete(e) => Some(e.0.guild_id),
Event::GuildScheduledEventUpdate(e) => Some(e.0.guild_id),
Event::GuildScheduledEventUserAdd(e) => Some(e.guild_id),
Event::GuildScheduledEventUserRemove(e) => Some(e.guild_id),
Event::GuildStickersUpdate(e) => Some(e.guild_id),
Event::GuildUpdate(e) => Some(e.0.id),
Event::IntegrationCreate(e) => e.0.guild_id,
Event::IntegrationDelete(e) => Some(e.guild_id),
Event::IntegrationUpdate(e) => e.0.guild_id,
Event::InteractionCreate(e) => e.0.guild_id,
Event::InviteCreate(e) => Some(e.guild_id),
Event::InviteDelete(e) => Some(e.guild_id),
Event::MemberAdd(e) => Some(e.guild_id),
Event::MemberChunk(e) => Some(e.guild_id),
Event::MemberRemove(e) => Some(e.guild_id),
Event::MemberUpdate(e) => Some(e.guild_id),
Event::MessageCreate(e) => e.0.guild_id,
Event::MessageDelete(e) => e.guild_id,
Event::MessageDeleteBulk(e) => e.guild_id,
Event::MessageUpdate(e) => e.0.guild_id,
Event::MessagePollVoteAdd(e) => e.guild_id,
Event::MessagePollVoteRemove(e) => e.guild_id,
Event::PresenceUpdate(e) => Some(e.0.guild_id),
Event::ReactionAdd(e) => e.0.guild_id,
Event::ReactionRemove(e) => e.0.guild_id,
Event::ReactionRemoveAll(e) => e.guild_id,
Event::ReactionRemoveEmoji(e) => Some(e.guild_id),
Event::RoleCreate(e) => Some(e.guild_id),
Event::RoleDelete(e) => Some(e.guild_id),
Event::RoleUpdate(e) => Some(e.guild_id),
Event::StageInstanceCreate(e) => Some(e.0.guild_id),
Event::StageInstanceDelete(e) => Some(e.0.guild_id),
Event::StageInstanceUpdate(e) => Some(e.0.guild_id),
Event::ThreadCreate(e) => e.0.guild_id,
Event::ThreadDelete(e) => Some(e.guild_id),
Event::ThreadListSync(e) => Some(e.guild_id),
Event::ThreadMemberUpdate(e) => Some(e.guild_id),
Event::ThreadMembersUpdate(e) => Some(e.guild_id),
Event::ThreadUpdate(e) => e.0.guild_id,
Event::TypingStart(e) => e.guild_id,
Event::UnavailableGuild(e) => Some(e.id),
Event::VoiceServerUpdate(e) => Some(e.guild_id),
Event::VoiceStateUpdate(e) => e.0.guild_id,
Event::WebhooksUpdate(e) => Some(e.guild_id),
Event::GatewayClose(_)
| Event::EntitlementCreate(_)
| Event::EntitlementDelete(_)
| Event::EntitlementUpdate(_)
| Event::GatewayHeartbeat
| Event::GatewayHeartbeatAck
| Event::GatewayHello(_)
| Event::GatewayInvalidateSession(_)
| Event::GatewayReconnect
| Event::Ready(_)
| Event::Resumed
| Event::UserUpdate(_) => None,
}
}
|
Guild ID of the event, if available.
|
guild_id
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/event/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/event/mod.rs
|
ISC
|
pub const fn new(guild_id: Id<GuildMarker>) -> Self {
Self {
guild_id,
nonce: None,
presences: None,
}
}
|
Create a new builder to configure and construct a
[`RequestGuildMembers`].
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/payload/outgoing/request_guild_members.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/payload/outgoing/request_guild_members.rs
|
ISC
|
pub fn user_ids(
self,
user_ids: impl Into<Vec<Id<UserMarker>>>,
) -> Result<RequestGuildMembers, UserIdsError> {
self._user_ids(user_ids.into())
}
|
Consume the builder, creating a request that requests the provided
user(s) in the specified guild(s).
Only up to 100 user IDs can be requested at once.
# Examples
Request two members within one guild and specify a nonce of "test":
```
use twilight_model::{
gateway::payload::outgoing::request_guild_members::{
RequestGuildMemberId,
RequestGuildMembers,
},
id::Id,
};
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let request = RequestGuildMembers::builder(Id::new(1))
.nonce("test")
.user_ids(vec![Id::new(2), Id::new(2)])?;
assert!(matches!(request.d.user_ids, Some(RequestGuildMemberId::Multiple(ids)) if ids.len() == 2));
# Ok(()) }
```
# Errors
Returns a [`UserIdsErrorType::TooMany`] error type if more than 100 user
IDs were provided.
|
user_ids
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/payload/outgoing/request_guild_members.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/payload/outgoing/request_guild_members.rs
|
ISC
|
pub fn new(
activities: impl Into<Vec<Activity>>,
afk: bool,
since: impl Into<Option<u64>>,
status: impl Into<Status>,
) -> Result<Self, UpdatePresenceError> {
let d = UpdatePresencePayload::new(activities, afk, since, status)?;
Ok(Self {
d,
op: OpCode::PresenceUpdate,
})
}
|
Create a new, valid [`UpdatePresence`] payload.
# Errors
Returns an error of type [`UpdatePresenceErrorType::MissingActivity`] if
an empty set of activities is provided.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/payload/outgoing/update_presence.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/payload/outgoing/update_presence.rs
|
ISC
|
pub fn new(
activities: impl Into<Vec<Activity>>,
afk: bool,
since: impl Into<Option<u64>>,
status: impl Into<Status>,
) -> Result<Self, UpdatePresenceError> {
Self::_new(activities.into(), afk, since.into(), status.into())
}
|
Create a validated stats update info struct.
# Errors
Returns an [`UpdatePresenceErrorType::MissingActivity`] error type if an
empty set of activities is provided.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/payload/outgoing/update_presence.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/payload/outgoing/update_presence.rs
|
ISC
|
pub const fn is_link(&self) -> bool {
matches!(self, Self::Link(_))
}
|
Whether the variant is a link button.
|
is_link
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/presence/activity_button.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/presence/activity_button.rs
|
ISC
|
pub const fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
|
Whether the variant is a text button.
|
is_text
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/presence/activity_button.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/presence/activity_button.rs
|
ISC
|
pub fn into_presence(self, guild_id: Id<GuildMarker>) -> Presence {
Presence {
activities: self.activities,
client_status: self.client_status,
guild_id: self.guild_id.unwrap_or(guild_id),
status: self.status,
user: self.user,
}
}
|
Inject guild ID into presence if not already present.
|
into_presence
|
rust
|
twilight-rs/twilight
|
twilight-model/src/gateway/presence/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/gateway/presence/mod.rs
|
ISC
|
fn cmp(&self, other: &Self) -> Ordering {
self.position
.cmp(&other.position)
.then(self.id.get().cmp(&other.id.get()))
}
|
Compare two roles to each other using their position and ID.
Roles are primarily ordered by their position in descending order. For example,
a role with a position of 17 is considered a higher role than one with a
position of 12.
Discord does not guarantee that role positions are positive, unique, or contiguous. When
two or more roles have the same position then the order is based on the roles' IDs in
ascending order. For example, given two roles with positions of 10 then a role
with an ID of 1 would be considered a higher role than one with an ID of 20.
### Examples
Compare the position of two roles:
```
# use twilight_model::{guild::{Permissions, Role, RoleFlags}, id::Id};
# use std::cmp::Ordering;
let role_a = Role {
id: Id::new(123),
position: 12,
# color: 0,
# hoist: true,
# icon: None,
# managed: false,
# mentionable: true,
# name: "test".to_owned(),
# permissions: Permissions::ADMINISTRATOR,
# flags: RoleFlags::empty(),
# tags: None,
# unicode_emoji: None,
// ...
};
let role_b = Role {
id: Id::new(456),
position: 13,
# color: 0,
# hoist: true,
# icon: None,
# managed: false,
# mentionable: true,
# name: "test".to_owned(),
# permissions: Permissions::ADMINISTRATOR,
# flags: RoleFlags::empty(),
# tags: None,
# unicode_emoji: None,
// ...
};
assert_eq!(Ordering::Less, role_a.cmp(&role_b));
assert_eq!(Ordering::Greater, role_b.cmp(&role_a));
assert_eq!(Ordering::Equal, role_a.cmp(&role_a));
assert_eq!(Ordering::Equal, role_b.cmp(&role_b));
```
Compare the position of two roles with the same position:
```
# use twilight_model::{guild::{Permissions, Role, RoleFlags}, id::Id};
# use std::cmp::Ordering;
let role_a = Role {
id: Id::new(123),
position: 12,
# color: 0,
# hoist: true,
# icon: None,
# managed: false,
# mentionable: true,
# name: "test".to_owned(),
# permissions: Permissions::ADMINISTRATOR,
# flags: RoleFlags::empty(),
# tags: None,
# unicode_emoji: None,
};
let role_b = Role {
id: Id::new(456),
position: 12,
# color: 0,
# hoist: true,
# icon: None,
# managed: false,
# mentionable: true,
# name: "test".to_owned(),
# permissions: Permissions::ADMINISTRATOR,
# flags: RoleFlags::empty(),
# tags: None,
# unicode_emoji: None,
};
assert_eq!(Ordering::Less, role_a.cmp(&role_b));
assert_eq!(Ordering::Greater, role_b.cmp(&role_a));
assert_eq!(Ordering::Equal, role_a.cmp(&role_a));
assert_eq!(Ordering::Equal, role_b.cmp(&role_b));
```
|
cmp
|
rust
|
twilight-rs/twilight
|
twilight-model/src/guild/role.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/guild/role.rs
|
ISC
|
pub const fn name(self) -> &'static str {
match self {
Self::AfkChannelId => "afk_channel_id",
Self::AfkTimeout => "afk_timeout",
Self::Allow => "allow",
Self::ApplicationId => "application_id",
Self::Archived => "archived",
Self::Asset => "asset",
Self::AutoArchiveDuration => "auto_archive_duration",
Self::Available => "available",
Self::AvatarHash => "avatar_hash",
Self::BannerHash => "banner_hash",
Self::Bitrate => "bitrate",
Self::ChannelId => "channel_id",
Self::Code => "code",
Self::Color => "color",
Self::CommandId => "command_id",
Self::CommunicationDisabledUntil => "communication_disabled_until",
Self::Deaf => "deaf",
Self::DefaultAutoArchiveDuration => "default_auto_archive_duration",
Self::DefaultMessageNotifications => "default_message_notifications",
Self::Deny => "deny",
Self::Description => "description",
Self::DiscoverySplashHash => "discovery_splash_hash",
Self::EnableEmoticons => "enable_emoticons",
Self::EntityType => "entity_type",
Self::ExpireBehavior => "expire_behavior",
Self::ExpireGracePeriod => "expire_grace_period",
Self::ExplicitContentFilter => "explicit_content_filter",
Self::FormatType => "format_type",
Self::GuildId => "guild_id",
Self::Hoist => "hoist",
Self::IconHash => "icon_hash",
Self::Id => "id",
Self::ImageHash => "image_hash",
Self::Invitable => "invitable",
Self::InviterId => "inviter_id",
Self::Location => "location",
Self::Locked => "locked",
Self::MaxAge => "max_age",
Self::MaxUses => "max_uses",
Self::Mentionable => "mentionable",
Self::MfaLevel => "mfa_level",
Self::Mute => "mute",
Self::Name => "name",
Self::Nick => "nick",
Self::Nsfw => "nsfw",
Self::NsfwLevel => "nsfw_level",
Self::OwnerId => "owner_id",
Self::PermissionOverwrites => "permission_overwrites",
Self::Permissions => "permissions",
Self::Position => "position",
Self::PreferredLocale => "preferred_locale",
Self::PrivacyLevel => "privacy_level",
Self::PruneDeleteDays => "prune_delete_days",
Self::PublicUpdatesChannelId => "public_updates_channel_id",
Self::RateLimitPerUser => "rate_limit_per_user",
Self::Region => "region",
Self::RoleAdded => "$add",
Self::RoleRemoved => "$remove",
Self::RulesChannelId => "rules_channel_id",
Self::SplashHash => "splash_hash",
Self::Status => "status",
Self::SystemChannelId => "system_channel_id",
Self::Tags => "tags",
Self::Temporary => "temporary",
Self::Topic => "topic",
Self::Type => "type",
Self::UnicodeEmoji => "unicode_emoji",
Self::UserLimit => "user_limit",
Self::Uses => "uses",
Self::VanityUrlCode => "vanity_url_code",
Self::VerificationLevel => "verification_level",
Self::WidgetChannelId => "widget_channel_id",
Self::WidgetEnabled => "widget_enabled",
}
}
|
Raw name of the key.
The raw names of keys are in `snake_case` form.
# Examples
Check the names of the [`Allow`] and [`BannerHash`] keys:
```
use twilight_model::guild::audit_log::AuditLogChangeKey;
assert_eq!("allow", AuditLogChangeKey::Allow.name());
assert_eq!("banner_hash", AuditLogChangeKey::BannerHash.name());
```
[`Allow`]: Self::Allow
[`BannerHash`]: Self::BannerHash
|
name
|
rust
|
twilight-rs/twilight
|
twilight-model/src/guild/audit_log/change_key.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/guild/audit_log/change_key.rs
|
ISC
|
pub const fn from_bytes(filename: String, file: Vec<u8>, id: u64) -> Self {
Self {
description: None,
file,
filename,
id,
}
}
|
Create an attachment from a filename and bytes.
# Examples
Create an attachment with a grocery list named "grocerylist.txt":
```
use twilight_model::http::attachment::Attachment;
let filename = "grocerylist.txt".to_owned();
let file_content = b"Apples\nGrapes\nLemonade".to_vec();
let id = 1;
let attachment = Attachment::from_bytes(filename, file_content, id);
```
|
from_bytes
|
rust
|
twilight-rs/twilight
|
twilight-model/src/http/attachment.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/http/attachment.rs
|
ISC
|
pub fn description(&mut self, description: String) {
self.description = Some(description);
}
|
Set the description of the attachment.
Attachment descriptions are useful for those requiring screen readers
and are displayed as alt text.
|
description
|
rust
|
twilight-rs/twilight
|
twilight-model/src/http/attachment.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/http/attachment.rs
|
ISC
|
pub const fn new_checked(n: u64) -> Option<Self> {
if let Some(n) = NonZeroU64::new(n) {
Some(Self::from_nonzero(n))
} else {
None
}
}
|
Create an ID if the provided value is not zero.
# Examples
```
use twilight_model::id::{marker::GenericMarker, Id};
assert!(Id::<GenericMarker>::new_checked(123).is_some());
assert!(Id::<GenericMarker>::new_checked(0).is_none());
```
Equivalent to [`NonZeroU64::new`].
|
new_checked
|
rust
|
twilight-rs/twilight
|
twilight-model/src/id/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/id/mod.rs
|
ISC
|
const fn range(index: usize, value: u8) -> Self {
Self {
kind: ImageHashParseErrorType::Range { index, value },
}
}
|
Instantiate a new error with an [`ImageHashParseErrorType::Range`] error
type.
|
range
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
pub const fn new(bytes: [u8; 16], animated: bool) -> Self {
Self { animated, bytes }
}
|
Instantiate a new hash from its raw parts.
Parts can be obtained via [`is_animated`] and [`bytes`].
# Examples
Parse an image hash, deconstruct it, and then reconstruct it:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::util::ImageHash;
let input = "1acefe340fafb4ecefae407f3abdb323";
let parsed = ImageHash::parse(input.as_bytes())?;
let (bytes, is_animated) = (parsed.bytes(), parsed.is_animated());
let constructed = ImageHash::new(bytes, is_animated);
assert_eq!(input, constructed.to_string());
# Ok(()) }
```
[`is_animated`]: Self::is_animated
[`bytes`]: Self::bytes
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
pub const fn parse(value: &[u8]) -> Result<Self, ImageHashParseError> {
/// Number of digits allocated in the half-byte.
///
/// In other words, the number of numerical representations before
/// reaching alphabetical representations in the half-byte.
const DIGITS_ALLOCATED: u8 = 10;
if Self::is_clyde(value) {
return Ok(Self::CLYDE);
}
let animated = Self::starts_with(value, ANIMATED_KEY.as_bytes());
let mut seeking_idx = if animated { ANIMATED_KEY.len() } else { 0 };
// We start at the end because hashes are stored in little endian.
let mut storage_idx = 15;
if value.len() - seeking_idx != HASH_LEN {
return Err(ImageHashParseError::FORMAT);
}
let mut bytes = [0; 16];
while seeking_idx < value.len() {
let byte_left = match value[seeking_idx] {
byte @ b'0'..=b'9' => byte - b'0',
byte @ b'a'..=b'f' => byte - b'a' + DIGITS_ALLOCATED,
other => return Err(ImageHashParseError::range(seeking_idx, other)),
};
seeking_idx += 1;
let byte_right = match value[seeking_idx] {
byte @ b'0'..=b'9' => byte - b'0',
byte @ b'a'..=b'f' => byte - b'a' + DIGITS_ALLOCATED,
other => return Err(ImageHashParseError::range(seeking_idx, other)),
};
bytes[storage_idx] = (byte_left << 4) | byte_right;
seeking_idx += 1;
storage_idx = storage_idx.saturating_sub(1);
}
Ok(Self { animated, bytes })
}
|
Parse an image hash into an efficient integer-based storage.
# Examples
Parse a static image hash:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::util::ImageHash;
let input = "b2a6536641da91a0b59bd66557c56c36";
let parsed = ImageHash::parse(input.as_bytes())?;
assert!(!parsed.is_animated());
assert_eq!(input, parsed.to_string());
# Ok(()) }
```
Parse an animated image hash:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::util::ImageHash;
let input = "a_b2a6536641da91a0b59bd66557c56c36";
let parsed = ImageHash::parse(input.as_bytes())?;
assert!(parsed.is_animated());
assert_eq!(input, parsed.to_string());
# Ok(()) }
```
# Errors
Returns an [`ImageHashParseErrorType::Format`] error type if the
provided value isn't in a Discord image hash format. Refer to the
variant's documentation for more details.
Returns an [`ImageHashParseErrorType::Range`] error type if one of the
hex values is outside of the accepted range. Refer to the variant's
documentation for more details.
|
parse
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
const fn is_clyde(value: &[u8]) -> bool {
if value.len() < 5 {
return false;
}
value[0] == b'c'
&& value[1] == b'l'
&& value[2] == b'y'
&& value[3] == b'd'
&& value[4] == b'e'
}
|
Determine whether a value is the Clyde AI image hash.
|
is_clyde
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
const fn starts_with(haystack: &[u8], needle: &[u8]) -> bool {
if needle.len() > haystack.len() {
return false;
}
let mut idx = 0;
while idx < needle.len() {
if haystack[idx] != needle[idx] {
return false;
}
idx += 1;
}
true
}
|
Determine whether a haystack starts with a needle.
|
starts_with
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct ImageHashVisitor;
impl Visitor<'_> for ImageHashVisitor {
type Value = ImageHash;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("image hash")
}
fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
ImageHash::parse(v.as_bytes()).map_err(DeError::custom)
}
}
deserializer.deserialize_any(ImageHashVisitor)
}
|
Parse an image hash string into an efficient decimal store.
# Examples
Refer to [`ImageHash::parse`]'s documentation for examples.
# Errors
Returns an [`ImageHashParseErrorType::Format`] error type if the
provided value isn't in a Discord image hash format. Refer to the
variant's documentation for more details.
Returns an [`ImageHashParseErrorType::Range`] error type if one of the
hex values is outside of the accepted range. Refer to the variant's
documentation for more details.
|
deserialize
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
if *self == Self::CLYDE {
return f.write_str("clyde");
}
if self.is_animated() {
f.write_str(ANIMATED_KEY)?;
}
for hex_value in self.nibbles() {
let legible = char::from(hex_value);
Display::fmt(&legible, f)?;
}
Ok(())
}
|
Format the image hash as a hex string.
# Examples
Parse a hash and then format it to ensure it matches the input:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::util::ImageHash;
let input = "a_b0e09d6697b11e9c79a89e5e3756ddee";
let parsed = ImageHash::parse(input.as_bytes())?;
assert_eq!(input, parsed.to_string());
# Ok(()) }
```
|
fmt
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
const fn new(inner: ImageHash) -> Self {
Self {
idx: usize::MAX,
inner,
}
}
|
Create a new iterator over an image hash, creating nibbles.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
fn advance_idx_by(&mut self, by: usize) {
self.idx = if self.idx == usize::MAX {
0
} else {
let mut new_idx = self.idx.saturating_add(by);
if new_idx == usize::MAX {
new_idx -= 1;
}
new_idx
}
}
|
Advance the index in the iterator by the provided amount.
|
advance_idx_by
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
const fn byte(&self) -> Option<u8> {
const BITS_IN_HALF_BYTE: u8 = 4;
/// Greatest index that the hash byte array can be indexed into.
const BYTE_ARRAY_BOUNDARY: usize = HASH_LEN - 1;
const RIGHT_MASK: u8 = (1 << BITS_IN_HALF_BYTE) - 1;
if self.idx >= HASH_LEN {
return None;
}
let (byte, left) = ((BYTE_ARRAY_BOUNDARY - self.idx) / 2, self.idx % 2 == 0);
let store = self.inner.bytes[byte];
let bits = if left {
store >> BITS_IN_HALF_BYTE
} else {
store & RIGHT_MASK
};
Some(Self::nibble(bits))
}
|
Parse the byte at the stored index.
|
byte
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
const fn nibble(value: u8) -> u8 {
if value < 10 {
b'0' + value
} else {
b'a' + (value - 10)
}
}
|
Convert 4 bits in a byte integer to a nibble.
Values 0-9 correlate to representations '0' through '9', while values
10-15 correlate to representations 'a' through 'f'.
|
nibble
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/image_hash.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/image_hash.rs
|
ISC
|
pub(super) const fn new(timestamp: Timestamp) -> Self {
Self {
timestamp,
with_microseconds: true,
}
}
|
Create a new ISO 8601 display formatter for a timestamp.
|
new
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/datetime/display.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/datetime/display.rs
|
ISC
|
pub fn from_micros(unix_microseconds: i64) -> Result<Self, TimestampParseError> {
let nanoseconds = i128::from(unix_microseconds) * i128::from(NANOSECONDS_PER_MICROSECOND);
OffsetDateTime::from_unix_timestamp_nanos(nanoseconds)
.map(|offset| Self(PrimitiveDateTime::new(offset.date(), offset.time())))
.map_err(TimestampParseError::from_component_range)
}
|
Create a timestamp from a Unix timestamp with microseconds precision.
# Errors
Returns a [`TimestampParseErrorType::Parsing`] error type if the parsing
failed.
[`TimestampParseErrorType::Parsing`]: self::error::TimestampParseErrorType::Parsing
|
from_micros
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/datetime/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/datetime/mod.rs
|
ISC
|
pub fn from_secs(unix_seconds: i64) -> Result<Self, TimestampParseError> {
OffsetDateTime::from_unix_timestamp(unix_seconds)
.map(|offset| Self(PrimitiveDateTime::new(offset.date(), offset.time())))
.map_err(TimestampParseError::from_component_range)
}
|
Create a timestamp from a Unix timestamp with seconds precision.
# Errors
Returns a [`TimestampParseErrorType::Parsing`] error type if the parsing
failed.
[`TimestampParseErrorType::Parsing`]: self::error::TimestampParseErrorType::Parsing
|
from_secs
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/datetime/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/datetime/mod.rs
|
ISC
|
pub const fn as_micros(self) -> i64 {
let utc = self.0.assume_utc();
(utc.unix_timestamp() * MICROSECONDS_PER_SECOND) + (utc.microsecond() as i64)
}
|
Total number of microseconds within the timestamp.
# Examples
Parse a formatted timestamp and then get its Unix timestamp value with
microseconds precision:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::str::FromStr;
use twilight_model::util::Timestamp;
let timestamp = Timestamp::from_str("2021-08-10T11:16:37.123456+00:00")?;
assert_eq!(1_628_594_197_123_456, timestamp.as_micros());
# Ok(()) }
```
|
as_micros
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/datetime/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/datetime/mod.rs
|
ISC
|
fn parse_iso8601(input: &str) -> Result<PrimitiveDateTime, TimestampParseError> {
/// Discord sends some timestamps with the microseconds and some without.
const TIMESTAMP_LENGTH: usize = "2021-01-01T01:01:01+00:00".len();
if input.len() < TIMESTAMP_LENGTH {
return Err(TimestampParseError::FORMAT);
}
OffsetDateTime::parse(input, &Rfc3339)
.map(|offset| PrimitiveDateTime::new(offset.date(), offset.time()))
.map_err(TimestampParseError::from_parse)
}
|
Parse an input ISO 8601 timestamp into a Unix timestamp with microseconds.
Input in the format of "2021-01-01T01:01:01.010000+00:00" is acceptable.
# Errors
Returns a [`TimestampParseErrorType::Parsing`] if the parsing failed.
|
parse_iso8601
|
rust
|
twilight-rs/twilight
|
twilight-model/src/util/datetime/mod.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-model/src/util/datetime/mod.rs
|
ISC
|
pub fn process(&self, event: &Event) -> ProcessResults {
tracing::trace!(event_type = ?event.kind(), ?event, "processing event");
let mut completions = ProcessResults::new();
match event {
Event::InteractionCreate(e) => {
if e.kind == InteractionType::MessageComponent {
if let Some(message) = &e.message {
completions.add_with(&Self::process_specific_event(
&self.components,
message.id,
e,
));
}
}
}
Event::MessageCreate(e) => {
completions.add_with(&Self::process_specific_event(
&self.messages,
e.0.channel_id,
e,
));
}
Event::ReactionAdd(e) => {
completions.add_with(&Self::process_specific_event(
&self.reactions,
e.0.message_id,
e,
));
}
_ => {}
}
if let Some(guild_id) = event.guild_id() {
completions.add_with(&Self::process_specific_event(&self.guilds, guild_id, event));
}
completions.add_with(&Self::process_event(&self.events, event));
completions
}
|
Process an event, calling any bystanders that might be waiting on it.
Returns statistics about matched [`Standby`] calls and how they were
processed. For example, by using [`ProcessResults::matched`] you can
determine how many calls were sent an event.
When a bystander checks to see if an event is what it's waiting for, it
will receive the event by cloning it.
This function must be called when events are received in order for
futures returned by methods to fulfill.
|
process
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for<F: Fn(&Event) -> bool + Send + Sync + 'static>(
&self,
guild_id: Id<GuildMarker>,
check: impl Into<Box<F>>,
) -> WaitForGuildEventFuture {
tracing::trace!(%guild_id, "waiting for event in guild");
WaitForGuildEventFuture {
rx: Self::insert_future(&self.guilds, guild_id, check),
}
}
|
Wait for an event in a certain guild.
To wait for multiple guild events matching the given predicate use
[`wait_for_stream`].
# Examples
Wait for a [`BanAdd`] event in guild 123:
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::{
gateway::event::{Event, EventType},
id::Id,
};
use twilight_standby::Standby;
let standby = Standby::new();
let guild_id = Id::new(123);
let reaction = standby
.wait_for(guild_id, |event: &Event| event.kind() == EventType::BanAdd)
.await?;
# Ok(()) }
```
# Errors
The returned future resolves to a [`Canceled`] error if the associated
[`Standby`] instance is dropped.
[`BanAdd`]: twilight_model::gateway::payload::incoming::BanAdd
[`Canceled`]: future::Canceled
[`wait_for_stream`]: Self::wait_for_stream
|
wait_for
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_stream<F: Fn(&Event) -> bool + Send + Sync + 'static>(
&self,
guild_id: Id<GuildMarker>,
check: impl Into<Box<F>>,
) -> WaitForGuildEventStream {
tracing::trace!(%guild_id, "waiting for event in guild");
WaitForGuildEventStream {
rx: Self::insert_stream(&self.guilds, guild_id, check),
}
}
|
Wait for a stream of events in a certain guild.
To wait for only one guild event matching the given predicate use
[`wait_for`].
# Examples
Wait for multiple [`BanAdd`] events in guild 123:
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use tokio_stream::StreamExt;
use twilight_model::{
gateway::event::{Event, EventType},
id::Id,
};
use twilight_standby::Standby;
let standby = Standby::new();
let guild_id = Id::new(123);
let mut stream =
standby.wait_for_stream(guild_id, |event: &Event| event.kind() == EventType::BanAdd);
while let Some(event) = stream.next().await {
if let Event::BanAdd(ban) = event {
println!("user {} was banned in guild {}", ban.user.id, ban.guild_id);
}
}
# Ok(()) }
```
# Errors
The returned stream ends when the associated [`Standby`] instance is
dropped.
[`BanAdd`]: twilight_model::gateway::payload::incoming::BanAdd
[`wait_for`]: Self::wait_for
|
wait_for_stream
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_event<F: Fn(&Event) -> bool + Send + Sync + 'static>(
&self,
check: impl Into<Box<F>>,
) -> WaitForEventFuture {
tracing::trace!("waiting for event");
let (tx, rx) = oneshot::channel();
self.events.insert(
self.next_event_id(),
Bystander {
func: check.into(),
sender: Some(Sender::Future(tx)),
},
);
WaitForEventFuture { rx }
}
|
Wait for an event not in a certain guild. This must be filtered by an
event type.
To wait for multiple events matching the given predicate use
[`wait_for_event_stream`].
# Examples
Wait for a [`Ready`] event for shard 5:
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::gateway::event::{Event, EventType};
use twilight_standby::Standby;
let standby = Standby::new();
let ready = standby
.wait_for_event(|event: &Event| {
if let Event::Ready(ready) = event {
ready.shard.map_or(false, |id| id.number() == 5)
} else {
false
}
})
.await?;
# Ok(()) }
```
# Errors
The returned future resolves to a [`Canceled`] error if the associated
[`Standby`] instance is dropped.
[`Canceled`]: future::Canceled
[`Ready`]: twilight_model::gateway::payload::incoming::Ready
[`wait_for_event_stream`]: Self::wait_for_event_stream
|
wait_for_event
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_event_stream<F: Fn(&Event) -> bool + Send + Sync + 'static>(
&self,
check: impl Into<Box<F>>,
) -> WaitForEventStream {
tracing::trace!("waiting for event");
let (tx, rx) = mpsc::unbounded_channel();
self.events.insert(
self.next_event_id(),
Bystander {
func: check.into(),
sender: Some(Sender::Stream(tx)),
},
);
WaitForEventStream { rx }
}
|
Wait for a stream of events not in a certain guild. This must be
filtered by an event type.
To wait for only one event matching the given predicate use
[`wait_for_event`].
# Examples
Wait for multiple [`Ready`] events on shard 5:
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use tokio_stream::StreamExt;
use twilight_model::gateway::event::{Event, EventType};
use twilight_standby::Standby;
let standby = Standby::new();
let mut events = standby.wait_for_event_stream(|event: &Event| {
if let Event::Ready(ready) = event {
ready.shard.map_or(false, |id| id.number() == 5)
} else {
false
}
});
while let Some(event) = events.next().await {
println!("got event with type {:?}", event.kind());
}
# Ok(()) }
```
# Errors
The returned stream ends when the associated [`Standby`] instance is
dropped.
[`Ready`]: twilight_model::gateway::payload::incoming::Ready
[`wait_for_event`]: Self::wait_for_event
|
wait_for_event_stream
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_message<F: Fn(&MessageCreate) -> bool + Send + Sync + 'static>(
&self,
channel_id: Id<ChannelMarker>,
check: impl Into<Box<F>>,
) -> WaitForMessageFuture {
tracing::trace!(%channel_id, "waiting for message in channel");
WaitForMessageFuture {
rx: Self::insert_future(&self.messages, channel_id, check),
}
}
|
Wait for a message in a certain channel.
To wait for multiple messages matching the given predicate use
[`wait_for_message_stream`].
# Examples
Wait for a message in channel 123 by user 456 with the content "test":
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::{gateway::payload::incoming::MessageCreate, id::Id};
use twilight_standby::Standby;
let standby = Standby::new();
let author_id = Id::new(456);
let channel_id = Id::new(123);
let message = standby
.wait_for_message(channel_id, move |event: &MessageCreate| {
event.author.id == author_id && event.content == "test"
})
.await?;
# Ok(()) }
```
# Errors
The returned future resolves to a [`Canceled`] error if the associated
[`Standby`] instance is dropped.
[`Canceled`]: future::Canceled
[`wait_for_message_stream`]: Self::wait_for_message_stream
|
wait_for_message
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_message_stream<F: Fn(&MessageCreate) -> bool + Send + Sync + 'static>(
&self,
channel_id: Id<ChannelMarker>,
check: impl Into<Box<F>>,
) -> WaitForMessageStream {
tracing::trace!(%channel_id, "waiting for message in channel");
WaitForMessageStream {
rx: Self::insert_stream(&self.messages, channel_id, check),
}
}
|
Wait for a stream of message in a certain channel.
To wait for only one message matching the given predicate use
[`wait_for_message`].
# Examples
Wait for multiple messages in channel 123 by user 456 with the content
"test":
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use tokio_stream::StreamExt;
use twilight_model::{gateway::payload::incoming::MessageCreate, id::Id};
use twilight_standby::Standby;
let standby = Standby::new();
let author_id = Id::new(456);
let channel_id = Id::new(123);
let mut messages = standby.wait_for_message_stream(channel_id, move |event: &MessageCreate| {
event.author.id == author_id && event.content == "test"
});
while let Some(message) = messages.next().await {
println!("got message by {}", message.author.id);
}
# Ok(()) }
```
# Errors
The returned stream ends when the associated [`Standby`] instance is
dropped.
[`wait_for_message`]: Self::wait_for_message
|
wait_for_message_stream
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub fn wait_for_reaction<F: Fn(&ReactionAdd) -> bool + Send + Sync + 'static>(
&self,
message_id: Id<MessageMarker>,
check: impl Into<Box<F>>,
) -> WaitForReactionFuture {
tracing::trace!(%message_id, "waiting for reaction on message");
WaitForReactionFuture {
rx: Self::insert_future(&self.reactions, message_id, check),
}
}
|
Wait for a reaction on a certain message.
To wait for multiple reactions matching the given predicate use
[`wait_for_reaction_stream`].
# Examples
Wait for a reaction on message 123 by user 456:
```no_run
# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_model::{gateway::payload::incoming::ReactionAdd, id::Id};
use twilight_standby::Standby;
let standby = Standby::new();
let message_id = Id::new(123);
let user_id = Id::new(456);
let reaction = standby
.wait_for_reaction(message_id, move |event: &ReactionAdd| {
event.user_id == user_id
})
.await?;
# Ok(()) }
```
# Errors
The returned future resolves to a [`Canceled`] error if the associated
[`Standby`] instance is dropped.
[`Canceled`]: future::Canceled
[`wait_for_reaction_stream`]: Self::wait_for_reaction_stream
|
wait_for_reaction
|
rust
|
twilight-rs/twilight
|
twilight-standby/src/lib.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-standby/src/lib.rs
|
ISC
|
pub const fn new() -> Self {
Self(InteractionResponseData {
allowed_mentions: None,
attachments: None,
choices: None,
components: None,
content: None,
custom_id: None,
embeds: None,
flags: None,
title: None,
tts: None,
})
}
|
Create a new builder to construct an [`InteractionResponseData`].
|
new
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn attachments(mut self, attachments: impl IntoIterator<Item = Attachment>) -> Self {
self.0.attachments = Some(attachments.into_iter().collect());
self
}
|
Set the attachments of the message.
Defaults to [`None`].
|
attachments
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn choices(mut self, choices: impl IntoIterator<Item = CommandOptionChoice>) -> Self {
self.0.choices = Some(choices.into_iter().collect());
self
}
|
Set the autocomplete choices of the response.
Only valid when the type of the interaction is
[`ApplicationCommandAutocompleteResult`].
[`ApplicationCommandAutocompleteResult`]: twilight_model::http::interaction::InteractionResponseType::ApplicationCommandAutocompleteResult
|
choices
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn components(mut self, components: impl IntoIterator<Item = Component>) -> Self {
self.0.components = Some(components.into_iter().collect());
self
}
|
Set the message [`Component`]s of the callback.
Defaults to [`None`].
|
components
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn content(mut self, content: impl Into<String>) -> Self {
self.0.content = Some(content.into());
self
}
|
Set the message content of the callback.
Defaults to [`None`].
|
content
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn custom_id(mut self, custom_id: impl Into<String>) -> Self {
self.0.custom_id = Some(custom_id.into());
self
}
|
Set the custom ID of the callback.
Defaults to [`None`].
|
custom_id
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn embeds(mut self, embeds: impl IntoIterator<Item = Embed>) -> Self {
self.0.embeds = Some(embeds.into_iter().collect());
self
}
|
Set the [`Embed`]s of the callback.
Defaults to an empty list.
|
embeds
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub const fn flags(mut self, flags: MessageFlags) -> Self {
self.0.flags = Some(flags);
self
}
|
Set the [`MessageFlags`].
The only supported flags are [`EPHEMERAL`] and [`SUPPRESS_EMBEDS`].
Defaults to [`None`].
[`EPHEMERAL`]: twilight_model::channel::message::MessageFlags::EPHEMERAL
[`SUPPRESS_EMBEDS`]: twilight_model::channel::message::MessageFlags::SUPPRESS_EMBEDS
|
flags
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn title(mut self, title: impl Into<String>) -> Self {
self.0.title = Some(title.into());
self
}
|
Set the title of the callback.
Defaults to [`None`].
|
title
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub const fn tts(mut self, value: bool) -> Self {
self.0.tts = Some(value);
self
}
|
Set whether the response has text-to-speech enabled.
Defaults to [`None`].
|
tts
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/interaction_response_data.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/interaction_response_data.rs
|
ISC
|
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
Self(EmbedField {
inline: false,
name: name.into(),
value: value.into(),
})
}
|
Create a new embed field builder.
Refer to [`FIELD_NAME_LENGTH`] for the maximum number of UTF-16 code
points that can be in a field name.
Refer to [`FIELD_VALUE_LENGTH`] for the maximum number of UTF-16 code
points that can be in a field value.
[`FIELD_NAME_LENGTH`]: twilight_validate::embed::FIELD_NAME_LENGTH
[`FIELD_VALUE_LENGTH`]: twilight_validate::embed::FIELD_VALUE_LENGTH
|
new
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/field.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/field.rs
|
ISC
|
pub const fn inline(mut self) -> Self {
self.0.inline = true;
self
}
|
Inline the field.
# Examples
Create an inlined field:
```no_run
use twilight_util::builder::embed::EmbedFieldBuilder;
let field = EmbedFieldBuilder::new("twilight", "is cool")
.inline()
.build();
```
|
inline
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/field.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/field.rs
|
ISC
|
pub fn new(text: impl Into<String>) -> Self {
Self(EmbedFooter {
icon_url: None,
proxy_icon_url: None,
text: text.into(),
})
}
|
Create a new embed footer builder.
Refer to [`FOOTER_TEXT_LENGTH`] for the maximum number of UTF-16 code
points that can be in a footer's text.
[`FOOTER_TEXT_LENGTH`]: twilight_validate::embed::FOOTER_TEXT_LENGTH
|
new
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/footer.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/footer.rs
|
ISC
|
pub fn icon_url(mut self, image_source: ImageSource) -> Self {
self.0.icon_url.replace(image_source.0);
self
}
|
Add a footer icon.
# Examples
Create a footer by Twilight with a URL to an image of its logo:
```
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use twilight_util::builder::embed::{EmbedFooterBuilder, ImageSource};
let icon_url =
ImageSource::url("https://raw.githubusercontent.com/twilight-rs/twilight/main/logo.png")?;
let footer = EmbedFooterBuilder::new("Twilight")
.icon_url(icon_url)
.build();
# Ok(()) }
```
|
icon_url
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/footer.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/footer.rs
|
ISC
|
pub fn attachment(filename: impl AsRef<str>) -> Result<Self, ImageSourceAttachmentError> {
let filename = filename.as_ref();
let dot = filename.rfind('.').ok_or(ImageSourceAttachmentError {
kind: ImageSourceAttachmentErrorType::ExtensionMissing,
})? + 1;
if filename
.get(dot..)
.ok_or(ImageSourceAttachmentError {
kind: ImageSourceAttachmentErrorType::ExtensionMissing,
})?
.is_empty()
{
return Err(ImageSourceAttachmentError {
kind: ImageSourceAttachmentErrorType::ExtensionEmpty,
});
}
Ok(Self(format!("attachment://{filename}")))
}
|
Create an attachment image source.
This will automatically prepend `attachment://` to the source.
# Errors
Returns an [`ImageSourceAttachmentErrorType::ExtensionEmpty`] if an
extension exists but is empty.
Returns an [`ImageSourceAttachmentErrorType::ExtensionMissing`] if an
extension is missing.
|
attachment
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/image_source.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/image_source.rs
|
ISC
|
pub fn url(url: impl Into<String>) -> Result<Self, ImageSourceUrlError> {
let url = url.into();
if !url.starts_with("https:") && !url.starts_with("http:") {
return Err(ImageSourceUrlError {
kind: ImageSourceUrlErrorType::ProtocolUnsupported { url },
});
}
Ok(Self(url))
}
|
Create a URL image source.
The following URL protocols are acceptable:
- https
- http
# Errors
Returns an [`ImageSourceUrlErrorType::ProtocolUnsupported`] error type
if the URL's protocol is unsupported.
|
url
|
rust
|
twilight-rs/twilight
|
twilight-util/src/builder/embed/image_source.rs
|
https://github.com/twilight-rs/twilight/blob/master/twilight-util/src/builder/embed/image_source.rs
|
ISC
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.