Skip to main content

Context

Struct Context 

Source
pub struct Context {
    pub http: Arc<Http>,
    pub cache: Arc<Cache>,
    pub gateway_tx: Arc<Sender<String>>,
    pub voice_states: Arc<Mutex<HashMap<String, VoiceState>>>,
    /* private fields */
}
Expand description

Shared state passed into every event handler call. This is how you interact with the API from inside your event handlers.

ctx.http.send_message("channel_id", "Hello!").await.unwrap();

Fields§

§http: Arc<Http>

HTTP client for REST API calls.

§cache: Arc<Cache>

In-memory cache populated automatically from gateway events.

§gateway_tx: Arc<Sender<String>>

Raw gateway sender. You probably won’t need this directly – voice join/leave use it internally.

§voice_states: Arc<Mutex<HashMap<String, VoiceState>>>

Per-guild voice state, populated from VOICE_STATE_UPDATE and VOICE_SERVER_UPDATE. Used internally by join_voice / leave_voice.

Implementations§

Source§

impl Context

Source

pub async fn join_voice( &self, guild_id: &str, channel_id: &str, ) -> Result<FluxerVoiceConnection, ClientError>

Joins a voice channel. Sends an opcode 4 to the gateway and waits up to 10 seconds for the server to send back connection details.

Examples found in repository?
examples/voice.rs (line 56)
28    async fn on_message(&self, ctx: Context, msg: Message) {
29        if msg.author.bot.unwrap_or(false) {
30            return;
31        }
32
33        let content = match msg.content.as_deref() {
34            Some(c) => c,
35            None => return,
36        };
37
38        let channel_id = msg.channel_id.as_deref().unwrap_or_default();
39        let guild_id = match msg.guild_id.as_deref() {
40            Some(id) => id,
41            None => return,
42        };
43
44        let (cmd, args) = match parse_command(content) {
45            Some(v) => v,
46            None => return,
47        };
48
49        match cmd {
50            "join" => {
51                if args.is_empty() {
52                    let _ = ctx.http.send_message(channel_id, "`!join <voice_channel_id>`").await;
53                    return;
54                }
55
56                match ctx.join_voice(guild_id, args).await {
57                    Ok(conn) => {
58                        *self.voice.lock().await = Some(conn);
59                        let _ = ctx.http.send_message(channel_id, "Joined.").await;
60                    }
61                    Err(e) => {
62                        let _ = ctx.http.send_message(channel_id, &format!("Failed: {}", e)).await;
63                    }
64                }
65            }
66
67            "leave" => {
68                if let Some(handle) = self.playback.lock().await.take() {
69                    handle.abort();
70                }
71                *self.voice.lock().await = None;
72                let _ = ctx.leave_voice(guild_id).await;
73                let _ = ctx.http.send_message(channel_id, "Left.").await;
74            }
75
76            "play" => {
77                let conn = self.voice.lock().await;
78                let conn = match conn.as_ref() {
79                    Some(c) => c,
80                    None => {
81                        let _ = ctx.http.send_message(channel_id, "Not in a voice channel.").await;
82                        return;
83                    }
84                };
85
86                if let Some(handle) = self.playback.lock().await.take() {
87                    handle.abort();
88                }
89
90                match conn.play_music(AUDIO_FILE, ctx.http.clone(), channel_id.to_string()).await {
91                    Ok(handle) => {
92                        *self.playback.lock().await = Some(handle);
93                        let _ = ctx.http.send_message(channel_id, &format!("Playing `{}`.", AUDIO_FILE)).await;
94                    }
95                    Err(e) => {
96                        let _ = ctx.http.send_message(channel_id, &format!("Failed: {}", e)).await;
97                    }
98                }
99            }
100
101            "stop" => {
102                if let Some(handle) = self.playback.lock().await.take() {
103                    handle.abort();
104                    let _ = ctx.http.send_message(channel_id, "Stopped.").await;
105                } else {
106                    let _ = ctx.http.send_message(channel_id, "Nothing is playing.").await;
107                }
108            }
109
110            _ => {}
111        }
112    }
Source

pub async fn leave_voice(&self, guild_id: &str) -> Result<(), ClientError>

Leaves a voice channel. Closes the LiveKit room and tells the gateway.

Examples found in repository?
examples/voice.rs (line 72)
28    async fn on_message(&self, ctx: Context, msg: Message) {
29        if msg.author.bot.unwrap_or(false) {
30            return;
31        }
32
33        let content = match msg.content.as_deref() {
34            Some(c) => c,
35            None => return,
36        };
37
38        let channel_id = msg.channel_id.as_deref().unwrap_or_default();
39        let guild_id = match msg.guild_id.as_deref() {
40            Some(id) => id,
41            None => return,
42        };
43
44        let (cmd, args) = match parse_command(content) {
45            Some(v) => v,
46            None => return,
47        };
48
49        match cmd {
50            "join" => {
51                if args.is_empty() {
52                    let _ = ctx.http.send_message(channel_id, "`!join <voice_channel_id>`").await;
53                    return;
54                }
55
56                match ctx.join_voice(guild_id, args).await {
57                    Ok(conn) => {
58                        *self.voice.lock().await = Some(conn);
59                        let _ = ctx.http.send_message(channel_id, "Joined.").await;
60                    }
61                    Err(e) => {
62                        let _ = ctx.http.send_message(channel_id, &format!("Failed: {}", e)).await;
63                    }
64                }
65            }
66
67            "leave" => {
68                if let Some(handle) = self.playback.lock().await.take() {
69                    handle.abort();
70                }
71                *self.voice.lock().await = None;
72                let _ = ctx.leave_voice(guild_id).await;
73                let _ = ctx.http.send_message(channel_id, "Left.").await;
74            }
75
76            "play" => {
77                let conn = self.voice.lock().await;
78                let conn = match conn.as_ref() {
79                    Some(c) => c,
80                    None => {
81                        let _ = ctx.http.send_message(channel_id, "Not in a voice channel.").await;
82                        return;
83                    }
84                };
85
86                if let Some(handle) = self.playback.lock().await.take() {
87                    handle.abort();
88                }
89
90                match conn.play_music(AUDIO_FILE, ctx.http.clone(), channel_id.to_string()).await {
91                    Ok(handle) => {
92                        *self.playback.lock().await = Some(handle);
93                        let _ = ctx.http.send_message(channel_id, &format!("Playing `{}`.", AUDIO_FILE)).await;
94                    }
95                    Err(e) => {
96                        let _ = ctx.http.send_message(channel_id, &format!("Failed: {}", e)).await;
97                    }
98                }
99            }
100
101            "stop" => {
102                if let Some(handle) = self.playback.lock().await.take() {
103                    handle.abort();
104                    let _ = ctx.http.send_message(channel_id, "Stopped.").await;
105                } else {
106                    let _ = ctx.http.send_message(channel_id, "Nothing is playing.").await;
107                }
108            }
109
110            _ => {}
111        }
112    }

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Context

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more