Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ jobs:

steps:
- name: Checkout sources
uses: actions/checkout@v2
uses: actions/checkout@v3

- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
Expand Down
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ bot's token. You must also depend on `futures`, `tokio`,
```rust,no_run
use std::{env, error::Error, sync::Arc};
use twilight_cache_inmemory::{InMemoryCache, ResourceType};
use twilight_gateway::{Event, Shard, ShardId};
use twilight_gateway::{Config, Event, Shard, ShardId};
use twilight_http::Client as HttpClient;
use twilight_model::gateway::Intents;

Expand All @@ -133,11 +133,8 @@ async fn main() -> anyhow::Result<()> {
let token = env::var("DISCORD_TOKEN")?;

// Use intents to only receive guild message events.
let mut shard = Shard::new(
ShardId::ONE,
token.clone(),
Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT,
);
let config = Config::new(token.clone(), Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT);
let mut shard = Shard::new(ShardId::ONE, config);

// HTTP is separate from the gateway, so create a new client.
let http = Arc::new(HttpClient::new(token));
Expand Down
6 changes: 3 additions & 3 deletions book/src/chapter_1_crates/section_3_gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,16 @@ Starting a `Shard` and printing the contents of new messages as they come in:

```rust,no_run
use std::{env, error::Error};
use twilight_gateway::{Intents, Shard, ShardId};
use twilight_gateway::{Config, Intents, Shard, ShardId};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// Initialize the tracing subscriber.
tracing_subscriber::fmt::init();

let token = env::var("DISCORD_TOKEN")?;
let intents = Intents::GUILD_MESSAGES;
let mut shard = Shard::new(ShardId::ONE, token, intents);
let config = Config::new(token, Intents::GUILD_MESSAGES);
let mut shard = Shard::new(ShardId::ONE, config);
tracing::info!("created shard");

loop {
Expand Down
5 changes: 3 additions & 2 deletions book/src/chapter_1_crates/section_4_cache_inmemory.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ Process new messages that come over a shard into the cache:
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::env;
use twilight_cache_inmemory::InMemoryCache;
use twilight_gateway::{Intents, Shard, ShardId};
use twilight_gateway::{Config, Intents, Shard, ShardId};

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

let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILD_MESSAGES);
let config = Config::new(token, Intents::GUILD_MESSAGES);
let mut shard = Shard::new(ShardId::ONE, config);

let cache = InMemoryCache::new();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ use std::{
net::SocketAddr,
str::FromStr,
};
use twilight_gateway::{Intents, Shard, ShardId};
use twilight_gateway::{Config, Intents, Shard, ShardId};
use twilight_http::Client as HttpClient;
use twilight_lavalink::Lavalink;

Expand All @@ -65,8 +65,8 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let lavalink = Lavalink::new(user_id, shard_count);
lavalink.add(lavalink_host, lavalink_auth).await?;

let intents = Intents::GUILD_MESSAGES | Intents::GUILD_VOICE_STATES;
let mut shard = Shard::new(ShardId::ONE, token, intents);
let config = Config::new(token, Intents::GUILD_MESSAGES | Intents::GUILD_VOICE_STATES);
let mut shard = Shard::new(ShardId::ONE, config);

