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

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