Skip to content

Commit

Permalink
Improve token semantics
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrasnitski committed Nov 19, 2024
1 parent 41229ac commit 6e246ad
Show file tree
Hide file tree
Showing 18 changed files with 218 additions and 192 deletions.
7 changes: 5 additions & 2 deletions examples/e02_transparent_guild_sharding/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,15 @@ impl EventHandler for Handler {
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment")
.parse()
.expect("Invalid token");
let intents = GatewayIntents::GUILD_MESSAGES
| GatewayIntents::DIRECT_MESSAGES
| GatewayIntents::MESSAGE_CONTENT;
let mut client =
Client::builder(&token, intents).event_handler(Handler).await.expect("Err creating client");
Client::builder(token, intents).event_handler(Handler).await.expect("Err creating client");

// The total number of shards to use. The "current shard number" of a shard - that is, the
// shard it is assigned to - is indexed at 0, while the total shard count is indexed at 1.
Expand Down
7 changes: 5 additions & 2 deletions examples/e07_shard_manager/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,16 @@ impl EventHandler for Handler {
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment")
.parse()
.expect("Invalid token");

let intents = GatewayIntents::GUILD_MESSAGES
| GatewayIntents::DIRECT_MESSAGES
| GatewayIntents::MESSAGE_CONTENT;
let mut client =
Client::builder(&token, intents).event_handler(Handler).await.expect("Err creating client");
Client::builder(token, intents).event_handler(Handler).await.expect("Err creating client");

// Here we clone a lock to the Shard Manager, and then move it into a new thread. The thread
// will unlock the manager and print shards' status on a loop.
Expand Down
7 changes: 5 additions & 2 deletions examples/e10_gateway_intents/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ impl EventHandler for Handler {
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment")
.parse()
.expect("Invalid token");

// Intents are a bitflag, bitwise operations can be used to dictate which intents to use
let intents =
GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT;
// Build our client.
let mut client = Client::builder(&token, intents)
let mut client = Client::builder(token, intents)
.event_handler(Handler)
.await
.expect("Error creating client");
Expand Down
7 changes: 5 additions & 2 deletions examples/e13_sqlite_database/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ impl EventHandler for Bot {
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
let token = std::env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let token = std::env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment")
.parse()
.expect("Invalid token");

// Initiate a connection to the database file, creating the file if required.
let database = sqlx::sqlite::SqlitePoolOptions::new()
Expand All @@ -96,6 +99,6 @@ async fn main() {
| GatewayIntents::DIRECT_MESSAGES
| GatewayIntents::MESSAGE_CONTENT;
let mut client =
Client::builder(&token, intents).event_handler(bot).await.expect("Err creating client");
Client::builder(token, intents).event_handler(bot).await.expect("Err creating client");
client.start().await.unwrap();
}
2 changes: 1 addition & 1 deletion examples/e15_webhook/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serenity::model::webhook::Webhook;
#[tokio::main]
async fn main() {
// You don't need a token when you are only dealing with webhooks.
let http = Http::new("");
let http = Http::new();
let webhook = Webhook::from_url(&http, "https://discord.com/api/webhooks/133742013374206969/hello-there-oPNtRN5UY5DVmBe7m1N0HE-replace-me-Dw9LRkgq3zI7LoW3Rb-k-q")
.await
.expect("Replace the webhook with your own");
Expand Down
41 changes: 21 additions & 20 deletions src/gateway/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ use crate::gateway::{
ShardManagerOptions,
DEFAULT_WAIT_BETWEEN_SHARD_START,
};
use crate::http::{parse_token, Http};
use crate::http::Http;
use crate::internal::prelude::*;
use crate::internal::tokio::spawn_named;
use crate::model::gateway::GatewayIntents;
Expand All @@ -70,7 +70,7 @@ use crate::model::user::OnlineStatus;
/// A builder implementing [`IntoFuture`] building a [`Client`] to interact with Discord.
#[must_use = "Builders do nothing unless they are awaited"]
pub struct ClientBuilder {
token: SecretString,
token: Token,
data: Option<Arc<dyn std::any::Any + Send + Sync>>,
http: Arc<Http>,
intents: GatewayIntents,
Expand All @@ -94,8 +94,8 @@ impl ClientBuilder {
/// **Panic**: If you have enabled the `framework`-feature (on by default), you must specify a
/// framework via the [`Self::framework`] method, otherwise awaiting the builder will cause a
/// panic.
pub fn new(token: &str, intents: GatewayIntents) -> Self {
Self::new_with_http(token, Arc::new(Http::new(token)), intents)
pub fn new(token: Token, intents: GatewayIntents) -> Self {
Self::new_with_http(token.clone(), Arc::new(Http::with_token(token)), intents)
}

/// Construct a new builder with a [`Http`] instance to calls methods on for the client
Expand All @@ -104,9 +104,9 @@ impl ClientBuilder {
/// **Panic**: If you have enabled the `framework`-feature (on by default), you must specify a
/// framework via the [`Self::framework`] method, otherwise awaiting the builder will cause a
/// panic.
pub fn new_with_http(token: &str, http: Arc<Http>, intents: GatewayIntents) -> Self {
pub fn new_with_http(token: Token, http: Arc<Http>, intents: GatewayIntents) -> Self {
Self {
token: SecretString::new(parse_token(token)),
token,
http,
intents,
data: None,
Expand Down Expand Up @@ -416,8 +416,9 @@ impl IntoFuture for ClientBuilder {
/// }
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client =
/// Client::builder("my token here", GatewayIntents::default()).event_handler(Handler).await?;
/// Client::builder(token, GatewayIntents::default()).event_handler(Handler).await?;
///
/// client.start().await?;
/// # Ok(())
Expand Down Expand Up @@ -500,7 +501,7 @@ pub struct Client {
}

impl Client {
pub fn builder(token: &str, intents: GatewayIntents) -> ClientBuilder {
pub fn builder(token: Token, intents: GatewayIntents) -> ClientBuilder {
ClientBuilder::new(token, intents)
}

Expand Down Expand Up @@ -543,8 +544,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start().await {
/// println!("Err with client: {:?}", why);
Expand Down Expand Up @@ -586,8 +587,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start_autosharded().await {
/// println!("Err with client: {:?}", why);
Expand Down Expand Up @@ -633,8 +634,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start_shard(3, 5).await {
/// println!("Err with client: {:?}", why);
Expand All @@ -652,8 +653,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start_shard(0, 1).await {
/// println!("Err with client: {:?}", why);
Expand Down Expand Up @@ -695,8 +696,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start_shards(8).await {
/// println!("Err with client: {:?}", why);
Expand Down Expand Up @@ -738,8 +739,8 @@ impl Client {
/// use serenity::Client;
///
/// # async fn run() -> Result<(), Box<dyn Error>> {
/// let token = std::env::var("DISCORD_TOKEN")?;
/// let mut client = Client::builder(&token, GatewayIntents::default()).await?;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
/// let mut client = Client::builder(token, GatewayIntents::default()).await?;
///
/// if let Err(why) = client.start_shard_range(4..7, 10).await {
/// println!("Err with client: {:?}", why);
Expand Down
7 changes: 3 additions & 4 deletions src/gateway/sharding/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub struct Shard {
// This acts as a timeout to determine if the shard has - for some reason - not started within
// a decent amount of time.
pub started: Instant,
token: SecretString,
token: Token,
ws_url: Arc<str>,
resume_ws_url: Option<FixedString>,
compression: TransportCompression,
Expand All @@ -136,14 +136,13 @@ impl Shard {
/// use serenity::gateway::{Shard, TransportCompression};
/// use serenity::model::gateway::{GatewayIntents, ShardInfo};
/// use serenity::model::id::ShardId;
/// use serenity::secret_string::SecretString;
/// use tokio::sync::Mutex;
/// #
/// # use serenity::http::Http;
/// #
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http: Arc<Http> = unimplemented!();
/// let token = SecretString::new(Arc::from(std::env::var("DISCORD_BOT_TOKEN")?));
/// let token = std::env::var("DISCORD_BOT_TOKEN")?.parse()?;
/// let shard_info = ShardInfo {
/// id: ShardId(0),
/// total: NonZeroU16::MIN,
Expand Down Expand Up @@ -173,7 +172,7 @@ impl Shard {
/// TLS error.
pub async fn new(
ws_url: Arc<str>,
token: SecretString,
token: Token,
shard_info: ShardInfo,
intents: GatewayIntents,
presence: Option<PresenceData>,
Expand Down
6 changes: 3 additions & 3 deletions src/gateway/sharding/shard_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ pub const DEFAULT_WAIT_BETWEEN_SHARD_START: Duration = Duration::from_secs(5);
/// use std::env;
/// use std::sync::{Arc, OnceLock};
///
/// # use serenity::secret_string::SecretString;
/// use serenity::gateway::client::EventHandler;
/// use serenity::gateway::{
/// ShardManager,
Expand All @@ -85,9 +84,10 @@ pub const DEFAULT_WAIT_BETWEEN_SHARD_START: Duration = Duration::from_secs(5);
/// let ws_url = Arc::from(gateway_info.url);
/// let event_handler = Arc::new(Handler);
/// let max_concurrency = std::num::NonZeroU16::MIN;
/// let token = std::env::var("DISCORD_TOKEN")?.parse()?;
///
/// ShardManager::new(ShardManagerOptions {
/// # token,
/// token,
/// data,
/// event_handler: Some(event_handler),
/// raw_event_handler: None,
Expand Down Expand Up @@ -380,7 +380,7 @@ impl Drop for ShardManager {
}

pub struct ShardManagerOptions {
pub token: SecretString,
pub token: Token,
pub data: Arc<dyn std::any::Any + Send + Sync>,
pub event_handler: Option<Arc<dyn EventHandler>>,
pub raw_event_handler: Option<Arc<dyn RawEventHandler>>,
Expand Down
2 changes: 1 addition & 1 deletion src/gateway/sharding/shard_queuer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use crate::model::gateway::{GatewayIntents, ShardInfo};
/// A shard queuer instance _should_ be run in its own thread, due to the blocking nature of the
/// loop itself as well as a 5 second thread sleep between shard starts.
pub struct ShardQueuer {
pub(super) token: SecretString,
pub(super) token: Token,
/// A copy of [`Client::data`] to be given to runners for contextual dispatching.
///
/// [`Client::data`]: crate::Client::data
Expand Down
Loading

0 comments on commit 6e246ad

Please sign in to comment.