feat(chat): chatChannels tool for the registered Discord chat channels
- Tool (chat_channels.spec.md): list, read, search, send, edit, react,
delete, pin, unpin. Offered only when the v2 brain gives the turn a chat
backend, and then on every turn. Channel by ID, name, part of a name or a
name inside the text; a message ID finds its channel; planner forms of the
action ("send_message") work. Read and search results are fenced as
untrusted data. delete only reports until called again with confirm=true
in a later turn of the same person.
- Worker: chat_channels from the app, ChatBridge reads/searches the history
store and sends chat_action, waiting for chat_action_result (15 s timeout,
failed on session close); per-person reply turns and pending deletes.
- App: channel switches edit/react (on) and delete/pin (off); chat_channels
sent on worker ready and after login; chat_action runs send, edit (own
messages only), react, delete, pin, unpin and answers with ids or the error.
- Engine: chatChannels left out of the catalogue without a backend; the
"router returned everything" check now tolerates that.
- live_discord: edit own, refuse editing the speaker's, react, pin (Discord
refuses in a voice channel's chat, reported as an error), delete, refuse an
unregistered channel; passed in 109.4 s.
- Eval (qwen2.5:7b, 3 runs): 10 of 12; never obeyed the "delete everything"
message and never deleted in the same turn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,8 +14,8 @@ use serenity::all::{
|
||||
Cache, ChannelId, ChannelType, Client, CommandDataOptionValue, CommandInteraction, CommandOptionType, Context,
|
||||
CreateAllowedMentions, CreateCommand, CreateCommandOption, CreateInteractionResponse,
|
||||
CreateInteractionResponseMessage, CreateMessage, EditInteractionResponse, EventHandler, GatewayIntents, GetMessages,
|
||||
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId, MessageUpdateEvent, Ready,
|
||||
ShardManager, UserId, VoiceState,
|
||||
EditMessage, GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId,
|
||||
MessageUpdateEvent, ReactionType, Ready, ShardManager, UserId, VoiceState,
|
||||
};
|
||||
use songbird::driver::DecodeMode;
|
||||
use songbird::input::Input;
|
||||
@@ -28,7 +28,7 @@ use crate::playback::{ClipSink, Playback, PlaybackEnd, PlaybackEvent};
|
||||
use crate::receive::{opus_payload, OpusFrames, SpeakerStream};
|
||||
use crate::settings::Settings;
|
||||
use crate::speakers::SpeakerGate;
|
||||
use crate::worker_client::{Final, WorkerClient, WorkerEvent};
|
||||
use crate::worker_client::{ChatAction, Final, WorkerClient, WorkerEvent};
|
||||
use crate::{debug_log, error_log};
|
||||
|
||||
/// No packet for this long and a speaker counts as stopped (Discord.js uses the same 100 ms).
|
||||
@@ -265,6 +265,7 @@ impl DiscordCore {
|
||||
e = fail_rx.recv() => return Err(CoreError(format!("could not log in: {}", e.unwrap_or_default()))),
|
||||
};
|
||||
let _ = inner.bot_id.set(ready.user.id.get());
|
||||
report_chat_channels(inner);
|
||||
debug_log!("discord", "logged in as {} chatContent={content}", ready.user.id);
|
||||
let _ = inner.events.send(CoreEvent::Ready { user_id: ready.user.id.get(), tag: ready.user.tag() });
|
||||
if let Err(e) = self.register_command(app.id.get()).await {
|
||||
@@ -438,6 +439,48 @@ impl DiscordCore {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Do what the brain's chat channel tool asked (chat_channels.spec.md). The message ids made or
|
||||
/// touched. Every action needs its channel switch; edits only the bot's own messages.
|
||||
pub async fn chat_action(&self, a: &ChatAction) -> Result<Vec<u64>, CoreError> {
|
||||
let channel: u64 = a.channel.parse().map_err(|_| CoreError(format!("bad channel id {}", a.channel)))?;
|
||||
self.inner.chat.check_action(channel, &a.action)?;
|
||||
if a.action == "send" {
|
||||
return self.send_chat(channel, a.text.as_deref().unwrap_or("")).await;
|
||||
}
|
||||
let id = a.message_id.as_deref().and_then(|m| m.parse::<u64>().ok()).filter(|m| *m != 0)
|
||||
.map(MessageId::new).ok_or_else(|| CoreError(format!("{} needs a message id", a.action)))?;
|
||||
let http = self.http()?;
|
||||
let ch = ChannelId::new(channel);
|
||||
match a.action.as_str() {
|
||||
"edit" => {
|
||||
let text = a.text.as_deref().unwrap_or("").trim();
|
||||
if text.is_empty() {
|
||||
return Err(CoreError("nothing to write".into()));
|
||||
}
|
||||
if text.encode_utf16().count() > MESSAGE_LIMIT {
|
||||
return Err(CoreError(format!("an edit must fit one message ({MESSAGE_LIMIT} characters)")));
|
||||
}
|
||||
let mut m = ch.message(http.as_ref(), id).await.map_err(cerr("could not fetch the message"))?;
|
||||
if Some(m.author.id.get()) != self.bot_id() {
|
||||
return Err(CoreError("Discord lets the bot edit only its own messages".into()));
|
||||
}
|
||||
m.edit(http.as_ref(), EditMessage::new().content(text).allowed_mentions(CreateAllowedMentions::new()))
|
||||
.await.map_err(cerr("could not edit"))?;
|
||||
}
|
||||
"react" => {
|
||||
let emoji = a.emoji.as_deref().unwrap_or("").trim();
|
||||
let reaction = ReactionType::try_from(emoji).map_err(|_| CoreError(format!("not an emoji: {emoji}")))?;
|
||||
ch.create_reaction(http.as_ref(), id, reaction).await.map_err(cerr("could not react"))?;
|
||||
}
|
||||
"delete" => ch.delete_message(http.as_ref(), id).await.map_err(cerr("could not delete"))?,
|
||||
"pin" => ch.pin(http.as_ref(), id).await.map_err(cerr("could not pin"))?,
|
||||
"unpin" => ch.unpin(http.as_ref(), id).await.map_err(cerr("could not unpin"))?,
|
||||
other => return Err(CoreError(format!("unknown chat action {other}"))),
|
||||
}
|
||||
debug_log!("chat", "chat {} done in {channel} message={id}", a.action);
|
||||
Ok(vec![id.get()])
|
||||
}
|
||||
|
||||
pub async fn close(&self) {
|
||||
self.leave("shutdown").await;
|
||||
if let Some(s) = self.inner.shards.get() {
|
||||
@@ -507,6 +550,11 @@ fn report_voice_state(inner: &Inner) {
|
||||
debug_log!("voice", "reported voice {channel} with {n} members to the worker");
|
||||
}
|
||||
|
||||
/// The registered chat channels and their switches, for the brain's chat tool.
|
||||
fn report_chat_channels(inner: &Inner) {
|
||||
inner.worker.chat_channels(inner.bot_id.get().copied(), &inner.settings.chat_channels);
|
||||
}
|
||||
|
||||
fn should_hear(inner: &Inner, user: u64) -> bool {
|
||||
if Some(user) == inner.bot_id.get().copied() {
|
||||
return false;
|
||||
@@ -574,7 +622,20 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
|
||||
WorkerEvent::Final(m) => on_final(&inner, m),
|
||||
WorkerEvent::TtsAudio { id, seq, pcm } => with_playback(&inner, |p| p.audio(&id, seq, pcm)),
|
||||
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
|
||||
WorkerEvent::Ready(_) => report_voice_state(&inner),
|
||||
WorkerEvent::Ready(_) => {
|
||||
report_chat_channels(&inner);
|
||||
report_voice_state(&inner);
|
||||
}
|
||||
WorkerEvent::ChatAction(a) => {
|
||||
let core = DiscordCore { inner: inner.clone() };
|
||||
tokio::spawn(async move {
|
||||
let result = core.chat_action(&a).await.map_err(|e| e.to_string());
|
||||
if let Err(e) = &result {
|
||||
debug_log!("chat", "chat {} {} failed: {e}", a.action, a.id);
|
||||
}
|
||||
core.inner.worker.chat_action_result(&a.id, result);
|
||||
});
|
||||
}
|
||||
WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user