aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / spark-discord-hub / src / gateway.rs
| 1 | use futures_util::{SinkExt, StreamExt}; |
| 2 | use serde_json::json; |
| 3 | use std::sync::atomic::{AtomicI64, Ordering}; |
| 4 | use std::sync::Arc; |
| 5 | use std::time::Duration; |
| 6 | use tokio::sync::mpsc; |
| 7 | use tokio::time::sleep; |
| 8 | use tokio_tungstenite::connect_async; |
| 9 | use tokio_tungstenite::tungstenite::Message as WsMessage; |
| 10 | use tracing::{error, info, warn}; |
| 11 | |
| 12 | use crate::atlas_bot::AtlasBot; |
| 13 | use crate::gideon_bot::GideonBot; |
| 14 | use crate::models::DiscordMessage; |
| 15 | |
| 16 | pub struct DiscordGatewayHub { |
| 17 | token: String, |
| 18 | atlas_bot: Arc<AtlasBot>, |
| 19 | gideon_bot: Arc<GideonBot>, |
| 20 | bot_user_id: Arc<tokio::sync::Mutex<Option<String>>>, |
| 21 | } |
| 22 | |
| 23 | impl DiscordGatewayHub { |
| 24 | pub fn new(token: String) -> Self { |
| 25 | Self { |
| 26 | atlas_bot: Arc::new(AtlasBot::new(token.clone())), |
| 27 | gideon_bot: Arc::new(GideonBot::new(token.clone())), |
| 28 | token, |
| 29 | bot_user_id: Arc::new(tokio::sync::Mutex::new(None)), |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> { |
| 34 | let gateway_url = "wss://gateway.discord.gg/?v=10&encoding=json"; |
| 35 | info!("[GatewayHub] Connecting to Discord Gateway at {}...", gateway_url); |
| 36 | |
| 37 | let mut backoff_secs = 5; |
| 38 | |
| 39 | loop { |
| 40 | match connect_async(gateway_url).await { |
| 41 | Ok((ws_stream, _)) => { |
| 42 | info!("[GatewayHub] Connected to Discord Gateway WebSocket."); |
| 43 | backoff_secs = 5; |
| 44 | |
| 45 | let (mut write, mut read) = ws_stream.split(); |
| 46 | let (outbound_tx, mut outbound_rx) = mpsc::channel::<WsMessage>(64); |
| 47 | |
| 48 | // Writer task: forwards outbound messages to the WebSocket sink |
| 49 | let writer_handle = tokio::spawn(async move { |
| 50 | while let Some(msg) = outbound_rx.recv().await { |
| 51 | if let Err(e) = write.send(msg).await { |
| 52 | warn!("[GatewayHub] WebSocket send failed: {}", e); |
| 53 | break; |
| 54 | } |
| 55 | } |
| 56 | }); |
| 57 | |
| 58 | let last_seq = Arc::new(AtomicI64::new(-1)); |
| 59 | let mut heartbeat_handle: Option<tokio::task::JoinHandle<()>> = None; |
| 60 | |
| 61 | while let Some(msg_result) = read.next().await { |
| 62 | match msg_result { |
| 63 | Ok(WsMessage::Text(text)) => { |
| 64 | if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) { |
| 65 | let op = v.get("op").and_then(|o| o.as_i64()).unwrap_or(-1); |
| 66 | |
| 67 | // Track sequence number |
| 68 | if let Some(s) = v.get("s").and_then(|s| s.as_i64()) { |
| 69 | last_seq.store(s, Ordering::Relaxed); |
| 70 | } |
| 71 | |
| 72 | // Opcode 10: Hello |
| 73 | if op == 10 { |
| 74 | if let Some(hb_ms) = v.pointer("/d/heartbeat_interval").and_then(|h| h.as_u64()) { |
| 75 | info!("[GatewayHub] Received Hello. Heartbeat interval: {}ms", hb_ms); |
| 76 | |
| 77 | // 1. Identify immediately (Intents: Guilds 1 + Guild Messages 512 + Message Content 32768 = 33281) |
| 78 | let identify = json!({ |
| 79 | "op": 2, |
| 80 | "d": { |
| 81 | "token": self.token, |
| 82 | "intents": 33281, |
| 83 | "properties": { |
| 84 | "os": "linux", |
| 85 | "browser": "spark-discord-hub", |
| 86 | "device": "spark-gb10" |
| 87 | } |
| 88 | } |
| 89 | }); |
| 90 | let _ = outbound_tx.send(WsMessage::Text(identify.to_string())).await; |
| 91 | |
| 92 | // 2. Spawn periodic heartbeat task |
| 93 | if let Some(h) = heartbeat_handle.take() { |
| 94 | h.abort(); |
| 95 | } |
| 96 | let hb_tx = outbound_tx.clone(); |
| 97 | let seq_ref = last_seq.clone(); |
| 98 | heartbeat_handle = Some(tokio::spawn(async move { |
| 99 | let mut interval = tokio::time::interval(Duration::from_millis(hb_ms)); |
| 100 | interval.tick().await; // first tick finishes immediately |
| 101 | loop { |
| 102 | interval.tick().await; |
| 103 | let s = seq_ref.load(Ordering::Relaxed); |
| 104 | let hb_payload = if s >= 0 { |
| 105 | json!({"op": 1, "d": s}) |
| 106 | } else { |
| 107 | json!({"op": 1, "d": null}) |
| 108 | }; |
| 109 | if hb_tx.send(WsMessage::Text(hb_payload.to_string())).await.is_err() { |
| 110 | break; |
| 111 | } |
| 112 | } |
| 113 | })); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // Opcode 1: Heartbeat requested by Discord server |
| 118 | if op == 1 { |
| 119 | let s = last_seq.load(Ordering::Relaxed); |
| 120 | let hb_reply = if s >= 0 { |
| 121 | json!({"op": 1, "d": s}) |
| 122 | } else { |
| 123 | json!({"op": 1, "d": null}) |
| 124 | }; |
| 125 | let _ = outbound_tx.send(WsMessage::Text(hb_reply.to_string())).await; |
| 126 | } |
| 127 | |
| 128 | // Opcode 7: Reconnect request from server |
| 129 | if op == 7 { |
| 130 | warn!("[GatewayHub] Discord requested reconnect (Opcode 7)."); |
| 131 | break; |
| 132 | } |
| 133 | |
| 134 | // Opcode 9: Invalid session |
| 135 | if op == 9 { |
| 136 | warn!("[GatewayHub] Discord invalid session (Opcode 9)."); |
| 137 | break; |
| 138 | } |
| 139 | |
| 140 | // Opcode 0: Dispatch event |
| 141 | if op == 0 { |
| 142 | let event_name = v.get("t").and_then(|t| t.as_str()).unwrap_or(""); |
| 143 | if event_name == "READY" { |
| 144 | if let Some(id) = v.pointer("/d/user/id").and_then(|i| i.as_str()) { |
| 145 | *self.bot_user_id.lock().await = Some(id.to_string()); |
| 146 | info!("[GatewayHub] Gateway Ready. Authenticated as bot ID: {}", id); |
| 147 | } |
| 148 | } else if event_name == "MESSAGE_CREATE" { |
| 149 | if let Some(d) = v.get("d") { |
| 150 | if let Ok(msg) = serde_json::from_value::<DiscordMessage>(d.clone()) { |
| 151 | self.route_message(msg).await; |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | Ok(WsMessage::Close(frame)) => { |
| 159 | warn!("[GatewayHub] WebSocket closed by Discord: {:?}", frame); |
| 160 | break; |
| 161 | } |
| 162 | Err(e) => { |
| 163 | error!("[GatewayHub] WebSocket read error: {}", e); |
| 164 | break; |
| 165 | } |
| 166 | _ => {} |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | if let Some(h) = heartbeat_handle { |
| 171 | h.abort(); |
| 172 | } |
| 173 | writer_handle.abort(); |
| 174 | } |
| 175 | Err(e) => { |
| 176 | error!("[GatewayHub] Failed to connect: {}. Retrying in {}s...", e, backoff_secs); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | sleep(Duration::from_secs(backoff_secs)).await; |
| 181 | backoff_secs = (backoff_secs * 2).min(60); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | async fn route_message(&self, msg: DiscordMessage) { |
| 186 | if msg.author.bot.unwrap_or(false) { |
| 187 | return; |
| 188 | } |
| 189 | |
| 190 | let my_id = self.bot_user_id.lock().await.clone().unwrap_or_default(); |
| 191 | let content = msg.content.trim(); |
| 192 | |
| 193 | // 1. Gideon bot commands |
| 194 | if content.starts_with("!gideon") || content.starts_with("!verify") || content.starts_with("!link") { |
| 195 | let g = self.gideon_bot.clone(); |
| 196 | let c_id = msg.channel_id.clone(); |
| 197 | let m_id = msg.id.clone(); |
| 198 | let text = content.to_string(); |
| 199 | let author = msg.author.username.clone(); |
| 200 | tokio::spawn(async move { |
| 201 | g.handle_command(&c_id, &m_id, &text, &author).await; |
| 202 | }); |
| 203 | return; |
| 204 | } |
| 205 | |
| 206 | // 2. Atlas bot inquiries |
| 207 | let is_atlas_mention = !my_id.is_empty() && content.contains(&format!("<@{}>", my_id)); |
| 208 | let is_atlas_command = content.starts_with("!atlas") || content.starts_with("!ask"); |
| 209 | |
| 210 | if is_atlas_mention || is_atlas_command { |
| 211 | let clean_prompt = if is_atlas_command { |
| 212 | content.trim_start_matches("!atlas").trim_start_matches("!ask").trim().to_string() |
| 213 | } else { |
| 214 | content.replace(&format!("<@{}>", my_id), "").trim().to_string() |
| 215 | }; |
| 216 | |
| 217 | if clean_prompt.is_empty() { |
| 218 | return; |
| 219 | } |
| 220 | |
| 221 | let a = self.atlas_bot.clone(); |
| 222 | let c_id = msg.channel_id.clone(); |
| 223 | let m_id = msg.id.clone(); |
| 224 | let prompt = clean_prompt.to_string(); |
| 225 | let author = msg.author.username.clone(); |
| 226 | tokio::spawn(async move { |
| 227 | a.handle_message(&c_id, &m_id, &prompt, &author).await; |
| 228 | }); |
| 229 | } |
| 230 | } |
| 231 | } |