- 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
1149 lines
44 KiB
TypeScript
1149 lines
44 KiB
TypeScript
/*
|
|
* Vencord, a Discord client mod
|
|
* Copyright (c) 2026 Vendicated and contributors
|
|
* SPDX-License-Identifier: GPL-3.0-or-later
|
|
*/
|
|
|
|
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 { RenderModalProps } from "@vencord/discord-types";
|
|
import {
|
|
ChannelStore,
|
|
GuildMemberStore,
|
|
GuildStore,
|
|
Modal,
|
|
openModal,
|
|
PresenceStore,
|
|
React,
|
|
Select,
|
|
TextInput,
|
|
UserStore,
|
|
VoiceStateStore,
|
|
} from "@webpack/common";
|
|
|
|
const Native = VencordNative.pluginHelpers.WatchCord as PluginNative<
|
|
typeof import("./native")
|
|
>;
|
|
|
|
interface WatchItem {
|
|
id: string;
|
|
odUserId: string;
|
|
guildId: string;
|
|
watchVoice: boolean;
|
|
watchStatus: boolean;
|
|
watchMessage: boolean;
|
|
watchTyping: boolean;
|
|
playVoiceSound: boolean;
|
|
playStatusSound: boolean;
|
|
}
|
|
|
|
interface LogEntry {
|
|
timestamp: string;
|
|
type: "voice" | "status" | "message" | "typing";
|
|
message: string;
|
|
}
|
|
|
|
// In-memory logs (synced to file)
|
|
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: {
|
|
type: OptionType.STRING,
|
|
description: "Discord Webhook URL (optional - leave empty to disable)",
|
|
default: "",
|
|
},
|
|
enableNotifications: {
|
|
type: OptionType.BOOLEAN,
|
|
description: "Show desktop notifications",
|
|
default: true,
|
|
},
|
|
debugMode: {
|
|
type: OptionType.BOOLEAN,
|
|
description: "Log verbose debug information to the DevTools console (filter by 'WatchCord')",
|
|
default: false,
|
|
},
|
|
watchListManager: {
|
|
type: OptionType.COMPONENT,
|
|
description: "Manage watched users",
|
|
component: () => <WatchListManager />,
|
|
},
|
|
logsViewer: {
|
|
type: OptionType.COMPONENT,
|
|
description: "View activity logs",
|
|
component: () => <LogsViewer />,
|
|
},
|
|
});
|
|
|
|
// Helper functions
|
|
function getTimestamp(): string {
|
|
return new Date().toLocaleString();
|
|
}
|
|
|
|
// Debug logging — only active when the "debugMode" setting is enabled.
|
|
// Filter the DevTools console by "WatchCord" to see the trace.
|
|
function debugLog(...args: any[]) {
|
|
if (!settings.store.debugMode) return;
|
|
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[] {
|
|
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.
|
|
// 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,
|
|
watchStatus: item?.watchStatus ?? false,
|
|
watchMessage: item?.watchMessage ?? false,
|
|
watchTyping: item?.watchTyping ?? false,
|
|
playVoiceSound: item?.playVoiceSound ?? false,
|
|
playStatusSound: item?.playStatusSound ?? false,
|
|
}));
|
|
} catch (e) {
|
|
debugLog("getWatchList failed to parse stored value:", e);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function setWatchList(list: WatchItem[]) {
|
|
Vencord.Settings.plugins.WatchCord.watchList = JSON.stringify(list);
|
|
}
|
|
|
|
async function addLog(type: LogEntry["type"], message: string) {
|
|
const entry: LogEntry = {
|
|
timestamp: getTimestamp(),
|
|
type,
|
|
message,
|
|
};
|
|
logs.unshift(entry);
|
|
|
|
// Keep only last 500 logs in memory
|
|
if (logs.length > 500) logs = logs.slice(0, 500);
|
|
|
|
// 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 {
|
|
await Native.appendLog(logLine);
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to save log", e);
|
|
}
|
|
}
|
|
|
|
async function sendWebhookMessage(message: string) {
|
|
const { webhookUrl } = settings.store;
|
|
if (webhookUrl) {
|
|
try {
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
function showNotification(title: string, body: string) {
|
|
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 {
|
|
audioContext ??= new (window.AudioContext ||
|
|
(window as any).webkitAudioContext)();
|
|
if (audioContext.state === "suspended") void audioContext.resume();
|
|
const oscillator = audioContext.createOscillator();
|
|
const gainNode = audioContext.createGain();
|
|
|
|
oscillator.connect(gainNode);
|
|
gainNode.connect(audioContext.destination);
|
|
|
|
oscillator.frequency.value = 800; // Frequency in Hz
|
|
oscillator.type = "sine";
|
|
|
|
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
|
|
gainNode.gain.exponentialRampToValueAtTime(
|
|
0.01,
|
|
audioContext.currentTime + 0.5
|
|
);
|
|
|
|
oscillator.start(audioContext.currentTime);
|
|
oscillator.stop(audioContext.currentTime + 0.5);
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to play sound", e);
|
|
}
|
|
}
|
|
|
|
function getChannelName(channel: any): string {
|
|
if (!channel) return "Unknown";
|
|
if (channel.name) return channel.name;
|
|
// DM / group DM channels have no name — use the recipient's username
|
|
const recipient =
|
|
channel.rawRecipients?.[0] ?? channel.recipients?.[0];
|
|
return recipient?.username ?? "DM";
|
|
}
|
|
|
|
// Shared handler for TYPING_START (fires for other users' typing)
|
|
function handleTypingEvent(event: any) {
|
|
debugLog("TYPING_START fired →", event);
|
|
|
|
const userId = event.userId ?? event.user_id;
|
|
const channelId = event.channelId ?? event.channel_id;
|
|
|
|
if (!userId || !channelId) {
|
|
debugLog(
|
|
"TYPING_START → skip: missing userId/channelId",
|
|
{ userId, channelId }
|
|
);
|
|
return;
|
|
}
|
|
|
|
const watchList = getWatchList();
|
|
if (watchList.length === 0) {
|
|
debugLog("TYPING_START → skip: watch list is empty");
|
|
return;
|
|
}
|
|
|
|
const channel = ChannelStore.getChannel(channelId);
|
|
// guildId is undefined for DMs — derive it from the channel as a fallback
|
|
const guildId = event.guildId ?? event.guild_id ?? channel?.guild_id;
|
|
|
|
const match = watchList.find(
|
|
item =>
|
|
item.odUserId === userId &&
|
|
item.watchTyping &&
|
|
(item.guildId === "*" || item.guildId === guildId)
|
|
);
|
|
|
|
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);
|
|
const guild = guildId ? GuildStore.getGuild(guildId) : undefined;
|
|
const guildName = guild?.name || "DM";
|
|
|
|
const logMessage = `<@${userId}>(${username}-${userId}) started typing in ${channelName}(${channelId}) in ${guildName}`;
|
|
debugLog("TYPING_START → MATCH, logging:", logMessage);
|
|
addLog("typing", logMessage);
|
|
sendWebhookMessage(
|
|
`\`[${getTimestamp()}]\` ⌨️ <@${userId}>(${username}) started typing in ${guildId ? `<#${channelId}>` : channelName} in ${guildName}`
|
|
);
|
|
} else {
|
|
const candidate = watchList.find(i => i.odUserId === userId);
|
|
debugLog("TYPING_START → no match:", {
|
|
userId,
|
|
guildId,
|
|
candidateFound: !!candidate,
|
|
reason: !candidate
|
|
? "user is not in the watch list"
|
|
: !candidate.watchTyping
|
|
? "watchTyping is OFF for this entry (tick it in the watch list)"
|
|
: `guild mismatch (entry guildId=${candidate.guildId}, event guildId=${guildId})`,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Watch List Manager Component
|
|
function WatchListManager() {
|
|
const [watchList, setWatchListState] = React.useState<WatchItem[]>(
|
|
getWatchList()
|
|
);
|
|
const [newUserId, setNewUserId] = React.useState("");
|
|
const [newGuildId, setNewGuildId] = React.useState("*");
|
|
const [watchVoice, setWatchVoice] = React.useState(true);
|
|
const [watchStatus, setWatchStatus] = React.useState(true);
|
|
const [watchMessage, setWatchMessage] = React.useState(false);
|
|
const [watchTyping, setWatchTyping] = React.useState(false);
|
|
const [playVoiceSound, setPlayVoiceSound] = React.useState(false);
|
|
const [playStatusSound, setPlayStatusSound] = React.useState(false);
|
|
|
|
const guilds = Object.values(GuildStore.getGuilds()) as any[];
|
|
|
|
const addEntry = () => {
|
|
if (!newUserId.trim()) return;
|
|
const newItem: WatchItem = {
|
|
id: Date.now().toString(),
|
|
odUserId: newUserId.trim(),
|
|
guildId: newGuildId,
|
|
watchVoice,
|
|
watchStatus,
|
|
watchMessage,
|
|
watchTyping,
|
|
playVoiceSound,
|
|
playStatusSound,
|
|
};
|
|
const newList = [...watchList, newItem];
|
|
setWatchListState(newList);
|
|
setWatchList(newList);
|
|
setNewUserId("");
|
|
// Seed current state so the very first change after adding is logged
|
|
seedUserState(newItem.odUserId);
|
|
};
|
|
|
|
const removeEntry = (id: string) => {
|
|
const newList = watchList.filter(i => i.id !== id);
|
|
setWatchListState(newList);
|
|
setWatchList(newList);
|
|
};
|
|
|
|
const toggleEntryFlag = (
|
|
id: string,
|
|
flag: keyof Pick<
|
|
WatchItem,
|
|
| "watchVoice"
|
|
| "watchStatus"
|
|
| "watchMessage"
|
|
| "watchTyping"
|
|
| "playVoiceSound"
|
|
| "playStatusSound"
|
|
>
|
|
) => {
|
|
const newList = watchList.map(i =>
|
|
i.id === id ? { ...i, [flag]: !i[flag] } : i
|
|
);
|
|
setWatchListState(newList);
|
|
setWatchList(newList);
|
|
};
|
|
|
|
const getUserDisplay = (odUserId: string) => {
|
|
const user = UserStore.getUser(odUserId);
|
|
return user ? `${user.username} (${odUserId})` : odUserId;
|
|
};
|
|
|
|
const getGuildDisplay = (guildId: string) => {
|
|
if (guildId === "*") return "All Servers";
|
|
const guild = GuildStore.getGuild(guildId);
|
|
return guild ? guild.name : guildId;
|
|
};
|
|
|
|
return (
|
|
<div>
|
|
<div>
|
|
<Heading tag="h4">Add New Watch Entry</Heading>
|
|
|
|
<Paragraph style={{ marginBottom: "8px" }}>
|
|
User ID
|
|
</Paragraph>
|
|
<TextInput
|
|
placeholder="Enter user ID..."
|
|
value={newUserId}
|
|
onChange={setNewUserId}
|
|
/>
|
|
|
|
<Paragraph
|
|
style={{ marginTop: "12px", marginBottom: "8px" }}
|
|
>
|
|
Server
|
|
</Paragraph>
|
|
<Select
|
|
options={[
|
|
{ label: "All Servers (*)", value: "*" },
|
|
...guilds.map(g => ({ label: g.name, value: g.id })),
|
|
]}
|
|
select={setNewGuildId}
|
|
isSelected={v => v === newGuildId}
|
|
serialize={v => v}
|
|
/>
|
|
|
|
<div
|
|
style={{
|
|
display: "grid",
|
|
gridTemplateColumns: "1fr 1fr",
|
|
gap: "15px",
|
|
margin: "12px 0",
|
|
}}
|
|
>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={watchVoice}
|
|
onChange={e => setWatchVoice(e.target.checked)}
|
|
/>
|
|
Watch Voice
|
|
</label>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={watchStatus}
|
|
onChange={e => setWatchStatus(e.target.checked)}
|
|
/>
|
|
Watch Status
|
|
</label>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={watchMessage}
|
|
onChange={e => setWatchMessage(e.target.checked)}
|
|
/>
|
|
Watch Messages
|
|
</label>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={watchTyping}
|
|
onChange={e => setWatchTyping(e.target.checked)}
|
|
/>
|
|
Watch Typing
|
|
</label>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={playVoiceSound}
|
|
onChange={e =>
|
|
setPlayVoiceSound(e.target.checked)
|
|
}
|
|
/>
|
|
🔊 Voice Sound
|
|
</label>
|
|
<label
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "5px",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={playStatusSound}
|
|
onChange={e =>
|
|
setPlayStatusSound(e.target.checked)
|
|
}
|
|
/>
|
|
🔊 Status Sound
|
|
</label>
|
|
</div>
|
|
|
|
<Button onClick={addEntry}>Add Entry</Button>
|
|
</div>
|
|
|
|
<Heading tag="h4" style={{ marginTop: "16px" }}>
|
|
Current Watch List ({watchList.length})
|
|
</Heading>
|
|
|
|
{watchList.length === 0 ? (
|
|
<Paragraph>No users being watched</Paragraph>
|
|
) : (
|
|
watchList.map(item => (
|
|
<div
|
|
key={item.id}
|
|
style={{
|
|
display: "flex",
|
|
justifyContent: "space-between",
|
|
alignItems: "center",
|
|
background: "var(--background-secondary-alt)",
|
|
padding: "12px",
|
|
borderRadius: "8px",
|
|
marginBottom: "8px",
|
|
}}
|
|
>
|
|
<div>
|
|
<Paragraph>
|
|
<strong>User:</strong>{" "}
|
|
{getUserDisplay(item.odUserId)}
|
|
</Paragraph>
|
|
<Paragraph>
|
|
<strong>Server:</strong>{" "}
|
|
{getGuildDisplay(item.guildId)}
|
|
</Paragraph>
|
|
<div
|
|
style={{
|
|
display: "flex",
|
|
flexWrap: "wrap",
|
|
gap: "8px",
|
|
marginTop: "6px",
|
|
}}
|
|
>
|
|
{(
|
|
[
|
|
["watchVoice", "Voice"],
|
|
["watchStatus", "Status"],
|
|
["watchMessage", "Messages"],
|
|
["watchTyping", "Typing"],
|
|
["playVoiceSound", "🔔 Voice"],
|
|
["playStatusSound", "🔔 Status"],
|
|
] as const
|
|
).map(([flag, label]) => (
|
|
<label
|
|
key={flag}
|
|
style={{
|
|
display: "flex",
|
|
alignItems: "center",
|
|
gap: "4px",
|
|
fontSize: "12px",
|
|
cursor: "pointer",
|
|
}}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={item[flag]}
|
|
onChange={() =>
|
|
toggleEntryFlag(item.id, flag)
|
|
}
|
|
/>
|
|
{label}
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
<Button
|
|
variant="dangerPrimary"
|
|
size="small"
|
|
onClick={() => removeEntry(item.id)}
|
|
>
|
|
Remove
|
|
</Button>
|
|
</div>
|
|
))
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Logs Viewer Component
|
|
function LogsViewer() {
|
|
const [displayLogs, setDisplayLogs] = React.useState<LogEntry[]>(logs);
|
|
const [filter, setFilter] = React.useState<
|
|
"all" | "voice" | "status" | "message" | "typing"
|
|
>("all");
|
|
|
|
React.useEffect(() => {
|
|
const interval = setInterval(() => {
|
|
setDisplayLogs([...logs]);
|
|
}, 1000);
|
|
return () => clearInterval(interval);
|
|
}, []);
|
|
|
|
const filteredLogs =
|
|
filter === "all"
|
|
? displayLogs
|
|
: displayLogs.filter(l => l.type === filter);
|
|
|
|
const clearLogs = async () => {
|
|
logs = [];
|
|
setDisplayLogs([]);
|
|
try {
|
|
await Native.clearLogs();
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to clear logs", e);
|
|
}
|
|
};
|
|
|
|
const openLogFile = async () => {
|
|
try {
|
|
await Native.openLogFile();
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to open log file", e);
|
|
}
|
|
};
|
|
|
|
const openStatusChangeFile = async () => {
|
|
try {
|
|
await Native.openStatusChangeFile();
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to open status change file", e);
|
|
}
|
|
};
|
|
|
|
const clearStatusChanges = async () => {
|
|
try {
|
|
await Native.clearStatusChanges();
|
|
} catch (e) {
|
|
console.error("WatchCord: Failed to clear status changes", e);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div>
|
|
<div
|
|
style={{
|
|
display: "flex",
|
|
gap: "10px",
|
|
marginBottom: "12px",
|
|
alignItems: "center",
|
|
flexWrap: "wrap",
|
|
}}
|
|
>
|
|
<Select
|
|
options={[
|
|
{ label: "All Logs", value: "all" },
|
|
{ label: "Voice Only", value: "voice" },
|
|
{ label: "Status Only", value: "status" },
|
|
{ label: "Messages Only", value: "message" },
|
|
{ label: "Typing Only", value: "typing" },
|
|
]}
|
|
select={v => setFilter(v as any)}
|
|
isSelected={v => v === filter}
|
|
serialize={v => v}
|
|
/>
|
|
|
|
<Button onClick={openLogFile}>Open Log File</Button>
|
|
<Button onClick={openStatusChangeFile} variant="primary">
|
|
Open Full Status Changes
|
|
</Button>
|
|
<Button variant="dangerPrimary" onClick={clearLogs}>
|
|
Clear Logs
|
|
</Button>
|
|
<Button variant="dangerPrimary" onClick={clearStatusChanges}>
|
|
Clear Status Changes
|
|
</Button>
|
|
</div>
|
|
|
|
<div
|
|
style={{
|
|
background: "var(--background-secondary-alt)",
|
|
borderRadius: "8px",
|
|
padding: "12px",
|
|
maxHeight: "400px",
|
|
overflowY: "auto",
|
|
fontFamily: "monospace",
|
|
fontSize: "12px",
|
|
}}
|
|
>
|
|
{filteredLogs.length === 0 ? (
|
|
<div
|
|
style={{
|
|
color: "var(--text-muted)",
|
|
fontStyle: "italic",
|
|
}}
|
|
>
|
|
No logs yet...
|
|
</div>
|
|
) : (
|
|
filteredLogs.map((log, i) => (
|
|
<div
|
|
key={i}
|
|
style={{
|
|
padding: "5px",
|
|
borderBottom:
|
|
"1px solid var(--background-tertiary)",
|
|
color:
|
|
log.type === "voice"
|
|
? "var(--text-positive)"
|
|
: log.type === "status"
|
|
? "var(--text-warning)"
|
|
: log.type === "message"
|
|
? "var(--text-link)"
|
|
: "var(--brand-500, #9b59b6)",
|
|
}}
|
|
>
|
|
<span style={{ color: "var(--text-muted)" }}>
|
|
[{log.timestamp}]
|
|
</span>{" "}
|
|
<span style={{ fontWeight: "bold" }}>
|
|
[{log.type.toUpperCase()}]
|
|
</span>{" "}
|
|
{log.message}
|
|
</div>
|
|
))
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// 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 (
|
|
<Modal
|
|
{...modalProps}
|
|
size="lg"
|
|
title="WatchCord"
|
|
subtitle="Manage watched users and view activity logs"
|
|
actions={[
|
|
{ text: "Close", variant: "secondary", onClick: modalProps.onClose },
|
|
]}
|
|
>
|
|
<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:
|
|
"Tracks when specific users join voice channels or change their status.",
|
|
authors: [{ name: "You", id: 0n }],
|
|
settings,
|
|
|
|
toolboxActions: {
|
|
"Open WatchCord": openWatchCordModal,
|
|
"Open WatchCord Log File": () => {
|
|
Native.openLogFile().catch(e =>
|
|
console.error("WatchCord: Failed to open log file", e)
|
|
);
|
|
},
|
|
},
|
|
|
|
flux: {
|
|
VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: any[]; }) {
|
|
const watchList = getWatchList();
|
|
if (watchList.length === 0) return;
|
|
|
|
for (const state of voiceStates) {
|
|
const { userId, channelId, guildId } = state;
|
|
|
|
// Get old channel from our own tracking, falling back to Discord's oldChannelId
|
|
const prevChannelId =
|
|
previousVoiceChannels.get(userId) ?? state.oldChannelId ?? null;
|
|
|
|
// Update our tracking
|
|
if (channelId) previousVoiceChannels.set(userId, channelId);
|
|
else previousVoiceChannels.delete(userId);
|
|
|
|
// Check if this user is being watched
|
|
const match = watchList.find(
|
|
(item: WatchItem) =>
|
|
item.odUserId === userId &&
|
|
item.watchVoice &&
|
|
(item.guildId === "*" || item.guildId === guildId)
|
|
);
|
|
|
|
if (match) {
|
|
// Skip if no state change for watched user
|
|
if (channelId === prevChannelId) continue;
|
|
|
|
const user = UserStore.getUser(userId);
|
|
const guild = GuildStore.getGuild(guildId);
|
|
const username = user?.username || "Unknown";
|
|
const guildName = guild?.name || "Unknown";
|
|
|
|
// ! Log
|
|
// User left old channel (if there was one)
|
|
if (prevChannelId) {
|
|
const oldChannel = ChannelStore.getChannel(prevChannelId);
|
|
const oldChannelName = oldChannel?.name || "Unknown";
|
|
const leaveMessage = `<@${userId}>(${username}-${userId}) left ${oldChannelName}(${prevChannelId}) in ${guildName}(${guildId})`;
|
|
addLog("voice", leaveMessage);
|
|
sendWebhookMessage(`\`[${getTimestamp()}]\` 🔴 <@${userId}>(${username}) left ${oldChannelName} in ${guildName}`);
|
|
}
|
|
|
|
// User joined new channel (if there is one)
|
|
if (channelId) {
|
|
const newChannel = ChannelStore.getChannel(channelId);
|
|
const newChannelName = newChannel?.name || "Unknown";
|
|
const joinMessage = `<@${userId}>(${username}-${userId}) joined ${newChannelName}(${channelId}) in ${guildName}(${guildId})`;
|
|
addLog("voice", joinMessage);
|
|
sendWebhookMessage(`\`[${getTimestamp()}]\` 🟢 <@${userId}>(${username}) joined ${newChannelName} in ${guildName}`);
|
|
|
|
// Log existing users in the channel
|
|
const voiceStatesInChannel = VoiceStateStore.getVoiceStatesForChannel(channelId);
|
|
const usersInChannel = Object.values(voiceStatesInChannel)
|
|
.filter((vs: any) => vs.userId !== userId) // Exclude the user who just joined
|
|
.map((vs: any) => {
|
|
const u = UserStore.getUser(vs.userId);
|
|
return u ? `${u.username}(${vs.userId})` : vs.userId;
|
|
});
|
|
|
|
if (usersInChannel.length > 0) {
|
|
const existingUsersMessage = ` └─ Existing users in channel: ${usersInChannel.join(", ")}`;
|
|
addLog("voice", existingUsersMessage);
|
|
} else {
|
|
addLog("voice", " └─ Empty channel");
|
|
}
|
|
}
|
|
|
|
// ! Play Sound
|
|
// Play sound if enabled for voice changes
|
|
if (match.playVoiceSound && (prevChannelId || channelId)) {
|
|
playNotificationSound();
|
|
}
|
|
}
|
|
|
|
// 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
|
|
|
|
// Check if someone joined the watched user's channel
|
|
if (channelId === watchedUserChannelId && prevChannelId !== watchedUserChannelId) {
|
|
const user = UserStore.getUser(userId);
|
|
const watchedUser = UserStore.getUser(watchedUserId);
|
|
const channel = ChannelStore.getChannel(channelId);
|
|
const guild = GuildStore.getGuild(guildId);
|
|
const username = user?.username || "Unknown";
|
|
const watchedUsername = watchedUser?.username || "Unknown";
|
|
const channelName = channel?.name || "Unknown";
|
|
const guildName = guild?.name || "Unknown";
|
|
|
|
const joinWatchedMessage = `<@${userId}>(${username}-${userId}) joined <@${watchedUserId}>(${watchedUsername})'s channel ${channelName}(${channelId}) in ${guildName}(${guildId})`;
|
|
addLog("voice", joinWatchedMessage);
|
|
}
|
|
|
|
// Check if someone left the watched user's channel
|
|
if (prevChannelId === watchedUserChannelId && channelId !== watchedUserChannelId) {
|
|
const user = UserStore.getUser(userId);
|
|
const watchedUser = UserStore.getUser(watchedUserId);
|
|
const channel = ChannelStore.getChannel(prevChannelId);
|
|
const guild = GuildStore.getGuild(guildId);
|
|
const username = user?.username || "Unknown";
|
|
const watchedUsername = watchedUser?.username || "Unknown";
|
|
const channelName = channel?.name || "Unknown";
|
|
const guildName = guild?.name || "Unknown";
|
|
|
|
const leaveWatchedMessage = `<@${userId}>(${username}-${userId}) left <@${watchedUserId}>(${watchedUsername})'s channel ${channelName}(${prevChannelId}) in ${guildName}(${guildId})`;
|
|
addLog("voice", leaveWatchedMessage);
|
|
}
|
|
}
|
|
|
|
// ! Notification (only for watched users)
|
|
if (match) {
|
|
const user = UserStore.getUser(userId);
|
|
const guild = GuildStore.getGuild(guildId);
|
|
const username = user?.username || "Unknown";
|
|
const guildName = guild?.name || "Unknown";
|
|
|
|
if (prevChannelId && channelId) {
|
|
const oldChannel = ChannelStore.getChannel(prevChannelId);
|
|
const newChannel = ChannelStore.getChannel(channelId);
|
|
showNotification(
|
|
"Voice Activity",
|
|
`${username} moved from ${oldChannel?.name || "Unknown"
|
|
} to ${newChannel?.name || "Unknown"} in ${guildName}`
|
|
);
|
|
} else if (channelId) {
|
|
const channel = ChannelStore.getChannel(channelId);
|
|
showNotification(
|
|
"Voice Activity",
|
|
`${username} joined ${channel?.name || "Unknown"
|
|
} in ${guildName}`
|
|
);
|
|
} else if (prevChannelId) {
|
|
const oldChannel = ChannelStore.getChannel(prevChannelId);
|
|
showNotification(
|
|
"Voice Activity",
|
|
`${username} left ${oldChannel?.name || "Unknown"
|
|
} in ${guildName}`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
PRESENCE_UPDATES({ updates }: { updates: any[]; }) {
|
|
const watchList = getWatchList();
|
|
if (watchList.length === 0) return;
|
|
|
|
for (const update of updates) {
|
|
const { user, status, guildId } = update;
|
|
if (!user?.id) continue;
|
|
|
|
const userId = user.id;
|
|
const prevStatus = previousStatuses.get(userId);
|
|
|
|
// Update stored status
|
|
previousStatuses.set(userId, status);
|
|
|
|
// 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 ||
|
|
GuildMemberStore.isMember(item.guildId, userId))
|
|
);
|
|
|
|
if (match && prevStatus !== undefined) {
|
|
// Log the full status change object to separate file
|
|
Native.logFullStatusChange(update).catch(e =>
|
|
console.error("WatchCord: Failed to log full status change", e)
|
|
);
|
|
|
|
const fullUser = UserStore.getUser(userId);
|
|
const username =
|
|
fullUser?.username || user.username || "Unknown";
|
|
|
|
const statusLabels: Record<string, string> = {
|
|
online: "Online",
|
|
idle: "Away/Idle",
|
|
dnd: "Do Not Disturb",
|
|
offline: "Offline",
|
|
invisible: "Invisible",
|
|
};
|
|
|
|
const prevLabel = statusLabels[prevStatus] || prevStatus;
|
|
const newLabel = statusLabels[status] || status;
|
|
|
|
const message = `<@${userId}>(${username}-${userId}) status changed: ${prevLabel} → ${newLabel}`;
|
|
|
|
addLog("status", message);
|
|
sendWebhookMessage(`\`[${getTimestamp()}]\` <@${userId}>(${username}) status changed: ${prevLabel} → ${newLabel}`);
|
|
showNotification(
|
|
"Status Change",
|
|
`${username}: ${prevLabel} → ${newLabel}`
|
|
);
|
|
|
|
// Play sound if enabled for status changes
|
|
if (match.playStatusSound) {
|
|
playNotificationSound();
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
MESSAGE_CREATE({ message, optimistic }: { message: any; optimistic: boolean; }) {
|
|
debugLog("MESSAGE_CREATE fired →", {
|
|
optimistic,
|
|
authorId: message?.author?.id,
|
|
channelId: message?.channel_id,
|
|
guildId: message?.guild_id,
|
|
content: message?.content?.slice(0, 60),
|
|
});
|
|
|
|
// Skip your own optimistic messages — only watch the watched user's messages
|
|
if (optimistic) {
|
|
debugLog("MESSAGE_CREATE → skip: optimistic (this is YOUR own message)");
|
|
return;
|
|
}
|
|
if (!message?.author?.id) {
|
|
debugLog("MESSAGE_CREATE → skip: no author id");
|
|
return;
|
|
}
|
|
|
|
const watchList = getWatchList();
|
|
debugLog(
|
|
"MESSAGE_CREATE watch list:",
|
|
watchList.map(i => ({
|
|
odUserId: i.odUserId,
|
|
guildId: i.guildId,
|
|
watchMessage: i.watchMessage,
|
|
}))
|
|
);
|
|
if (watchList.length === 0) {
|
|
debugLog("MESSAGE_CREATE → skip: watch list is empty");
|
|
return;
|
|
}
|
|
|
|
const userId = message.author.id;
|
|
const channelId = message.channel_id;
|
|
const channel = ChannelStore.getChannel(channelId);
|
|
// The Message object may not carry guild_id, so fall back to the channel
|
|
const guildId = message.guild_id ?? channel?.guild_id;
|
|
|
|
const match = watchList.find(
|
|
item =>
|
|
item.odUserId === userId &&
|
|
item.watchMessage &&
|
|
(item.guildId === "*" || item.guildId === guildId)
|
|
);
|
|
|
|
if (match) {
|
|
const user = UserStore.getUser(userId);
|
|
const username =
|
|
user?.username || message.author.username || "Unknown";
|
|
const channelName = getChannelName(channel);
|
|
const guild = guildId ? GuildStore.getGuild(guildId) : undefined;
|
|
const guildName = guild?.name || "DM";
|
|
const content =
|
|
message.content?.trim() ||
|
|
(message.attachments?.length
|
|
? `[${message.attachments.length} attachment(s)]`
|
|
: "[no text]") || "[no text]";
|
|
|
|
const guildOrDm = guildId ?? "@me";
|
|
const channelRef = guildId ? `<#${channelId}>` : channelName;
|
|
const jumpLink = `https://discord.com/channels/${guildOrDm}/${channelId}/${message.id}`;
|
|
|
|
const logMessage = `<@${userId}>(${username}-${userId}) sent in ${channelName}(${channelId}) in ${guildName}: "${content}"`;
|
|
debugLog("MESSAGE_CREATE → MATCH, logging:", logMessage);
|
|
addLog("message", logMessage);
|
|
sendWebhookMessage(
|
|
`\`[${getTimestamp()}]\` 💬 <@${userId}>(${username}) sent in ${channelRef} in ${guildName}: "${content}"\n[Go to message](${jumpLink})`
|
|
);
|
|
} else {
|
|
const candidate = watchList.find(i => i.odUserId === userId);
|
|
debugLog("MESSAGE_CREATE → no match:", {
|
|
userId,
|
|
guildId,
|
|
candidateFound: !!candidate,
|
|
reason: !candidate
|
|
? "this author is not in the watch list"
|
|
: !candidate.watchMessage
|
|
? "watchMessage is OFF for this entry (tick it in the watch list)"
|
|
: `guild mismatch (entry guildId=${candidate.guildId}, event guildId=${guildId})`,
|
|
});
|
|
}
|
|
},
|
|
|
|
TYPING_START(event: any) {
|
|
handleTypingEvent(event);
|
|
},
|
|
},
|
|
|
|
start() {
|
|
// Diagnostic dump: what is actually persisted and how it parses
|
|
debugLog(
|
|
"started — raw persisted watchList:",
|
|
Vencord.Settings.plugins.WatchCord?.watchList
|
|
);
|
|
debugLog(
|
|
"started — parsed watch list:",
|
|
getWatchList().map(i => ({
|
|
odUserId: i.odUserId,
|
|
guildId: i.guildId,
|
|
watchVoice: i.watchVoice,
|
|
watchStatus: i.watchStatus,
|
|
watchMessage: i.watchMessage,
|
|
watchTyping: i.watchTyping,
|
|
}))
|
|
);
|
|
|
|
// 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
|
|
const startupMessage = "WatchCord started";
|
|
const logLine = `[${getTimestamp()}] [SYSTEM] ${startupMessage}`;
|
|
|
|
Native.appendLog(logLine).catch(() =>
|
|
console.error("WatchCord: Failed to log startup")
|
|
);
|
|
|
|
const { webhookUrl } = settings.store;
|
|
if (webhookUrl) {
|
|
Native.sendWebhook(
|
|
webhookUrl,
|
|
logLine.replace("[", "`[").replace("]", "]`")
|
|
).catch(() =>
|
|
console.error("WatchCord: Failed to send startup webhook")
|
|
);
|
|
}
|
|
|
|
debugLog("WatchCord started — waiting for its flux events");
|
|
},
|
|
|
|
stop() {
|
|
previousStatuses.clear();
|
|
previousVoiceChannels.clear();
|
|
lastTypingLogged.clear();
|
|
audioContext?.close().catch(() => { });
|
|
audioContext = null;
|
|
debugLog("WatchCord stopped");
|
|
},
|
|
});
|