|
| 1 | +use super::{PinnedBoxedFutureResult, Priority, Service, ServiceInfo, ServiceInternals}; |
| 2 | +use log::info; |
| 3 | +use serenity::{ |
| 4 | + all::{GatewayIntents, Ready}, |
| 5 | + async_trait, |
| 6 | + client::{self, Cache, Context}, |
| 7 | + framework::{standard::Configuration, StandardFramework}, |
| 8 | + gateway::{ShardManager, VoiceGatewayManager}, |
| 9 | + http::Http, |
| 10 | + prelude::TypeMap, |
| 11 | + Client, Error, |
| 12 | +}; |
| 13 | +use std::{sync::Arc, time::Duration}; |
| 14 | +use tokio::{ |
| 15 | + sync::{Mutex, Notify, RwLock}, |
| 16 | + task::JoinHandle, |
| 17 | + time::timeout, |
| 18 | +}; |
| 19 | + |
| 20 | +pub struct DiscordService { |
| 21 | + info: ServiceInfo, |
| 22 | + discord_token: String, |
| 23 | + connection_timeout: Duration, |
| 24 | + pub client: Arc<Mutex<Option<Ready>>>, |
| 25 | + client_handle: Option<JoinHandle<Result<(), Error>>>, |
| 26 | + pub cache: Option<Arc<Cache>>, |
| 27 | + pub data: Option<Arc<RwLock<TypeMap>>>, |
| 28 | + pub http: Option<Arc<Http>>, |
| 29 | + pub shard_manager: Option<Arc<ShardManager>>, |
| 30 | + pub voice_manager: Option<Arc<dyn VoiceGatewayManager>>, |
| 31 | + pub ws_url: Option<Arc<Mutex<String>>>, |
| 32 | +} |
| 33 | + |
| 34 | +impl DiscordService { |
| 35 | + pub fn new(discord_token: &str, connection_timeout: Duration) -> Self { |
| 36 | + Self { |
| 37 | + info: ServiceInfo::new("lum_builtin_discord", "Discord", Priority::Essential), |
| 38 | + discord_token: discord_token.to_string(), |
| 39 | + connection_timeout, |
| 40 | + client: Arc::new(Mutex::new(None)), |
| 41 | + client_handle: None, |
| 42 | + cache: None, |
| 43 | + data: None, |
| 44 | + http: None, |
| 45 | + shard_manager: None, |
| 46 | + voice_manager: None, |
| 47 | + ws_url: None, |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl ServiceInternals for DiscordService { |
| 53 | + fn start(&mut self) -> PinnedBoxedFutureResult<'_, ()> { |
| 54 | + Box::pin(async move { |
| 55 | + let framework = StandardFramework::new(); |
| 56 | + framework.configure(Configuration::new().prefix("!")); |
| 57 | + |
| 58 | + let client_ready_notify = Arc::new(Notify::new()); |
| 59 | + |
| 60 | + let mut client = Client::builder(self.discord_token.as_str(), GatewayIntents::all()) |
| 61 | + .framework(framework) |
| 62 | + .event_handler(EventHandler::new( |
| 63 | + Arc::clone(&self.client), |
| 64 | + Arc::clone(&client_ready_notify), |
| 65 | + )) |
| 66 | + .await?; |
| 67 | + |
| 68 | + self.cache = Some(Arc::clone(&client.cache)); |
| 69 | + self.data = Some(Arc::clone(&client.data)); |
| 70 | + self.http = Some(Arc::clone(&client.http)); |
| 71 | + self.shard_manager = Some(Arc::clone(&client.shard_manager)); |
| 72 | + if let Some(shard_manager) = &self.shard_manager { |
| 73 | + self.shard_manager = Some(Arc::clone(shard_manager)); |
| 74 | + } |
| 75 | + if let Some(voice_manager) = &self.voice_manager { |
| 76 | + self.voice_manager = Some(Arc::clone(voice_manager)); |
| 77 | + } |
| 78 | + self.ws_url = Some(Arc::clone(&client.ws_url)); |
| 79 | + |
| 80 | + info!("Connecting to Discord"); |
| 81 | + let client_handle = tokio::spawn(async move { client.start().await }); |
| 82 | + |
| 83 | + if timeout(self.connection_timeout, client_ready_notify.notified()) |
| 84 | + .await |
| 85 | + .is_err() |
| 86 | + { |
| 87 | + client_handle.abort(); |
| 88 | + |
| 89 | + return Err(format!( |
| 90 | + "Discord client failed to connect within {} seconds", |
| 91 | + self.connection_timeout.as_secs() |
| 92 | + ) |
| 93 | + .into()); |
| 94 | + } |
| 95 | + |
| 96 | + if client_handle.is_finished() { |
| 97 | + client_handle.await??; |
| 98 | + return Err("Discord client stopped unexpectedly and with no error".into()); |
| 99 | + } |
| 100 | + |
| 101 | + self.client_handle = Some(client_handle); |
| 102 | + Ok(()) |
| 103 | + }) |
| 104 | + } |
| 105 | + |
| 106 | + fn stop(&mut self) -> PinnedBoxedFutureResult<'_, ()> { |
| 107 | + Box::pin(async move { |
| 108 | + if let Some(handle) = self.client_handle.take() { |
| 109 | + info!("Waiting for Discord client to stop..."); |
| 110 | + handle.abort(); |
| 111 | + |
| 112 | + let result = match handle.await { |
| 113 | + Ok(result) => result, |
| 114 | + Err(_) => { |
| 115 | + info!("Discord client stopped"); |
| 116 | + return Ok(()); |
| 117 | + } |
| 118 | + }; |
| 119 | + |
| 120 | + result?; |
| 121 | + } |
| 122 | + |
| 123 | + Ok(()) |
| 124 | + }) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +impl Service for DiscordService { |
| 129 | + fn info(&self) -> &ServiceInfo { |
| 130 | + &self.info |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +struct EventHandler { |
| 135 | + client: Arc<Mutex<Option<Ready>>>, |
| 136 | + ready_notify: Arc<Notify>, |
| 137 | +} |
| 138 | + |
| 139 | +impl EventHandler { |
| 140 | + pub fn new(client: Arc<Mutex<Option<Ready>>>, ready_notify: Arc<Notify>) -> Self { |
| 141 | + Self { |
| 142 | + client, |
| 143 | + ready_notify, |
| 144 | + } |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +#[async_trait] |
| 149 | +impl client::EventHandler for EventHandler { |
| 150 | + async fn ready(&self, _ctx: Context, data_about_bot: Ready) { |
| 151 | + info!("Connected to Discord as {}", data_about_bot.user.tag()); |
| 152 | + *self.client.lock().await = Some(data_about_bot); |
| 153 | + self.ready_notify.notify_one(); |
| 154 | + } |
| 155 | +} |
0 commit comments