From f06f2f493b69355f8422f0077da461ab14008bff Mon Sep 17 00:00:00 2001 From: X4Lo Date: Wed, 11 Nov 2026 17:41:39 +0000 Subject: [PATCH] Initial commit: autoMover, friendsCheck, watchCord plugins and README --- .gitignore | 3 + README.md | 60 ++ autoMover/README.md | 122 ++++ autoMover/docs/workflows.md | 244 ++++++++ autoMover/index.tsx | 1047 +++++++++++++++++++++++++++++++++ friendsCheck/README.md | 48 ++ friendsCheck/index.tsx | 284 +++++++++ watchCord/README.md | 445 ++++++++++++++ watchCord/docs/workflows.md | 373 ++++++++++++ watchCord/index.tsx | 1083 +++++++++++++++++++++++++++++++++++ watchCord/native.ts | 90 +++ 11 files changed, 3799 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 autoMover/README.md create mode 100644 autoMover/docs/workflows.md create mode 100644 autoMover/index.tsx create mode 100644 friendsCheck/README.md create mode 100644 friendsCheck/index.tsx create mode 100644 watchCord/README.md create mode 100644 watchCord/docs/workflows.md create mode 100644 watchCord/index.tsx create mode 100644 watchCord/native.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0722fea --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.DS_Store +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..fe23965 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# Vencord Plugins + +A collection of custom [Vencord](https://vencord.dev/) user plugins for Discord. + +## Plugins + +| Plugin | Description | +|--------|-------------| +| [autoMover](autoMover/README.md) | Automatically moves target users between random voice channels, disconnects them, or applies server mute/deafen when they join voice. Per-user config, right-click context menu, optional DM on start. | +| [friendsCheck](friendsCheck/README.md) | Adds a title-bar button to look up mutual friends you share with any user on your friends list. | +| [watchCord](watchCord/README.md) | Monitors and logs activity of watched users: voice channel joins/leaves/switches, status changes, messages, and typing. Supports desktop notifications, sounds, Discord webhooks, and an in-app log viewer. | + +Each plugin folder has its own README with full feature lists, configuration, and troubleshooting. + +## Installation + +These are Vencord **user plugins**, so they require a source build of Vencord. + +1. Clone and set up Vencord from source (see the [Vencord install guide](https://docs.vencord.dev/installing/)). +2. Copy the plugin folder(s) you want into Vencord's `src/userPlugins/` directory: + ``` + src/userPlugins/ + ├── autoMover/ + ├── friendsCheck/ + └── watchCord/ + ``` +3. Build and inject Vencord: + ```bash + pnpm build + pnpm inject + ``` +4. Restart Discord and enable the plugin(s) in **Settings → Vencord → Plugins**. + +> `watchCord` includes a `native.ts` file for file and network access, so it only works on the desktop client, not the web version. + +## Repository layout + +``` +. +├── autoMover/ +│ ├── index.tsx +│ ├── README.md +│ └── docs/workflows.md +├── friendsCheck/ +│ ├── index.tsx +│ └── README.md +└── watchCord/ + ├── index.tsx + ├── native.ts + ├── README.md + └── docs/workflows.md +``` + +## Disclaimer + +Client mods are against Discord's Terms of Service. Some of these plugins act on or track other users. Use them responsibly and at your own risk. + +## License + +GPL-3.0-or-later, matching Vencord. diff --git a/autoMover/README.md b/autoMover/README.md new file mode 100644 index 0000000..770fc95 --- /dev/null +++ b/autoMover/README.md @@ -0,0 +1,122 @@ +# autoMover + +A Vencord plugin that automatically moves target users randomly between voice channels when they connect, disconnects them, or applies server mute/deafen on join. + +## Features + +- **Multi-user support** — add multiple users with per-user configuration +- **Auto-move** — moves a user to random voice channels every N milliseconds +- **Auto-disconnect** — disconnects a user as soon as they join a voice channel +- **Auto server mute** — server-mutes a user when they join a voice channel +- **Auto server deafen** — server-deafens a user when they join a voice channel +- **Mutual exclusion** — auto-move and auto-disconnect cannot be active simultaneously for the same user/server; enabling one automatically disables the other +- **Independent actions** — server mute and server deafen work independently of move/disconnect; they can be combined with any mode +- **Per-user toggle** — enable/disable for individual users +- **Configurable delay** — set the interval between moves in milliseconds (default: 2000) +- **Server-specific** — target a specific server or all servers (`*`) +- **Right-click context menu** — four checkboxes: + - **Auto Mover** — toggle auto-move + - **Auto Disconnect** — toggle auto-disconnect + - **Auto Server Mute** — toggle server mute on join + - **Auto Server Deafen** — toggle server deafen on join +- **Optional DM** — send a custom DM message when the action starts +- **Immediate start** — if the user is already in a voice channel when toggled on, the action starts right away +- **Safe toggling** — toggling any setting while a loop is running stops the old loop and restarts with the new configuration +- **Toolbar button** — shuffle icon in the Discord toolbar for quick access to plugin settings + +## Installation + +1. Copy the `autoMover` folder to your Vencord `userPlugins` directory: + ``` + src/userPlugins/autoMover/ + ├── index.tsx + └── README.md + ``` +2. Rebuild Vencord or restart Discord +3. Enable the plugin in Settings → Vencord → Plugins → autoMover + +## Configuration + +### Settings UI + +Access via: **Settings → Vencord → Plugins → autoMover** or click the shuffle icon in the toolbar. + +#### Adding an Entry +1. Enter the **User ID** (enable Developer Mode → right-click user → Copy User ID) +2. Select the **Server** to watch (or "All Servers") +3. Choose mode: + - Unchecked **Auto Disconnect** → auto-move (moves user between channels) + - Checked **Auto Disconnect** → disconnect (kicks from voice on join) +4. For auto-move: set the **Delay** in milliseconds (default: 2000) +5. Optionally enable **Server Mute** / **Server Deafen** (works with any mode) +6. Optionally enable **Send DM on start** and set a message +7. Click **Add Entry** + +#### Managing Entries +Each entry in the list shows: +- **User** and **Server** display +- **Mode**: Move (with delay) or Disconnect +- **Enabled** checkbox — master on/off; toggling on restarts if user is in VC +- **Disconnect** checkbox — switches between move and disconnect mode; stops any active loop and restarts with the new mode +- **Server Mute** checkbox — toggle server mute on join (independent) +- **Server Deafen** checkbox — toggle server deafen on join (independent) +- **Send DM** checkbox — toggle DM sending +- **Delay input** (visible in Move mode) — milliseconds between moves +- **DM message** text input (visible when Send DM is enabled) +- **Remove** button — delete the entry + +### Right-Click Context Menu + +Right-click any user anywhere in Discord: + +| Menu Item | What it does | +|-----------|-------------| +| **Auto Mover** | Creates/enables entry with auto-move mode. Disables auto-disconnect if it was active. Starts immediately if user is already in VC. | +| **Auto Disconnect** | Creates/enables entry with disconnect mode. Disables auto-move if it was active. Disconnects immediately if user is already in VC. | +| **Auto Server Mute** | Toggles server mute on join. Independent — does not affect move/disconnect. Applies immediately if user is already in VC. | +| **Auto Server Deafen** | Toggles server deafen on join. Independent — does not affect move/disconnect. Applies immediately if user is already in VC. | + +Both options are mutually exclusive — checking one unchecks the other for the same user/server. + +## How It Works + +### Auto-Move Mode +1. The plugin listens to `VOICE_STATE_UPDATES` events +2. When a tracked and enabled user connects to a voice channel in the configured server: + - Optionally sends a DM (if configured) + - Picks a random voice channel in the server (different from their current one) + - Moves the user via Discord's HTTP API + - Repeats after the configured delay +3. Stops when: + - The user disconnects from voice + - The entry is disabled + - The mode is switched to disconnect + - The entry is removed + - No other voice channels are available + +### Auto-Disconnect Mode +1. When a tracked and enabled user connects to a voice channel: + - Optionally sends a DM (if configured) + - Applies server mute/deafen if configured + - Disconnects them immediately via Discord's HTTP API (`channel_id: null`) +2. This is a one-shot action — no loop + +### Auto Server Mute / Deafen +1. When a user connects to a voice channel and has server mute/deafen enabled: + - Applies `mute: true` and/or `deaf: true` via Discord's HTTP API +2. Works independently of auto-move and auto-disconnect +3. Can be combined with any other mode + +## Permissions Required + +You need the **Move Members** permission in the target server for auto-move and auto-disconnect. Server mute requires **Mute Members**, and server deafen requires **Deafen Members**. Without the appropriate permission, the corresponding action will silently fail (logged to console). + +## License + +This plugin is part of Vencord and is licensed under GPL-3.0-or-later. + +``` +Vencord, a Discord client mod +Copyright (c) 2026 Vendicated and contributors +SPDX-License-Identifier: GPL-3.0-or-later +``` diff --git a/autoMover/docs/workflows.md b/autoMover/docs/workflows.md new file mode 100644 index 0000000..069c2b2 --- /dev/null +++ b/autoMover/docs/workflows.md @@ -0,0 +1,244 @@ +# autoMover — Detailed Documentation + +## Architecture Overview + +The plugin operates on a list of `MoveItem` entries, one per (user, server) pair. Each entry carries all configuration for that target. Entries are persisted as JSON in Vencord's plugin settings. + +``` +┌─────────────────────────────────────────────────────┐ +│ autoMover Plugin │ +├─────────────────────────────────────────────────────┤ +│ Settings UI (MoveListManager) │ +│ ├─ Add / remove / toggle entries │ +│ └─ Reads/writes Vencord.Settings.plugins.autoMover │ +├─────────────────────────────────────────────────────┤ +│ Context Menu (user-context) │ +│ ├─ Auto Mover checkbox │ +│ ├─ Auto Disconnect checkbox │ +│ ├─ Auto Server Mute checkbox │ +│ └─ Auto Server Deafen checkbox │ +├─────────────────────────────────────────────────────┤ +│ Flux Handler (VOICE_STATE_UPDATES) │ +│ └─ Detects voice joins → calls startMoving() │ +├─────────────────────────────────────────────────────┤ +│ Core Logic │ +│ ├─ startMoving() — action chain with delays │ +│ ├─ scheduleMove() — recursive move loop │ +│ ├─ tryStartIfInVoice() — starts if user already in VC│ +│ └─ toggleServerAction() — mute/deafen toggle handler │ +└─────────────────────────────────────────────────────┘ +``` + +## Data Types + +### MoveItem + +```ts +interface MoveItem { + id: string; // unique ID (Date.now().toString()) + userId: string; // Discord user ID + guildId: string; // Server ID or "*" for all + enabled: boolean; // master toggle for move/disconnect + disconnectOnJoin: boolean; // true = disconnect, false = move loop + delay: number; // ms between moves (default: 2000) + serverMute: boolean; // server-mute on join + serverDeafen: boolean; // server-deafen on join + sendDm: boolean; // send DM before actions + dmMessage: string; // DM text +} +``` + +### MoveState (runtime only, not persisted) + +```ts +interface MoveState { + timer: ReturnType | null; + guildId: string; +} +``` + +Stored in `activeMoves: Map`. Tracks running move loops. + +## Action Chain (startMoving) + +When a user joins a voice channel and a matching entry is found, `startMoving()` executes the following **sequential** chain with a **1-second delay** between each step: + +``` +User joins VC + │ + ▼ +┌──────────────────┐ +│ 1. Send DM │ if sendDm === true +│ wait 1000ms │ +├──────────────────┤ +│ 2. Server Mute │ if serverMute === true +│ wait 1000ms │ +├──────────────────┤ +│ 3. Server Deafen │ if serverDeafen === true +│ wait 1000ms │ +├──────────────────┤ +│ 4a. Disconnect │ if disconnectOnJoin === true → one-shot, done +│ or │ +│ 4b. Move Loop │ if enabled && !disconnectOnJoin → recursive +└──────────────────┘ +``` + +Each step only executes if its corresponding flag is set. Steps 1–3 are independent of steps 4a/4b — you can have server mute without any move/disconnect. + +## Feature Workflows + +### Auto-Move + +``` +VOICE_STATE_UPDATES + │ + ├─ state.userId matches entry.userId + ├─ state.channelId is set (user joined, not left) + ├─ entry.guildId matches state.guildId (or "*") + ├─ entry.enabled === true + └─ entry.disconnectOnJoin === false + │ + ▼ + startMoving(entry) + │ + ▼ + scheduleMove(entry) ← recursive loop + │ + ├─ Check: entry still enabled & in move mode? + ├─ Check: user still in VC & matching guild? + ├─ Pick random voice channel (exclude current) + ├─ PATCH /guilds/{guildId}/members/{userId} { channel_id } + └─ setTimeout(scheduleMove, entry.delay) + │ + └─ repeats until user disconnects or entry disabled +``` + +**Stop conditions:** +- User disconnects from voice +- Entry disabled or removed +- Mode switched to disconnect +- No other voice channels available in the guild + +### Auto-Disconnect + +``` +VOICE_STATE_UPDATES → same filter as auto-move + │ + ▼ +startMoving(entry) + │ + ├─ (DM, mute, deafen with delays if configured) + └─ PATCH /guilds/{guildId}/members/{userId} { channel_id: null } + │ + └─ one-shot — no loop +``` + +### Auto Server Mute + +``` +VOICE_STATE_UPDATES + │ + ├─ state.userId matches entry.userId + ├─ state.channelId is set + ├─ entry.guildId matches state.guildId (or "*") + └─ entry.serverMute === true + │ + ▼ + startMoving(entry) + │ + ├─ (DM with delay if configured) + └─ PATCH /guilds/{guildId}/members/{userId} { mute: true } +``` + +Works independently — can be active alongside auto-move or auto-disconnect, or on its own. + +### Auto Server Deafen + +Same as Auto Server Mute, but sends `{ deaf: true }`. + +## Mutual Exclusion Rules + +| If you enable… | This happens to the other | +|---------------|--------------------------| +| Auto Mover | Auto Disconnect → disabled | +| Auto Disconnect | Auto Mover → disabled | +| Server Mute | No effect on others | +| Server Deafen | No effect on others | + +Server mute and deafen are **fully independent** — they can be combined with move, disconnect, both, or neither. + +## Context Menu Behavior + +Right-clicking a user shows four checkboxes. The `guildId` from the context is used to scope the entry: + +| Context | guildId value | +|---------|--------------| +| Right-click in a server | That server's ID | +| Right-click in DMs / friends | `undefined` → stored as `"*"` (all servers) | + +### Checkbox logic + +| Checkbox | If user NOT in list | If user IS in list | +|----------|--------------------|--------------------| +| Auto Mover | Creates entry: `enabled=true, disconnectOnJoin=false` | If same mode active → toggle off. Otherwise → switch to move, disable disconnect. | +| Auto Disconnect | Creates entry: `enabled=true, disconnectOnJoin=true` | If same mode active → toggle off. Otherwise → switch to disconnect, disable move. | +| Server Mute | Creates entry: `enabled=false, serverMute=true` | Toggles `serverMute` | +| Server Deafen | Creates entry: `enabled=false, serverDeafen=true` | Toggles `serverDeafen` | + +If the user is already in a voice channel when toggled on, the action applies **immediately**. + +## Settings UI Behavior + +Same mutual exclusion rules apply as context menu. Toggling the **Enabled** checkbox or **Disconnect** checkbox: +- Stops any running move loop +- Restarts with the new configuration if the user is currently in VC + +Toggling **Server Mute** or **Server Deafen**: +- Applies immediately via API if user is in VC +- Does not affect move/disconnect loops + +Changing the **delay**: +- Takes effect on the next tick of the move loop (picked up from stored settings) + +## API Endpoints Used + +| Action | Method | URL | Body | +|--------|--------|-----|------| +| Move user | `PATCH` | `/guilds/{guildId}/members/{userId}` | `{ channel_id: channelId }` | +| Disconnect | `PATCH` | `/guilds/{guildId}/members/{userId}` | `{ channel_id: null }` | +| Server mute | `PATCH` | `/guilds/{guildId}/members/{userId}` | `{ mute: true }` | +| Server deafen | `PATCH` | `/guilds/{guildId}/members/{userId}` | `{ deaf: true }` | + +## Permissions Required + +| Action | Permission | +|--------|-----------| +| Move / Disconnect | **Move Members** | +| Server Mute | **Mute Members** | +| Server Deafen | **Deafen Members** | + +## Key Constants + +| Constant | Value | Description | +|----------|-------|-------------| +| `ACTION_DELAY_MS` | `1000` | Delay between sequential actions in `startMoving()` | +| Default move delay | `2000` | Delay between moves in the auto-move loop | + +## Edge Cases Handled + +- **User in multiple guilds' VCs**: `getVoiceStateForUser` returns one state. Guild check via optional `voiceState.guildId` — only blocks on explicit mismatch. +- **No other voice channels**: Move loop stops gracefully. +- **Entry removed mid-loop**: `scheduleMove` re-reads the stored list each tick and bails if entry is gone. +- **Mode switched mid-loop**: `scheduleMove` checks `disconnectOnJoin` and stops if mode changed. +- **Rapid toggle**: `stopMoving()` is always called before starting a new action, preventing duplicate loops. +- **DM channel doesn't exist**: Automatically opens a private channel via `ChannelActionCreators.openPrivateChannel`. + +## File Structure + +``` +autoMover/ +├── index.tsx # Main plugin: types, logic, UI, flux handler, context menu +├── README.md # User-facing documentation +└── docs/ + └── workflows.md # This file — detailed architecture & workflows +``` diff --git a/autoMover/index.tsx b/autoMover/index.tsx new file mode 100644 index 0000000..cd3b6a6 --- /dev/null +++ b/autoMover/index.tsx @@ -0,0 +1,1047 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { NavContextMenuPatchCallback } from "@api/ContextMenu"; +import { definePluginSettings } from "@api/Settings"; +import ErrorBoundary from "@components/ErrorBoundary"; +import { sendMessage } from "@utils/discord"; +import definePlugin, { OptionType } from "@utils/types"; +import { findComponentByCodeLazy } from "@webpack"; +import { + ChannelActionCreators, + ChannelStore, + GuildStore, + Menu, + React, + RestAPI, + Select, + SettingsRouter, + TextInput, + UserStore, + VoiceStateStore, +} from "@webpack/common"; + +const HeaderBarIcon = findComponentByCodeLazy(".HEADER_BAR_BADGE_BOTTOM,", 'position:"bottom"'); + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +interface MoveItem { + id: string; + userId: string; + guildId: string; + enabled: boolean; + /** true = disconnect on join, false = auto-move loop */ + disconnectOnJoin: boolean; + /** delay between moves in ms (default: 2000) */ + delay: number; + /** server-mute on join */ + serverMute: boolean; + /** server-deafen on join */ + serverDeafen: boolean; + sendDm: boolean; + dmMessage: string; +} + +interface MoveState { + timer: ReturnType | null; + guildId: string; +} + +const ACTION_DELAY_MS = 1000; + +/** Pause for a given number of milliseconds */ +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +// --------------------------------------------------------------------------- +// State +// --------------------------------------------------------------------------- + +const activeMoves = new Map(); + +// --------------------------------------------------------------------------- +// Settings +// --------------------------------------------------------------------------- + +const settings = definePluginSettings({ + moveListManager: { + type: OptionType.COMPONENT, + description: "Manage auto-move targets", + component: () => , + }, +}); + +// --------------------------------------------------------------------------- +// Persistence helpers +// --------------------------------------------------------------------------- + +function getMoveList(): MoveItem[] { + try { + const stored = Vencord.Settings.plugins.autoMover?.moveList; + return stored ? JSON.parse(stored) : []; + } catch { + return []; + } +} + +function setMoveList(list: MoveItem[]) { + Vencord.Settings.plugins.autoMover.moveList = JSON.stringify(list); +} + +// --------------------------------------------------------------------------- +// Move logic +// --------------------------------------------------------------------------- + +function stopMoving(userId: string) { + const state = activeMoves.get(userId); + if (state) { + if (state.timer) clearTimeout(state.timer); + activeMoves.delete(userId); + } +} + +function getRandomVoiceChannel( + guildId: string, + excludeChannelId: string, +): string | null { + const channels = ChannelStore.getMutableGuildChannelsForGuild(guildId); + // Channel type 2 = GUILD_VOICE + const voiceChannels = Object.values(channels).filter( + (c) => (c as any).type === 2 && c.id !== excludeChannelId, + ); + + if (voiceChannels.length === 0) return null; + return voiceChannels[Math.floor(Math.random() * voiceChannels.length)].id; +} + +async function moveUser(userId: string, guildId: string, channelId: string) { + try { + await RestAPI.patch({ + url: `/guilds/${guildId}/members/${userId}`, + body: { channel_id: channelId }, + }); + } catch (e) { + console.error("[autoMover] Failed to move user:", e); + } +} + +async function disconnectUser(userId: string, guildId: string) { + try { + await RestAPI.patch({ + url: `/guilds/${guildId}/members/${userId}`, + body: { channel_id: null }, + }); + } catch (e) { + console.error("[autoMover] Failed to disconnect user:", e); + } +} + +async function serverMuteUser(userId: string, guildId: string) { + try { + await RestAPI.patch({ + url: `/guilds/${guildId}/members/${userId}`, + body: { mute: true }, + }); + } catch (e) { + console.error("[autoMover] Failed to server-mute user:", e); + } +} + +async function serverDeafenUser(userId: string, guildId: string) { + try { + await RestAPI.patch({ + url: `/guilds/${guildId}/members/${userId}`, + body: { deaf: true }, + }); + } catch (e) { + console.error("[autoMover] Failed to server-deafen user:", e); + } +} + +async function sendDmToUser(item: MoveItem) { + const message = item.dmMessage; + if (!message) return; + + try { + let dmChannelId = ChannelStore.getDMFromUserId(item.userId); + if (!dmChannelId) { + await ChannelActionCreators.openPrivateChannel(item.userId); + await new Promise((r) => setTimeout(r, 500)); + dmChannelId = ChannelStore.getDMFromUserId(item.userId); + } + + if (dmChannelId) { + await sendMessage(dmChannelId, { content: message }); + } + } catch (e) { + console.error("[autoMover] Failed to send DM:", e); + } +} + +function scheduleMove(item: MoveItem) { + const { userId, guildId } = item; + + // Check if item is still in the list and enabled + const list = getMoveList(); + const current = list.find((i) => i.id === item.id); + if (!current || !current.enabled || current.disconnectOnJoin) { + stopMoving(userId); + return; + } + + // Check if user is still in a voice channel in this guild + const voiceState = VoiceStateStore.getVoiceStateForUser(userId); + + if ( + !voiceState || + !voiceState.channelId || + (voiceState.guildId && voiceState.guildId !== guildId) + ) { + stopMoving(userId); + return; + } + + // Pick a random voice channel different from current + const nextChannelId = getRandomVoiceChannel(guildId, voiceState.channelId); + if (!nextChannelId) { + stopMoving(userId); + return; + } + + moveUser(userId, guildId, nextChannelId); + + // Schedule next move using the configured delay + const state = activeMoves.get(userId); + if (state) { + state.timer = setTimeout(() => scheduleMove(item), current.delay); + } +} + +async function startMoving(item: MoveItem) { + // Stop any existing move for this user + stopMoving(item.userId); + + // 1. Send DM if enabled + if (item.sendDm) { + await sendDmToUser(item); + await wait(ACTION_DELAY_MS); + } + + // 2. Server mute if enabled + if (item.serverMute) { + await serverMuteUser(item.userId, item.guildId); + await wait(ACTION_DELAY_MS); + } + + // 3. Server deafen if enabled + if (item.serverDeafen) { + await serverDeafenUser(item.userId, item.guildId); + await wait(ACTION_DELAY_MS); + } + + // 4. Disconnect or start move loop + if (item.disconnectOnJoin) { + await disconnectUser(item.userId, item.guildId); + } else if (item.enabled) { + const state: MoveState = { timer: null, guildId: item.guildId }; + activeMoves.set(item.userId, state); + scheduleMove(item); + } +} + +// --------------------------------------------------------------------------- +// Context Menu (right-click user → toggle autoMover / autoDisconnect) +// --------------------------------------------------------------------------- + +interface UserContextProps { + channel: any; + guildId?: string; + user: { id: string }; +} + +/** + * Toggle an entry for the given user. + * @param disconnectMode false = auto-move, true = auto-disconnect. + */ +function toggleUserInList( + userId: string, + guildId: string | undefined, + disconnectMode: boolean, +) { + const list = getMoveList(); + const gid = guildId ?? "*"; + const existing = list.find((i) => i.userId === userId && i.guildId === gid); + + if (existing) { + const wasActive = existing.enabled; + + // If clicking the already-active mode, toggle off + if (existing.enabled && existing.disconnectOnJoin === disconnectMode) { + existing.enabled = !existing.enabled; + } else { + // Switch mode (or enable from off) + existing.enabled = true; + existing.disconnectOnJoin = disconnectMode; + } + setMoveList(list); + + // Always stop any running loop before potentially restarting + if (wasActive) stopMoving(userId); + + if (!existing.enabled) { + stopMoving(userId); + } else { + // If user is already in a VC, start immediately + tryStartIfInVoice(existing); + } + } else { + // Create new entry + const newItem: MoveItem = { + id: Date.now().toString(), + userId, + guildId: gid, + enabled: true, + disconnectOnJoin: disconnectMode, + delay: 2000, + serverMute: false, + serverDeafen: false, + sendDm: false, + dmMessage: "", + }; + setMoveList([...list, newItem]); + + // If user is already in a VC, start immediately + tryStartIfInVoice(newItem); + } +} + +/** + * Toggle serverMute or serverDeafen for a user. + * Creates an entry if none exists yet (with move/disconnect disabled). + */ +function toggleServerAction( + userId: string, + guildId: string | undefined, + key: "serverMute" | "serverDeafen", +) { + const list = getMoveList(); + const gid = guildId ?? "*"; + const existing = list.find((i) => i.userId === userId && i.guildId === gid); + + if (existing) { + (existing as any)[key] = !(existing as any)[key]; + setMoveList(list); + + // If toggling on and user is in VC, apply immediately + if ((existing as any)[key]) { + const voiceState = VoiceStateStore.getVoiceStateForUser(userId); + if ( + voiceState?.channelId && + (existing.guildId === "*" || + voiceState.guildId === existing.guildId) + ) { + if (key === "serverMute") { + serverMuteUser( + userId, + voiceState.guildId || existing.guildId, + ); + } else { + serverDeafenUser( + userId, + voiceState.guildId || existing.guildId, + ); + } + } + } + } else { + const newItem: MoveItem = { + id: Date.now().toString(), + userId, + guildId: gid, + enabled: false, + disconnectOnJoin: false, + delay: 2000, + serverMute: key === "serverMute", + serverDeafen: key === "serverDeafen", + sendDm: false, + dmMessage: "", + }; + setMoveList([...list, newItem]); + + // Apply immediately if user is in VC + const voiceState = VoiceStateStore.getVoiceStateForUser(userId); + if ( + voiceState?.channelId && + (newItem.guildId === "*" || voiceState.guildId === newItem.guildId) + ) { + if (key === "serverMute") { + serverMuteUser(userId, voiceState.guildId || newItem.guildId); + } else { + serverDeafenUser(userId, voiceState.guildId || newItem.guildId); + } + } + } +} + +/** If the item's user is currently in a matching voice channel, start */ +function tryStartIfInVoice(item: MoveItem) { + if ( + (!item.enabled && !item.serverMute && !item.serverDeafen) || + activeMoves.has(item.userId) + ) + return; + + const voiceState = VoiceStateStore.getVoiceStateForUser(item.userId); + if (!voiceState?.channelId) return; + + // guildId is optional on VoiceState — only block on explicit mismatch + if ( + item.guildId !== "*" && + voiceState.guildId && + voiceState.guildId !== item.guildId + ) + return; + + startMoving(item); +} + +const UserContextMenuPatch: NavContextMenuPatchCallback = ( + children, + { user, guildId }: UserContextProps, +) => { + if (!user) return; + + const list = getMoveList(); + const existing = list.find( + (i) => i.userId === user.id && i.guildId === (guildId ?? "*"), + ); + + const moveChecked = existing + ? existing.enabled && !existing.disconnectOnJoin + : false; + const disconnectChecked = existing + ? existing.enabled && existing.disconnectOnJoin + : false; + const muteChecked = existing ? existing.serverMute : false; + const deafenChecked = existing ? existing.serverDeafen : false; + + children.push( + toggleUserInList(user.id, guildId, false)} + />, + toggleUserInList(user.id, guildId, true)} + />, + toggleServerAction(user.id, guildId, "serverMute")} + />, + toggleServerAction(user.id, guildId, "serverDeafen")} + />, + ); +}; + +// --------------------------------------------------------------------------- +// Settings UI Component +// --------------------------------------------------------------------------- + +function MoveListManager() { + const [moveList, setMoveListState] = + React.useState(getMoveList()); + const [newUserId, setNewUserId] = React.useState(""); + const [newGuildId, setNewGuildId] = React.useState("*"); + const [newDisconnect, setNewDisconnect] = React.useState(false); + const [newDelay, setNewDelay] = React.useState("2000"); + const [newServerMute, setNewServerMute] = React.useState(false); + const [newServerDeafen, setNewServerDeafen] = React.useState(false); + const [newSendDm, setNewSendDm] = React.useState(false); + const [newDmMessage, setNewDmMessage] = React.useState(""); + + const guilds = Object.values(GuildStore.getGuilds()) as any[]; + + const addEntry = () => { + if (!newUserId.trim()) return; + const newItem: MoveItem = { + id: Date.now().toString(), + userId: newUserId.trim(), + guildId: newGuildId, + enabled: true, + disconnectOnJoin: newDisconnect, + delay: parseInt(newDelay, 10) || 2000, + serverMute: newServerMute, + serverDeafen: newServerDeafen, + sendDm: newSendDm, + dmMessage: newDmMessage, + }; + const newList = [...moveList, newItem]; + setMoveListState(newList); + setMoveList(newList); + setNewUserId(""); + setNewDmMessage(""); + setNewSendDm(false); + setNewDisconnect(false); + setNewServerMute(false); + setNewServerDeafen(false); + setNewDelay("2000"); + }; + + const removeEntry = (id: string) => { + const entry = moveList.find((i) => i.id === id); + if (entry) stopMoving(entry.userId); + const newList = moveList.filter((i) => i.id !== id); + setMoveListState(newList); + setMoveList(newList); + }; + + const toggleEnabled = (id: string) => { + const newList = moveList.map((i) => { + if (i.id === id) { + const updated = { ...i, enabled: !i.enabled }; + if (!updated.enabled) { + stopMoving(i.userId); + } else { + // Restart if user is already in VC + tryStartIfInVoice(updated); + } + return updated; + } + return i; + }); + setMoveListState(newList); + setMoveList(newList); + }; + + const toggleDisconnect = (id: string) => { + const newList = moveList.map((i) => { + if (i.id === id) { + // If toggling disconnect on, also enable and stop any move loop + if (!i.disconnectOnJoin) { + stopMoving(i.userId); + const updated = { + ...i, + enabled: true, + disconnectOnJoin: true, + }; + // Disconnect immediately if user is in VC + tryStartIfInVoice(updated); + return updated; + } + // Toggling disconnect off → switch to move mode + stopMoving(i.userId); + const updated = { ...i, disconnectOnJoin: false }; + // Restart move loop if user is in VC + tryStartIfInVoice(updated); + return updated; + } + return i; + }); + setMoveListState(newList); + setMoveList(newList); + }; + + const toggleSendDm = (id: string) => { + const newList = moveList.map((i) => + i.id === id ? { ...i, sendDm: !i.sendDm } : i, + ); + setMoveListState(newList); + setMoveList(newList); + }; + + const toggleServerMute = (id: string) => { + const newList = moveList.map((i) => { + if (i.id === id) { + const updated = { ...i, serverMute: !i.serverMute }; + // Apply immediately if user is in VC + if (updated.serverMute) { + const voiceState = VoiceStateStore.getVoiceStateForUser( + i.userId, + ); + if ( + voiceState?.channelId && + (i.guildId === "*" || voiceState.guildId === i.guildId) + ) { + serverMuteUser( + i.userId, + voiceState.guildId || i.guildId, + ); + } + } + return updated; + } + return i; + }); + setMoveListState(newList); + setMoveList(newList); + }; + + const toggleServerDeafen = (id: string) => { + const newList = moveList.map((i) => { + if (i.id === id) { + const updated = { ...i, serverDeafen: !i.serverDeafen }; + // Apply immediately if user is in VC + if (updated.serverDeafen) { + const voiceState = VoiceStateStore.getVoiceStateForUser( + i.userId, + ); + if ( + voiceState?.channelId && + (i.guildId === "*" || voiceState.guildId === i.guildId) + ) { + serverDeafenUser( + i.userId, + voiceState.guildId || i.guildId, + ); + } + } + return updated; + } + return i; + }); + setMoveListState(newList); + setMoveList(newList); + }; + + const updateDmMessage = (id: string, message: string) => { + const newList = moveList.map((i) => + i.id === id ? { ...i, dmMessage: message } : i, + ); + setMoveListState(newList); + setMoveList(newList); + }; + + const updateDelay = (id: string, delayStr: string) => { + const delay = parseInt(delayStr, 10) || 2000; + const newList = moveList.map((i) => + i.id === id ? { ...i, delay } : i, + ); + setMoveListState(newList); + setMoveList(newList); + }; + + const getUserDisplay = (userId: string) => { + const user = UserStore.getUser(userId); + return user ? `${user.username} (${userId})` : userId; + }; + + const getGuildDisplay = (guildId: string) => { + if (guildId === "*") return "All Servers"; + const guild = GuildStore.getGuild(guildId); + return guild ? guild.name : guildId; + }; + + return ( +
+
+

