1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use super::{DiscordHandler, DiscordMsg};
use async_trait::async_trait;

/// Prints events at [`tracing::Level::DEBUG`] and errors at [`tracing::Level::WARN`]
pub struct Printer;

#[async_trait]
impl DiscordHandler for Printer {
    async fn on_message(&self, msg: DiscordMsg) {
        match msg {
            DiscordMsg::Event(eve) => tracing::debug!(event = ?eve),
            DiscordMsg::Error(err) => tracing::warn!(error = ?err),
        }
    }
}

/// Forwards messages to a receiver
///
/// ```no_run
/// use discord_sdk as ds;
/// let (forwarder, mut events) = ds::handlers::Forwarder::new();
/// let discord = ds::Discord::new(ds::DiscordApp::PlainId(1), ds::Subscriptions::ALL, Box::new(forwarder)).unwrap();
/// ```
pub struct Forwarder {
    tx: tokio::sync::mpsc::UnboundedSender<DiscordMsg>,
}

impl Forwarder {
    pub fn new() -> (Self, tokio::sync::mpsc::UnboundedReceiver<DiscordMsg>) {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

        (Self { tx }, rx)
    }
}

#[async_trait]
impl DiscordHandler for Forwarder {
    async fn on_message(&self, msg: DiscordMsg) {
        if let Err(msg) = self.tx.send(msg) {
            tracing::warn!(msg = ?msg.0, "message dropped");
        }
    }
}