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:
1 parent
f06f2f493b
commit
bd8f826bb6
3 files changed
+155
-82
No files matched your search
+4
-4
@@ -338,10 +338,10 @@ For debugging and advanced analysis, WatchCord logs the **complete status change
|
||||
|
||||
## 🎨 UI Features
|
||||
|
||||
### Toolbar Button
|
||||
- **Location**: Top toolbar (next to inbox)
|
||||
- **Icon**: Eye/watch icon
|
||||
- **Action**: Opens Vencord plugin settings
|
||||
### Toolbox Actions
|
||||
- **Location**: Vencord Toolbox button in Discord's title bar (requires the built-in **VencordToolbox** plugin)
|
||||
- **Open WatchCord**: Opens a modal with the watch list manager and the logs viewer
|
||||
- **Open WatchCord Log File**: Opens `watchcord-logs.txt` in your default text editor
|
||||
|
||||
### Notification Sound
|
||||
- **Type**: Procedurally generated beep
|
||||
|
||||
+141
-76
@@ -5,25 +5,26 @@
|
||||
*/
|
||||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Button } from "@components/Button";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Heading } from "@components/Heading";
|
||||
import { Paragraph } from "@components/Paragraph";
|
||||
import definePlugin, { OptionType, PluginNative } from "@utils/types";
|
||||
import { findComponentByCodeLazy } from "@webpack";
|
||||
import { RenderModalProps } from "@vencord/discord-types";
|
||||
import {
|
||||
Button,
|
||||
ChannelStore,
|
||||
Forms,
|
||||
GuildMemberStore,
|
||||
GuildStore,
|
||||
Modal,
|
||||
openModal,
|
||||
PresenceStore,
|
||||
React,
|
||||
Select,
|
||||
SettingsRouter,
|
||||
TextInput,
|
||||
UserStore,
|
||||
VoiceStateStore,
|
||||
} from "@webpack/common";
|
||||
|
||||
const HeaderBarIcon = findComponentByCodeLazy(".HEADER_BAR_BADGE_BOTTOM,", 'position:"bottom"');
|
||||
|
||||
const Native = VencordNative.pluginHelpers.WatchCord as PluginNative<
|
||||
typeof import("./native")
|
||||
>;
|
||||
@@ -50,6 +51,10 @@ interface LogEntry {
|
||||
let logs: LogEntry[] = [];
|
||||
const previousStatuses: Map<string, string> = 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({
|
||||
webhookUrl: {
|
||||
@@ -91,17 +96,30 @@ function debugLog(...args: any[]) {
|
||||
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[] {
|
||||
try {
|
||||
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 [];
|
||||
const parsed = JSON.parse(stored);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
|
||||
// Normalize entries so legacy data missing newer fields (e.g.
|
||||
// watchMessage / watchTyping) still loads with sensible defaults.
|
||||
return parsed.map((item: any) => ({
|
||||
id: item?.id ?? Date.now().toString(),
|
||||
// The id fallback must be stable, otherwise remove/toggle can't find the entry.
|
||||
return parsed.map((item: any, index: number) => ({
|
||||
id: item?.id ?? `legacy-${index}-${item?.odUserId ?? ""}`,
|
||||
odUserId: item?.odUserId ?? "",
|
||||
guildId: item?.guildId ?? "*",
|
||||
watchVoice: item?.watchVoice ?? false,
|
||||
@@ -132,8 +150,8 @@ async function addLog(type: LogEntry["type"], message: string) {
|
||||
// Keep only last 500 logs in memory
|
||||
if (logs.length > 500) logs = logs.slice(0, 500);
|
||||
|
||||
// Format log line
|
||||
const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message}`;
|
||||
// Format log line (escape newlines so one event stays on one line in the file)
|
||||
const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message.replace(/\r?\n/g, "\\n")}`;
|
||||
|
||||
// Save to file
|
||||
try {
|
||||
@@ -147,10 +165,8 @@ async function sendWebhookMessage(message: string) {
|
||||
const { webhookUrl } = settings.store;
|
||||
if (webhookUrl) {
|
||||
try {
|
||||
await Native.sendWebhook(
|
||||
webhookUrl,
|
||||
message
|
||||
);
|
||||
const res = await Native.sendWebhook(webhookUrl, message);
|
||||
if (!res.ok) console.error("WatchCord: Webhook request failed", res.error);
|
||||
} catch (e) {
|
||||
console.error("WatchCord: Failed to send webhook", e);
|
||||
}
|
||||
@@ -158,15 +174,23 @@ async function sendWebhookMessage(message: string) {
|
||||
}
|
||||
|
||||
function showNotification(title: string, body: string) {
|
||||
if (settings.store.enableNotifications) {
|
||||
if (!settings.store.enableNotifications) return;
|
||||
try {
|
||||
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() {
|
||||
try {
|
||||
const audioContext = new (window.AudioContext ||
|
||||
audioContext ??= new (window.AudioContext ||
|
||||
(window as any).webkitAudioContext)();
|
||||
if (audioContext.state === "suspended") void audioContext.resume();
|
||||
const oscillator = audioContext.createOscillator();
|
||||
const gainNode = audioContext.createGain();
|
||||
|
||||
@@ -231,6 +255,15 @@ function handleTypingEvent(event: any) {
|
||||
);
|
||||
|
||||
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 username = user?.username || "Unknown";
|
||||
const channelName = getChannelName(channel);
|
||||
@@ -291,6 +324,8 @@ function WatchListManager() {
|
||||
setWatchListState(newList);
|
||||
setWatchList(newList);
|
||||
setNewUserId("");
|
||||
// Seed current state so the very first change after adding is logged
|
||||
seedUserState(newItem.odUserId);
|
||||
};
|
||||
|
||||
const removeEntry = (id: string) => {
|
||||
@@ -331,23 +366,23 @@ function WatchListManager() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Forms.FormSection>
|
||||
<Forms.FormTitle tag="h4">Add New Watch Entry</Forms.FormTitle>
|
||||
<div>
|
||||
<Heading tag="h4">Add New Watch Entry</Heading>
|
||||
|
||||
<Forms.FormText style={{ marginBottom: "8px" }}>
|
||||
<Paragraph style={{ marginBottom: "8px" }}>
|
||||
User ID
|
||||
</Forms.FormText>
|
||||
</Paragraph>
|
||||
<TextInput
|
||||
placeholder="Enter user ID..."
|
||||
value={newUserId}
|
||||
onChange={setNewUserId}
|
||||
/>
|
||||
|
||||
<Forms.FormText
|
||||
<Paragraph
|
||||
style={{ marginTop: "12px", marginBottom: "8px" }}
|
||||
>
|
||||
Server
|
||||
</Forms.FormText>
|
||||
</Paragraph>
|
||||
<Select
|
||||
options={[
|
||||
{ label: "All Servers (*)", value: "*" },
|
||||
@@ -457,14 +492,14 @@ function WatchListManager() {
|
||||
</div>
|
||||
|
||||
<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})
|
||||
</Forms.FormTitle>
|
||||
</Heading>
|
||||
|
||||
{watchList.length === 0 ? (
|
||||
<Forms.FormText>No users being watched</Forms.FormText>
|
||||
<Paragraph>No users being watched</Paragraph>
|
||||
) : (
|
||||
watchList.map(item => (
|
||||
<div
|
||||
@@ -480,14 +515,14 @@ function WatchListManager() {
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<Forms.FormText>
|
||||
<Paragraph>
|
||||
<strong>User:</strong>{" "}
|
||||
{getUserDisplay(item.odUserId)}
|
||||
</Forms.FormText>
|
||||
<Forms.FormText>
|
||||
</Paragraph>
|
||||
<Paragraph>
|
||||
<strong>Server:</strong>{" "}
|
||||
{getGuildDisplay(item.guildId)}
|
||||
</Forms.FormText>
|
||||
</Paragraph>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
@@ -529,8 +564,8 @@ function WatchListManager() {
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
color={Button.Colors.RED}
|
||||
size={Button.Sizes.SMALL}
|
||||
variant="dangerPrimary"
|
||||
size="small"
|
||||
onClick={() => removeEntry(item.id)}
|
||||
>
|
||||
Remove
|
||||
@@ -620,13 +655,13 @@ function LogsViewer() {
|
||||
/>
|
||||
|
||||
<Button onClick={openLogFile}>Open Log File</Button>
|
||||
<Button onClick={openStatusChangeFile} color={Button.Colors.BRAND}>
|
||||
<Button onClick={openStatusChangeFile} variant="primary">
|
||||
Open Full Status Changes
|
||||
</Button>
|
||||
<Button color={Button.Colors.RED} onClick={clearLogs}>
|
||||
<Button variant="dangerPrimary" onClick={clearLogs}>
|
||||
Clear Logs
|
||||
</Button>
|
||||
<Button color={Button.Colors.RED} onClick={clearStatusChanges}>
|
||||
<Button variant="dangerPrimary" onClick={clearStatusChanges}>
|
||||
Clear Status Changes
|
||||
</Button>
|
||||
</div>
|
||||
@@ -666,7 +701,7 @@ function LogsViewer() {
|
||||
? "var(--text-warning)"
|
||||
: log.type === "message"
|
||||
? "var(--text-link)"
|
||||
: "var(--text-muted)",
|
||||
: "var(--brand-500, #9b59b6)",
|
||||
}}
|
||||
>
|
||||
<span style={{ color: "var(--text-muted)" }}>
|
||||
@@ -684,27 +719,51 @@ function LogsViewer() {
|
||||
);
|
||||
}
|
||||
|
||||
// Toolbar Button Component
|
||||
function WatchCordButton() {
|
||||
// Seed the current voice channel and status of a user so the first change
|
||||
// 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 (
|
||||
<HeaderBarIcon
|
||||
className="vc-watchcord-btn"
|
||||
onClick={() => SettingsRouter.open("VencordPlugins")}
|
||||
tooltip="WatchCord Settings"
|
||||
icon={() => (
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
<Modal
|
||||
{...modalProps}
|
||||
size="lg"
|
||||
title="WatchCord"
|
||||
subtitle="Manage watched users and view activity logs"
|
||||
actions={[
|
||||
{ text: "Close", variant: "secondary", onClick: modalProps.onClose },
|
||||
]}
|
||||
>
|
||||
<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" />
|
||||
</svg>
|
||||
)}
|
||||
/>
|
||||
<WatchListManager />
|
||||
<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({
|
||||
name: "WatchCord",
|
||||
description:
|
||||
@@ -712,18 +771,14 @@ export default definePlugin({
|
||||
authors: [{ name: "You", id: 0n }],
|
||||
settings,
|
||||
|
||||
patches: [
|
||||
{
|
||||
// Inject button into the toolbar next to inbox
|
||||
find: "toolbar:function",
|
||||
replacement: {
|
||||
match: /(function \i\(\i\){var \i=\i\.className.*?children):\[(\i\.useMemo[^}]+"div",{className:\i\(\).*?}\),)/,
|
||||
replace: "$1:[$self.ToolbarButton(),$2",
|
||||
toolboxActions: {
|
||||
"Open WatchCord": openWatchCordModal,
|
||||
"Open WatchCord Log File": () => {
|
||||
Native.openLogFile().catch(e =>
|
||||
console.error("WatchCord: Failed to open log file", e)
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
ToolbarButton: ErrorBoundary.wrap(WatchCordButton, { noop: true }),
|
||||
|
||||
flux: {
|
||||
VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: any[]; }) {
|
||||
@@ -733,11 +788,13 @@ export default definePlugin({
|
||||
for (const state of voiceStates) {
|
||||
const { userId, channelId, guildId } = state;
|
||||
|
||||
// Get old channel from our own tracking (Discord doesn't always provide oldChannelId)
|
||||
const prevChannelId = previousVoiceChannels.get(userId) || null;
|
||||
// Get old channel from our own tracking, falling back to Discord's oldChannelId
|
||||
const prevChannelId =
|
||||
previousVoiceChannels.get(userId) ?? state.oldChannelId ?? null;
|
||||
|
||||
// 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
|
||||
const match = watchList.find(
|
||||
@@ -799,12 +856,16 @@ export default definePlugin({
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (!item.watchVoice) continue;
|
||||
if (item.guildId !== "*" && item.guildId !== guildId) continue;
|
||||
|
||||
const watchedUserId = item.odUserId;
|
||||
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);
|
||||
if (!watchedUserChannelId) continue; // Watched user is not in any channel
|
||||
@@ -891,11 +952,17 @@ export default definePlugin({
|
||||
// Skip if status hasn't changed
|
||||
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(
|
||||
item =>
|
||||
item.odUserId === userId &&
|
||||
item.watchStatus &&
|
||||
(item.guildId === "*" || item.guildId === guildId)
|
||||
(item.guildId === "*" ||
|
||||
item.guildId === guildId ||
|
||||
GuildMemberStore.isMember(item.guildId, userId))
|
||||
);
|
||||
|
||||
if (match && prevStatus !== undefined) {
|
||||
@@ -1043,15 +1110,10 @@ export default definePlugin({
|
||||
}))
|
||||
);
|
||||
|
||||
// Initialize previous statuses for watched users
|
||||
const watchList = getWatchList();
|
||||
for (const item of watchList) {
|
||||
if (item.watchStatus) {
|
||||
const status = PresenceStore.getStatus(item.odUserId);
|
||||
if (status) {
|
||||
previousStatuses.set(item.odUserId, status);
|
||||
}
|
||||
}
|
||||
// Seed voice channels and statuses so the first change after startup is detected
|
||||
// (otherwise a watched user already in VC who leaves is never logged).
|
||||
for (const item of getWatchList()) {
|
||||
seedUserState(item.odUserId);
|
||||
}
|
||||
|
||||
// Log and send webhook for startup
|
||||
@@ -1078,6 +1140,9 @@ export default definePlugin({
|
||||
stop() {
|
||||
previousStatuses.clear();
|
||||
previousVoiceChannels.clear();
|
||||
lastTypingLogged.clear();
|
||||
audioContext?.close().catch(() => { });
|
||||
audioContext = null;
|
||||
debugLog("WatchCord stopped");
|
||||
},
|
||||
});
|
||||
+10
-2
@@ -49,12 +49,20 @@ export async function sendWebhook(
|
||||
content: string
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
try {
|
||||
// Webhook messages are capped at 2000 characters
|
||||
const safeContent = content.length > 2000 ? content.slice(0, 1997) + "..." : content;
|
||||
const res = await fetch(webhookUrl, {
|
||||
method: "POST",
|
||||
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) {
|
||||
return { ok: false, error: String(e) };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user