The user asked for a faster, real app instead of Electron. The app is now a Rust crate (serenity + songbird); the GUI in M5 will be a Tauri 2 shell on the system WebView2. - Same behaviour as the Electron core: one voice channel, per-speaker PCM to the voice worker, speaking_end and speaker_leave, sentence playback with stop and cancel, transcription notice on join, slash command join/leave/stop (create-or-update), registered chat channels with live events, history and sends that never ping, worker process with a fresh token and restart backoff. - songbird 0.6.1 garbles about a third of received frames under DAVE (its decoder keeps the bytes DAVE decryption leaves at the end of the payload; a 20 ms stepped test tone showed repeats, skips and reordering, while sending was exact). songbird now only decrypts; the core reorders packets in a small window (Opus FEC for the last lost frame) and decodes them with libopus itself. - Live test on real Discord with two bots: five sentences heard (CER 0/0/0/5/12.5%), 0.71-0.90 s from end of speech to final, speech read back at 3.4%, sound gone 0.08 s after stop. The release binary uses about 16 MB of memory; a Windows build (MinGW) logs in under Wine. - Spec moved to app/src/discord_core.spec.md; architecture, decisions, roadmap and pc-features updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
180 lines
6.3 KiB
Rust
180 lines
6.3 KiB
Rust
//! Registered chat channels: which ones the bot may read or write, and message splitting.
|
|
|
|
use crate::settings::ChatChannelSettings;
|
|
use std::collections::HashMap;
|
|
|
|
/// Discord's message length limit, in UTF-16 code units as Discord counts.
|
|
pub const MESSAGE_LIMIT: usize = 2000;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct ChatMessage {
|
|
pub channel_id: u64,
|
|
pub message_id: u64,
|
|
pub author_id: u64,
|
|
pub author_name: String,
|
|
pub author_is_bot: bool,
|
|
/// Written by this bot. Live events never carry these; history reads do.
|
|
pub from_self: bool,
|
|
/// What the person wrote. Data, never instructions (privacy.md).
|
|
pub content: String,
|
|
/// RFC 3339.
|
|
pub created_at: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct ChatAccessError(pub String);
|
|
|
|
impl std::fmt::Display for ChatAccessError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.write_str(&self.0)
|
|
}
|
|
}
|
|
impl std::error::Error for ChatAccessError {}
|
|
|
|
pub struct ChatChannels {
|
|
by_id: HashMap<u64, ChatChannelSettings>,
|
|
}
|
|
|
|
impl ChatChannels {
|
|
pub fn new(channels: &[ChatChannelSettings]) -> Self {
|
|
Self { by_id: channels.iter().map(|c| (c.id, c.clone())).collect() }
|
|
}
|
|
|
|
/// Some channel is readable, so the bot needs the message intents.
|
|
pub fn any_readable(&self) -> bool {
|
|
self.by_id.values().any(|c| c.read)
|
|
}
|
|
|
|
pub fn can_read(&self, id: u64) -> bool {
|
|
self.by_id.get(&id).is_some_and(|c| c.read)
|
|
}
|
|
|
|
pub fn can_send(&self, id: u64) -> bool {
|
|
self.by_id.get(&id).is_some_and(|c| c.send)
|
|
}
|
|
|
|
pub fn check_read(&self, id: u64) -> Result<(), ChatAccessError> {
|
|
match self.by_id.get(&id) {
|
|
None => Err(ChatAccessError(format!("channel {id} is not a registered chat channel"))),
|
|
Some(c) if !c.read => Err(ChatAccessError(format!("reading channel {id} is turned off"))),
|
|
Some(_) => Ok(()),
|
|
}
|
|
}
|
|
|
|
pub fn check_send(&self, id: u64) -> Result<(), ChatAccessError> {
|
|
match self.by_id.get(&id) {
|
|
None => Err(ChatAccessError(format!("channel {id} is not a registered chat channel"))),
|
|
Some(c) if !c.send => Err(ChatAccessError(format!("sending to channel {id} is turned off"))),
|
|
Some(_) => Ok(()),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Split text into messages of at most `limit` UTF-16 units, breaking at the last newline, else the
|
|
/// last space, else hard (never inside a character). Nothing is lost except the newline or space a
|
|
/// break happens at.
|
|
pub fn split_message(text: &str, limit: usize) -> Vec<String> {
|
|
let mut out = Vec::new();
|
|
let mut rest = text;
|
|
loop {
|
|
// Byte offset just past the longest prefix within the limit, and whether more follows.
|
|
let mut units = 0;
|
|
let mut cut = rest.len();
|
|
let mut window_end = rest.len(); // the prefix plus one more character, to see a break right at the limit
|
|
for (i, ch) in rest.char_indices() {
|
|
if units + ch.len_utf16() > limit {
|
|
cut = i;
|
|
window_end = i + ch.len_utf8();
|
|
break;
|
|
}
|
|
units += ch.len_utf16();
|
|
}
|
|
if cut == rest.len() {
|
|
if !rest.is_empty() {
|
|
out.push(rest.to_owned());
|
|
}
|
|
return out;
|
|
}
|
|
let window = &rest[..window_end];
|
|
let brk = window.rfind('\n').filter(|&b| b > 0).or_else(|| window.rfind(' ').filter(|&b| b > 0));
|
|
match brk {
|
|
Some(b) => {
|
|
out.push(rest[..b].to_owned());
|
|
rest = &rest[b + 1..];
|
|
}
|
|
None => {
|
|
out.push(rest[..cut].to_owned());
|
|
rest = &rest[cut..];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Message Content intent bits in the application flags (GATEWAY_MESSAGE_CONTENT and its _LIMITED form).
|
|
pub fn has_message_content_intent(application_flags: u64) -> bool {
|
|
application_flags & ((1 << 18) | (1 << 19)) != 0
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn utf16_len(s: &str) -> usize {
|
|
s.encode_utf16().count()
|
|
}
|
|
|
|
#[test]
|
|
fn short_text_is_left_alone() {
|
|
assert_eq!(split_message("안녕하세요", MESSAGE_LIMIT), vec!["안녕하세요"]);
|
|
assert!(split_message("", MESSAGE_LIMIT).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn breaks_at_the_last_newline_then_space_and_loses_only_the_break() {
|
|
assert_eq!(split_message("aaaa bbbb\ncccc dddd", 12), vec!["aaaa bbbb", "cccc dddd"]);
|
|
assert_eq!(split_message("aaaa bbbb cccc", 10), vec!["aaaa bbbb", "cccc"]);
|
|
// A break exactly at the limit is used.
|
|
assert_eq!(split_message("aaaa bbbb", 4), vec!["aaaa", "bbbb"]);
|
|
}
|
|
|
|
#[test]
|
|
fn hard_cuts_keep_emoji_whole() {
|
|
let text = format!("{}😀y", "x".repeat(MESSAGE_LIMIT - 1));
|
|
let parts = split_message(&text, MESSAGE_LIMIT);
|
|
assert!(parts.iter().all(|p| utf16_len(p) <= MESSAGE_LIMIT));
|
|
assert_eq!(parts.concat(), text);
|
|
assert!(parts[1].starts_with('😀'));
|
|
}
|
|
|
|
#[test]
|
|
fn every_part_fits_for_long_mixed_text() {
|
|
let text: Vec<String> = (0..900).map(|i| format!("줄 {i} 내용입니다")).collect();
|
|
let text = text.join("\n");
|
|
let parts = split_message(&text, MESSAGE_LIMIT);
|
|
assert!(parts.len() > 1);
|
|
assert!(parts.iter().all(|p| !p.is_empty() && utf16_len(p) <= MESSAGE_LIMIT));
|
|
assert_eq!(parts.join("\n"), text);
|
|
}
|
|
|
|
fn ch(id: u64, read: bool, send: bool) -> ChatChannelSettings {
|
|
ChatChannelSettings { id, name: String::new(), description: String::new(), read, send }
|
|
}
|
|
|
|
#[test]
|
|
fn each_channel_follows_its_switches_and_strangers_are_refused() {
|
|
let c = ChatChannels::new(&[ch(1, true, false), ch(2, false, true)]);
|
|
assert!(c.can_read(1) && !c.can_send(1) && !c.can_read(2) && c.can_send(2));
|
|
assert!(c.check_send(1).is_err() && c.check_read(2).is_err());
|
|
assert!(c.check_read(3).unwrap_err().0.contains("not a registered"));
|
|
assert!(c.any_readable());
|
|
assert!(!ChatChannels::new(&[ch(2, false, true)]).any_readable());
|
|
}
|
|
|
|
#[test]
|
|
fn message_content_intent_full_or_limited() {
|
|
assert!(has_message_content_intent(1 << 18));
|
|
assert!(has_message_content_intent(1 << 19));
|
|
assert!(!has_message_content_intent((1 << 15) | (1 << 13)));
|
|
}
|
|
}
|