Files
Vencord-Plugins/watchCord/index.tsx
T

1084 lines
41 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 ErrorBoundary from "@components/ErrorBoundary";
import definePlugin, { OptionType, PluginNative } from "@utils/types";
import { findComponentByCodeLazy } from "@webpack";
import {
Button,
ChannelStore,
Forms,
GuildStore,
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")
>;
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();
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);
}
function getWatchList(): WatchItem[] {
try {
const stored = Vencord.Settings.plugins.WatchCord?.watchList;
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(),
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
const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message}`;
// 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 {
await Native.sendWebhook(
webhookUrl,
message
);
} catch (e) {
console.error("WatchCord: Failed to send webhook", e);
}
}
}
function showNotification(title: string, body: string) {
if (settings.store.enableNotifications) {
new Notification(title, { body });
}
}
function playNotificationSound() {
try {
const audioContext = new (window.AudioContext ||
(window as any).webkitAudioContext)();
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 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("");
};
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>
<Forms.FormSection>
<Forms.FormTitle tag="h4">Add New Watch Entry</Forms.FormTitle>
<Forms.FormText style={{ marginBottom: "8px" }}>
User ID
</Forms.FormText>
<TextInput
placeholder="Enter user ID..."
value={newUserId}
onChange={setNewUserId}
/>
<Forms.FormText
style={{ marginTop: "12px", marginBottom: "8px" }}
>
Server
</Forms.FormText>
<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>
</Forms.FormSection>
<Forms.FormTitle tag="h4" style={{ marginTop: "16px" }}>
Current Watch List ({watchList.length})
</Forms.FormTitle>
{watchList.length === 0 ? (
<Forms.FormText>No users being watched</Forms.FormText>
) : (
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>
<Forms.FormText>
<strong>User:</strong>{" "}
{getUserDisplay(item.odUserId)}
</Forms.FormText>
<Forms.FormText>
<strong>Server:</strong>{" "}
{getGuildDisplay(item.guildId)}
</Forms.FormText>
<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
color={Button.Colors.RED}
size={Button.Sizes.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} color={Button.Colors.BRAND}>
Open Full Status Changes
</Button>
<Button color={Button.Colors.RED} onClick={clearLogs}>
Clear Logs
</Button>
<Button color={Button.Colors.RED} 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(--text-muted)",
}}
>
<span style={{ color: "var(--text-muted)" }}>
[{log.timestamp}]
</span>{" "}
<span style={{ fontWeight: "bold" }}>
[{log.type.toUpperCase()}]
</span>{" "}
{log.message}
</div>
))
)}
</div>
</div>
);
}
// Toolbar Button Component
function WatchCordButton() {
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"
>
<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>
)}
/>
);
}
export default definePlugin({
name: "WatchCord",
description:
"Tracks when specific users join voice channels or change their status.",
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",
},
},
],
ToolbarButton: ErrorBoundary.wrap(WatchCordButton, { noop: true }),
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 (Discord doesn't always provide oldChannelId)
const prevChannelId = previousVoiceChannels.get(userId) || null;
// Update our tracking
previousVoiceChannels.set(userId, channelId || null);
// 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
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)
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;
const match = watchList.find(
item =>
item.odUserId === userId &&
item.watchStatus &&
(item.guildId === "*" || item.guildId === guildId)
);
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,
}))
);
// 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);
}
}
}
// 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();
debugLog("WatchCord stopped");
},
});