Add New Entry

+ +
+ User ID +
+ + +
+ Server +
+ setNewDisconnect(e.target.checked)} + /> + Auto Disconnect (instead of auto-move) + +
+ + {!newDisconnect && ( +
+
Delay between moves (ms)
+ +
+ )} + +
+ +
+ + {newSendDm && ( + + )} + +
+ +
+ +
+ +
+ +
+ +
+ + +

Move List ({moveList.length})

+ + {moveList.length === 0 ? ( +
No entries configured
+ ) : ( + moveList.map((item) => ( +
+
+
+ User:{" "} + {getUserDisplay(item.userId)} +
+
+ Server:{" "} + {getGuildDisplay(item.guildId)} +
+
+ Mode:{" "} + {item.disconnectOnJoin ? "Disconnect" : "Move"} + {!item.disconnectOnJoin && ` (${item.delay}ms)`} + {item.serverMute && " 🔇Mute"} + {item.serverDeafen && " 🔇Deafen"} +
+
+ + + + + +
+ {!item.disconnectOnJoin && ( +
+ + Delay (ms): + + + updateDelay(item.id, v) + } + /> +
+ )} + {item.sendDm && ( +
+ + updateDmMessage(item.id, v) + } + /> +
+ )} +
+ +
+ )) + )} + + ); +} + +// --------------------------------------------------------------------------- +// Toolbar Button +// --------------------------------------------------------------------------- + +function AutoMoverButton() { + return ( + SettingsRouter.open("VencordPlugins")} + tooltip="autoMover Settings" + icon={() => ( + + + + )} + /> + ); +} + +// --------------------------------------------------------------------------- +// Plugin definition +// --------------------------------------------------------------------------- + +export default definePlugin({ + name: "autoMover", + description: + "Automatically moves target users randomly between voice channels when they connect, or disconnects them", + 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(AutoMoverButton, { noop: true }), + + contextMenus: { + "user-context": UserContextMenuPatch, + }, + + flux: { + VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: any[] }) { + const moveList = getMoveList(); + if (moveList.length === 0) return; + + for (const state of voiceStates) { + const { userId, channelId, guildId } = state; + if (!channelId) continue; + + for (const item of moveList) { + if (!item.enabled && !item.serverMute && !item.serverDeafen) + continue; + if (item.userId !== userId) continue; + if (item.guildId !== "*" && item.guildId !== guildId) + continue; + + // Already moving this user — skip + if (activeMoves.has(userId)) continue; + + startMoving(item); + } + } + }, + }, + + start() { + console.log("autoMover started"); + }, + + stop() { + for (const userId of activeMoves.keys()) { + stopMoving(userId); + } + console.log("autoMover stopped"); + }, +}); diff --git a/friendsCheck/README.md b/friendsCheck/README.md new file mode 100644 index 0000000..7882a2d --- /dev/null +++ b/friendsCheck/README.md @@ -0,0 +1,48 @@ +# Friends Check Plugin + +A Vencord plugin that adds a button to Discord's title bar to check mutual friends with any of your friends. + +## Features + +- **Header Bar Button**: Adds a convenient button to Discord's title bar +- **User ID Input**: Simple form to enter a friend's Discord User ID +- **Mutual Friends Display**: Shows a list of friends you have in common with the specified user +- **Friend Validation**: Only works with users who are already on your friends list +- **User Avatars**: Displays profile pictures alongside friend names +- **Error Handling**: Provides clear feedback for invalid inputs or API errors + +## How to Use + +1. Click the Friends Check button in Discord's title bar (looks like a contact list icon) +2. Enter the Discord User ID of a friend you want to check mutual friends with +3. Click "Check Mutual Friends" +4. View the list of mutual friends displayed with their avatars and usernames + +## How to Get Someone's User ID + +1. Enable Developer Mode in Discord (Settings → Advanced → Developer Mode) +2. Right-click on the user's profile or message +3. Select "Copy User ID" from the context menu + +## Requirements + +- The target user must be on your friends list +- You need to have Developer Mode enabled to easily copy User IDs +- The plugin uses Discord's internal API to fetch relationship data + +## Technical Details + +- Uses Discord's `/api/v9/users/{userId}/relationships` endpoint +- Validates friend relationships using RelationshipStore +- Implements proper error handling and loading states +- Follows Vencord's plugin architecture and UI patterns + +## Troubleshooting + +- **"User not found"**: Make sure the User ID is correct and the user exists +- **"You can only check mutual friends with people on your friends list"**: The target user must be on your friends list +- **"Failed to fetch mutual friends"**: Check your internet connection or try again later + +## Privacy & Security + +This plugin only accesses data that Discord already provides through its internal APIs. It does not store any user data permanently and only processes friend relationships that you already have access to through Discord's interface. diff --git a/friendsCheck/index.tsx b/friendsCheck/index.tsx new file mode 100644 index 0000000..211a2fe --- /dev/null +++ b/friendsCheck/index.tsx @@ -0,0 +1,284 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import ErrorBoundary from "@components/ErrorBoundary"; +import { Devs } from "@utils/constants"; +import { openUserProfile } from "@utils/discord"; +import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal"; +import definePlugin from "@utils/types"; +import { Button, GuildMemberStore, GuildStore, RestAPI, SelectedGuildStore, showToast, Text, TextInput, Toasts, UserStore, useState } from "@webpack/common"; + +interface MutualFriend { + id: string; + username: string; + discriminator: string; + avatar: string | null; + global_name?: string; +} + +interface GuildMemberWithMutual { + id: string; + username: string; + discriminator: string; + avatar: string | null; + global_name?: string; + nick?: string; +} + +function FriendsCheckModal({ modalProps, onClose }: { modalProps: ModalProps; onClose: () => void; }) { + const [friendId, setFriendId] = useState(""); + const [loading, setLoading] = useState(false); + const [results, setResults] = useState([]); + const [error, setError] = useState(null); + const [checkedCount, setCheckedCount] = useState(0); + const [totalCount, setTotalCount] = useState(0); + + const currentGuildId = SelectedGuildStore.getGuildId(); + const currentGuild = currentGuildId ? GuildStore.getGuild(currentGuildId) : null; + + const handleSubmit = async () => { + if (!friendId.trim()) { + setError("Please enter a friend's user ID"); + return; + } + + if (!currentGuildId) { + setError("Please select a server first (click on a server in Discord)"); + return; + } + + setLoading(true); + setError(null); + setResults([]); + setCheckedCount(0); + + try { + // Get all members of the current guild + const guildMembers = GuildMemberStore.getMembers(currentGuildId); + const currentUserId = UserStore.getCurrentUser()?.id; + + if (!guildMembers || guildMembers.length === 0) { + setError("No members found in this server. Try scrolling through the member list first to load them."); + setLoading(false); + return; + } + + setTotalCount(guildMembers.length); + const membersWithMutualFriend: GuildMemberWithMutual[] = []; + + // Check each member's mutual friends + for (let i = 0; i < guildMembers.length; i++) { + const member = guildMembers[i]; + + // Skip yourself + if (member.userId === currentUserId) { + setCheckedCount(i + 1); + continue; + } + + try { + // Fetch mutual friends between this member and the target friend + const response = await RestAPI.get({ + url: `/users/${member.userId}/relationships`, + }); + + if (response.body && Array.isArray(response.body)) { + // Check if the target friend ID is in this member's friends list + const hasMutualFriend = response.body.some( + (friend: MutualFriend) => friend.id === friendId.trim() + ); + + if (hasMutualFriend) { + // Get user details + const user = UserStore.getUser(member.userId); + if (user) { + membersWithMutualFriend.push({ + id: user.id, + username: user.username, + discriminator: user.discriminator || "0", + avatar: user.avatar, + global_name: user.globalName, + nick: member.nick + }); + } + } + } + } catch (err) { + // This endpoint might not work for all users, try alternative approach + // Skip this member if we can't fetch their relationships + console.log(`Could not fetch relationships for ${member.userId}`); + } + + setCheckedCount(i + 1); + + // Small delay to avoid rate limiting + if (i % 5 === 0 && i > 0) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + } + + setResults(membersWithMutualFriend); + + showToast( + `Found ${membersWithMutualFriend.length} members who are friends with that user`, + Toasts.Type.SUCCESS + ); + } catch (err: any) { + console.error("FriendsCheck error:", err); + setError(err.message || "Failed to check members. Please try again."); + } finally { + setLoading(false); + } + }; + + const handleFriendIdChange = (value: string) => { + setFriendId(value); + setError(null); + }; + + const handleUserClick = (userId: string) => { + openUserProfile(userId); + }; + + return ( + + + Friends Check + + + + +
+ Current Server + + {currentGuild ? currentGuild.name : "No server selected - please click on a server first"} + + + Enter Friend's User ID + + Enter the User ID of a friend. The plugin will find members in this server who are also friends with that user. + + + {error && ( + + {error} + + )} + +
+ + {results.length > 0 && ( +
+ + Members who are friends with that user ({results.length}) + +
+ {results.map(member => ( +
handleUserClick(member.id)} + style={{ + display: "flex", + alignItems: "center", + padding: "8px", + borderRadius: "4px", + backgroundColor: "var(--background-secondary)", + marginBottom: "4px", + cursor: "pointer", + transition: "background-color 0.2s" + }} + onMouseEnter={e => e.currentTarget.style.backgroundColor = "var(--background-secondary-alt)"} + onMouseLeave={e => e.currentTarget.style.backgroundColor = "var(--background-secondary)"} + > + {member.username} +
+ + {member.nick || member.global_name || member.username} + + + {member.username}{member.discriminator !== "0" && `#${member.discriminator}`} + +
+
+ ))} +
+
+ )} + + {results.length === 0 && !loading && !error && checkedCount > 0 && ( +
+ + No members found who are friends with that user. + +
+ )} +
+ + + + +
+ ); +} + +function openFriendsCheckModal() { + openModal((modalProps) => ( + + + + )); +} + +export default definePlugin({ + name: "FriendsCheck", + description: "Check which server members are friends with a specific user", + authors: [Devs.Ven], + + toolboxActions: { + "Open Friends Check": openFriendsCheckModal, + } +}); diff --git a/watchCord/README.md b/watchCord/README.md new file mode 100644 index 0000000..32b89b9 --- /dev/null +++ b/watchCord/README.md @@ -0,0 +1,445 @@ +# WatchCord + +A comprehensive Vencord plugin for monitoring and logging Discord user activity, including voice channel changes and online status updates. + +## 📋 Features + +### Core Functionality +- **Voice Activity Tracking**: Monitor when specific users join, leave, or switch voice channels + - **Channel Members Logging**: Automatically logs existing users in a channel when a watched user joins + - **Associated Activity Tracking**: Logs when other users join or leave a watched user's current voice channel +- **Status Change Tracking**: Track when users change their online status (Online, Idle, DND, Offline, Invisible) +- **Message Watching**: Log when a watched user sends a message (works in servers and DMs) +- **Typing Watching**: Log when a watched user starts typing ("`User` started typing in `#channel`") +- **Per-User Configuration**: Customize tracking settings individually for each watched user +- **Server-Specific Tracking**: Watch users globally or only in specific servers + +### Notification Options +- **Desktop Notifications**: Get native desktop notifications for tracked events +- **Sound Alerts**: Optional notification sounds for voice and status changes +- **Discord Webhooks**: Send activity logs (voice, status, messages, typing) to a Discord webhook for external monitoring +- **In-App Logs Viewer**: Built-in interface to view and filter activity logs + +### Data Management +- **Persistent Logging**: All events are saved to a text file (`watchcord-logs.txt`) +- **In-Memory Cache**: Fast access to recent logs (last 500 entries) +- **Log Filtering**: Filter logs by type (Voice, Status, or All) +- **Easy Export**: Direct access to log file via "Open Log File" button + +## 🚀 Installation + +1. Ensure you have [Vencord](https://vencord.dev/) installed +2. Copy the `watchCord` folder to your Vencord `userPlugins` directory: + ``` + src/userPlugins/watchCord/ + ├── index.tsx + ├── native.ts + └── README.md + ``` +3. Rebuild Vencord or restart Discord +4. Enable the plugin in Settings → Vencord → Plugins → WatchCord + +## ⚙️ Configuration + +### Plugin Settings + +Access settings via: **Settings → Vencord → Plugins → WatchCord** + +#### 1. Webhook URL (Optional) +- **Description**: Discord webhook URL for remote logging +- **Format**: `https://discord.com/api/webhooks/...` +- **Usage**: Leave empty to disable webhook notifications +- **Example**: Logs will be sent as messages to the specified webhook + +#### 2. Enable Notifications +- **Description**: Show native desktop notifications for tracked events +- **Default**: Enabled +- **Note**: Requires notification permissions in your browser/client + +#### 3. Debug Mode +- **Description**: Log verbose debug information to the DevTools console +- **Default**: Disabled +- **Usage**: Enable it, then open DevTools (Ctrl+Shift+I) → Console and filter by `WatchCord` to see a full trace of the message/typing pipeline (raw events, skip decisions, watch list, and the reason a match did or didn't happen) +- **Note**: `TYPING_START` fires for everyone typing in channels you can see, so this can be noisy — turn it off when done + +### Watch List Manager + +Add users to monitor with granular control: + +#### Adding a User +1. **User ID**: Discord user ID (right-click user → Copy User ID) +2. **Server**: Choose specific server or "All Servers (*)" +3. **Tracking Options**: + - ✅ **Watch Voice**: Track voice channel activity + - ✅ **Watch Status**: Track online status changes + - 💬 **Watch Messages**: Log messages sent by the user + - ⌨️ **Watch Typing**: Log when the user starts typing + - 🔊 **Voice Sound**: Play sound on voice activity + - 🔊 **Status Sound**: Play sound on status changes +4. Click **Add Entry** + +> 💡 Existing entries can be toggled inline: each entry in the watch list shows its own checkboxes, so you can enable/disable **Messages** or **Typing** (or any other flag) without removing and re-adding the user. + +#### Watch List Display +Each entry shows: +- **User**: Username and User ID +- **Server**: Server name or "All Servers" +- **Active Features**: Icons indicating enabled tracking options +- **Remove Button**: Delete the watch entry + +### Logs Viewer + +View and manage activity logs: + +#### Features +- **Filter Logs**: View All, Voice Only, Status Only, Messages Only, or Typing Only +- **Auto-Refresh**: Logs update every second +- **Color Coding**: + - 🟢 Green: Voice activity + - 🟡 Yellow: Status changes + - 🔵 Blue: Messages + - 🟣 Purple: Typing +- **Buttons**: + - **Open Log File**: Open `watchcord-logs.txt` in your default text editor + - **Open Full Status Changes**: Open `watchcord-full-status-changes.json` to view complete status change objects + - **Clear Logs**: Delete all logs (both in-memory and file) + - **Clear Status Changes**: Delete all full status change records + +## 📊 Log Format + +### Log Entry Structure +``` +[MM/DD/YYYY, HH:MM:SS AM/PM] [TYPE] Message +``` + +### Log Types + +#### Voice Activity - Watched Users +``` +[2/11/2026, 3:45:12 PM] [VOICE] <@123456789>(Username-123456789) joined General(987654321) in ServerName(111222333) + └─ Existing users in channel: Alice(111111111), Bob(222222222), Charlie(333333333) +[2/11/2026, 3:47:30 PM] [VOICE] <@123456789>(Username-123456789) left General(987654321) in ServerName(111222333) +``` + +**Note**: When a watched user joins a voice channel, the plugin logs all existing users in that channel. If the channel is empty, it logs "Empty channel". + +#### Voice Activity - Associated Users +``` +[2/11/2026, 3:50:00 PM] [VOICE] <@444444444>(David-444444444) joined <@123456789>(Username)'s channel General(987654321) in ServerName(111222333) +[2/11/2026, 3:55:00 PM] [VOICE] <@444444444>(David-444444444) left <@123456789>(Username)'s channel General(987654321) in ServerName(111222333) +``` + +**Note**: When someone joins or leaves a channel where a watched user is currently present, those events are also logged. + +#### Status Changes +``` +[2/11/2026, 4:15:00 PM] [STATUS] <@123456789>(Username-123456789) status changed: Online → Away/Idle +[2/11/2026, 4:30:22 PM] [STATUS] <@123456789>(Username-123456789) status changed: Away/Idle → Offline +``` + +#### Messages +``` +[2/11/2026, 5:00:12 PM] [MESSAGE] <@123456789>(Username-123456789) sent in general(987654321) in ServerName(111222333): "hello world" +``` + +#### Typing +``` +[2/11/2026, 5:05:40 PM] [TYPING] <@123456789>(Username-123456789) started typing in general(987654321) in ServerName(111222333) +``` + +**Note**: In DMs, the channel name is replaced with the recipient's username (e.g. `started typing in Alice(123456789) in DM`). + +#### System Events +``` +[2/11/2026, 2:00:00 PM] [SYSTEM] WatchCord started +``` + +## 🔔 Webhook Integration + +### Setup +1. Create a Discord webhook in your server: + - Server Settings → Integrations → Webhooks → New Webhook + - Copy the webhook URL +2. Paste the URL in WatchCord settings → Webhook URL +3. Save settings + +### Webhook Message Format + +#### Voice Activity +``` +`[2/11/2026, 3:45:12 PM]` 🟢 <@123456789>(Username) joined General in ServerName +`[2/11/2026, 3:47:30 PM]` 🔴 <@123456789>(Username) left General in ServerName +``` + +#### Status Changes +``` +`[2/11/2026, 4:15:00 PM]` <@123456789>(Username) status changed: Online → Away/Idle +``` + +#### Messages +``` +`[2/11/2026, 5:00:12 PM]` 💬 <@123456789>(Username) sent in #general in ServerName: "hello world" +[Go to message](https://discord.com/channels/111222333/987654321/555555555) +``` +The channel renders as a clickable link, and `[Go to message]` jumps directly to the message in Discord. + +#### Typing +``` +`[2/11/2026, 5:05:40 PM]` ⌨️ <@123456789>(Username) started typing in #general in ServerName +``` +The channel renders as a clickable link. + +**Note**: For DMs (which have no guild), the channel link falls back to the recipient's name, and the message jump link uses `@me` as the guild segment. + +**Note**: User mentions (`<@123456789>`) will be clickable in Discord if they share servers with the webhook + +## 📝 Advanced Logging Features + +### Channel Member Tracking +When a watched user joins a voice channel, WatchCord automatically logs: +- The user joining the channel +- All existing members already in the channel (with usernames and IDs) +- If the channel is empty, it explicitly notes "Empty channel" + +**Example scenario:** +``` +Alice (watched user) joins "General Voice" +Bob and Charlie are already in the channel +``` + +**Log output:** +``` +[2/11/2026, 3:45:12 PM] [VOICE] <@111111111>(Alice-111111111) joined General(987654321) in MyServer(123456789) + └─ Existing users in channel: Bob(222222222), Charlie(333333333) +``` + +### Associated User Tracking +WatchCord monitors voice activity around watched users by logging when: +- Someone joins a channel where a watched user is present +- Someone leaves a channel where a watched user is present + +**Example scenario:** +``` +Alice (watched user) is in "General Voice" +Bob joins the same channel +``` + +**Log output:** +``` +[2/11/2026, 3:50:00 PM] [VOICE] <@222222222>(Bob-222222222) joined <@111111111>(Alice)'s channel General(987654321) in MyServer(123456789) +``` + +**Benefits:** +- See who is interacting with watched users +- Track social patterns and voice channel usage +- Identify who joins/leaves when specific people are present + +**Important Notes:** +- These detailed logs are **only saved to the local log file**, not sent to webhooks +- Webhooks only receive simplified notifications about the watched user's own activity +- This prevents webhook spam while maintaining detailed local records + +## 🎯 Use Cases + +### Parental Monitoring +- Track when children join voice channels +- Monitor their online hours and status + +### Community Management +- Monitor VIP members or moderators +- Track staff availability and activity + +### Personal Security +- Monitor your own account across different devices +- Get alerted to unusual activity + +### Research & Analytics +- Collect data on user behavior patterns +- Analyze voice channel usage statistics + +## 🔧 Technical Details + +### File Structure +``` +watchCord/ +├── index.tsx # Main plugin logic, UI components, event handlers +├── native.ts # Node.js/Electron file operations, webhook requests +└── README.md # This file +``` + +### Data Storage +- **Log File Location**: `%APPDATA%/discord/watchcord-logs.txt` (Windows) +- **Full Status Changes**: `%APPDATA%/discord/watchcord-full-status-changes.json` (Windows) +- **Watch List**: Stored in Vencord settings (JSON format) +- **In-Memory Logs**: Last 500 entries for quick access + +### Full Status Change Logging + +For debugging and advanced analysis, WatchCord logs the **complete status change object** from Discord to a separate JSON file. + +**File**: `watchcord-full-status-changes.json` + +**Format**: Each entry contains: +- **timestamp**: ISO 8601 timestamp +- **data**: Complete status change object from Discord's PRESENCE_UPDATES event + +**Example entry**: +```json +{ + "timestamp": "2026-02-26T15:30:45.123Z", + "data": { + "user": { + "id": "123456789", + "username": "ExampleUser", + "discriminator": "0001", + "avatar": "abc123...", + "bot": false, + "system": false + }, + "status": "idle", + "activities": [ + { + "name": "Visual Studio Code", + "type": 0, + "created_at": 1708960245000 + } + ], + "client_status": { + "desktop": "idle" + }, + "guildId": "987654321" + } +} +--- +``` + +**Benefits**: +- Full Discord presence data for debugging +- See activities, client status, and all metadata +- Useful for understanding Discord's status system +- Can be parsed programmatically for analysis + +**Access**: Use the "Open Full Status Changes" button in the Logs Viewer + +### Event Listeners +- `VOICE_STATE_UPDATES`: Monitors voice channel activity +- `PRESENCE_UPDATES`: Tracks online status changes +- `MESSAGE_CREATE`: Logs messages sent by watched users (skips your own `optimistic` messages) +- `TYPING_START`: Logs when watched users start typing (your own typing is ignored) + +### Status Labels +| Discord Status | Display Label | +| -------------- | -------------- | +| `online` | Online | +| `idle` | Away/Idle | +| `dnd` | Do Not Disturb | +| `offline` | Offline | +| `invisible` | Invisible | + +## 🎨 UI Features + +### Toolbar Button +- **Location**: Top toolbar (next to inbox) +- **Icon**: Eye/watch icon +- **Action**: Opens Vencord plugin settings + +### Notification Sound +- **Type**: Procedurally generated beep +- **Frequency**: 800 Hz sine wave +- **Duration**: 0.5 seconds +- **Volume**: 30% (0.3 gain) + +## 🐛 Troubleshooting + +### Notifications Not Showing +1. Check if "Enable Notifications" is enabled in settings +2. Ensure Discord has notification permissions in your OS +3. Check browser/client notification settings + +### Webhook Not Working +1. Verify webhook URL is correct and active +2. Check console for error messages (Ctrl+Shift+I) +3. Ensure webhook has permission to send messages +4. Test webhook with a curl command or webhook tester + +### User Not Being Tracked +1. Verify User ID is correct +2. Check if tracking options are enabled (Voice/Status/Messages/Typing) for that entry +3. Ensure server selection matches where you want to track +4. User must be in a mutual server with you + +### Messages or Typing Not Logging +1. Make sure **Messages** / **Typing** is ticked for the entry (use the inline checkboxes in the watch list) +2. Turn on **Debug Mode**, open DevTools (Ctrl+Shift+I) → Console, and filter by `WatchCord` +3. Trigger the event from the **watched** account — your own messages are skipped (`optimistic`) and your own typing never fires `TYPING_START` +4. Read the `reason` in the log: it shows whether the user isn't watched, the flag is off, or the guild doesn't match +5. For DMs, the entry must use **All Servers (*)** + +### Logs Not Saving +1. Check file system permissions +2. Look for errors in DevTools console +3. Verify `watchcord-logs.txt` exists in Discord's app data folder + +### Sound Not Playing +1. Check system audio settings +2. Verify "Play Sound" options are enabled for the user +3. Check browser audio permissions +4. Ensure volume is not muted + +## 📝 Privacy & Ethics + +**Important Considerations:** + +⚠️ **User Privacy**: This plugin tracks other users' activity. Please use responsibly and ethically. + +- Only track users with their knowledge and consent when possible +- Be aware of privacy laws in your jurisdiction +- Don't use this plugin to harass or stalk users +- Consider informing tracked users about monitoring +- Respect Discord's Terms of Service + +**Data Security:** +- Logs are stored locally on your device +- Webhook data is transmitted over HTTPS +- No data is sent to third-party services (except configured webhooks) + +## 📄 License + +This plugin is part of Vencord and is licensed under GPL-3.0-or-later. + +``` +Vencord, a Discord client mod +Copyright (c) 2026 Vendicated and contributors +SPDX-License-Identifier: GPL-3.0-or-later +``` + +## 🤝 Contributing + +Contributions are welcome! Please follow Vencord's contribution guidelines. + +### Feature Ideas +- [ ] Export logs to CSV/JSON +- [ ] Activity graphs and statistics +- [ ] Custom notification sounds +- [ ] Regex-based filters for logs +- [ ] Schedule-based tracking (only track during certain hours) +- [ ] Multiple webhook support + +## 📞 Support + +For issues or questions: +1. Check the troubleshooting section above +2. Review Vencord's documentation +3. Open an issue in the Vencord repository + +## 🙏 Acknowledgments + +- Built for [Vencord](https://vencord.dev/) +- Thanks to the Vencord team and contributors +- Inspired by user activity monitoring needs in Discord communities + +--- + +**Version**: 1.0.0 +**Last Updated**: February 2026 +**Compatibility**: Vencord (Discord Desktop/Web) diff --git a/watchCord/docs/workflows.md b/watchCord/docs/workflows.md new file mode 100644 index 0000000..11428af --- /dev/null +++ b/watchCord/docs/workflows.md @@ -0,0 +1,373 @@ +# WatchCord — Detailed Documentation + +## Architecture Overview + +WatchCord monitors Discord user activity (voice channel changes, online status changes, sent messages, and typing events) for a configurable list of users. Events are logged to a local file, shown in an in-app viewer, optionally sent to a webhook, and can trigger desktop notifications and sound alerts. + +``` +┌─────────────────────────────────────────────────────┐ +│ WatchCord Plugin │ +├─────────────────────────────────────────────────────┤ +│ Settings UI │ +│ ├─ WatchListManager — add/remove watched users │ +│ └─ LogsViewer — view/filter/clear logs │ +├─────────────────────────────────────────────────────┤ +│ Toolbar Button (eye icon) → opens plugin settings │ +├─────────────────────────────────────────────────────┤ +│ Flux Handlers │ +│ ├─ VOICE_STATE_UPDATES — voice join/leave/move │ +│ ├─ PRESENCE_UPDATES — online status changes │ +│ ├─ MESSAGE_CREATE — watched user sends message │ +│ └─ TYPING_START — watched user starts typing │ +├─────────────────────────────────────────────────────┤ +│ Core Logic (renderer) │ +│ ├─ addLog() — in-memory + file logging │ +│ ├─ sendWebhookMessage() — optional remote logging │ +│ ├─ showNotification() — native desktop notifications│ +│ └─ playNotificationSound() — WebAudio beep │ +├─────────────────────────────────────────────────────┤ +│ Native Module (native.ts) │ +│ ├─ appendLog / clearLogs / openLogFile │ +│ ├─ sendWebhook │ +│ └─ logFullStatusChange / openStatusChangeFile / clearStatusChanges │ +└─────────────────────────────────────────────────────┘ +``` + +## Data Types + +### WatchItem (persisted) + +```ts +interface WatchItem { + id: string; // unique ID (Date.now().toString()) + odUserId: string; // Discord user ID + guildId: string; // Server ID or "*" for all servers + watchVoice: boolean; // track voice channel changes + watchStatus: boolean; // track online status changes + watchMessage: boolean; // track sent messages + watchTyping: boolean; // track typing events + playVoiceSound: boolean; // play sound on voice events + playStatusSound: boolean;// play sound on status events +} +``` + +### LogEntry (in-memory only) + +```ts +interface LogEntry { + timestamp: string; // localized timestamp from getTimestamp() + type: "voice" | "status" | "message" | "typing"; + message: string; +} +``` + +### Module-level state + +| Variable | Type | Purpose | +|----------|------|---------| +| `logs` | `LogEntry[]` | In-memory cache of last 500 entries | +| `previousStatuses` | `Map` | Tracks last known status per user | +| `previousVoiceChannels` | `Map` | Tracks last known voice channel per user | + +## Settings + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `webhookUrl` | String | `""` | Discord webhook URL for remote logging (empty = disabled) | +| `enableNotifications` | Boolean | `true` | Show native desktop notifications | +| `debugMode` | Boolean | `false` | Log verbose debug trace to the DevTools console | +| `watchListManager` | Component | — | UI for managing watched users | +| `logsViewer` | Component | — | UI for viewing/clearing logs | + +## Persistence + +The watch list is stored as JSON in `Vencord.Settings.plugins.WatchCord.watchList`. + +```ts +function getWatchList(): WatchItem[] { + const stored = Vencord.Settings.plugins.WatchCord?.watchList; + return stored ? JSON.parse(stored) : []; +} + +function setWatchList(list: WatchItem[]) { + Vencord.Settings.plugins.WatchCord.watchList = JSON.stringify(list); +} +``` + +## Logging Pipeline + +### addLog(type, message) + +1. Creates a `LogEntry` with current timestamp +2. Prepends to in-memory `logs` array +3. Trims to the last 500 entries +4. Formats `[timestamp] [TYPE] message` +5. Writes to file via `Native.appendLog()` + +``` +Event detected + │ + ▼ +addLog("voice" | "status" | "message" | "typing", message) + │ + ├─ logs.unshift(entry) → in-memory cache (last 500) + ├─ Native.appendLog(logLine) → watchcord-logs.txt on disk + └─ (optional) sendWebhookMessage → Discord webhook +``` + +## Feature Workflows + +### Voice Activity Tracking + +`VOICE_STATE_UPDATES` fires for each changed voice state. For each state: + +``` +VOICE_STATE_UPDATES({ voiceStates }) + │ + ├─ Load watchList; skip if empty + │ + ▼ +for each state: + │ + ├─ Capture userId, channelId, guildId + ├─ prevChannelId = previousVoiceChannels.get(userId) + ├─ Update previousVoiceChannels + │ + ├─ Match watched user (watchVoice && guild matches) + │ └─ Skip if channelId === prevChannelId (no change) + │ └─ Log "left old channel" (if prevChannelId) + │ └─ Log "joined new channel" (if channelId) + │ └─ Log existing users in the new channel + │ └─ Play voice sound (if enabled) + │ + ├─ Associated-activity tracking: + │ For each watched user, detect OTHER users joining/leaving + │ the watched user's current channel + │ + └─ Desktop notification (for watched user's own movement) +``` + +**Message examples:** +``` +<@123>(User-123) joined General(987) in ServerName(111) + └─ Existing users in channel: Alice(222), Bob(333) +<@123>(User-123) left General(987) in ServerName(111) +<@444>(David-444) joined <@123>(User)'s channel General(987) in ServerName(111) +``` + +### Status Change Tracking + +`PRESENCE_UPDATES` fires for each presence update. For each update: + +``` +PRESENCE_UPDATES({ updates }) + │ + ├─ Load watchList; skip if empty + │ + ▼ +for each update: + │ + ├─ Capture user.id, status, guildId + ├─ prevStatus = previousStatuses.get(userId) + ├─ Update previousStatuses + ├─ Skip if prevStatus === status (no change) + │ + ├─ Match watched user (watchStatus && guild matches) + │ └─ Skip if prevStatus === undefined (first sighting) + │ └─ Log full status object to JSON file (Native.logFullStatusChange) + │ └─ addLog("status", "<@id>(name-id) status changed: A → B") + │ └─ sendWebhookMessage(...) + │ └─ showNotification("Status Change", ...) + │ └─ Play status sound (if enabled) +``` + +**Status label mapping:** + +| Discord status | Display label | +|----------------|---------------| +| `online` | Online | +| `idle` | Away/Idle | +| `dnd` | Do Not Disturb | +| `offline` | Offline | +| `invisible` | Invisible | + +### Associated-User Tracking + +When a watched user is in a voice channel, WatchCord also logs when **other** users join or leave that same channel. This is tracked inside `VOICE_STATE_UPDATES`: + +- `channelId === watchedUserChannelId && prevChannelId !== watchedUserChannelId` → someone joined the watched user's channel +- `prevChannelId === watchedUserChannelId && channelId !== watchedUserChannelId` → someone left the watched user's channel + +These detailed logs are **only written to the local log file**, not sent to webhooks (to avoid spam). + +### Message Watching + +`MESSAGE_CREATE` fires whenever a message is created. WatchCord only reacts to messages **from a watched user** (matched on `odUserId`, never your own account): + +``` +MESSAGE_CREATE({ message, optimistic }) + │ + ├─ Skip if optimistic (your own messages) or no author + │ + ▼ + ├─ userId = message.author.id + ├─ channel = ChannelStore.getChannel(message.channel_id) + ├─ guildId = message.guild_id ?? channel.guild_id + │ (undefined for DMs — use "*" to match) + │ + ├─ Match watched user (watchMessage && guild matches) + │ └─ addLog("message", "<@id>(name-id) sent in #channel(id) in guild: \"content\"") + │ └─ sendWebhookMessage("`[ts]` 💬 <@id>(name) sent in <#channelId> in guild: \"content\"" + "\n[Go to message](https://discord.com/channels/guild/channel/message)") +``` + +**Matching rules:** +- `item.odUserId === userId` — only the watched entry's user ID, never self +- `item.watchMessage` must be enabled +- `item.guildId === "*"` matches any server **and DMs**; otherwise the specific guild must match +- The `optimistic` flag (your own sent messages) is always skipped + +**Content fallback:** attachment-only messages log `[N attachment(s)]`; empty content logs `[no text]`. + +### Typing Watching + +`TYPING_START` fires when **another user** starts typing (your own typing fires `TYPING_START_LOCAL`, which is intentionally ignored): + +``` +TYPING_START(event) + │ + ├─ userId = event.userId ?? event.user_id + ├─ channelId = event.channelId ?? event.channel_id + │ + ├─ channel = ChannelStore.getChannel(channelId) + ├─ guildId = event.guildId ?? event.guild_id ?? channel.guild_id + │ + ├─ Match watched user (watchTyping && guild matches) + │ └─ addLog("typing", "<@id>(name-id) started typing in #channel(id) in guild") + │ └─ sendWebhookMessage("`[ts]` ⌨️ <@id>(name) started typing in <#channelId> in guild") +``` + +**Note:** DM channel names are resolved from the recipient's username via `getChannelName()` (group DMs use the channel `name`), so DM typing/message logs show the other person's name instead of "Unknown". + +## Lifecycle + +### start() + +1. Iterates the watch list and initializes `previousStatuses` from `PresenceStore.getStatus()` for users with `watchStatus` enabled +2. Writes a `[SYSTEM] WatchCord started` log line to file +3. Sends the startup message to the webhook (if configured) +4. Logs `WatchCord started` to console + +### stop() + +1. Clears `previousStatuses` +2. Clears `previousVoiceChannels` +3. Logs `WatchCord stopped` to console + +## Debug Logging + +All verbose diagnostic output is routed through a single helper: + +```ts +debugLog(...args) // prefixes every line with [WatchCord] +``` + +It is **disabled by default** and only prints when the **Debug Mode** setting is enabled. This keeps the console clean during normal use while allowing a full trace of the message/typing pipeline when troubleshooting. + +When enabled, DevTools (Ctrl+Shift+I) → Console shows: + +- **On start** — the raw persisted `watchList` string and the parsed/normalized entries +- **`MESSAGE_CREATE`** — the raw event fields (`optimistic`, `authorId`, `channelId`, `guildId`, `content`), each skip decision, the current watch list, and either the matched log line or a `reason` explaining why no match occurred +- **`TYPING_START`** — the raw event, plus the same match decision / `reason` detail + +`reason` is one of: `user is not in the watch list`, `watchMessage`/`watchTyping` is `OFF for this entry`, or a `guild mismatch` (with both guild IDs shown). + +> Note: `TYPING_START` fires for **everyone** typing in channels you can see, so enabling Debug Mode can be noisy in busy servers. Turn it back off once you're done troubleshooting. + +## Native Module (native.ts) + +Runs in Electron's main process via IPC (`VencordNative.pluginHelpers.WatchCord`). All file I/O and webhook requests happen here. + +| Function | Purpose | +|----------|---------| +| `appendLog(logLine)` | Append a line to `watchcord-logs.txt` | +| `clearLogs()` | Truncate `watchcord-logs.txt` | +| `openLogFile()` | Open the log file in the default editor (creates if missing) | +| `sendWebhook(url, content)` | POST a Discord webhook message | +| `logFullStatusChange(obj)` | Append a full status object to `watchcord-full-status-changes.json` | +| `openStatusChangeFile()` | Open the status-changes file | +| `clearStatusChanges()` | Truncate the status-changes file | + +**File locations** (relative to Electron `app.getPath("userData")`): + +| File | Path | +|------|------| +| Logs | `/watchcord-logs.txt` | +| Full status changes | `/watchcord-full-status-changes.json` | + +## Settings UI + +### WatchListManager + +Adds/removes watched users with per-user toggles: + +- **User ID** — text input +- **Server** — dropdown (All Servers or a specific server) +- **Watch Voice** — track voice activity +- **Watch Status** — track status changes +- **Watch Messages** — log when the user sends a message +- **Watch Typing** — log when the user starts typing +- **Voice Sound** — play sound on voice events +- **Status Sound** — play sound on status events + +Each entry in the "Current Watch List" also shows inline checkboxes, so existing entries can have any flag toggled on/off without removing and re-adding them. Legacy entries (saved before these fields existed) load with `watchMessage`/`watchTyping` set to `false`. + +Displays the current list with username/server name and a Remove button. + +### LogsViewer + +- Filter dropdown: All / Voice / Status / Messages / Typing +- Auto-refreshes every 1 second +- Color-coded: green (voice), yellow (status), blue (message), purple (typing) +- Buttons: Open Log File, Open Full Status Changes, Clear Logs, Clear Status Changes + +## Toolbar Button + +Injected next to the inbox via a patch on `toolbar:function`. The eye icon opens Vencord plugin settings (`SettingsRouter.open("VencordPlugins")`). Wrapped in `ErrorBoundary` to avoid crashes. + +## Notification Sound + +Procedurally generated WebAudio beep: +- **Frequency:** 800 Hz +- **Waveform:** sine +- **Duration:** 0.5 seconds +- **Volume:** 30% (0.3 gain, exponential decay to 0.01) + +## Webhook Integration + +- Configured via the `webhookUrl` setting +- `Native.sendWebhook()` POSTs JSON `{ content }` to the URL +- Messages use Markdown backticks around timestamps so they render in Discord +- The channel is rendered as a clickable link via a `<#channelId>` channel mention (guild channels only; DMs fall back to the recipient's name) +- Message events append a `[Go to message](...)` jump link pointing at the message in the client +- Startup message, voice events, status changes, messages, and typing events are all sent + +## Edge Cases + +- **First status sighting:** `prevStatus === undefined` → status is recorded but not logged (no "unknown → online" noise) +- **Own messages/typing:** `MESSAGE_CREATE` skips `optimistic: true`, and `TYPING_START_LOCAL` is not handled — the plugin never logs your own activity +- **Direct messages:** `guildId`/`guild_id` is `undefined` for DMs; a watch entry with `guildId === "*"` matches DMs. DM channel names fall back to the recipient's username +- **Log buffer:** In-memory logs capped at 500 entries; file is unbounded +- **Missing user/guild:** Fallback to `"Unknown"` for display names +- **Guild wildcard:** `guildId === "*"` matches any server (and DMs) +- **Webhook failure:** Errors are caught and logged to console, not thrown + +## File Structure + +``` +watchCord/ +├── index.tsx # Main plugin: types, flux handlers, UI components, toolbar button +├── native.ts # Electron main-process: file I/O and webhook requests +├── README.md # User-facing documentation +└── docs/ + └── workflows.md # This file — detailed architecture & workflows +``` diff --git a/watchCord/index.tsx b/watchCord/index.tsx new file mode 100644 index 0000000..628114e --- /dev/null +++ b/watchCord/index.tsx @@ -0,0 +1,1083 @@ +/* + * 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 = new Map(); +const previousVoiceChannels: Map = 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: () => , + }, + logsViewer: { + type: OptionType.COMPONENT, + description: "View activity logs", + component: () => , + }, +}); + +// 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( + 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 ( +
+ + Add New Watch Entry + + + User ID + + + + + Server + + setWatchVoice(e.target.checked)} + /> + Watch Voice + + + + + + +
+ + + + + + Current Watch List ({watchList.length}) + + + {watchList.length === 0 ? ( + No users being watched + ) : ( + watchList.map(item => ( +
+
+ + User:{" "} + {getUserDisplay(item.odUserId)} + + + Server:{" "} + {getGuildDisplay(item.guildId)} + +
+ {( + [ + ["watchVoice", "Voice"], + ["watchStatus", "Status"], + ["watchMessage", "Messages"], + ["watchTyping", "Typing"], + ["playVoiceSound", "🔔 Voice"], + ["playStatusSound", "🔔 Status"], + ] as const + ).map(([flag, label]) => ( + + ))} +
+
+ +
+ )) + )} + + ); +} + +// Logs Viewer Component +function LogsViewer() { + const [displayLogs, setDisplayLogs] = React.useState(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 ( +
+
+