watchCord: fix tracking bugs, add Vencord Toolbox actions

- Seed voice channels and statuses on start and when adding a user so
  the first leave/move/status change is detected
- Match server-specific status entries by guild membership
- Webhooks never ping (allowed_mentions) and are capped at 2000 chars
- Throttle repeated typing events, reuse a single AudioContext
- Dedupe associated voice logs, stable ids for legacy entries,
  cache parsed watch list, escape newlines in log file
- Replace fragile toolbar patch with toolbox actions and a modal
- Migrate to new Heading/Paragraph/Button and Modal components
This commit is contained in:
X4Lo committed 2026-11-11 18:56:00 +00:00
1 parent f06f2f493b
commit bd8f826bb6
3 files changed
+155 -82

No files matched your search

+4 -4
View File
@@ -338,10 +338,10 @@ For debugging and advanced analysis, WatchCord logs the **complete status change
## 🎨 UI Features ## 🎨 UI Features
### Toolbar Button ### Toolbox Actions
- **Location**: Top toolbar (next to inbox) - **Location**: Vencord Toolbox button in Discord's title bar (requires the built-in **VencordToolbox** plugin)
- **Icon**: Eye/watch icon - **Open WatchCord**: Opens a modal with the watch list manager and the logs viewer
- **Action**: Opens Vencord plugin settings - **Open WatchCord Log File**: Opens `watchcord-logs.txt` in your default text editor
### Notification Sound ### Notification Sound
- **Type**: Procedurally generated beep - **Type**: Procedurally generated beep
+141 -76
View File
@@ -5,25 +5,26 @@
*/ */
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { Button } from "@components/Button";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Heading } from "@components/Heading";
import { Paragraph } from "@components/Paragraph";
import definePlugin, { OptionType, PluginNative } from "@utils/types"; import definePlugin, { OptionType, PluginNative } from "@utils/types";
import { findComponentByCodeLazy } from "@webpack"; import { RenderModalProps } from "@vencord/discord-types";
import { import {
Button,
ChannelStore, ChannelStore,
Forms, GuildMemberStore,
GuildStore, GuildStore,
Modal,
openModal,
PresenceStore, PresenceStore,
React, React,
Select, Select,
SettingsRouter,
TextInput, TextInput,
UserStore, UserStore,
VoiceStateStore, VoiceStateStore,
} from "@webpack/common"; } from "@webpack/common";
const HeaderBarIcon = findComponentByCodeLazy(".HEADER_BAR_BADGE_BOTTOM,", 'position:"bottom"');
const Native = VencordNative.pluginHelpers.WatchCord as PluginNative< const Native = VencordNative.pluginHelpers.WatchCord as PluginNative<
typeof import("./native") typeof import("./native")
>; >;
@@ -50,6 +51,10 @@ interface LogEntry {
let logs: LogEntry[] = []; let logs: LogEntry[] = [];
const previousStatuses: Map<string, string> = new Map(); const previousStatuses: Map<string, string> = new Map();
const previousVoiceChannels: Map<string, string | null> = new Map(); const previousVoiceChannels: Map<string, string | null> = new Map();
// Last time a typing event was logged per user+channel. Discord re-sends
// TYPING_START every ~8s while someone keeps typing, so we throttle it.
const lastTypingLogged: Map<string, number> = new Map();
const TYPING_THROTTLE_MS = 15_000;
const settings = definePluginSettings({ const settings = definePluginSettings({
webhookUrl: { webhookUrl: {
@@ -91,17 +96,30 @@ function debugLog(...args: any[]) {
console.log("[WatchCord]", ...args); console.log("[WatchCord]", ...args);
} }
// getWatchList() runs on every PRESENCE_UPDATES / TYPING_START event, so
// cache the parsed result and only re-parse when the stored string changes.
let cachedWatchListRaw: string | undefined;
let cachedWatchList: WatchItem[] = [];
function getWatchList(): WatchItem[] { function getWatchList(): WatchItem[] {
try {
const stored = Vencord.Settings.plugins.WatchCord?.watchList; const stored = Vencord.Settings.plugins.WatchCord?.watchList;
if (stored === cachedWatchListRaw) return cachedWatchList;
cachedWatchListRaw = stored;
cachedWatchList = parseWatchList(stored);
return cachedWatchList;
}
function parseWatchList(stored: string | undefined): WatchItem[] {
try {
if (!stored) return []; if (!stored) return [];
const parsed = JSON.parse(stored); const parsed = JSON.parse(stored);
if (!Array.isArray(parsed)) return []; if (!Array.isArray(parsed)) return [];
// Normalize entries so legacy data missing newer fields (e.g. // Normalize entries so legacy data missing newer fields (e.g.
// watchMessage / watchTyping) still loads with sensible defaults. // watchMessage / watchTyping) still loads with sensible defaults.
return parsed.map((item: any) => ({ // The id fallback must be stable, otherwise remove/toggle can't find the entry.
id: item?.id ?? Date.now().toString(), return parsed.map((item: any, index: number) => ({
id: item?.id ?? `legacy-${index}-${item?.odUserId ?? ""}`,
odUserId: item?.odUserId ?? "", odUserId: item?.odUserId ?? "",
guildId: item?.guildId ?? "*", guildId: item?.guildId ?? "*",
watchVoice: item?.watchVoice ?? false, watchVoice: item?.watchVoice ?? false,
@@ -132,8 +150,8 @@ async function addLog(type: LogEntry["type"], message: string) {
// Keep only last 500 logs in memory // Keep only last 500 logs in memory
if (logs.length > 500) logs = logs.slice(0, 500); if (logs.length > 500) logs = logs.slice(0, 500);
// Format log line // Format log line (escape newlines so one event stays on one line in the file)
const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message}`; const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message.replace(/\r?\n/g, "\\n")}`;
// Save to file // Save to file
try { try {
@@ -147,10 +165,8 @@ async function sendWebhookMessage(message: string) {
const { webhookUrl } = settings.store; const { webhookUrl } = settings.store;
if (webhookUrl) { if (webhookUrl) {
try { try {
await Native.sendWebhook( const res = await Native.sendWebhook(webhookUrl, message);
webhookUrl, if (!res.ok) console.error("WatchCord: Webhook request failed", res.error);
message
);
} catch (e) { } catch (e) {
console.error("WatchCord: Failed to send webhook", e); console.error("WatchCord: Failed to send webhook", e);
} }
@@ -158,15 +174,23 @@ async function sendWebhookMessage(message: string) {
} }
function showNotification(title: string, body: string) { function showNotification(title: string, body: string) {
if (settings.store.enableNotifications) { if (!settings.store.enableNotifications) return;
try {
new Notification(title, { body }); new Notification(title, { body });
} catch (e) {
console.error("WatchCord: Failed to show notification", e);
} }
} }
// Reuse one AudioContext: creating a new one per beep leaks contexts and
// Chromium stops allowing new ones after a while.
let audioContext: AudioContext | null = null;
function playNotificationSound() { function playNotificationSound() {
try { try {
const audioContext = new (window.AudioContext || audioContext ??= new (window.AudioContext ||
(window as any).webkitAudioContext)(); (window as any).webkitAudioContext)();
if (audioContext.state === "suspended") void audioContext.resume();
const oscillator = audioContext.createOscillator(); const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain(); const gainNode = audioContext.createGain();
@@ -231,6 +255,15 @@ function handleTypingEvent(event: any) {
); );
if (match) { if (match) {
const throttleKey = `${userId}:${channelId}`;
const now = Date.now();
const last = lastTypingLogged.get(throttleKey);
if (last !== undefined && now - last < TYPING_THROTTLE_MS) {
debugLog("TYPING_START → skip: throttled (still typing)");
return;
}
lastTypingLogged.set(throttleKey, now);
const user = UserStore.getUser(userId); const user = UserStore.getUser(userId);
const username = user?.username || "Unknown"; const username = user?.username || "Unknown";
const channelName = getChannelName(channel); const channelName = getChannelName(channel);
@@ -291,6 +324,8 @@ function WatchListManager() {
setWatchListState(newList); setWatchListState(newList);
setWatchList(newList); setWatchList(newList);
setNewUserId(""); setNewUserId("");
// Seed current state so the very first change after adding is logged
seedUserState(newItem.odUserId);
}; };
const removeEntry = (id: string) => { const removeEntry = (id: string) => {
@@ -331,23 +366,23 @@ function WatchListManager() {
return ( return (
<div> <div>
<Forms.FormSection> <div>
<Forms.FormTitle tag="h4">Add New Watch Entry</Forms.FormTitle> <Heading tag="h4">Add New Watch Entry</Heading>
<Forms.FormText style={{ marginBottom: "8px" }}> <Paragraph style={{ marginBottom: "8px" }}>
User ID User ID
</Forms.FormText> </Paragraph>
<TextInput <TextInput
placeholder="Enter user ID..." placeholder="Enter user ID..."
value={newUserId} value={newUserId}
onChange={setNewUserId} onChange={setNewUserId}
/> />
<Forms.FormText <Paragraph
style={{ marginTop: "12px", marginBottom: "8px" }} style={{ marginTop: "12px", marginBottom: "8px" }}
> >
Server Server
</Forms.FormText> </Paragraph>
<Select <Select
options={[ options={[
{ label: "All Servers (*)", value: "*" }, { label: "All Servers (*)", value: "*" },
@@ -457,14 +492,14 @@ function WatchListManager() {
</div> </div>
<Button onClick={addEntry}>Add Entry</Button> <Button onClick={addEntry}>Add Entry</Button>
</Forms.FormSection> </div>
<Forms.FormTitle tag="h4" style={{ marginTop: "16px" }}> <Heading tag="h4" style={{ marginTop: "16px" }}>
Current Watch List ({watchList.length}) Current Watch List ({watchList.length})
</Forms.FormTitle> </Heading>
{watchList.length === 0 ? ( {watchList.length === 0 ? (
<Forms.FormText>No users being watched</Forms.FormText> <Paragraph>No users being watched</Paragraph>
) : ( ) : (
watchList.map(item => ( watchList.map(item => (
<div <div
@@ -480,14 +515,14 @@ function WatchListManager() {
}} }}
> >
<div> <div>
<Forms.FormText> <Paragraph>
<strong>User:</strong>{" "} <strong>User:</strong>{" "}
{getUserDisplay(item.odUserId)} {getUserDisplay(item.odUserId)}
</Forms.FormText> </Paragraph>
<Forms.FormText> <Paragraph>
<strong>Server:</strong>{" "} <strong>Server:</strong>{" "}
{getGuildDisplay(item.guildId)} {getGuildDisplay(item.guildId)}
</Forms.FormText> </Paragraph>
<div <div
style={{ style={{
display: "flex", display: "flex",
@@ -529,8 +564,8 @@ function WatchListManager() {
</div> </div>
</div> </div>
<Button <Button
color={Button.Colors.RED} variant="dangerPrimary"
size={Button.Sizes.SMALL} size="small"
onClick={() => removeEntry(item.id)} onClick={() => removeEntry(item.id)}
> >
Remove Remove
@@ -620,13 +655,13 @@ function LogsViewer() {
/> />
<Button onClick={openLogFile}>Open Log File</Button> <Button onClick={openLogFile}>Open Log File</Button>
<Button onClick={openStatusChangeFile} color={Button.Colors.BRAND}> <Button onClick={openStatusChangeFile} variant="primary">
Open Full Status Changes Open Full Status Changes
</Button> </Button>
<Button color={Button.Colors.RED} onClick={clearLogs}> <Button variant="dangerPrimary" onClick={clearLogs}>
Clear Logs Clear Logs
</Button> </Button>
<Button color={Button.Colors.RED} onClick={clearStatusChanges}> <Button variant="dangerPrimary" onClick={clearStatusChanges}>
Clear Status Changes Clear Status Changes
</Button> </Button>
</div> </div>
@@ -666,7 +701,7 @@ function LogsViewer() {
? "var(--text-warning)" ? "var(--text-warning)"
: log.type === "message" : log.type === "message"
? "var(--text-link)" ? "var(--text-link)"
: "var(--text-muted)", : "var(--brand-500, #9b59b6)",
}} }}
> >
<span style={{ color: "var(--text-muted)" }}> <span style={{ color: "var(--text-muted)" }}>
@@ -684,27 +719,51 @@ function LogsViewer() {
); );
} }
// Toolbar Button Component // Seed the current voice channel and status of a user so the first change
function WatchCordButton() { // after startup (or after adding them) is detected correctly.
function seedUserState(userId: string) {
const voiceState = VoiceStateStore.getVoiceStateForUser(userId);
if (voiceState?.channelId) {
previousVoiceChannels.set(userId, voiceState.channelId);
// Also seed everyone already in that channel, so their leaves get logged
const inChannel = VoiceStateStore.getVoiceStatesForChannel(voiceState.channelId);
for (const vs of Object.values(inChannel) as any[]) {
if (vs?.userId) previousVoiceChannels.set(vs.userId, voiceState.channelId);
}
}
const status = PresenceStore.getStatus(userId);
if (status) previousStatuses.set(userId, status);
}
// Modal opened from the Vencord toolbox (title bar)
function WatchCordModal({ modalProps }: { modalProps: RenderModalProps; }) {
return ( return (
<HeaderBarIcon <Modal
className="vc-watchcord-btn" {...modalProps}
onClick={() => SettingsRouter.open("VencordPlugins")} size="lg"
tooltip="WatchCord Settings" title="WatchCord"
icon={() => ( subtitle="Manage watched users and view activity logs"
<svg actions={[
width="20" { text: "Close", variant: "secondary", onClick: modalProps.onClose },
height="20" ]}
viewBox="0 0 24 24"
fill="currentColor"
> >
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z" /> <WatchListManager />
</svg> <Heading tag="h4" style={{ marginTop: "24px", marginBottom: "8px" }}>
)} Activity Logs
/> </Heading>
<LogsViewer />
</Modal>
); );
} }
function openWatchCordModal() {
openModal(modalProps => (
<ErrorBoundary>
<WatchCordModal modalProps={modalProps} />
</ErrorBoundary>
));
}
export default definePlugin({ export default definePlugin({
name: "WatchCord", name: "WatchCord",
description: description:
@@ -712,18 +771,14 @@ export default definePlugin({
authors: [{ name: "You", id: 0n }], authors: [{ name: "You", id: 0n }],
settings, settings,
patches: [ toolboxActions: {
{ "Open WatchCord": openWatchCordModal,
// Inject button into the toolbar next to inbox "Open WatchCord Log File": () => {
find: "toolbar:function", Native.openLogFile().catch(e =>
replacement: { console.error("WatchCord: Failed to open log file", e)
match: /(function \i\(\i\){var \i=\i\.className.*?children):\[(\i\.useMemo[^}]+"div",{className:\i\(\).*?}\),)/, );
replace: "$1:[$self.ToolbarButton(),$2",
}, },
}, },
],
ToolbarButton: ErrorBoundary.wrap(WatchCordButton, { noop: true }),
flux: { flux: {
VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: any[]; }) { VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: any[]; }) {
@@ -733,11 +788,13 @@ export default definePlugin({
for (const state of voiceStates) { for (const state of voiceStates) {
const { userId, channelId, guildId } = state; const { userId, channelId, guildId } = state;
// Get old channel from our own tracking (Discord doesn't always provide oldChannelId) // Get old channel from our own tracking, falling back to Discord's oldChannelId
const prevChannelId = previousVoiceChannels.get(userId) || null; const prevChannelId =
previousVoiceChannels.get(userId) ?? state.oldChannelId ?? null;
// Update our tracking // Update our tracking
previousVoiceChannels.set(userId, channelId || null); if (channelId) previousVoiceChannels.set(userId, channelId);
else previousVoiceChannels.delete(userId);
// Check if this user is being watched // Check if this user is being watched
const match = watchList.find( const match = watchList.find(
@@ -799,12 +856,16 @@ export default definePlugin({
} }
// Check if someone joined/left a watched user's channel // Check if someone joined/left a watched user's channel
// (dedupe so a user with several entries isn't logged twice)
const handledWatched = new Set<string>();
for (const item of watchList) { for (const item of watchList) {
if (!item.watchVoice) continue; if (!item.watchVoice) continue;
if (item.guildId !== "*" && item.guildId !== guildId) continue; if (item.guildId !== "*" && item.guildId !== guildId) continue;
const watchedUserId = item.odUserId; const watchedUserId = item.odUserId;
if (watchedUserId === userId) continue; // Skip the watched user's own movements (already handled above) if (watchedUserId === userId) continue; // Skip the watched user's own movements (already handled above)
if (handledWatched.has(watchedUserId)) continue;
handledWatched.add(watchedUserId);
const watchedUserChannelId = previousVoiceChannels.get(watchedUserId); const watchedUserChannelId = previousVoiceChannels.get(watchedUserId);
if (!watchedUserChannelId) continue; // Watched user is not in any channel if (!watchedUserChannelId) continue; // Watched user is not in any channel
@@ -891,11 +952,17 @@ export default definePlugin({
// Skip if status hasn't changed // Skip if status hasn't changed
if (prevStatus === status) continue; if (prevStatus === status) continue;
// Status is global, but Discord sends one PRESENCE_UPDATE per shared
// guild. Only the first one carries the change, and its guildId is
// arbitrary, so for server-specific entries check membership instead
// of comparing against the event's guildId.
const match = watchList.find( const match = watchList.find(
item => item =>
item.odUserId === userId && item.odUserId === userId &&
item.watchStatus && item.watchStatus &&
(item.guildId === "*" || item.guildId === guildId) (item.guildId === "*" ||
item.guildId === guildId ||
GuildMemberStore.isMember(item.guildId, userId))
); );
if (match && prevStatus !== undefined) { if (match && prevStatus !== undefined) {
@@ -1043,15 +1110,10 @@ export default definePlugin({
})) }))
); );
// Initialize previous statuses for watched users // Seed voice channels and statuses so the first change after startup is detected
const watchList = getWatchList(); // (otherwise a watched user already in VC who leaves is never logged).
for (const item of watchList) { for (const item of getWatchList()) {
if (item.watchStatus) { seedUserState(item.odUserId);
const status = PresenceStore.getStatus(item.odUserId);
if (status) {
previousStatuses.set(item.odUserId, status);
}
}
} }
// Log and send webhook for startup // Log and send webhook for startup
@@ -1078,6 +1140,9 @@ export default definePlugin({
stop() { stop() {
previousStatuses.clear(); previousStatuses.clear();
previousVoiceChannels.clear(); previousVoiceChannels.clear();
lastTypingLogged.clear();
audioContext?.close().catch(() => { });
audioContext = null;
debugLog("WatchCord stopped"); debugLog("WatchCord stopped");
}, },
}); });
+10 -2
View File
@@ -49,12 +49,20 @@ export async function sendWebhook(
content: string content: string
): Promise<{ ok: boolean; error?: string }> { ): Promise<{ ok: boolean; error?: string }> {
try { try {
// Webhook messages are capped at 2000 characters
const safeContent = content.length > 2000 ? content.slice(0, 1997) + "..." : content;
const res = await fetch(webhookUrl, { const res = await fetch(webhookUrl, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }), body: JSON.stringify({
content: safeContent,
// Never ping anyone: logged messages may contain @everyone/@here or
// user mentions, and our own <@id> references should only render.
allowed_mentions: { parse: [] },
}),
}); });
return { ok: res.ok }; if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
return { ok: true };
} catch (e) { } catch (e) {
return { ok: false, error: String(e) }; return { ok: false, error: String(e) };
} }