Skip to content

Commit e552918

Browse files
authored
Remove ShardMessenger and clean up ShardRunner (#3120)
Follow up to #3108. Inlines the fields and methods of `ShardMessenger` into `Context` and changes collectors to take `&Context`. Also, removes the `ShardRunnerMessage::{Close, Message}` variants, adds an `UpdateVoiceState` variant (Songbird will want to use this) and combines the 3 presence-related variants into one. Plus some miscellaneous cleanup of the `ShardRunner` code.
1 parent 9a811a7 commit e552918

File tree

11 files changed

+411
-471
lines changed

11 files changed

+411
-471
lines changed

examples/e09_collectors/src/main.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ impl EventHandler for Handler {
2626
// There is a method implemented for some models to conveniently collect replies. They
2727
// return a builder that can be turned into a Stream, or here, where we can await a
2828
// single reply
29-
let collector =
30-
msg.author.id.collect_messages(ctx.shard.clone()).timeout(Duration::from_secs(10));
29+
let collector = msg.author.id.collect_messages(&ctx).timeout(Duration::from_secs(10));
3130
if let Some(answer) = collector.await {
3231
if answer.content.to_lowercase() == "ferris" {
3332
let _ = answer.reply(&ctx.http, "That's correct!").await;
@@ -47,7 +46,7 @@ impl EventHandler for Handler {
4746
// The message model can also be turned into a Collector to collect reactions on it.
4847
let collector = react_msg
4948
.id
50-
.collect_reactions(ctx.shard.clone())
49+
.collect_reactions(&ctx)
5150
.timeout(Duration::from_secs(10))
5251
.author_id(msg.author.id);
5352

@@ -65,7 +64,7 @@ impl EventHandler for Handler {
6564
let _ = msg.reply(&ctx.http, "Write 5 messages in 10 seconds").await;
6665

6766
// We can create a collector from scratch too using this builder future.
68-
let collector = MessageCollector::new(ctx.shard.clone())
67+
let collector = MessageCollector::new(&ctx)
6968
// Only collect messages by this user.
7069
.author_id(msg.author.id)
7170
.channel_id(msg.channel_id)
@@ -100,7 +99,7 @@ impl EventHandler for Handler {
10099
// We can also collect arbitrary events using the collect() function. For example, here we
101100
// collect updates to the messages that the user sent above and check for them updating all
102101
// 5 of them.
103-
let mut collector = serenity::collector::collect(&ctx.shard, move |event| match event {
102+
let mut collector = serenity::collector::collect(&ctx, move |event| match event {
104103
// Only collect MessageUpdate events for the 5 MessageIds we're interested in.
105104
Event::MessageUpdate(event)
106105
if collected.iter().any(|msg| event.message.id == msg.id) =>

examples/e14_message_components/src/main.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl EventHandler for Handler {
6060
// manually in the EventHandler.
6161
let interaction = match m
6262
.id
63-
.collect_component_interactions(ctx.shard.clone())
63+
.collect_component_interactions(&ctx)
6464
.timeout(Duration::from_secs(60 * 3))
6565
.await
6666
{
@@ -108,9 +108,7 @@ impl EventHandler for Handler {
108108

109109
// Wait for multiple interactions
110110
let mut interaction_stream =
111-
m.id.collect_component_interactions(ctx.shard.clone())
112-
.timeout(Duration::from_secs(60 * 3))
113-
.stream();
111+
m.id.collect_component_interactions(&ctx).timeout(Duration::from_secs(60 * 3)).stream();
114112

115113
while let Some(interaction) = interaction_stream.next().await {
116114
let sound = &interaction.data.custom_id;

examples/testing/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
122122
.await?;
123123
let button_press = msg
124124
.id
125-
.collect_component_interactions(ctx.shard.clone())
125+
.collect_component_interactions(ctx)
126126
.timeout(std::time::Duration::from_secs(10))
127127
.await;
128128
match button_press {
@@ -181,7 +181,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
181181
.await?;
182182

183183
let msg_id = msg.id;
184-
let mut message_updates = serenity::collector::collect(&ctx.shard, move |ev| match ev {
184+
let mut message_updates = serenity::collector::collect(ctx, move |ev| match ev {
185185
Event::MessageUpdate(x) if x.message.id == msg_id => Some(()),
186186
_ => None,
187187
});

src/collector/mod.rs

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ use futures::future::pending;
66
use futures::{Stream, StreamExt as _};
77
pub use quick_modal::*;
88

9-
use crate::gateway::{CollectorCallback, ShardMessenger};
9+
use crate::gateway::CollectorCallback;
10+
use crate::gateway::client::Context;
1011
use crate::internal::prelude::*;
1112
use crate::model::prelude::*;
1213

@@ -18,10 +19,10 @@ use crate::model::prelude::*;
1819
/// # use std::time::Duration;
1920
/// # use futures::StreamExt as _;
2021
/// # use serenity::model::prelude::Event;
21-
/// # use serenity::gateway::ShardMessenger;
22+
/// # use serenity::gateway::client::Context;
2223
/// # use serenity::collector::collect;
23-
/// # async fn example_(shard: &ShardMessenger) {
24-
/// let stream = collect(shard, |event| match event {
24+
/// # async fn example_(ctx: &Context) {
25+
/// let stream = collect(ctx, |event| match event {
2526
/// Event::ReactionRemove(event) => Some(event.reaction.clone()),
2627
/// _ => None,
2728
/// });
@@ -33,18 +34,20 @@ use crate::model::prelude::*;
3334
/// .await;
3435
/// # }
3536
/// ```
36-
pub fn collect<T, F>(shard: &ShardMessenger, extractor: F) -> impl Stream<Item = T> + use<T, F>
37+
pub fn collect<T, F>(ctx: &Context, extractor: F) -> impl Stream<Item = T> + use<T, F>
3738
where
3839
T: Send + 'static,
3940
F: Fn(&Event) -> Option<T> + Send + Sync + 'static,
4041
{
4142
let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
4243

4344
// Register an event callback in the shard. It's kept alive as long as we return `true`
44-
shard.add_collector(CollectorCallback(Arc::new(move |event| match extractor(event) {
45-
// If this event matches, we send it to the receiver stream
46-
Some(item) => sender.send(item).is_ok(),
47-
None => !sender.is_closed(),
45+
ctx.collectors.write().push(CollectorCallback(Arc::new(move |event| {
46+
match extractor(event) {
47+
// If this event matches, we send it to the receiver stream
48+
Some(item) => sender.send(item).is_ok(),
49+
None => !sender.is_closed(),
50+
}
4851
})));
4952

5053
// Convert the mpsc Receiver into a Stream
@@ -62,18 +65,18 @@ macro_rules! make_specific_collector {
6265
#[doc = concat!("A [`", stringify!($collector_type), "`] receives [`", stringify!($item_type), "`]'s match the given filters for a set duration.")]
6366
$( #[ $($meta)* ] )*
6467
#[must_use]
65-
pub struct $collector_type {
66-
shard: ShardMessenger,
68+
pub struct $collector_type<'a> {
69+
ctx: &'a Context,
6770
duration: Option<std::time::Duration>,
6871
filter: Option<Box<dyn Fn(&$item_type) -> bool + Send + Sync>>,
6972
$( $filter_name: Option<$filter_type>, )*
7073
}
7174

72-
impl $collector_type {
75+
impl<'a> $collector_type<'a> {
7376
/// Creates a new collector without any filters configured.
74-
pub fn new(shard: ShardMessenger) -> Self {
77+
pub fn new(ctx: &'a Context) -> Self {
7578
Self {
76-
shard,
79+
ctx,
7780
duration: None,
7881
filter: None,
7982
$( $filter_name: None, )*
@@ -124,7 +127,7 @@ macro_rules! make_specific_collector {
124127
None => pending::<()>().await,
125128
} };
126129

127-
let stream = collect(&self.shard, move |event| match event {
130+
let stream = collect(&self.ctx, move |event| match event {
128131
$extractor if filters_pass($extracted_item) => Some($extracted_item.clone()),
129132
_ => None,
130133
});
@@ -139,23 +142,23 @@ macro_rules! make_specific_collector {
139142
}
140143
}
141144

142-
impl IntoFuture for $collector_type {
145+
impl<'a> IntoFuture for $collector_type<'a> {
143146
type Output = Option<$item_type>;
144-
type IntoFuture = futures::future::BoxFuture<'static, Self::Output>;
147+
type IntoFuture = futures::future::BoxFuture<'a, Self::Output>;
145148

146149
fn into_future(self) -> Self::IntoFuture {
147150
Box::pin(self.next())
148151
}
149152
}
150153

151154
pub trait $collector_trait {
152-
fn $method_name(self, shard_messenger: ShardMessenger) -> $collector_type;
155+
fn $method_name(self, ctx: &Context) -> $collector_type<'_>;
153156
}
154157

155158
$(
156159
impl $collector_trait for $filter_type {
157-
fn $method_name(self, shard_messenger: ShardMessenger) -> $collector_type {
158-
$collector_type::new(shard_messenger).$filter_name(self)
160+
fn $method_name(self, ctx: &Context) -> $collector_type<'_> {
161+
$collector_type::new(ctx).$filter_name(self)
159162
}
160163
}
161164
)*

src/collector/quick_modal.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ impl<'a> CreateQuickModal<'a> {
9898
);
9999
builder.execute(&ctx.http, interaction_id, token).await?;
100100

101-
let collector = ModalInteractionCollector::new(ctx.shard.clone())
101+
let collector = ModalInteractionCollector::new(ctx)
102102
.custom_ids(vec![FixedString::from_str_trunc(&modal_custom_id)]);
103103

104104
let collector = match self.timeout {

0 commit comments

Comments
 (0)