loop {
let event = match shard.next_event().await {
Expand Down
6 changes: 3 additions & 3 deletions book/src/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ in from a channel:
```rust,no_run
use std::{env, error::Error, sync::Arc};
use twilight_cache_inmemory::{InMemoryCache, ResourceType};
use twilight_gateway::{Event, Intents, Shard, ShardId};
use twilight_gateway::{Config, Event, Intents, Shard, ShardId};
use twilight_http::Client as HttpClient;

#[tokio::main]
Expand All @@ -58,9 +58,9 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// Specify intents requesting events about things like new and updated
// messages in a guild and direct messages.
let intents = Intents::GUILD_MESSAGES | Intents::DIRECT_MESSAGES | Intents::MESSAGE_CONTENT;

let config = Config::new(token.clone(), intents);
// Create a single shard.
let mut shard = Shard::new(ShardId::ONE, token.clone(), intents);
let mut shard = Shard::new(ShardId::ONE, config);

// The http client is separate from the gateway, so startup a new
// one, also use Arc such that it can be cloned to other threads.
Expand Down
8 changes: 0 additions & 8 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ twilight-lavalink = { path = "../twilight-lavalink" }
twilight-model = { path = "../twilight-model" }
twilight-standby = { path = "../twilight-standby" }

[[example]]
name = "gateway-intents"
path = "gateway-intents.rs"

[[example]]
name = "gateway-parallel"
path = "gateway-parallel.rs"
Expand All @@ -40,10 +36,6 @@ path = "gateway-reshard.rs"
name = "gateway-request-members"
path = "gateway-request-members.rs"

[[example]]
name = "gateway-shard"
path = "gateway-shard.rs"

[[example]]
name = "http-allowed-mentions"
path = "http-allowed-mentions.rs"
Expand Down
31 changes: 0 additions & 31 deletions examples/gateway-intents.rs

This file was deleted.

45 changes: 18 additions & 27 deletions examples/gateway-parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@
//! [`ShardMessageStream`]: twilight_gateway::stream::ShardMessageStream

use futures_util::{future::join_all, StreamExt};
use std::{env, iter, sync::Arc, thread};
use std::{env, iter, thread};
use tokio::{signal, sync::watch, task::JoinSet};
use twilight_gateway::{
queue::LocalQueue,
stream::{self, ShardEventStream},
CloseFrame, Config, Intents, Shard,
};
use twilight_gateway::{stream::ShardEventStream, CloseFrame, Config, Intents, Shard, ShardId};
use twilight_http::Client;

#[tokio::main]
Expand All @@ -21,29 +17,24 @@ async fn main() -> anyhow::Result<()> {
let token = env::var("DISCORD_TOKEN")?;
let client = Client::new(token.clone());

let queue = Arc::new(LocalQueue::new());
// callback to create a config for each shard, useful for when not all
// shards have the same configuration, such as for per-shard presences
let config_callback = |_| {
Config::builder(token.clone(), Intents::GUILDS)
.queue(queue.clone())
.build()
let config = Config::new(token, Intents::GUILDS);
let recommended_shards = client.gateway().authed().await?.model().await?.shards;
let shards = {
let tasks = thread::available_parallelism()?.get();

// Split shards into a vec of `tasks` vecs of shards.
let init = iter::repeat_with(Vec::new)
.take(tasks)
.collect::<Vec<Vec<_>>>();
(0..recommended_shards)
.map(|id| Shard::new(ShardId::new(id, recommended_shards), config.clone()))
.enumerate()
.fold(init, |mut fold, (idx, shard)| {
fold[idx % tasks].push(shard);
fold
})
};

let tasks = thread::available_parallelism()?.get();

// Split shards into a vec of `tasks` vecs of shards.
let init = iter::repeat_with(Vec::new)
.take(tasks)
.collect::<Vec<Vec<_>>>();
let shards = stream::create_recommended(&client, config_callback)
.await?
.enumerate()
.fold(init, |mut fold, (idx, shard)| {
fold[idx % tasks].push(shard);
fold
});

let (tx, rx) = watch::channel(false);

let mut set = JoinSet::new();
Expand Down
11 changes: 5 additions & 6 deletions examples/gateway-request-members.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use std::env;
use twilight_gateway::{Event, Intents, Shard, ShardId};
use twilight_gateway::{Config, Event, Intents, Shard, ShardId};
use twilight_model::{gateway::payload::outgoing::RequestGuildMembers, id::Id};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Initialize the tracing subscriber.
tracing_subscriber::fmt::init();

let mut shard = Shard::new(
ShardId::ONE,
env::var("DISCORD_TOKEN")?,
Intents::GUILD_MEMBERS | Intents::GUILDS,
);
let token = env::var("DISCORD_TOKEN")?;

let config = Config::new(token, Intents::GUILD_MEMBERS | Intents::GUILDS);
let mut shard = Shard::new(ShardId::ONE, config);

loop {
let event = match shard.next_event().await {
Expand Down
36 changes: 12 additions & 24 deletions examples/gateway-reshard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use futures_util::StreamExt;
use std::{env, sync::Arc, time::Duration};
use tokio::time;
use twilight_gateway::{
queue::{LocalQueue, Queue},
stream::{self, ShardEventStream, ShardMessageStream},
stream::{ShardEventStream, ShardMessageStream},
Config, Event, Intents, Shard, ShardId,
};
use twilight_http::Client;
Expand All @@ -15,21 +14,12 @@ async fn main() -> anyhow::Result<()> {

let token = env::var("DISCORD_TOKEN")?;
let client = Arc::new(Client::new(token.clone()));
let queue: Arc<dyn Queue> = Arc::new(LocalQueue::new());

let config_callback = |_| {
// A queue must be specified in the builder for the shards to reuse the
// same one, which is necessary to not hit any gateway queue ratelimit.
Config::builder(
token.clone(),
Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT,
)
.queue(Arc::clone(&queue))
.build()
};
let mut shards = stream::create_recommended(&client, &config_callback)
.await?
.collect::<Vec<_>>();

let config = Config::new(token, Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT);
let recommended_shards = client.gateway().authed().await?.model().await?.shards;
let mut shards = (0..recommended_shards)
.map(|id| Shard::new(ShardId::new(id, recommended_shards), config.clone()))
.collect();

loop {
// Run `gateway_runner` and `reshard` concurrently until the first one
Expand All @@ -40,7 +30,7 @@ async fn main() -> anyhow::Result<()> {
_ = gateway_runner(Arc::clone(&client), shards) => break,
// Resharding complete! Time to run `gateway_runner` with the new
// list of shards.
Ok(Some(new_shards)) = reshard(&client, config_callback) => {
Ok(Some(new_shards)) = reshard(&client, config.clone()) => {
// Assign the new list of shards to `shards`, dropping the
// old list.
shards = new_shards;
Expand Down Expand Up @@ -92,17 +82,15 @@ async fn event_handler(client: Arc<Client>, event: Event) -> anyhow::Result<()>
// Instrument to differentiate between the logs produced here and
// in `gateway_runner`.
#[tracing::instrument(skip_all)]
async fn reshard(
client: &Client,
config_callback: impl Fn(ShardId) -> Config,
) -> anyhow::Result<Option<Vec<Shard>>> {
async fn reshard(client: &Client, config: Config) -> anyhow::Result<Option<Vec<Shard>>> {
const RESHARD_DURATION: Duration = Duration::from_secs(60 * 60 * 8);

// Reshard every eight hours.
time::sleep(RESHARD_DURATION).await;

let mut shards = stream::create_recommended(client, config_callback)
.await?
let recommended_shards = client.gateway().authed().await?.model().await?.shards;
let mut shards = (0..recommended_shards)
.map(|id| Shard::new(ShardId::new(id, recommended_shards), config.clone()))
.collect::<Vec<_>>();

let mut identified = vec![false; shards.len()];
Expand Down
30 changes: 0 additions & 30 deletions examples/gateway-shard.rs

This file was deleted.

5 changes: 3 additions & 2 deletions examples/lavalink-basic-bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use hyper::{
Body, Request,
};
use std::{env, future::Future, net::SocketAddr, str::FromStr, sync::Arc};
use twilight_gateway::{Event, Intents, MessageSender, Shard, ShardId};
use twilight_gateway::{Config, Event, Intents, MessageSender, Shard, ShardId};
use twilight_http::Client as HttpClient;
use twilight_lavalink::{
http::LoadedTracks,
Expand Down Expand Up @@ -54,7 +54,8 @@ async fn main() -> anyhow::Result<()> {

let intents =
Intents::GUILD_MESSAGES | Intents::GUILD_VOICE_STATES | Intents::MESSAGE_CONTENT;
let shard = Shard::new(ShardId::ONE, token, intents);
let config = Config::new(token, intents);
let shard = Shard::new(ShardId::ONE, config);
let sender = shard.sender();

(
Expand Down
5 changes: 3 additions & 2 deletions twilight-cache-inmemory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,16 @@ Update a cache with events that come in through the gateway:
```rust,no_run
use std::{env, error::Error};
use twilight_cache_inmemory::InMemoryCache;
use twilight_gateway::{Intents, Shard, ShardId};
use twilight_gateway::{Config, Intents, Shard, ShardId};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Initialize the tracing subscriber.
tracing_subscriber::fmt::init();

let token = env::var("DISCORD_TOKEN")?;
let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILD_MESSAGES);
let config = Config::new(token, Intents::GUILD_MESSAGES);
let mut shard = Shard::new(ShardId::ONE, config);

// Create a cache, caching up to 10 messages per channel:
let cache = InMemoryCache::builder().message_cache_size(10).build();
Expand Down
Loading