Initial commit: autoMover, friendsCheck, watchCord plugins and README

This commit is contained in:
X4Lo committed 2026-11-11 17:41:39 +00:00
commit f06f2f493b
11 files changed
+3799

No files matched your search

+373
View File
@@ -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<userId, status>` | Tracks last known status per user |
| `previousVoiceChannels` | `Map<userId, channelId>` | 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 | `<userData>/watchcord-logs.txt` |
| Full status changes | `<userData>/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
```