Document all ten cogs
+118
@@ -0,0 +1,118 @@
|
||||
# AlbumOfTheDay
|
||||
|
||||
Posts the current album from a 1001 Albums Generator group into a Discord channel once a day, with an embed containing the album, group statistics, genres and streaming links.
|
||||
|
||||
This cog replaces a GitHub Actions workflow that posted through a webhook. The equivalent work happens inside the bot, with per-guild settings and an internal scheduler.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A 1001 Albums Generator group and its API URL.
|
||||
- Outbound HTTPS access from the bot host.
|
||||
- Manage Server or a Red admin role for setup commands. The manual post command has no restriction.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Open the group page. The public URL looks like `https://1001albumsgenerator.com/groups/<slug>`.
|
||||
2. Build the API URL by inserting `/api/v1` before `/groups`:
|
||||
|
||||
```
|
||||
https://1001albumsgenerator.com/api/v1/groups/<slug>
|
||||
```
|
||||
|
||||
3. Configure the guild:
|
||||
|
||||
```
|
||||
[p]aotd seturl https://1001albumsgenerator.com/api/v1/groups/<slug>
|
||||
[p]aotd setchannel #album-of-the-day
|
||||
[p]aotd settime 8 0
|
||||
```
|
||||
|
||||
4. Test immediately with `[p]aotd now`.
|
||||
|
||||
`seturl` requires the URL to start with `https://` but performs no other validation. A wrong slug is reported by the API as a 404 when a post is attempted.
|
||||
|
||||
## Commands
|
||||
|
||||
The group is `albumoftheday`, alias `aotd`, and it is guild only.
|
||||
|
||||
| Command | Arguments | Permission | Behavior |
|
||||
|---|---|---|---|
|
||||
| `[p]aotd now` | none | Any member | Posts today's album in the current channel |
|
||||
| `[p]aotd seturl` | `<url>` | Manage Server | Saves the API URL after an HTTPS check |
|
||||
| `[p]aotd setchannel` | `[channel]` | Manage Server | Sets the daily channel, defaulting to the current one |
|
||||
| `[p]aotd settime` | `<hour> [minute]` | Manage Server | Sets the daily time in the configured timezone, 24 hour clock |
|
||||
| `[p]aotd settz` | `<iana name>` | Manage Server | Sets the timezone, alias `settimezone` |
|
||||
| `[p]aotd settings` | none | Manage Server | Shows URL, channel, time, current local time and last posted date |
|
||||
| `[p]aotd clear` | none | Manage Server | Resets the guild configuration and stops daily posting |
|
||||
|
||||
`settime` rejects hours outside 0-23 and minutes outside 0-59. `settz` validates the name against `zoneinfo.available_timezones()` and suggests `America/Chicago`, `America/New_York` or `Europe/London` on failure.
|
||||
|
||||
`settings` resolves the channel mention when the channel still exists and computes the current local time in the configured zone. `clear` restores the defaults, which unset the URL and channel and therefore stop posting.
|
||||
|
||||
## Scheduling
|
||||
|
||||
The scheduler is a `tasks.loop` with a one minute interval. It is started in `__init__`, restarted by `on_ready` if it is not running, and waits for Red to be ready before its first iteration.
|
||||
|
||||
Each iteration:
|
||||
|
||||
1. Loads every guild's configuration.
|
||||
2. Skips guilds without both an API URL and a channel ID.
|
||||
3. Reads the timezone. An invalid stored value logs a warning and falls back to `America/Chicago`.
|
||||
4. Compares the guild's local hour and minute with the configured values. Anything other than an exact match is skipped.
|
||||
5. Skips when `last_posted` equals the local date, which prevents duplicates within one local day, including across reloads and restarts.
|
||||
6. Resolves the guild and channel. A missing channel is logged and skipped.
|
||||
7. Fetches, posts and stores the local date as `last_posted`.
|
||||
|
||||
Because the match is exact and the loop runs once a minute, a bot that is offline for the scheduled minute does not post later. There is no catch-up. Two guilds can share a time without interfering, and each keeps its own last posted date.
|
||||
|
||||
Daylight saving is handled by `zoneinfo`, so a time stays fixed in local terms year-round.
|
||||
|
||||
## Embed contents
|
||||
|
||||
- Title: album name, artist, and the release date when present.
|
||||
- Description: a genre list with hyphens replaced by spaces and title cased, followed by links.
|
||||
- Links: Reviews from the group URL, Wikipedia, Spotify from `spotifyId`, Apple Music from `appleMusicId`. Missing links are omitted.
|
||||
- All-Time Favorite: the top entry of `highestRatedAlbums`, with name, artist and average rating out of 5.
|
||||
- Least Favorite: the top entry of `lowestRatedAlbums`.
|
||||
- Favorite Genre and Worst Genre: from `favoriteGenres` and `worstGenres`, with the rating.
|
||||
- Footer: number of generated albums, total votes, and group average.
|
||||
- Thumbnail: the first image URL.
|
||||
|
||||
Empty lists produce readable fallbacks such as "No favorites yet" and "No favorite genre yet".
|
||||
|
||||
## API handling
|
||||
|
||||
Requests use a 15 second total timeout. Failures produce a specific message:
|
||||
|
||||
| Condition | Message |
|
||||
|---|---|
|
||||
| Non-200 response | "API returned status N. Check the API URL points to a valid group." |
|
||||
| Unparseable JSON | "API returned malformed JSON." |
|
||||
| Connection failure | "Could not connect to the API. Check the bot's internet connection and the API URL." |
|
||||
| Timeout | "API request timed out after 15 seconds." |
|
||||
| Other client error | "API request failed: ..." |
|
||||
| Missing `currentAlbum` | "API response missing 'currentAlbum'. Check the API URL points to a valid group." |
|
||||
|
||||
`now` reports these to the channel. The scheduled post logs them at warning level and leaves `last_posted` unchanged. Since the loop only matches the configured minute once per day, a failed scheduled post is not retried until the next day.
|
||||
|
||||
## Limits
|
||||
|
||||
- One post per guild per local day.
|
||||
- The bot must be online during the configured minute.
|
||||
- The embed content depends entirely on the third-party API shape. A change to that API results in a logged failure rather than a partial post.
|
||||
- The scheduled path catches `ValueError` and `discord.DiscordException`. Other exceptions inside the loop are contained by the task framework and logged by Red.
|
||||
|
||||
## Stored data
|
||||
|
||||
Guild config under identifier `0xA1B00FDA`:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `api_url` | `null` |
|
||||
| `channel_id` | `null` |
|
||||
| `post_hour` | `8` |
|
||||
| `post_minute` | `0` |
|
||||
| `timezone` | `America/Chicago` |
|
||||
| `last_posted` | `null` |
|
||||
|
||||
The group API URL is public and the API returns group statistics, so no Discord user data is sent anywhere.
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# Assistant
|
||||
|
||||
A chat assistant that answers in a dedicated channel or when the bot is mentioned. It talks to any OpenAI-compatible chat completions API and defaults to a local Ollama server.
|
||||
|
||||
## Requirements
|
||||
|
||||
- An OpenAI-compatible backend. The default is `http://127.0.0.1:11434/v1`, which is Ollama's OpenAI-compatible endpoint.
|
||||
- For any non-local backend, an API key.
|
||||
- No Python package beyond `aiohttp`, which Red provides.
|
||||
|
||||
## Backend configuration
|
||||
|
||||
Global config:
|
||||
|
||||
| Key | Default | Set by |
|
||||
|---|---|---|
|
||||
| `base_url` | `http://127.0.0.1:11434/v1` | `[p]assistant baseurl [url]` |
|
||||
| `api_key` | `null` | `[p]assistant setkey` |
|
||||
|
||||
`setkey` posts a button. Pressing it opens a modal, and the submitted value is written to global config. The key is never echoed back and is stored in plain text.
|
||||
|
||||
`baseurl` with no argument resets the URL to the local default. A trailing slash is stripped. A URL containing `127.0.0.1` or `localhost` is reported as local and needs no key; any other URL is reported as remote and requires one.
|
||||
|
||||
The local check is a substring test, so a URL such as `http://127.0.0.1.example.com/v1` counts as local even though it is remote.
|
||||
|
||||
Per-guild config:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `enabled` | `true` |
|
||||
| `chat_channel` | `null` |
|
||||
| `model` | `llama3.2:3b-instruct-q4_K_M` |
|
||||
| `vision_model` | `llama3.2:3b-instruct-q4_K_M` |
|
||||
| `temperature` | `0.7` |
|
||||
| `system_prompt` | A short instruction to be witty, playful and brief |
|
||||
| `question_mode` | `false` |
|
||||
| `max_tokens` | `null` (unlimited) |
|
||||
| `reasoning_effort` | `null` (model default) |
|
||||
|
||||
## Commands
|
||||
|
||||
The group is `assistant`, guild only. Running it bare sends command help.
|
||||
|
||||
| Command | Arguments | Permission | Behavior |
|
||||
|---|---|---|---|
|
||||
| `[p]assistant setkey` | none | Bot owner | Button and modal to store the API key |
|
||||
| `[p]assistant baseurl` | `[url]` | Bot owner | Show or set the backend, no argument resets to local |
|
||||
| `[p]assistant toggle` | none | Any member | Enables or disables the assistant for the guild |
|
||||
| `[p]assistant channel` | `[channel]` | Any member | Sets or clears the dedicated chat channel |
|
||||
| `[p]assistant model` | `<model>` | Any member | Sets the model id |
|
||||
| `[p]assistant visionmodel` | `[model]` | Any member | Shows or sets the vision model id |
|
||||
| `[p]assistant models` | none | Any member | Lists models from the backend with reference prices |
|
||||
| `[p]assistant temp` | `<value>` | Any member | Sets temperature, 0.0 to 2.0 |
|
||||
| `[p]assistant maxlength` | `[tokens]` | Any member | Sets or clears the response token cap |
|
||||
| `[p]assistant reasoning` | `[level]` | Any member | Sets or clears reasoning effort |
|
||||
| `[p]assistant system` | `<prompt>` | Any member | Replaces the system prompt |
|
||||
| `[p]assistant showprompt` | none | Manage Server | Prints the system prompt in a code block |
|
||||
| `[p]assistant question` | none | Any member | Toggles question mode |
|
||||
| `[p]assistant clear` | none | Any member | Deletes the in-memory history for the current channel |
|
||||
| `[p]assistant settings` | none | Any member | Posts an embed of the current settings |
|
||||
|
||||
The permission split is deliberate in only two places. `setkey` and `baseurl` are owner only because they control credentials and cost. `showprompt` is admin only because it may contain internal instructions. Everything else, including the model, temperature, token cap, system prompt and chat channel, can be changed by any member who can run commands.
|
||||
|
||||
`reasoning` accepts `none`, `minimal`, `low`, `medium`, `high`, case-insensitively. An invalid value lists the options. No argument clears the setting.
|
||||
|
||||
`maxlength` rejects values below 1. No argument clears the cap.
|
||||
|
||||
`models` requires a key for remote backends and reports "API key not set" otherwise. It calls `GET <base_url>/models`, filters out known embedding and reranker ids, attaches a price table in EUR per million tokens for known ids, sorts by output price and then id, marks the current model, and sends an embed. Unknown ids are listed last with "pricing unknown". The price table is hardcoded for one provider and does not reflect the local Ollama catalogue.
|
||||
|
||||
## Message flow
|
||||
|
||||
The listener ignores bots and direct messages, then requires the guild to be enabled and a key to be present when the backend is remote. It responds only when the message is in the configured chat channel or mentions the bot. Mention tokens are stripped from the content.
|
||||
|
||||
The listener then collects image URLs from the invoking message's attachments and from the replied-to message's attachments and embeds. If there are any images, it replies "Images not supported at this time.", empties the list, and continues with the remaining text. If there is no text, it stops.
|
||||
|
||||
Question mode requires the text to end with a question mark. A mention that fails this test gets a reply explaining the rule. A message in the chat channel that fails is ignored silently.
|
||||
|
||||
The bot shows a typing indicator, calls the backend, and replies to the original message. A `None` reply produces "No response from the assistant." An empty string produces a note that the response was empty. Replies longer than 2000 characters are split into consecutive replies, each under the limit, in order.
|
||||
|
||||
## Request construction
|
||||
|
||||
The request body is:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "<guild model>",
|
||||
"messages": [{"role": "system", "content": "<prompt>"}, ...history],
|
||||
"temperature": 0.7
|
||||
}
|
||||
```
|
||||
|
||||
`max_tokens` is added when configured. `reasoning_effort` is added when configured. An `Authorization: Bearer` header is added whenever a key exists, including for local backends.
|
||||
|
||||
History is keyed by guild and channel and held in a dictionary. Each request sends the system prompt plus the last 20 entries. After a successful reply the history is trimmed to the last 20 entries once it exceeds 40, so the window grows to 40 and drops back to 20. History is lost on reload and is never written to disk.
|
||||
|
||||
The HTTP timeout is 120 seconds total. A non-200 response returns "API error <status>: <first 300 characters of the body>". Any exception returns "Request failed: <exception>". A response without `choices[0].message` returns "Unexpected API response."
|
||||
|
||||
## Vision
|
||||
|
||||
Vision is not available in the current code. The image collection code and the multimodal request branch exist, but the handler clears the image list before calling the API, so the branch for image content is unreachable. The `visionmodel` command and setting have no effect.
|
||||
|
||||
## Limits and failure modes
|
||||
|
||||
- No cooldown and no concurrency limit. Every qualifying message triggers an API call, and a busy channel produces one call per message.
|
||||
- Replies are posted as separate messages when chunked, which can trigger Discord rate limits during long outputs.
|
||||
- A local backend that is down produces a request failure reply for each message.
|
||||
- `[p]assistant clear` affects only the channel where it runs.
|
||||
- The guild `enabled` flag defaults to true, so a freshly loaded cog starts answering in any channel where the bot is mentioned.
|
||||
|
||||
## Stored data
|
||||
|
||||
Global config under identifier `987654321` holds the API key and base URL. Guild config holds the keys listed above. Chat history exists only in memory. `red_delete_data_for_user` is not implemented for this cog, so deleting a user's Red data does not remove their prompts from a running history.
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
# AutoRoom Commands
|
||||
|
||||
Two command groups: `autoroom` for room owners and members, and `autoroomset` for server administrators. Both are guild only.
|
||||
|
||||
## Member and owner commands
|
||||
|
||||
Group: `[p]autoroom`, alias `[p]vc`.
|
||||
|
||||
These commands operate on the room the invoking member is currently in, or the room they own. They do not require a permission check beyond being in the room. The cog verifies ownership and replies with a temporary error when the member is not allowed.
|
||||
|
||||
| Command | Aliases | Arguments | Description |
|
||||
|---|---|---|---|
|
||||
| `[p]autoroom settings` | `about`, `info` | none | Shows room settings and current access overwrites |
|
||||
| `[p]autoroom name` | none | `<name>` | Renames the room, capped at 100 characters |
|
||||
| `[p]autoroom bitrate` | `kbps` | `<kbps>` | Sets bitrate, clamped to 8 and the guild limit |
|
||||
| `[p]autoroom users` | `userlimit` | `<limit>` | Sets the user limit, clamped to 0 through 99 |
|
||||
| `[p]autoroom claim` | none | none | Takes ownership when the previous owner has left |
|
||||
| `[p]autoroom public` | none | none | Makes the room visible and joinable |
|
||||
| `[p]autoroom locked` | none | none | Makes the room visible but not joinable |
|
||||
| `[p]autoroom private` | none | none | Hides the room from everyone not allowed |
|
||||
| `[p]autoroom allow` | `add` | `<members or roles...>` | Grants access to one or more members or roles |
|
||||
| `[p]autoroom deny` | `ban`, `block` | `<member or role>` | Revokes access and disconnects affected members |
|
||||
|
||||
### settings
|
||||
|
||||
Reports the owner, or "Server Managed" when no owner is recorded. Then the access type derived from the source's member roles, the bitrate in kbps, and the channel's age. A second section lists allowed and denied members and roles taken from the channel's overwrites. Anyone in the room can run it, including members who do not own it.
|
||||
|
||||
### name
|
||||
|
||||
Rate limited by a per-channel bucket of two changes per 604 seconds, where the extra four seconds absorb Discord's own rename handling. Hitting the limit produces a message with the wait time and suggests renaming directly in Discord. When the server requires 2FA for moderation, the message notes that the member needs 2FA enabled to rename the channel manually.
|
||||
|
||||
The command deletes the invoking message after a short delay on success.
|
||||
|
||||
### bitrate and users
|
||||
|
||||
`bitrate` converts kbps to bits per second and clamps between 8000 and the guild's `bitrate_limit`. `users` clamps between 0 and 99, where 0 removes the limit. Both confirm with a check mark reaction and delete the command message after five seconds.
|
||||
|
||||
### claim
|
||||
|
||||
Claiming is refused when the current owner is still in the room. Otherwise a two minute per-channel cooldown applies. Administrators, moderators, configured admin and mod roles, and the guild owner bypass both restrictions.
|
||||
|
||||
On success the old owner's overwrites are reset to the source's default allow set and the new owner receives the source's owner permissions. The linked legacy text channel, when present, is updated the same way. The channel's stored `owner` is replaced.
|
||||
|
||||
### allow and deny
|
||||
|
||||
`allow` accepts several members or roles in one call. `deny` accepts one, disconnects any member in the room who can no longer connect, and records the denial.
|
||||
|
||||
Both require the bot to have Manage Roles on the room. The source must still exist, otherwise the command explains that the room can no longer be modified.
|
||||
|
||||
Denying a role removes access for everyone holding it. When the source uses member roles, those roles may still grant connect permission, so the deny can appear to have no effect.
|
||||
|
||||
## Administrator commands
|
||||
|
||||
Group: `[p]autoroomset`, requiring Manage Server or a Red admin role.
|
||||
|
||||
| Command | Aliases | Arguments | Description |
|
||||
|---|---|---|---|
|
||||
| `[p]autoroomset settings` | none | none | Shows server access settings and every configured source |
|
||||
| `[p]autoroomset permissions` | `perms` | none | Checks the bot's permissions for each source |
|
||||
| `[p]autoroomset create` | `enable`, `add` | `<source> <category>` | Creates or enables a source with an interactive setup |
|
||||
| `[p]autoroomset disable` | `delete`, `del` | `<source>` | Removes a source and stops room creation |
|
||||
| `[p]autoroomset access` | none | none | Parent group for access settings |
|
||||
|
||||
### settings
|
||||
|
||||
Prints a server section with admin access, moderator access and bot roles, then a section for each source showing its category, room type, name format and text settings. Source names are resolved to channel mentions where possible.
|
||||
|
||||
### permissions
|
||||
|
||||
Compares required permissions with the bot's effective permissions on the source and destination, and reports missing entries with a hint to grant them and rerun the command. This is the first command to run when room creation fails.
|
||||
|
||||
### create
|
||||
|
||||
Interactive. Asks for the source channel if not supplied, checks permissions, then asks for the destination category and room type. It can create a new source channel or adopt an existing one. On completion the source is stored in the custom `AUTOROOM_SOURCE` group with default settings.
|
||||
|
||||
### disable
|
||||
|
||||
Deletes the source configuration. Existing rooms are not deleted immediately; the cleanup task removes them once their source is gone.
|
||||
|
||||
### access
|
||||
|
||||
| Command | Behavior |
|
||||
|---|---|
|
||||
| `[p]autoroomset access admin` | Toggles administrator access to every room |
|
||||
| `[p]autoroomset access mod` | Toggles moderator access to every room |
|
||||
| `[p]autoroomset access bot add <role>` | Adds a role that may enter every room |
|
||||
| `[p]autoroomset access bot remove <role>` | Removes such a role |
|
||||
|
||||
Administrator and moderator checks use Red's configured roles for the guild, not Discord's permission flags alone.
|
||||
|
||||
### modify
|
||||
|
||||
Parent group for per-source settings. Each subcommand takes the source channel when a guild has more than one.
|
||||
|
||||
| Subcommand | Purpose |
|
||||
|---|---|
|
||||
| `[p]autoroomset modify category` | Changes the destination category |
|
||||
| `[p]autoroomset modify type` | Sets the default room type: `public`, `locked`, `private` or `server` |
|
||||
| `[p]autoroomset modify name` | Chooses the name format: `username`, `game` or `custom`, and accepts a custom template |
|
||||
| `[p]autoroomset modify text` | Sets the hint message posted in a new room's text channel, or disables it |
|
||||
| `[p]autoroomset modify legacytext` | Enables or disables a legacy per-room text channel |
|
||||
| `[p]autoroomset modify legacytexttopic` | Sets or disables the topic on that legacy text channel |
|
||||
| `[p]autoroomset modify defaults` | Resets source settings to their defaults |
|
||||
| `[p]autoroomset specialperms` | Parent group for owner permission toggles |
|
||||
|
||||
`specialperms ownermodify` controls whether owners may change the room's channel settings. `specialperms sendmessage` controls whether owners and members may send messages in the linked text channel. Both are stored per source as `perm_owner_manage_channels` and `perm_send_messages`.
|
||||
|
||||
### modify type server
|
||||
|
||||
The `server` type behaves like a public room, with the server as the owner instead of the creating member. No owner record is written, the creating member receives no owner permissions, and the room cannot be modified through the owner commands. It is the fourth option and can only be set as a source default by an administrator.
|
||||
|
||||
## Cooldowns
|
||||
|
||||
| Action | Limit | Scope |
|
||||
|---|---|---|
|
||||
| Room creation | 2 per 60 seconds | Member |
|
||||
| Creation warning message | 1 per 3600 seconds | Member |
|
||||
| Rename through command | 2 per 604 seconds | Channel |
|
||||
| Ownership claim | 1 per 120 seconds | Channel |
|
||||
|
||||
Cooldowns are in memory and reset when the cog reloads.
|
||||
|
||||
## Failure messages
|
||||
|
||||
Messages are sent as temporary errors and often delete themselves.
|
||||
|
||||
| Situation | Message |
|
||||
|---|---|
|
||||
| Command used outside the author's room | A request to use the command in their own AutoRoom |
|
||||
| Source deleted | The source no longer exists, so the room cannot be modified |
|
||||
| Missing Manage Roles | The bot lacks the permission and the message asks the member to tell staff |
|
||||
| Claim while owner present | Ownership can only be claimed after the owner leaves |
|
||||
| Claim cooldown | Wait time before claiming, in case the previous owner returns |
|
||||
| Rename cooldown | The limit, the window, and the remaining wait |
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
# AutoRoom Overview
|
||||
|
||||
AutoRoom creates a temporary voice channel for a member who joins a designated source channel, gives that member control of the new channel, and deletes it when the last person leaves.
|
||||
|
||||
The cog is PhasecoreX's AutoRoom version 4.0.7 with local modifications. Its command names, aliases and general design follow that upstream project. The notes below describe the code in this repository.
|
||||
|
||||
## Concepts
|
||||
|
||||
| Term | Meaning |
|
||||
|---|---|
|
||||
| AutoRoom Source | A voice channel marked as a source. Joining it creates a room |
|
||||
| AutoRoom | The temporary voice channel created for a member |
|
||||
| AutoRoom Owner | The member who owns the room, normally the member who triggered creation |
|
||||
| Member roles | The roles allowed to connect to a source, which decide who can use it |
|
||||
| Destination category | The category new rooms are created in |
|
||||
|
||||
A guild can have several sources, each with its own category, room type, name format and text settings.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Manage Channels, Manage Roles, Move Members, View Channel, Connect and Send Messages in the relevant channels.
|
||||
- A voice channel to use as the source and a category for the new rooms.
|
||||
- `func-timeout` and `jinja2` from the manifest.
|
||||
|
||||
`[p]autoroomset permissions` checks the bot's permissions against a source and reports what is missing.
|
||||
|
||||
## Setup
|
||||
|
||||
```
|
||||
[p]autoroomset create <source voice channel> <destination category>
|
||||
```
|
||||
|
||||
The command walks through the setup with prompts, offering to create a source, choose a room type, and set a name format. It warns when permissions are missing. After setup, join the source to confirm a room is created and you are moved into it.
|
||||
|
||||
Further changes are made with `[p]autoroomset modify`, which has subcommands for the category, room type, name format, text channel behaviour and defaults. `[p]autoroomset settings` shows the current server and source configuration.
|
||||
|
||||
## Room types
|
||||
|
||||
A room's type is stored per source and can be changed per room by its owner.
|
||||
|
||||
| Type | Behavior |
|
||||
|---|---|
|
||||
| Public | Everyone who can see the category can see and join |
|
||||
| Locked | Everyone who can see the category can see the room, nobody can join unless allowed |
|
||||
| Private | Nobody can see or join unless allowed |
|
||||
|
||||
`[p]autoroom public`, `locked` and `private` switch between these. `[p]autoroom allow` and `deny` add member or role overwrites that survive type changes.
|
||||
|
||||
## Member roles
|
||||
|
||||
Member roles are not a stored list. They are derived from the source channel's permission overwrites: a role counts as a member role when it is allowed to connect to the source while `@everyone` is denied connect. This behaviour comes from schema migration 6, which removed the old stored `member_role` setting.
|
||||
|
||||
Two consequences:
|
||||
|
||||
- Roles can be changed without a command, by editing the source channel's permissions in Discord.
|
||||
- A source that allows `@everyone` to connect has no member roles, and every member can create rooms from it.
|
||||
|
||||
Denying roles in a room that uses member roles can produce unexpected results, because allowed member roles may grant access back.
|
||||
|
||||
## Creating and deleting rooms
|
||||
|
||||
1. A member joins a source channel.
|
||||
2. The cog checks the member's create cooldown: two creations per 60 seconds per member. A warning is shown at most once per hour.
|
||||
3. A new voice channel is created in the source's destination category, named from the configured template.
|
||||
4. The member is moved into it and becomes the owner. The owner gets the permissions configured for owners, which by default include managing the channel, moving members and managing messages in the linked text channel.
|
||||
5. When the last member leaves, the channel is deleted. A channel with a bot inside stays alive, and so does one with a member who cannot be moved.
|
||||
|
||||
An owner who leaves and returns keeps ownership while the room exists. `[p]autoroom claim` transfers ownership when the owner has left, subject to a two minute cooldown per channel and the server access rules.
|
||||
|
||||
## Deletion and cleanup
|
||||
|
||||
Rooms are deleted when the last member leaves. A bot that remains in the channel counts as a member, so it keeps the room alive.
|
||||
|
||||
On load, a cleanup task walks every stored room record and deletes the record when the channel no longer exists in Discord. This clears entries after a room was deleted by hand or lost to a reset. The task does not delete live channels.
|
||||
|
||||
## Server access overrides
|
||||
|
||||
`[p]autoroomset access` controls who can enter rooms regardless of the room's type.
|
||||
|
||||
| Setting | Default | Command |
|
||||
|---|---|---|
|
||||
| Admin access to all rooms | On | `[p]autoroomset access admin` |
|
||||
| Moderator access to all rooms | Off | `[p]autoroomset access mod` |
|
||||
| Bot roles allowed in all rooms | Empty | `[p]autoroomset access bot add` and `remove` |
|
||||
|
||||
Admin and moderator access uses Red's role definitions, so a server's configured admin and mod roles apply.
|
||||
|
||||
## AutoRoom Source permissions
|
||||
|
||||
The bot needs these on a source:
|
||||
|
||||
- View Channel
|
||||
- Connect
|
||||
- Move Members
|
||||
|
||||
On the destination category it needs:
|
||||
|
||||
- View Channel
|
||||
- Connect
|
||||
- Send Messages
|
||||
- Manage Channels
|
||||
- Manage Messages
|
||||
- Move Members
|
||||
|
||||
`[p]autoroomset permissions` performs the check and reports missing entries.
|
||||
|
||||
## Limits
|
||||
|
||||
- Channel names are capped at 100 characters by the cog, and Discord enforces its own limit.
|
||||
- Owners can rename through the `name` command twice per roughly ten minutes per channel, with a four second allowance for Discord's own rename. The error message suggests renaming the channel directly in Discord instead.
|
||||
- Bitrate is clamped between 8 kbps and the guild's boost dependent limit.
|
||||
- User limit is clamped between 0 and 99, where 0 means no limit.
|
||||
- Room state lives in Discord channels plus config. Deleting a room's channel manually leaves its config entry until the next cleanup, which clears missing channels.
|
||||
|
||||
## Stored data
|
||||
|
||||
Global config under identifier `1224364860` holds `schema_version`.
|
||||
|
||||
Guild config:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `admin_access` | `true` |
|
||||
| `mod_access` | `false` |
|
||||
| `bot_access` | `[]` |
|
||||
|
||||
Custom group `AUTOROOM_SOURCE`, keyed by guild and source channel:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `dest_category_id` | `null` |
|
||||
| `room_type` | `public` |
|
||||
| `legacy_text_channel` | `false` |
|
||||
| `text_channel_hint` | `null` |
|
||||
| `text_channel_topic` | empty |
|
||||
| `channel_name_type` | `username` |
|
||||
| `channel_name_format` | empty |
|
||||
| `perm_owner_manage_channels` | `true` |
|
||||
| `perm_send_messages` | `true` |
|
||||
|
||||
Channel config for each created room:
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `source_channel` | ID of the source that created it |
|
||||
| `owner` | Member ID of the owner, or null |
|
||||
| `associated_text_channel` | ID of the linked text channel, when applicable |
|
||||
| `denied` | Stored deny list |
|
||||
|
||||
`red_delete_data_for_user` does nothing, so deleting a user's data does not remove ownership records from their rooms.
|
||||
|
||||
Next: [AutoRoom Commands](AutoRoom-Commands) and [AutoRoom Templates](AutoRoom-Templates).
|
||||
@@ -0,0 +1,105 @@
|
||||
# AutoRoom Templates
|
||||
|
||||
Room names and text channel hints are rendered with a small Jinja subset implemented in `pcx_template.py`. It supports variable substitution, `if`, `elif`, `else` and `endif`, comparison operators, and two filters.
|
||||
|
||||
## Variables
|
||||
|
||||
| Variable | Available in | Value |
|
||||
|---|---|---|
|
||||
| `username` | Name and hint | The owner's display name |
|
||||
| `game` | Name and hint | The game the owner is playing, or an empty string |
|
||||
| `dupenum` | Name | A counter starting at 1, incremented when a generated name already exists |
|
||||
| `mention` | Hint only | The owner's mention |
|
||||
|
||||
`game` is read at creation time. Starting or stopping a game later does not rename the room.
|
||||
|
||||
`dupenum` is computed by generating the name, checking for an existing channel with that name in the category, and incrementing until the name is free. A template that does not include `dupenum` therefore produces a duplicate name, and Discord allows duplicate channel names, so rooms can share a name.
|
||||
|
||||
## Default templates
|
||||
|
||||
The `username` format:
|
||||
|
||||
```
|
||||
{{username}}'s Room{% if dupenum > 1 %} ({{dupenum}}){% endif %}
|
||||
```
|
||||
|
||||
The `game` format:
|
||||
|
||||
```
|
||||
{{game}}{% if not game %}{{username}}'s Room{% endif %}{% if dupenum > 1 %} ({{dupenum}}){% endif %}
|
||||
```
|
||||
|
||||
Both append the duplicate number only from the second duplicate onward, so the first room has no suffix.
|
||||
|
||||
## Conditionals
|
||||
|
||||
The template engine accepts:
|
||||
|
||||
```
|
||||
{% if game %}...{% elif username %}...{% else %}...{% endif %}
|
||||
```
|
||||
|
||||
Conditions can compare a variable with a literal using `==`, `!=`, `>`, `<`, `>=` and `<=`, or test a variable for truth with `if game` and `if not game`. Undefined variables are treated as empty, so they are falsy.
|
||||
|
||||
Whitespace inside tags is ignored. Tags may appear inline with text.
|
||||
|
||||
## Filters
|
||||
|
||||
```
|
||||
{{username | lower}}
|
||||
{{game | upper}}
|
||||
```
|
||||
|
||||
| Filter | Effect |
|
||||
|---|---|
|
||||
| `lower` | Lowercases the value |
|
||||
| `upper` | Uppercases the value |
|
||||
|
||||
Filters are applied before insertion. Unknown filters raise a template error, which is reported to the administrator and the operation is cancelled.
|
||||
|
||||
## Hint message
|
||||
|
||||
`[p]autoroomset modify text set <template>` sets the message posted in a new room's text channel. It has access to `mention`, `username` and `game`. `[p]autoroomset modify text disable` turns the hint off.
|
||||
|
||||
The hint is posted once when the room is created, not on every join.
|
||||
|
||||
## Legacy text channels
|
||||
|
||||
`[p]autoroomset modify legacytext enable` creates a text channel alongside each room, with the owner allowed to manage it and read its history. `disable` stops creating them.
|
||||
|
||||
`[p]autoroomset modify legacytexttopic set <template>` sets the topic of those channels, using the same variables. `disable` clears the topic setting.
|
||||
|
||||
The modern alternative is Discord's own text chat inside a voice channel. The legacy option exists for servers that still want a separate channel.
|
||||
|
||||
## Length and validation
|
||||
|
||||
- Rendered names are truncated to 100 characters after rendering.
|
||||
- A template error cancels the operation and reports the error.
|
||||
- Empty output is rejected by Discord as an invalid channel name, which surfaces as a failed channel edit.
|
||||
- Templates are validated when saved through `modify name custom`, so a syntax error is reported immediately rather than at creation time.
|
||||
|
||||
## Examples
|
||||
|
||||
Game name with a fallback and a room number:
|
||||
|
||||
```
|
||||
{{game}}{% if not game %}{{username}}'s hangout{% endif %}{% if dupenum > 1 %} #{{dupenum}}{% endif %}
|
||||
```
|
||||
|
||||
Lowercased owner name with a fixed suffix:
|
||||
|
||||
```
|
||||
{{username | lower}} room
|
||||
```
|
||||
|
||||
Role-neutral hint:
|
||||
|
||||
```
|
||||
Welcome {{mention}}. This room belongs to you until everyone leaves.
|
||||
```
|
||||
|
||||
## Implementation notes
|
||||
|
||||
The renderer is a purpose-built parser, not full Jinja2. It does not support loops, macros, includes, arithmetic, filters with arguments, or attribute access. The bundled test file `pcx_template_test.py` covers the supported subset, including nested conditionals, comparisons and the duplicate number.
|
||||
|
||||
An administrator writing a template that uses an unsupported feature sees a template error rather than silent output. Test a new format with `[p]autoroomset modify name custom` and create a room before applying it to a busy source.
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# Cog Catalog
|
||||
|
||||
Summary of every cog in the repository. Line counts are for the Python source, excluding manifests and documentation.
|
||||
|
||||
| Cog | Source size | External dependency | State stored | Permission gate |
|
||||
|---|---|---|---|---|
|
||||
| AlbumOfTheDay | 322 lines | 1001 Albums Generator API over HTTPS | Per guild: API URL, channel, hour, minute, timezone, last posted date | Config commands require Manage Server |
|
||||
| Assistant | 546 lines | OpenAI-compatible chat completions API | Global API key and base URL, per guild model, prompt, temperature and flags, in-memory chat history | Mixed, see the page |
|
||||
| AutoRoom | 3,951 lines including tests | Discord only | Global schema version, guild access flags, per source config, per channel owner and denies | Setup requires Manage Server, room commands need ownership |
|
||||
| Deadman | 261 lines | Discord only | Global armed flag, expiry, users, alert channel | Bot owner |
|
||||
| ImageGrab | 187 lines | Discord CDN | None | Manage Messages |
|
||||
| PlayitStatus | 106 lines | `status.playit.gg` monitor API | Global channel ID, last known status map | Manage Server |
|
||||
| Renamer | 83 lines | Discord only | Unused `allowed_roles` guild key | Administrator |
|
||||
| Transcribe | 529 lines | Whisper and NLLB services | Per guild `show_original` | Manage Server for settings |
|
||||
| TtsToy | 3,761 lines plus engines | MiniMax, Chatterbox, DECTalk, Morshu, Piper | Global, guild and member config, voice files, SFX library | Mostly owner |
|
||||
| YTAudio | 759 lines | Lavalink and yt-dlp | Per guild volume, cache directories | No checks |
|
||||
|
||||
## Grouping by what they need
|
||||
|
||||
Cogs that work with Discord alone: AutoRoom, Deadman, ImageGrab, Renamer.
|
||||
|
||||
Cogs that need a local HTTP service: Transcribe, TtsToy, YTAudio.
|
||||
|
||||
Cogs that need a third-party API: AlbumOfTheDay, Assistant (unless pointed at a local model), PlayitStatus.
|
||||
|
||||
TtsToy is the only cog that needs another cog loaded, because it borrows the Lavalink client owned by YTAudio.
|
||||
|
||||
## Grouping by risk
|
||||
|
||||
Commands with no permission check, usable by any member: most of Assistant, all of YTAudio, `aotd now`, `[p]tts`, `[p]disconnect`.
|
||||
|
||||
Commands that modify other members: Renamer (administrator only), AutoRoom deny (room owner), Assistant `toggle` and `channel` (any member can change the server chat channel).
|
||||
|
||||
Commands that spend money: Assistant and TtsToy MiniMax mode, both of which call paid APIs.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Data and Privacy
|
||||
|
||||
This page lists the data each cog writes to Red's configuration store and the data it sends off the machine. Config identifiers are included so an administrator can find and reset a cog's data.
|
||||
|
||||
## Storage summary
|
||||
|
||||
| Cog | Config identifier | Scope | Keys |
|
||||
|---|---|---|---|
|
||||
| AlbumOfTheDay | `0xA1B00FDA` | Guild | `api_url`, `channel_id`, `post_hour`, `post_minute`, `timezone`, `last_posted` |
|
||||
| Assistant | `987654321` | Global and guild | Global `api_key`, `base_url`. Guild `enabled`, `chat_channel`, `model`, `vision_model`, `temperature`, `system_prompt`, `question_mode`, `max_tokens`, `reasoning_effort` |
|
||||
| AutoRoom | `1224364860` | Global, guild, custom `AUTOROOM_SOURCE`, channel | See the AutoRoom page |
|
||||
| Deadman | `918273645` | Global | `armed`, `expires_at`, `users`, `trigger_channel` |
|
||||
| ImageGrab | none | None | Nothing is stored |
|
||||
| PlayitStatus | `1234567890` | Global | `channel_id`, `last_status` |
|
||||
| Renamer | `182736451` | Guild | `allowed_roles`, registered but never read |
|
||||
| Transcribe | `481516234` | Guild | `show_original` |
|
||||
| TtsToy | `0x0A0A0A0A` | Global, guild, member, user | See the TtsToy page |
|
||||
| YTAudio | `0x5954415544494F` | Guild | `volume` |
|
||||
|
||||
## Message content
|
||||
|
||||
- Assistant sends message text to the configured chat completions backend. With a remote backend this leaves the machine. With the default local Ollama URL it stays on the host. Chat history is held in a Python dict and is lost on reload. It is never written to disk.
|
||||
- Transcribe sends downloaded audio to the local Whisper service and the transcript to the local NLLB service. Neither is a remote API.
|
||||
- TtsToy sends text to the selected engine. MiniMax is a remote API and receives the text. Chatterbox, DECTalk, Piper, Morshu and VOX are local.
|
||||
- ImageGrab downloads attachments from Discord's CDN and uploads zip files back to Discord. Nothing is written to disk.
|
||||
- AlbumOfTheDay polls a public group API and posts the result. No user data is involved.
|
||||
|
||||
## Files on disk
|
||||
|
||||
- YTAudio writes to `<cog data>/mp3cache` and `<cog data>/streams`. Both directories are deleted and recreated when the cog unloads. Individual stream and mp3 files are removed when a track finishes or is skipped.
|
||||
- TtsToy writes generated audio to `<cog data>/ttstoy`. A one hour loop deletes the whole directory. Chatterbox reference clips live in the Chatterbox server's data directory, not in the cog's.
|
||||
- TtsToy reads and writes a shared JSON file at `/tmp/ttstoy_webui_state.json` by default, overridable with `TTSTOY_SHARED_STATE`. The file holds a login secret, the web UI URL, user profile fields, and queued commands from the web UI. It is not encrypted, and default file permissions may allow other local users to read it.
|
||||
|
||||
## Data deletion
|
||||
|
||||
`red_delete_data_for_user` is implemented as a no-op in Deadman, AutoRoom, PlayitStatus and TtsToy. Deleting a user's data through Red's data deletion commands does not remove:
|
||||
|
||||
- Assistant chat history for that user's channels. It is in memory only and disappears on reload.
|
||||
- TtsToy uploaded voice filenames in user config and their files on the Chatterbox server.
|
||||
- AutoRoom channels a user created, or the owner field on them.
|
||||
- Deadman user IDs while the switch is armed.
|
||||
|
||||
An operator handling a deletion request must clear these manually with `[p]set api` style config commands or by removing the relevant config keys.
|
||||
|
||||
## Credentials
|
||||
|
||||
- Assistant stores the API key in plain text in Red's global config.
|
||||
- TtsToy stores the MiniMax key in plain text in global config.
|
||||
- YTAudio has the Lavalink password compiled into the source.
|
||||
- TtsToy web UI login requires an internal secret read from the shared state file.
|
||||
|
||||
Red's config files are readable by the account running the bot. Protect that account and its data directory accordingly.
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
# Deadman
|
||||
|
||||
A switch that alerts nominated users if the bot owner does not disable it before a deadline. The intended use is a solo operator who wants someone to be told if they stop responding.
|
||||
|
||||
## Requirements
|
||||
|
||||
None beyond Red. The cog uses Red's global configuration store and does not need any Python package outside the standard library and discord.py.
|
||||
|
||||
## Commands
|
||||
|
||||
All commands are in the `deadman` group and the group requires the bot owner. The check is on the group, so every subcommand inherits it.
|
||||
|
||||
| Command | Arguments | Behavior |
|
||||
|---|---|---|
|
||||
| `[p]deadman arm` | `<duration> <users...> [channel]` | Arms the switch, sets the deadline, and DMs each listed user |
|
||||
| `[p]deadman disable` | none | Clears the armed state, deadline, users and alert channel |
|
||||
| `[p]deadman status` | none | Shows armed state, deadline, remaining time and the user list |
|
||||
|
||||
### arm
|
||||
|
||||
```
|
||||
[p]deadman arm 6h @Alice @Bob #alerts
|
||||
```
|
||||
|
||||
- `duration` is required and parsed by the flexible parser described below.
|
||||
- At least one user is required. Without one the bot replies "You must provide at least one user to alert."
|
||||
- `users` uses `commands.Greedy`, so it consumes mentions until it reaches something that is not a user. The optional channel must therefore be a channel mention or ID that Discord resolves as a channel, placed after the users.
|
||||
- Each listed user receives a direct message describing the deadline and telling them to contact the bot owner if this was a mistake.
|
||||
- The confirmation message reports the deadline in UTC, the relative duration, the mentioned users, the alert channel if one was given, how many direct messages succeeded, and which users could not be reached.
|
||||
|
||||
Direct message failures do not stop arming. A user with closed direct messages still appears in the stored list and still gets mentioned in the alert channel.
|
||||
|
||||
### disable
|
||||
|
||||
Does nothing except reply "The deadman switch is not currently armed." when the switch is already off. When armed, it resets all four config keys and clears the in-memory trigger flag.
|
||||
|
||||
### status
|
||||
|
||||
When disarmed, replies that the switch is disarmed. When armed, shows the expiry in UTC, the remaining time as a `timedelta` string, and the stored user mentions. A negative remaining time means the deadline passed and the alert has already fired.
|
||||
|
||||
## Duration format
|
||||
|
||||
The parser lowercases the input and reads digits followed by a unit, repeating for each component.
|
||||
|
||||
| Unit accepted | Meaning |
|
||||
|---|---|
|
||||
| `s`, `sec`, `secs`, `second`, `seconds` | seconds |
|
||||
| `m`, `min`, `mins`, `minute`, `minutes` | minutes |
|
||||
| `h`, `hr`, `hrs`, `hour`, `hours` | hours |
|
||||
| `d`, `day`, `days` | days |
|
||||
| `w`, `week`, `weeks` | weeks |
|
||||
|
||||
Examples that parse: `30s`, `6h`, `2h30m`, `90s`, `1d`, `1d12h`, `1w2d3h4m5s`.
|
||||
|
||||
Examples that fail: `5m30` (trailing digits with no unit), `6 hours from now` (text after a unit that is not a unit), `0s` (zero total), `-5m` (a minus is read as a unit character before any digits, so parsing stops).
|
||||
|
||||
A failed parse replies with the example list and does not arm.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `arm` computes `datetime.utcnow() + duration` and stores it as a naive ISO string. The armed flag, user IDs and channel ID are stored in global config, so the switch survives restarts.
|
||||
2. `cog_load` starts `_monitor`, an asyncio task that sleeps 30 seconds between checks and swallows every exception to keep running.
|
||||
3. `_check_expiry` returns immediately when the switch is not armed or has no deadline. Otherwise it compares the current UTC time with the stored deadline.
|
||||
4. On expiry, `_trigger` runs once per process. It resolves each stored user ID with the cache first and `fetch_user` as a fallback, sends each user a direct message, then posts to the alert channel if one is configured.
|
||||
5. The alert channel message mentions only users the bot can resolve from its cache, because the mention string skips IDs where `bot.get_user` returns nothing.
|
||||
6. `_triggered` stays true until `disable` runs or the process restarts. The switch also stays armed, so `status` continues to show an expired deadline.
|
||||
|
||||
## Delivery behavior
|
||||
|
||||
- Direct messages are sent one at a time. `discord.Forbidden` and any other exception are swallowed, so a blocked user is silently skipped.
|
||||
- The channel post is skipped entirely when no channel was configured. When the channel was deleted or is no longer visible, the send raises and is swallowed.
|
||||
- The alert text is fixed: a heading, one sentence stating the switch triggered, and a request to contact the operator.
|
||||
|
||||
## Limits and failure modes
|
||||
|
||||
- The 30 second loop means an alert can arrive up to about 30 seconds after the deadline.
|
||||
- Trigger state is in memory. If the bot restarts after the deadline but before `disable`, the alert fires again, because the stored state is still armed and expired.
|
||||
- There is no catch-up logic for downtime. An expired switch triggers as soon as the cog loads and the monitor runs its first check.
|
||||
- User IDs are stored as integers. `red_delete_data_for_user` does nothing, so a deletion request does not remove a user from an armed switch.
|
||||
- The deadline uses naive UTC. Any change to the host clock or timezone does not affect it, but a clock jump forward or backward shifts the effective deadline.
|
||||
|
||||
## Stored data
|
||||
|
||||
Global config under identifier `918273645`:
|
||||
|
||||
| Key | Type | Default |
|
||||
|---|---|---|
|
||||
| `armed` | bool | `false` |
|
||||
| `expires_at` | ISO string or null | `null` |
|
||||
| `users` | list of int | `[]` |
|
||||
| `trigger_channel` | int or null | `null` |
|
||||
|
||||
There is no per-guild configuration. One switch exists for the whole bot.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# Development
|
||||
|
||||
## Layout
|
||||
|
||||
Each cog is a Python package at the repository root:
|
||||
|
||||
```
|
||||
albumoftheday/
|
||||
__init__.py
|
||||
albumoftheday.py
|
||||
info.json
|
||||
assistant/
|
||||
autoroom/
|
||||
__init__.py
|
||||
abc.py
|
||||
autoroom.py
|
||||
c_autoroom.py
|
||||
c_autoroomset.py
|
||||
pcx_lib.py
|
||||
pcx_template.py
|
||||
pcx_template_test.py
|
||||
deadman/
|
||||
imagegrab/
|
||||
playitstatus/
|
||||
renamer/
|
||||
transcribe/
|
||||
ttstoy/
|
||||
__init__.py
|
||||
ttstoy.py
|
||||
morshutalk_engine.py
|
||||
vox_engine.py
|
||||
sfx/
|
||||
dectalk-server/
|
||||
vox-server/
|
||||
morshu-server/
|
||||
ytaudio/
|
||||
```
|
||||
|
||||
Every `__init__.py` reads `info.json` for `__red_end_user_data_statement__` and exposes `async def setup(bot)`. YTAudio and AutoRoom do extra work in setup: YTAudio starts the Lavalink connect task, and AutoRoom awaits `initialize()` so config migrations run before the cog accepts commands.
|
||||
|
||||
## Manifest fields
|
||||
|
||||
`info.json` holds `author`, `description`, `install_msg`, `short`, `end_user_data_statement`, `requirements`, and optionally `hidden` and `disabled`. Red reads `requirements` at install time. A package missing from `requirements` fails at runtime when the cog is first used.
|
||||
|
||||
## Command conventions
|
||||
|
||||
- Groups use `invoke_without_command` when running the bare group should print a summary rather than an error.
|
||||
- Settings commands use `@checks.admin_or_permissions(manage_guild=True)` or `@commands.is_owner()`. Assistant and YTAudio are the exceptions with mostly ungated commands.
|
||||
- Cooldowns and concurrency limits are applied with `@commands.cooldown` and `@commands.max_concurrency`. Transcribe uses a per-user cooldown and a single global concurrency slot.
|
||||
- Long responses are chunked to fit Discord's 2000 character limit rather than truncated mid-message.
|
||||
|
||||
## Config identifiers
|
||||
|
||||
Identifiers are stable and must not change without a migration, or every guild loses its settings.
|
||||
|
||||
| Cog | Identifier |
|
||||
|---|---|
|
||||
| AlbumOfTheDay | `0xA1B00FDA` |
|
||||
| Assistant | `987654321` |
|
||||
| AutoRoom | `1224364860` |
|
||||
| Deadman | `918273645` |
|
||||
| PlayitStatus | `1234567890` |
|
||||
| Renamer | `182736451` |
|
||||
| Transcribe | `481516234` |
|
||||
| TtsToy | `0x0A0A0A0A` |
|
||||
| YTAudio | `0x5954415544494F` |
|
||||
|
||||
AutoRoom also uses schema migrations keyed on `schema_version` in global config. The current schema has removed the guild level `member_role`. Member roles are now derived from which roles can connect to the AutoRoom Source.
|
||||
|
||||
## Tests
|
||||
|
||||
`autoroom/pcx_template_test.py` is the only test file in the repository. It covers the Jinja subset implemented in `pcx_template.py`, including conditionals, filters and duplicate handling. Run it with:
|
||||
|
||||
```
|
||||
python -m unittest autoroom.pcx_template_test
|
||||
```
|
||||
|
||||
No cog has integration tests, and nothing tests Red command behavior, config migrations or the HTTP clients.
|
||||
|
||||
## Known defects in the current code
|
||||
|
||||
These are documented so the wiki matches the code. They are not fixed here.
|
||||
|
||||
- PlayitStatus has no background task. The manifest and older README describe a ten second poller and automatic alerts. Only `[p]playit status` checks the API, and it only posts when a status changed since the last check.
|
||||
- Assistant advertises vision. The message handler replies that images are unsupported, clears the image list, and then continues with text. The multimodal branch in `_chat` cannot be reached.
|
||||
- Assistant gates only `setkey`, `baseurl` and `showprompt`. Any member can change the model, temperature, max tokens, system prompt, question mode, and the server chat channel.
|
||||
- Assistant's `default_search` and pricing table assume a specific provider. The local default model is not in the pricing table, so it sorts last with `pricing unknown`.
|
||||
- Renamer registers `allowed_roles` per guild and never reads it. All three commands are administrator only.
|
||||
- Transcribe `translate` fetches replied messages without declaring the Read Message History check that `transcribe` declares. It works if the message is cached, and silently finds no text if the fetch fails.
|
||||
- Transcribe and Assistant contain literal em dash characters in user-facing strings.
|
||||
- YTAudio has no permission checks. Any member can skip, stop or change the volume of another member's playback, and any member can disconnect the bot.
|
||||
- TtsToy's `ffmpeg` concatenation assumes input files share codec parameters. Mixed engines can produce a file with audible discontinuities.
|
||||
- The TtsToy `[p]ttstoy info` text still mentions a default Chatterbox port of 8004 while the code uses 8099, and lists commands such as `chatterboxurl` that were renamed to `[p]chatterbox url`.
|
||||
- `ttstoy/stack.json` contains filesystem paths and a session secret for a specific deployment. It is not used by the cog.
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
# ImageGrab
|
||||
|
||||
Collects every image in a channel and uploads them as one or more zip files. The naming scheme supports a workflow where message text acts as a tag list for the images attached to that message.
|
||||
|
||||
## Requirements
|
||||
|
||||
- The invoking member needs Manage Messages.
|
||||
- The bot needs Attach Files and Read Message History in the channel it scans and in the channel where it replies.
|
||||
- No configuration and no stored data.
|
||||
|
||||
## Command
|
||||
|
||||
```
|
||||
[p]imagegrab [channel] [limit]
|
||||
```
|
||||
|
||||
| Argument | Meaning |
|
||||
|---|---|
|
||||
| `channel` | Text channel to scan. Defaults to the current channel |
|
||||
| `limit` | Maximum number of messages to scan, counted from the oldest message forward. Omit to scan the entire history |
|
||||
|
||||
The command is not guild only, but Discord resolves the channel argument only inside a guild.
|
||||
|
||||
## What counts as an image
|
||||
|
||||
Attachments whose filename ends with one of `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.bmp`, `.tiff`. The check is on the filename extension, not the content type.
|
||||
|
||||
Embedded images are included when the embed type is `image` and the embed URL, with any query string removed, ends in one of those extensions. Tenor and other services that serve extensionless URLs are skipped.
|
||||
|
||||
Videos, audio and files without those extensions are ignored.
|
||||
|
||||
## Naming rules
|
||||
|
||||
Message text becomes the filename base, which is why the description mentions WebTable card decks and type tags.
|
||||
|
||||
- Characters removed: `<`, `>`, `:`, `"`, `/`, `\`, `|`, `?`, `*`, and the null character.
|
||||
- Runs of whitespace collapse to single spaces.
|
||||
- The base is truncated to 200 characters.
|
||||
- Commas, spaces, hyphens and underscores survive.
|
||||
- One image in a message: `<base><ext>`.
|
||||
- Several images in a message: `<base>_1<ext>`, `<base>_2<ext>`, and so on.
|
||||
- No message text: `<message id><ext>`.
|
||||
|
||||
Two messages with identical text produce identical filenames in the zip. `zipfile` allows duplicate entries; extraction tools may overwrite or rename them.
|
||||
|
||||
Embedded images with no message text also use the message ID, so an embed and an attachment on the same message can collide on extension only if their extensions match.
|
||||
|
||||
## How it works
|
||||
|
||||
1. The bot posts a status message and edits it as work proceeds.
|
||||
2. `channel.history(limit=limit, oldest_first=True)` walks the channel from oldest to newest.
|
||||
3. Every 2000 messages scanned, the status message is edited to show the count and the number of images found so far.
|
||||
4. Image URLs are collected without downloading.
|
||||
5. Each URL is downloaded in sequence through one shared `aiohttp` session. A non-200 response or an exception increments the failure count.
|
||||
6. If every download fails, the status becomes "All image downloads failed." and nothing is sent.
|
||||
7. Downloaded bytes are written into zip archives, cutting a new archive when adding the next file would push the uncompressed byte count past 9 MiB.
|
||||
8. Each archive is uploaded as `<channel>_images.zip`, or `<channel>_images_part1.zip`, `_part2.zip` and so on when there is more than one.
|
||||
|
||||
## Limits and failure modes
|
||||
|
||||
- Everything is held in memory. A channel with thousands of large images can exhaust the bot's memory before the first zip is built.
|
||||
- The 9 MiB cutoff uses raw file sizes, not the compressed archive size, and does not account for zip headers. It leaves headroom under Discord's 10 MiB default upload limit.
|
||||
- A single image larger than 9 MiB goes into its own archive, which can exceed the upload limit and fail at upload time.
|
||||
- There is no per-image size cap and no retry. A transient CDN error counts as a failed download.
|
||||
- The scan is sequential, so a very large channel takes a long time and the status message edits are the only feedback.
|
||||
- History scanning requires the bot to be able to read messages that predate its permissions. Messages it cannot read are simply absent.
|
||||
|
||||
## Output
|
||||
|
||||
The final status message reports how many images were downloaded, the channel name, the number of archives, and the failure count when non-zero. Multi-part uploads also get a caption on each message identifying the part number.
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# Installation
|
||||
|
||||
## Bot requirements
|
||||
|
||||
- Red-DiscordBot 3.5.0 or newer.
|
||||
- Python 3.11 or newer. AutoRoom and Transcribe use syntax and standard library modules that do not exist on older versions.
|
||||
- `ffmpeg` on the PATH. YTAudio calls it for mp3 conversion, TtsToy calls it for volume adjustment, and Chatterbox reference clips are decoded with pydub, which also needs ffmpeg.
|
||||
- A Lavalink node on `localhost:2333` for YTAudio and TtsToy. The connection parameters are hardcoded in `ytaudio/ytaudio.py`.
|
||||
|
||||
## Adding the repository
|
||||
|
||||
```
|
||||
[p]repo add scrapyard http://192.168.0.200:3000/kingston/scrapyard-cogworks.git
|
||||
[p]cog list scrapyard
|
||||
```
|
||||
|
||||
## Installing a cog
|
||||
|
||||
Each cog installs on its own, which lets Red install only that cog's Python requirements.
|
||||
|
||||
```
|
||||
[p]cog install scrapyard transcribe
|
||||
[p]load transcribe
|
||||
```
|
||||
|
||||
Repeat with any of `albumoftheday`, `assistant`, `autoroom`, `deadman`, `imagegrab`, `playitstatus`, `renamer`, `ttstoy`, `ytaudio`.
|
||||
|
||||
## Load order
|
||||
|
||||
YTAudio owns the process-wide Lavalink client. It calls `lavalink.initialize()` when the bot becomes ready and `lavalink.close()` when it unloads. TtsToy only calls `lavalink.get_player()` and relies on that connection.
|
||||
|
||||
Install and load YTAudio before TtsToy so the node is connected when TtsToy first needs to play audio. If a different cog has already connected a node, YTAudio detects it with `lavalink.get_all_nodes()` and shares the connection instead of initializing a second one.
|
||||
|
||||
## Python packages
|
||||
|
||||
Declared in each `info.json`:
|
||||
|
||||
| Cog | Packages |
|
||||
|---|---|
|
||||
| albumoftheday | `aiohttp` |
|
||||
| assistant | `aiohttp` |
|
||||
| autoroom | `func-timeout`, `jinja2` |
|
||||
| deadman | none beyond Red |
|
||||
| imagegrab | `aiohttp` |
|
||||
| playitstatus | `aiohttp` |
|
||||
| renamer | none beyond Red |
|
||||
| transcribe | `aiohttp`, `langdetect` |
|
||||
| ttstoy | `requests`, `pydub`, `g2p_en`, `numpy`, and optionally `pynacl` for voice |
|
||||
| ytaudio | `yt-dlp`, `PyNaCl`, `lavalink` (provided by Red) |
|
||||
|
||||
`aiohttp` and `discord.py` are already present in a Red installation. Red installs `info.json` requirements automatically when the cog is installed, so install each cog rather than copying its directory into `cogs/` by hand.
|
||||
|
||||
## Local services
|
||||
|
||||
Several cogs expect services on fixed ports. [Local Services](Local-Services) lists all of them with their endpoints. A cog that cannot reach its service reports a connection failure and stops; it does not fall back to a different provider.
|
||||
|
||||
The following addresses are compiled into the source and cannot be changed with a command:
|
||||
|
||||
- Transcribe: Whisper at `http://127.0.0.1:8201`, NLLB at `http://127.0.0.1:8200`.
|
||||
- YTAudio: Lavalink at `localhost:2333` with password `youshallnotpass`.
|
||||
- TtsToy: health server binds `0.0.0.0:8097`, DECTalk defaults to `http://127.0.0.1:33001`, Morshu to `http://127.0.0.1:33002`, VOX to port `33003`.
|
||||
|
||||
The following addresses are configurable at runtime: TtsToy Chatterbox and Piper URLs, Assistant base URL, AlbumOfTheDay group URL, and PlayitStatus channel.
|
||||
|
||||
## Minimum setup per cog
|
||||
|
||||
| Cog | Minimum setup |
|
||||
|---|---|
|
||||
| AlbumOfTheDay | `[p]aotd seturl`, `[p]aotd setchannel` |
|
||||
| Assistant | none on a local Ollama backend, otherwise `[p]assistant setkey` and `[p]assistant baseurl` |
|
||||
| AutoRoom | `[p]autoroomset create <source> <category>` |
|
||||
| Deadman | none, arm with `[p]deadman arm` |
|
||||
| ImageGrab | none |
|
||||
| PlayitStatus | `[p]playit channel <channel id>` |
|
||||
| Renamer | none |
|
||||
| Transcribe | Whisper and NLLB servers running |
|
||||
| TtsToy | `[p]ttstoy mode` plus the engine server, or a MiniMax key |
|
||||
| YTAudio | Lavalink running |
|
||||
@@ -0,0 +1,92 @@
|
||||
# Local Services
|
||||
|
||||
Every network endpoint the cogs use, with the exact contract from the source. An address marked fixed is compiled into the code and can only be changed by editing and reloading the cog.
|
||||
|
||||
## Port table
|
||||
|
||||
| Port | Service | Used by | Address source | Protocol |
|
||||
|---|---|---|---|---|
|
||||
| 2333 | Lavalink node | YTAudio, TtsToy | Fixed, `localhost`, password `youshallnotpass` | WebSocket and HTTP |
|
||||
| 5006 | Piper HTTP server | TtsToy | Config `piper_api_url` | HTTP |
|
||||
| 8097 | TtsToy health server | Nothing in the repo | Fixed, binds `0.0.0.0` | HTTP |
|
||||
| 8098 | TtsToy web UI | TtsToy login command | `WEBUI_PORT` environment variable, default 8098 | HTTP |
|
||||
| 8099 | Chatterbox TTS server | TtsToy | Config `chatterbox_api_url` | HTTP |
|
||||
| 8200 | NLLB translation server | Transcribe | Fixed | HTTP |
|
||||
| 8201 | Whisper transcription server | Transcribe | Fixed | HTTP |
|
||||
| 11434 | Ollama, OpenAI-compatible | Assistant | Default base URL, configurable | HTTP |
|
||||
| 33001 | DECTalk server | TtsToy | Config `dectalk_api_url` | HTTP |
|
||||
| 33002 | Morshu server | TtsToy | Fixed | HTTP |
|
||||
| 33003 | VOX service port | TtsToy | Declared but unused by the current renderer | HTTP |
|
||||
|
||||
## Contracts
|
||||
|
||||
### Lavalink on 2333
|
||||
|
||||
YTAudio calls `lavalink.initialize(bot, host="localhost", password="youshallnotpass", port=2333, timeout=30, secured=False)`. It retries five times with two second pauses on timeout and stops for other errors. Playback uses Lavalink's `local` source, which reads a file path rather than a URL, so the node must have the local source enabled and must share a filesystem with the bot process.
|
||||
|
||||
### Whisper on 8201
|
||||
|
||||
`POST /transcribe` as multipart form data:
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| `file` | audio bytes with the original filename and content type |
|
||||
| `task` | `translate` or `transcribe` |
|
||||
| `vad` | always `true` |
|
||||
| `language` | omitted by Transcribe, so the service detects it |
|
||||
|
||||
Response is JSON. Transcribe reads `text`, `language`, and `language_probability`. Translation to English, or a request with no target language, uses `task=translate` and needs no second service.
|
||||
|
||||
### NLLB on 8200
|
||||
|
||||
`POST /translate` with a JSON body:
|
||||
|
||||
```json
|
||||
{"text": "...", "source": "fr", "target": "de"}
|
||||
```
|
||||
|
||||
Response is JSON with a `translation` field. The source and target accept ISO codes and FLORES-200 tags such as `zho_Hans`.
|
||||
|
||||
### Piper on 5006
|
||||
|
||||
TtsToy posts to `/synthesize` with `{"text": "...", "voice": "<model id>"}`. The `voice` key is omitted when no model is configured. The response body is WAV audio, which TtsToy writes to disk and then converts or concatenates.
|
||||
|
||||
The `[p]ttstoy pipervoice` listing calls `GET /voices`, which may return a dict of model ids or a list of objects with `key` or `name`. A model whose `.onnx` exists in the server's data directory can be selected even when it is missing from that listing.
|
||||
|
||||
### Chatterbox on 8099
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|---|---|
|
||||
| `POST /tts` | Synthesis, JSON body with `text`, `voice_mode: predefined`, `predefined_voice_id`, `output_format: wav`, `split_text: false`, plus optional `temperature`, `exaggeration`, `speed_factor` |
|
||||
| `POST /upload_predefined_voice` | Multipart `files` upload, returns `uploaded_files` and `errors` |
|
||||
| `DELETE /delete_predefined_voice/<filename>` | Remove a reference clip |
|
||||
| `GET /api/ui/initial-data` | Reachability check used by `[p]chatterbox url` and `[p]tts` |
|
||||
| `GET /openapi.json` | Route check that confirms `/tts` exists |
|
||||
| `GET /api/model-info` | Current model name, class and load state |
|
||||
| `POST /save_settings` | Set `model.repo_id` |
|
||||
| `POST /restart_server` | Hot swap the model |
|
||||
|
||||
### DECTalk on 33001
|
||||
|
||||
TtsToy posts the same payload shape it uses for MiniMax to `/v1/t2a_v2`, with a hex encoded audio field in the response. `GET /health` is used for the reachability check in `[p]tts` and `[p]ttstoy dectalkurl`.
|
||||
|
||||
### Morshu on 33002
|
||||
|
||||
`GET /say?text=...` returns MP3 bytes. When the service is unreachable, TtsToy falls back to the in-process `Morshu` engine, which requires `g2p_en`, `numpy` and `pydub`.
|
||||
|
||||
### Ollama and other OpenAI-compatible backends
|
||||
|
||||
`POST <base_url>/chat/completions` with `model`, `messages`, `temperature`, and optionally `max_tokens` and `reasoning_effort`. `GET <base_url>/models` powers `[p]assistant models`. A base URL containing `127.0.0.1` or `localhost` is treated as keyless.
|
||||
|
||||
## Health server on 8097
|
||||
|
||||
TtsToy starts a threaded `HTTPServer` bound to `0.0.0.0:8097` when the cog loads. It answers `GET /health` with `{"status": "ok", "service": "ttstoy"}` and returns 404 for every other path. It sends `Access-Control-Allow-Origin: *`. Nothing in the bot uses it; it exists for external monitoring.
|
||||
|
||||
## External APIs
|
||||
|
||||
| Service | Cog | Notes |
|
||||
|---|---|---|
|
||||
| `https://1001albumsgenerator.com/api/v1/groups/<slug>` | AlbumOfTheDay | 15 second timeout, HTTPS required by the seturl command |
|
||||
| `https://status.playit.gg/api/getMonitorList/AxwIw5PSiW` | PlayitStatus | Fixed monitor list ID |
|
||||
| `https://api.minimax.io/v1/t2a_v2` | TtsToy | Requires an API key |
|
||||
| Discord CDN | ImageGrab, Transcribe, Assistant | Attachment downloads |
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
# PlayitStatus
|
||||
|
||||
Checks the status of a playit.gg tunnel via the public status page and posts changes to a Discord channel.
|
||||
|
||||
This cog does not run a background monitor. The manifest and older documentation describe polling every ten seconds and alerting when the tunnel goes down. The code contains no loop. Status is fetched only when a command runs. Read the "Actual behavior" section before relying on it for outage alerts.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Manage Server or a Red admin role for every command, applied on the group.
|
||||
- The bot must be able to send messages and embed links in the target channel.
|
||||
- The channel must be visible to the bot when the command runs, because the channel is resolved from the cache with `bot.get_channel`.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Arguments | Behavior |
|
||||
|---|---|---|
|
||||
| `[p]playit channel` | `<channel_id>` | Saves the alert channel and posts the current state |
|
||||
| `[p]playit status` | none | Fetches the API and posts only changed states |
|
||||
|
||||
### channel
|
||||
|
||||
```
|
||||
[p]playit channel 123456789012345678
|
||||
```
|
||||
|
||||
Takes a numeric channel ID. A mention is not accepted. The ID must resolve from the bot's channel cache, which normally requires the bot to be in the guild and the channel to be a text channel it can see.
|
||||
|
||||
The command saves the ID, fetches the monitor list, and posts status for any monitor that is not up. It then confirms with "Monitoring set to {channel}. Status posted." even when the post contained nothing. If the fetch fails, the channel is still saved and the reply says the status fetch failed.
|
||||
|
||||
### status
|
||||
|
||||
```
|
||||
[p]playit status
|
||||
```
|
||||
|
||||
Requires a configured channel. Fetches the monitor list, compares each monitor with the last stored state, and posts an embed for each monitor that changed. The reply is "No changes. All services stable." when nothing changed. This command posts to the configured channel, not necessarily the channel where it was invoked.
|
||||
|
||||
## Actual behavior of the status check
|
||||
|
||||
The API URL is fixed:
|
||||
|
||||
```
|
||||
https://status.playit.gg/api/getMonitorList/AxwIw5PSiW
|
||||
```
|
||||
|
||||
It returns a JSON object with a `data` list. Each monitor has a `name` and a `statusClass`. A monitor counts as up when `statusClass` equals `success`; every other value counts as down.
|
||||
|
||||
The stored state is a map of monitor name to boolean. A monitor missing from the map is treated as previously up, so a monitor that is already down when first checked produces a DOWN alert.
|
||||
|
||||
For each monitor:
|
||||
|
||||
- Up now and up before: skipped.
|
||||
- Down now and up before: red embed titled "playit.gg DOWN" with a description naming the monitor.
|
||||
- Up now and down before: green embed titled "playit.gg UP".
|
||||
- Down now and down before: skipped.
|
||||
|
||||
The `channel` command calls the same routine with `changed_only=False`. That flag only skips unchanged monitors when it is true, and unchanged means both states are up. A monitor that stays down is skipped in both modes because the up/down comparison produces no embed and the loop continues.
|
||||
|
||||
## Limitations
|
||||
|
||||
- No scheduled checks. Automatic outage alerts do not happen. The only way to get a fresh alert is to run `[p]playit status` on a schedule from outside the bot, for example a cron job driving a webhook that triggers the command, or by adding a `tasks.loop` to the source.
|
||||
- The `aiohttp` session created by `init_session` is never closed. There is no `cog_unload`, so a reload leaks the session until the process ends.
|
||||
- API failures are swallowed. `fetch_status` returns an empty list for every exception and for any non-200 response, and the command reports a generic fetch failure.
|
||||
- Monitor names are used as dictionary keys, so two monitors with the same name share one state.
|
||||
- Embeds use naive UTC timestamps, which Discord interprets as UTC.
|
||||
- The monitor list ID is tied to one playit.gg account. A different account needs a different list ID, which requires editing the source.
|
||||
|
||||
## Stored data
|
||||
|
||||
Global config under identifier `1234567890`:
|
||||
|
||||
| Key | Type | Default |
|
||||
|---|---|---|
|
||||
| `channel_id` | int or null | `null` |
|
||||
| `last_status` | map of string to bool | `{}` |
|
||||
|
||||
`red_delete_data_for_user` does nothing. There is no per-guild configuration, so one channel serves the whole bot.
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Renamer
|
||||
|
||||
Administrator nickname tools. Three commands change one member, a list of members, or every member holding a role.
|
||||
|
||||
## Requirements
|
||||
|
||||
The bot needs Manage Nicknames and a role positioned above the members it renames. Discord refuses nickname changes for the server owner and for members whose highest role is at or above the bot's highest role.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Arguments | Permission |
|
||||
|---|---|---|
|
||||
| `[p]renamer rename` | `<member> [nickname]` | Administrator |
|
||||
| `[p]renamer bulkrename` | `<members...> <nickname>` | Administrator |
|
||||
| `[p]renamer massrename` | `<role> <nickname>` | Administrator |
|
||||
|
||||
All three are guild only. The check is `admin_or_permissions(administrator=True)`, which passes for members with the Administrator permission and for Red's admin roles.
|
||||
|
||||
### rename
|
||||
|
||||
```
|
||||
[p]renamer rename @Alice Alice
|
||||
[p]renamer rename @Alice
|
||||
```
|
||||
|
||||
The nickname argument is optional and keyword only. Leaving it out clears the nickname, and the confirmation says the nickname was cleared. The audit log reason is `Renamed by <author>`.
|
||||
|
||||
### bulkrename
|
||||
|
||||
```
|
||||
[p]renamer bulkrename @Alice @Bob @Carol Team
|
||||
```
|
||||
|
||||
`members` uses `Greedy`, so the final word is taken as the nickname. At least one member is required. Every member is set to the same nickname in sequence. The reply reports how many succeeded and how many failed, without naming the failures.
|
||||
|
||||
### massrename
|
||||
|
||||
```
|
||||
[p]renamer massrename @Team Team
|
||||
```
|
||||
|
||||
Iterates `role.members`, which comes from the local member cache, so very large guilds may include a partial list until the cache is complete. The reply includes the role mention and the same success and failure counts.
|
||||
|
||||
## Error handling
|
||||
|
||||
`rename` reports specific failures: a permission error produces "I don't have permission to rename that member." and an HTTP error includes the exception text.
|
||||
|
||||
`bulkrename` and `massrename` count `discord.Forbidden` and `discord.HTTPException` as failures and continue through the list. They do not report which members failed or why.
|
||||
|
||||
## How it works
|
||||
|
||||
Each command calls `member.edit(nick=..., reason=...)`. Discord applies its own rate limits; the cog does not pace requests, so a mass rename of a large role proceeds as fast as the API accepts and may hit the global rate limit, which appears as an HTTP failure in the count.
|
||||
|
||||
No hostname or moderator role hierarchy precheck is performed. A command can partially succeed.
|
||||
|
||||
## Limits
|
||||
|
||||
- Nickname length is enforced by Discord, which rejects values over 32 characters. The cog passes the value through and reports the HTTP error.
|
||||
- `bulkrename` and `massrename` accept one nickname for everyone, so the result is a set of identical display names.
|
||||
- There is no undo. The audit log records each change with the reason string.
|
||||
|
||||
## Stored data
|
||||
|
||||
Guild config under identifier `182736451` contains `allowed_roles`, an empty list by default. No command reads or writes it. It appears to be a leftover from an earlier permission model and has no effect on behavior.
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
# Transcribe
|
||||
|
||||
Speech to text for voice messages, with optional translation into another language. Audio is sent to a local Whisper service; translation either uses Whisper's own translate task or a local NLLB service.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Whisper HTTP service on `127.0.0.1:8201`, accepting multipart uploads at `/transcribe`.
|
||||
- An NLLB HTTP service on `127.0.0.1:8200`, accepting JSON at `/translate`, for any target other than English.
|
||||
- The `langdetect` package for automatic source detection when translating text.
|
||||
- Read Message History permission for the bot, required by the `transcribe` command.
|
||||
|
||||
Both service addresses are compiled into `transcribe/transcribe.py`. Changing hosts means editing `WHISPER_URL` or `NLLB_URL` and reloading the cog.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Aliases | Arguments | Cooldown | Concurrency |
|
||||
|---|---|---|---|---|
|
||||
| `[p]transcribe` | `stt` | `[language]` | 2 per 60 seconds per user | 1 across the bot, queued |
|
||||
| `[p]translate` | none | `<language> [text or from <source>]` | 4 per 60 seconds per user | 1 across the bot, queued |
|
||||
| `[p]transcribeset` | `sttset` | none | none | none |
|
||||
| `[p]transcribeset showoriginal` | none | `<true or false>` | none | none |
|
||||
|
||||
All commands are guild only. The settings group requires Manage Server or a Red admin role.
|
||||
|
||||
The single global concurrency slot means one transcription or translation runs at a time across every guild, and later requests wait in Red's queue rather than failing.
|
||||
|
||||
## Finding the audio
|
||||
|
||||
`[p]transcribe` looks in exactly three places, in order:
|
||||
|
||||
1. The message it is replying to.
|
||||
2. The invoking message's own attachments.
|
||||
3. The single message posted immediately before it.
|
||||
|
||||
It does not scan further back. This is intentional: an earlier version scanned 25 messages and would silently transcribe an unrelated older clip when the new message did not match the extension list.
|
||||
|
||||
A message qualifies when any attachment has a content type starting with `audio/` or `video/`, or a filename ending in one of:
|
||||
|
||||
```
|
||||
.ogg .opus .wav .mp3 .m4a .flac .aac .wma
|
||||
.mp4 .mov .m4v .mkv .webm .avi .mpeg .mpg
|
||||
```
|
||||
|
||||
Video containers are accepted because Whisper extracts the audio track, and members send videos expecting them to be transcribed.
|
||||
|
||||
When no media is found, the reply explains the three places it checked.
|
||||
|
||||
Each reply also includes a small-print note naming the author of the transcribed message and linking to it, so a wrong pick is visible.
|
||||
|
||||
## Transcription paths
|
||||
|
||||
### No target language, or English
|
||||
|
||||
`[p]transcribe` and `[p]transcribe english` send `task=translate` to Whisper. One model pass produces English text directly, and NLLB is not used. This path never reports a source language or a confidence value.
|
||||
|
||||
### Any other target language
|
||||
|
||||
1. The audio is sent with `task=transcribe`, so Whisper returns text, the detected language, and `language_probability`.
|
||||
2. If the detected language equals the target, the bot says the text is already in that language and posts the transcript.
|
||||
3. If the confidence is below 0.5, the bot refuses to translate, states the detected language and confidence, and posts the transcript instead. Translating from a guessed language produces fluent nonsense, so this is a hard stop.
|
||||
4. Otherwise the text is sent to NLLB with the detected language as source and the resolved target.
|
||||
|
||||
The result header names both languages in the form `Source to Target`. When the guild setting `show_original` is on, which is the default, the original transcript is appended in small print. The setting applies only to `transcribe`; `translate` never shows the source.
|
||||
|
||||
Replies are clipped near 1900 characters, with the note that the text was cut off.
|
||||
|
||||
## Progress and errors
|
||||
|
||||
The command holds a typing indicator for the whole operation. Service errors are prefixed with a warning symbol and include the specific cause:
|
||||
|
||||
| Message | Cause |
|
||||
|---|---|
|
||||
| "That audio is N MB, over the 20 MB limit." | Attachment size above 20 MiB |
|
||||
| "Could not download the audio (HTTP N)." | Discord CDN refused the download |
|
||||
| "The transcription service is not reachable on port 8201." | Connection refused |
|
||||
| "The transcription service timed out." | No response within 300 seconds |
|
||||
| "The translation service is not reachable on port 8200." | NLLB down |
|
||||
| "The translation service timed out." | NLLB slow |
|
||||
| "No speech detected in that message." | Whisper returned empty text |
|
||||
| "That audio file is empty." | Zero byte download |
|
||||
| "Something went wrong while transcribing that audio." | Any other exception, logged with a traceback |
|
||||
|
||||
Requests use a 300 second total timeout. Malformed JSON from a service is not caught specifically and falls into the generic message, because only connection and timeout errors are mapped.
|
||||
|
||||
## Text translation
|
||||
|
||||
`[p]translate <language>` translates a replied message or text typed after the language.
|
||||
|
||||
- A replied message's text is assembled from its content, embed titles, descriptions, footers and field values.
|
||||
- Text typed after the target is used when there is no reply, or when the reply has no readable text.
|
||||
- Adding `from <language>` at the start of the typed text states the source and skips detection. This form works with a reply too when the text is included.
|
||||
- Input is truncated to 8000 characters with a note in the reply.
|
||||
|
||||
Automatic detection uses `langdetect` with a fixed seed for repeatable results. It refuses in three cases:
|
||||
|
||||
- Input shorter than 12 characters, because short strings produce confident nonsense such as "ok" reading as Slovak.
|
||||
- Top guess below 0.70 probability.
|
||||
- Top guess within 15 points of the runner up.
|
||||
|
||||
Every refusal names the `from <language>` form as the fix.
|
||||
|
||||
If the detected or stated source equals the target, the bot reports there is nothing to do. If NLLB returns text identical to the input, the bot says it already reads as the target. A reply longer than 1800 characters is clipped.
|
||||
|
||||
`translate` does not declare the Read Message History check that `transcribe` declares. When the replied message is cached it works normally; when it is not cached and the fetch is forbidden, the fetch returns nothing and the command falls back to typed text.
|
||||
|
||||
## Language input
|
||||
|
||||
`_resolve_language` accepts several forms, checked in this order:
|
||||
|
||||
1. An English language name, case-insensitive, with underscores treated as spaces. Examples: `french`, `brazilian portuguese` is not present, `haitian creole` is. Over 90 names are mapped.
|
||||
2. A script variant, matched against the raw lowercased input: `zh-hant`, `zh-tw`, `zh-hk`, `traditional chinese`, `zh-hans`, `zh-cn`, `zh-sg`, `simplified chinese`, `cantonese traditional`.
|
||||
3. A FLORES-200 tag matching `aaa_Aaaa`, such as `zho_Hans`, passed straight through.
|
||||
4. An ISO code, taking the part before the first hyphen, such as `pt-BR` becoming `pt`, accepted when the code has a display label.
|
||||
|
||||
Anything else produces a message listing the accepted forms.
|
||||
|
||||
Unknown languages are rejected before any media is downloaded, so a typo costs nothing.
|
||||
|
||||
## Detection refinements
|
||||
|
||||
`langdetect` returns codes such as `zh-cn`. These are mapped to FLORES tags for Chinese so the translation service picks the right script. Other codes pass through unchanged.
|
||||
|
||||
The confidence threshold of 0.5 applies to Whisper's detection, not to `langdetect`. The two tools have separate thresholds in separate paths.
|
||||
|
||||
## Settings
|
||||
|
||||
`[p]transcribeset` with no subcommand prints whether the original transcript is shown. `[p]transcribeset showoriginal <value>` sets it. The value is parsed by Red's boolean converter, so `true`, `yes`, `on` and `1` work.
|
||||
|
||||
The setting affects only the `transcribe` command's non-English path. It has no effect on the English path, which has no source text to show, or on `translate`.
|
||||
|
||||
## Limits
|
||||
|
||||
| Limit | Value |
|
||||
|---|---|
|
||||
| Attachment size | 20 MiB |
|
||||
| HTTP timeout | 300 seconds |
|
||||
| Text translation input | 8000 characters |
|
||||
| Language confidence for translation | 0.5 from Whisper |
|
||||
| Text detection confidence | 0.70, and a 15 point lead |
|
||||
| Minimum text for detection | 12 characters |
|
||||
| Reply length | 1700 to 1900 characters depending on the branch |
|
||||
| User cooldown, transcribe | 2 per 60 seconds |
|
||||
| User cooldown, translate | 4 per 60 seconds |
|
||||
| Global concurrency | 1 |
|
||||
|
||||
## Stored data
|
||||
|
||||
Guild config under identifier `481516234`:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `show_original` | `true` |
|
||||
|
||||
Audio is downloaded into memory, forwarded to Whisper, and discarded. Nothing is written to disk. The transcript is sent to the local NLLB service when a non-English target is requested.
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
# Troubleshooting
|
||||
|
||||
Find the message or symptom, then follow the cause. Values in quotes are the strings the bot sends.
|
||||
|
||||
## "I don't see audio or video here"
|
||||
|
||||
Transcribe found no media. It checks three places in order: the message being replied to, the invoking message's own attachments, and exactly one message back in the channel. Anything older is ignored. Reply directly to the voice message, or attach the file to the command.
|
||||
|
||||
## "The transcription service is not reachable on port 8201"
|
||||
|
||||
Nothing is listening on `127.0.0.1:8201`, or it refused the connection. Check the Whisper service, confirm it binds loopback, and confirm the bot runs on the same host. The address is compiled into `transcribe/transcribe.py`.
|
||||
|
||||
## "The translation service is not reachable on port 8200"
|
||||
|
||||
Same check for NLLB. Note that `[p]transcribe` with no language and `[p]transcribe english` never call NLLB, so a failure there means the request named another target.
|
||||
|
||||
## "I only detected X (N percent confident)"
|
||||
|
||||
Whisper's language probability was below 0.5. The transcript is shown and translation is refused. This is deliberate: translating from a guessed language produces fluent nonsense. Speak more clearly, send a longer clip, or accept the transcript.
|
||||
|
||||
## "That's too short to identify the language reliably"
|
||||
|
||||
Text translation through NLLB requires at least 12 characters for detection. State the source explicitly with `[p]translate <target> from <source>`.
|
||||
|
||||
## "I'm not confident that's X (N percent)"
|
||||
|
||||
`langdetect` returned a top guess below 70 percent, or within 15 points of the runner up. Use the `from <language>` form.
|
||||
|
||||
## "Images not supported at this time"
|
||||
|
||||
Assistant rejects every image, including images in a replied message. This is current behavior, not a configuration problem.
|
||||
|
||||
## Assistant never replies
|
||||
|
||||
Check, in order: the guild has the assistant enabled (`[p]assistant settings`), the message is either in the configured chat channel or mentions the bot, the base URL is reachable, and a key is set when the base URL is not local. A remote URL without a key causes the listener to return silently. Question mode also requires a trailing question mark.
|
||||
|
||||
## "API error 401" or "API error 404" from Assistant
|
||||
|
||||
401 means the key is wrong or missing for a remote backend. 404 usually means the base URL is wrong; it must include the version segment, for example `http://127.0.0.1:11434/v1`.
|
||||
|
||||
## AlbumOfTheDay does not post
|
||||
|
||||
The scheduler runs once a minute and posts only when the guild's local hour and minute match exactly, and only once per local date. Check `[p]aotd settings` for the channel, the time and the last posted date. A missing channel or a bad timezone is logged and skipped. The bot must be online at that minute; there is no catch-up post.
|
||||
|
||||
## "API returned status 404" from AlbumOfTheDay
|
||||
|
||||
The group URL is wrong. It must be the API form with `/api/v1` inserted before `/groups`, and it must start with `https://`.
|
||||
|
||||
## "Channel not found" from PlayitStatus
|
||||
|
||||
`[p]playit channel` takes a numeric channel ID, not a mention. Use Developer Mode to copy the ID. The bot must already be in that guild when the command runs.
|
||||
|
||||
## PlayitStatus never alerts on its own
|
||||
|
||||
There is no background monitor. Alerts are produced only when `[p]playit status` runs and a monitor's state differs from the stored state. Schedule an external task if automatic checks are needed.
|
||||
|
||||
## "Lavalink is not connected yet. Try again in a moment."
|
||||
|
||||
YTAudio connects in the background after Red is ready, with up to five retries two seconds apart. Wait a few seconds. If it persists, check that the node is listening on 2333, that the password matches `youshallnotpass`, and that the bot can read and write the directories used for the growing stream files.
|
||||
|
||||
## YTAudio plays nothing but reports "Now playing"
|
||||
|
||||
Lavalink must be able to open the file path written by the bot. If Lavalink runs in a container or on another host, the path does not exist for the node and loading fails silently from the user's perspective. Keep the node on the same filesystem.
|
||||
|
||||
## "Failed to load: <query>"
|
||||
|
||||
Both the streaming path and the mp3 fallback failed. Common causes are a video that requires sign-in, a region block, or yt-dlp being older than the site's current player. Update yt-dlp in the bot's virtual environment.
|
||||
|
||||
## "You must be in a voice channel to use X mode"
|
||||
|
||||
`[p]tts` only allows use outside voice chat in Chatterbox mode, because that path returns an audio file instead of playing. Join a channel or switch modes.
|
||||
|
||||
## "Cannot reach Chatterbox TTS"
|
||||
|
||||
The URL check calls `/api/ui/initial-data` and then checks `/openapi.json` for a `/tts` route. A server that answers the first check but lacks the second is reported as running without the endpoint.
|
||||
|
||||
## "Chatterbox couldn't generate audio with voice X"
|
||||
|
||||
The reference clip is too short, too long, or in a format the server cannot decode. Use 5 to 15 seconds of one speaker with no background noise. Clips shorter than six seconds are looped and clips longer than thirty seconds are trimmed before upload, so this usually means the content itself is unusable.
|
||||
|
||||
## TtsToy DECTalk or Piper commands fail with connection errors
|
||||
|
||||
Both run as independent services, not as children of the bot. Start them with systemd and confirm `/health` for DECTalk and `/` for Piper respond on the configured ports.
|
||||
|
||||
## "The web UI is not running. Ask the bot owner to start it."
|
||||
|
||||
`[p]ttstoy login` reads the internal secret from `/tmp/ttstoy_webui_state.json`. If the file is missing or has no `internal_secret`, the login command refuses. Start the web UI service, which writes that file, or set `TTSTOY_SHARED_STATE` to the correct path.
|
||||
|
||||
## "I couldn't DM you"
|
||||
|
||||
Assistant and TtsToy both DM keys or instructions. Enable direct messages from server members, or ask an administrator to allow them.
|
||||
|
||||
## AutoRoom does not create a channel
|
||||
|
||||
The source voice channel must exist, the bot needs View Channel, Connect and Move Members on the source, and Manage Channels on the destination category. Run `[p]autoroomset permissions` for a check. Joining is also rate limited to two creations per minute per member.
|
||||
|
||||
## AutoRoom channel is not deleted
|
||||
|
||||
Deletion happens when the last member leaves. A bot or a member with a denied connect permission that remains in the channel keeps it alive. Check `[p]autoroomset settings` and the channel's current members.
|
||||
|
||||
## Renamer reports failures
|
||||
|
||||
The bot's role must sit above the target member's highest role. Discord also forbids renaming the server owner and members with a higher role. Failures are counted, not explained per member.
|
||||
@@ -0,0 +1,102 @@
|
||||
# TtsToy Accessibility
|
||||
|
||||
Accessibility mode reads messages from the text chat attached to the voice channel the bot is in, without requiring a command prefix. It exists so a member who cannot read the side chat can follow it by listening.
|
||||
|
||||
## Enabling
|
||||
|
||||
```
|
||||
[p]ttstoy accessibility start
|
||||
[p]ttstoy accessibility engine piper
|
||||
[p]ttstoy accessibility names on
|
||||
```
|
||||
|
||||
Start and stop require the bot owner. Engine and name announcements also require the owner. Members choose their own voice with `[p]ttstoy accessibility voice`, which needs no permission.
|
||||
|
||||
## Conditions for a message to be read
|
||||
|
||||
All of these must hold:
|
||||
|
||||
1. Accessibility mode is on.
|
||||
2. The bot is connected to a voice channel.
|
||||
3. The message is in that voice channel's text chat, which Discord exposes as a text channel with the same ID as the voice channel.
|
||||
4. The message is not from a bot.
|
||||
5. The message does not parse as a command, so `[p]tts` invocations are not read twice.
|
||||
6. The message does not start with `..`, which is the opt-out prefix for members.
|
||||
|
||||
## What gets spoken
|
||||
|
||||
| Message content | Spoken text |
|
||||
|---|---|
|
||||
| Plain text | The text, with emoji removed |
|
||||
| Attachment that is an image | "<name> sent an image" |
|
||||
| Other attachment | "<name> sent a file" |
|
||||
| A URL anywhere in the text, or any embed | "<name> sent a link" |
|
||||
| Only emoji, or only whitespace | Nothing |
|
||||
| Obvious keyboard mash or spam | Nothing |
|
||||
|
||||
The nonsense filter is conservative. It drops messages with a single character repeated over most of the text, one short token repeated five or more times, a long alphabetic run with almost no vowels, very low character variety over a long message, or a short unit repeated to fill the message. Short real messages such as "ok", "lol" or "brb" pass through.
|
||||
|
||||
## Name announcements
|
||||
|
||||
The first message from a speaker since anyone else last spoke is prefixed with "Name said:". A speaker who sends several messages in a row is announced once. The tracker resets when the bot joins, leaves or moves voice channels, so a stale state does not carry into a new session.
|
||||
|
||||
`[p]ttstoy accessibility names off` removes the prefix. Names attached to attachments and links are part of the announcement text itself, so they are spoken regardless of this setting.
|
||||
|
||||
## Voice assignment
|
||||
|
||||
Each speaker gets a distinct voice so listeners can tell them apart.
|
||||
|
||||
- The engine must be `dectalk` or `piper`.
|
||||
- The DECTalk pool is the nine built-in voices: paul, betty, harry, frank, dennis, kit, ursula, rita, wendy.
|
||||
- The Piper pool is five models chosen to bound GPU memory: `en_US-kristin-medium`, `en_US-hfc_female-medium`, `en_US-hfc_male-medium`, `en_US-john-medium`, `en_US-lessac-high`.
|
||||
- Assignment is round robin over the pool, skipping voices already used in the guild, and wrapping around when the pool is exhausted.
|
||||
- A member can pick a voice explicitly with `[p]ttstoy accessibility voice <name>`. The name may be the short label (`hfc_male`), the label with quality (`hfc_male-medium`), the full id, or an unambiguous prefix.
|
||||
- `[p]ttstoy accessibility voice auto` clears the choice and requests a fresh automatic assignment.
|
||||
- `[p]ttstoy accessibility voice` with no argument lists the pool and marks the current voice.
|
||||
|
||||
Assignments are stored per member per engine in config as `{engine: {"voice": ..., "explicit": ...}}`. They survive reloads and restarts. Only the active engine's voice is loaded into memory; the other engine's entry waits until that engine is selected.
|
||||
|
||||
Explicit choices are sticky. They survive a voice channel bounce and engine-neutral resets. Automatic assignments are rebuilt when the engine changes.
|
||||
|
||||
Changing the engine keeps stored voices. A stored voice that is not valid for the new engine is swapped for a valid one automatically, so switching from DECTalk to Piper does not leave a member with a DECTalk voice.
|
||||
|
||||
Starting or stopping accessibility mode resets the name tracker and keeps stored voices. The maps are rebuilt from member config when the cog loads.
|
||||
|
||||
## Engine behavior
|
||||
|
||||
In accessibility mode, `[p]tts` also forces the accessibility engine and strips emoji, so a member invoking the command gets the same voice treatment as auto-read messages.
|
||||
|
||||
Auto-read uses the same rendering path as normal speech and the same per-guild queue. Music pauses for the clip and resumes afterward, using the queue restore logic described in [YTAudio](YTAudio).
|
||||
|
||||
The generated files are named `access-<message id>.mp3` in the cog data directory and are removed by the hourly cleanup.
|
||||
|
||||
## Deliberate omissions
|
||||
|
||||
- No emoji are spoken, including mapped sound effect triggers.
|
||||
- No link contents are fetched. The listener says a link was sent.
|
||||
- No attachment contents are described beyond image or file.
|
||||
- No message edits or deletions are announced.
|
||||
- Direct messages and other channels are ignored.
|
||||
|
||||
## Operational notes
|
||||
|
||||
- The bot must stay in the voice channel. If it is pulled out to show a mute notice, auto-read stops until it returns.
|
||||
- Only one voice channel is served at a time, the one the bot occupies.
|
||||
- The queue is per guild, so a long clip delays subsequent messages.
|
||||
- Voice names are matched case-insensitively.
|
||||
- A member with no stored voice and an exhausted pool shares a voice with another speaker.
|
||||
- `red_delete_data_for_user` does nothing, so a deletion request does not clear stored voice assignments.
|
||||
|
||||
## Relevant config
|
||||
|
||||
Global:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `accessibility_mode` | `false` |
|
||||
| `accessibility_engine` | `dectalk` |
|
||||
| `accessibility_announce_names` | `true` |
|
||||
|
||||
Member: `access_voice`, a map of engine to `{"voice": str, "explicit": bool}`.
|
||||
|
||||
The in-memory maps `_access_user_override`, `_access_auto_voice`, `_access_assign_idx` and `_access_last_speaker` are rebuilt at load from stored member config and are never written directly.
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
# TtsToy Commands
|
||||
|
||||
Two command groups plus top-level shortcuts. `[p]ttstoy` is configuration and mode control; `[p]chatterbox` is voice management. `[p]tts`, `[p]disconnect` and `[p]login` are top-level commands.
|
||||
|
||||
Running either group with no subcommand prints its help.
|
||||
|
||||
## Speech
|
||||
|
||||
| Command | Aliases | Permission | Description |
|
||||
|---|---|---|---|
|
||||
| `[p]tts` | none | Any member | Generates speech, posts an MP3, and plays it in voice |
|
||||
| `[p]disconnect` | `dc` | Any member | Stops playback and disconnects from voice |
|
||||
| `[p]login` | none | Any member | Shortcut for `[p]ttstoy login`, DMs a web UI key |
|
||||
|
||||
`[p]tts` requires the author to be in a voice channel unless the mode is Chatterbox. See [TtsToy Overview](TtsToy-Overview) for the full behavior and inline `[mode|voice]` tags.
|
||||
|
||||
## Mode and engine settings
|
||||
|
||||
| Command | Permission | Description |
|
||||
|---|---|---|
|
||||
| `[p]ttstoy mode [mode]` | Owner | Shows or sets the engine |
|
||||
| `[p]ttstoy key` | Owner | Opens a button and modal to store the MiniMax key |
|
||||
| `[p]ttstoy model [model]` | Owner | Shows example MiniMax models or sets one |
|
||||
| `[p]ttstoy voice [name]` | Owner | Shows or sets the global default voice |
|
||||
| `[p]ttstoy myvoice [name]` | Any member, guild only | Shows or sets your personal voice |
|
||||
| `[p]ttstoy sfxvolume [0-100]` | Owner | Shows or sets sound effect volume |
|
||||
| `[p]ttstoy sfx` | Any member | Lists sound effect folders and their emoji triggers |
|
||||
| `[p]ttstoy info` | Any member | DMs setup and usage instructions |
|
||||
|
||||
`mode` accepts `minimax`, `chatterbox`, `dectalk`, `morshu`, `vox`, `piper`, and `local` as an alias for `chatterbox`. Selecting Morshu or VOX fails with an explanation when the engine did not import.
|
||||
|
||||
`voice` and `myvoice` behave differently per engine. DECTalk, Morshu and VOX ignore voice selection and explain the alternative, which is inline tags for DECTalk and `[p]ttstoy voxpack` for VOX. Chatterbox matches the display name of an uploaded clip. MiniMax accepts a label such as `Gaben` or a raw voice id.
|
||||
|
||||
## DECTalk, Piper and VOX settings
|
||||
|
||||
| Command | Permission | Description |
|
||||
|---|---|---|
|
||||
| `[p]ttstoy dectalkurl [url]` | Owner | Shows or sets the DECTalk URL, with a `/health` check |
|
||||
| `[p]ttstoy piperurl [url]` | Owner | Shows or sets the Piper URL, with a reachability check |
|
||||
| `[p]ttstoy pipervoice [model]` | Owner | Shows available Piper models or sets one; `reset` clears |
|
||||
| `[p]ttstoy voxpack [vox or vox2]` | Owner | Shows or sets the VOX word pack |
|
||||
| `[p]ttstoy voxwords` | Any member | Lists words in the current VOX pack |
|
||||
|
||||
The DECTalk and Piper commands validate the `http://` or `https://` prefix. A failed reachability check still saves the URL after a warning, so a service can be configured before it is started.
|
||||
|
||||
Piper model ids are the `.onnx` filename without the extension, for example `en_US-ryan-medium`. A model present in the server's data directory can be selected even when `/voices` does not list it.
|
||||
|
||||
DECTalk voices are chosen in the text rather than by command:
|
||||
|
||||
| Tag | Voice |
|
||||
|---|---|
|
||||
| `[:np]` | Paul, the default |
|
||||
| `[:nb]` | Betty |
|
||||
| `[:nh]` | Harry |
|
||||
| `[:nf]` | Frank |
|
||||
| `[:nd]` | Dennis |
|
||||
| `[:nk]` | Kit |
|
||||
| `[:nu]` | Ursula |
|
||||
| `[:nr]` | Rita |
|
||||
| `[:nw]` | Wendy |
|
||||
|
||||
Example: `[p]tts [:nh] Deep voice [:nb] and now a different one`.
|
||||
|
||||
The old commands `[p]ttstoy dectalkinstall`, `dectalkstart`, `dectalkstop`, `dectalkstatus` and `dectalkautotoggle` no longer exist. The DECTalk, Morshu and VOX services now run under systemd, outside the bot. See [TtsToy Servers](TtsToy-Servers).
|
||||
|
||||
## Web UI commands
|
||||
|
||||
| Command | Permission | Description |
|
||||
|---|---|---|
|
||||
| `[p]ttstoy login` | Any member, guild only | Requests a one-time login key and DMs it |
|
||||
| `[p]ttstoy webui` | Any member | Replies with the web UI URL |
|
||||
| `[p]ttstoy webuichannel [#channel]` | Owner, guild only | Shows or sets the channel for web UI audio |
|
||||
| `[p]ttstoy webuistatus` | Owner | Checks whether the web UI URL answers |
|
||||
| `[p]ttstoy webuirestart` | Owner | Explains that the web UI is a service and returns the restart command |
|
||||
|
||||
`login` requires the web UI to be running, because it reads an internal secret from the shared state file before asking the service to register a token. The token is valid for five minutes. The member must accept direct messages.
|
||||
|
||||
## Chatterbox voice management
|
||||
|
||||
Group `[p]chatterbox`.
|
||||
|
||||
| Command | Arguments | Description |
|
||||
|---|---|---|
|
||||
| `[p]chatterbox guide` | none | Two message feature guide |
|
||||
| `[p]chatterbox addvoice` | `[name] [url]` | Uploads a reference clip and makes it active |
|
||||
| `[p]chatterbox removevoice` | `<name>` | Removes a clip from your library |
|
||||
| `[p]chatterbox myvoices` | none | Lists your clips and marks the active one |
|
||||
| `[p]chatterbox sharevoice` | `<name> <member>` | Adds a clip to another member's library |
|
||||
| `[p]chatterbox temp` | `[value or reset]` | Randomness, stored per voice |
|
||||
| `[p]chatterbox exag` | `[value or reset]` | Expressiveness, stored per voice |
|
||||
| `[p]chatterbox volume` | `[dB or reset]` | Loudness offset, -20 to +20 |
|
||||
| `[p]chatterbox speed` | `[factor or reset]` | Speed, 0.25 to 4.0 |
|
||||
| `[p]chatterbox reset` | none | Clears all tuning for the current voice |
|
||||
| `[p]chatterbox model` | `[turbo or original]` | Owner only, hot swaps the server model |
|
||||
| `[p]chatterbox url` | `[url]` | Owner only, sets and tests the server URL |
|
||||
|
||||
### addvoice
|
||||
|
||||
Accepts a `.wav` or `.mp3` attachment, or a direct URL. A URL without an extension is assumed to be WAV. The name is reduced to letters, digits and underscores. The stored filename is `<user id>_<name>.wav`.
|
||||
|
||||
Before upload the clip is decoded with pydub, looped if shorter than six seconds, and trimmed to thirty seconds at a nearby silence boundary when longer. If pydub is unavailable the original bytes are uploaded unchanged.
|
||||
|
||||
### removevoice
|
||||
|
||||
Matches a display name or full filename. Removes the clip from the member's list and clears its temperature, exaggeration and volume offsets. The server file is deleted only when the filename starts with the caller's user id, which protects clips that were shared rather than uploaded by the caller. If the removed clip was active, the next clip in the list becomes active or the default voice is restored.
|
||||
|
||||
### Per-voice tuning
|
||||
|
||||
Values are keyed by filename, so each voice keeps its own settings. The commands accept no argument to show, a number to set, or the word `reset` to clear. Temperature and exaggeration are parsed as floats without range enforcement; volume and speed enforce their documented ranges.
|
||||
|
||||
### model
|
||||
|
||||
`turbo` is the faster 350M model and supports tags such as `[laugh]`, `[sigh]` and `[clear throat]`. `original` is the 0.5B model with stronger cloning and emotion control. The switch calls `/save_settings` and then `/restart_server`, which can take a minute; the command edits its status message when the server replies.
|
||||
|
||||
The server must expose both endpoints. A stock Chatterbox build may not.
|
||||
|
||||
### url
|
||||
|
||||
Validates the scheme, then requests `/api/ui/initial-data`. A failure produces a warning but the URL is saved anyway.
|
||||
|
||||
## Accessibility commands
|
||||
|
||||
Group `[p]ttstoy accessibility`, alias `[p]ttstoy access`.
|
||||
|
||||
| Command | Permission | Description |
|
||||
|---|---|---|
|
||||
| `[p]ttstoy accessibility` | Any member | Shows mode, engine and name announcement state |
|
||||
| `[p]ttstoy accessibility start` | Owner | Enables auto-read |
|
||||
| `[p]ttstoy accessibility stop` | Owner | Disables auto-read |
|
||||
| `[p]ttstoy accessibility engine` | Owner | Shows or sets `dectalk` or `piper`, alias `tts` |
|
||||
| `[p]ttstoy accessibility names` | Owner | Shows or sets whether names are announced, alias `announcenames` |
|
||||
| `[p]ttstoy accessibility voice [name]` | Any member, guild only | Shows the voice list or sets your voice, `auto` clears |
|
||||
|
||||
See [TtsToy Accessibility](TtsToy-Accessibility) for the behavior behind these commands.
|
||||
|
||||
## Permission summary
|
||||
|
||||
Owner only: `mode`, `key`, `model`, `voice`, `sfxvolume`, `dectalkurl`, `piperurl`, `pipervoice`, `voxpack`, `webuistatus`, `webuirestart`, `webuichannel`, `chatterbox model`, `chatterbox url`, accessibility `start`, `stop`, `engine` and `names`.
|
||||
|
||||
Any member: `tts`, `disconnect`, `login`, `ttstoy sfx`, `ttstoy info`, `ttstoy myvoice`, `ttstoy voxwords`, `ttstoy webui`, `chatterbox addvoice`, `removevoice`, `myvoices`, `sharevoice`, `temp`, `exag`, `volume`, `speed`, `reset`, `guide`, and accessibility `voice`.
|
||||
|
||||
No command has a cooldown. Nothing prevents a member from queueing many clips or filling the engine server with requests.
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# TtsToy Overview
|
||||
|
||||
Text to speech with six interchangeable engines, per-user cloned voices, emoji triggered sound effects, an accessibility mode that reads voice channel text chat aloud, and a companion web UI.
|
||||
|
||||
The cog generates an MP3 for every request, posts it in the channel, and plays it in voice chat when the author is connected.
|
||||
|
||||
## Engines
|
||||
|
||||
| Mode | Where it runs | Needs | Notes |
|
||||
|---|---|---|---|
|
||||
| `minimax` | MiniMax cloud API | API key | Best quality, paid, sends text off site, reports detected language |
|
||||
| `chatterbox` | Local server on port 8099 | Chatterbox server | Voice cloning from uploaded clips, per-voice tuning |
|
||||
| `dectalk` | Local server on port 33001 | DECTalk service | Nine classic voices selected with inline tags |
|
||||
| `morshu` | Port 33002, in-process fallback | Optional `g2p_en`, `numpy`, `pydub` | Always the Morshu voice |
|
||||
| `vox` | In process | Bundled word packs | Black Mesa announcer, unknown words skipped |
|
||||
| `piper` | Local server on port 5006 | Piper HTTP server | Fast neural voices, optional model id |
|
||||
|
||||
`[p]ttstoy mode` shows the current engine and the relevant address. `[p]ttstoy mode <name>` changes it for the whole bot; the mode is global, not per guild.
|
||||
|
||||
Mode selection is owner only.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Red 3.5 or newer.
|
||||
- YTAudio loaded and a Lavalink node connected, for playback in voice.
|
||||
- `ffmpeg` on the PATH, used for volume offsets and concatenation.
|
||||
- `requests`, `pydub`, `numpy`, `g2p_en` for the local engines, per the manifest.
|
||||
- The engine service for the selected mode, if any.
|
||||
|
||||
Audio playback borrows YTAudio's Lavalink client. Load YTAudio first. Without a connected node, `[p]tts` still generates and posts the file but cannot play it.
|
||||
|
||||
## The speak command
|
||||
|
||||
```
|
||||
[p]tts Hello world
|
||||
```
|
||||
|
||||
- Joins the author's voice channel through Lavalink if the bot is not already connected.
|
||||
- Requires the author to be in a voice channel unless the mode is Chatterbox. Outside voice, only Chatterbox is allowed, because the command still returns an audio file.
|
||||
- Runs a reachability check for the selected engine before synthesis.
|
||||
- Rejects the request when MiniMax has no key, Morshu failed to import, or VOX is unavailable.
|
||||
- Generates the audio, sends it as `<mode>-tts-<message id>.mp3` with a donation link button, and adds a line naming the detected language for engines that report one.
|
||||
- Queues the file for voice playback when the author is in a channel and the bot is connected, announcing the queue position when something is already playing.
|
||||
- Reacts to the command message with a speaking emoji.
|
||||
|
||||
There is no cooldown and no text length limit. Long text is sent to the engine as is, and very long output can exceed the engine's own limits or the HTTP timeout.
|
||||
|
||||
## Inline voice switching
|
||||
|
||||
Text can switch engine and voice mid-message:
|
||||
|
||||
```
|
||||
[p]tts [minimax|robotnik] Hands off. [dectalk] [:nh] You have been warned.
|
||||
```
|
||||
|
||||
The syntax is `[mode|voice]` or `[mode]`. Valid modes are the six engine names. An invalid tag is read as literal text. Each segment is rendered separately and concatenated into one MP3, so a single message can mix engines.
|
||||
|
||||
When the tag names a voice, it is resolved against the engine: MiniMax labels or raw ids, DECTalk speaker names, a Chatterbox filename or display name, or a Piper model id. An unknown name is passed through to the engine, which may reject it.
|
||||
|
||||
The multi-voice path skips the fast single-engine path, so expect a longer generation time and slightly different loudness between segments.
|
||||
|
||||
## Emoji sound effects
|
||||
|
||||
Any emoji in the text with a mapped folder in `sfx/` is replaced by a randomly chosen clip from that folder. Folders without audio fall back to speaking the emoji name.
|
||||
|
||||
The mapping lives in `sfx/emoji_map.json` and can be edited, with defaults compiled into the cog. `[p]ttstoy sfx` lists folders, their emoji triggers and whether they contain audio. `[p]ttstoy sfxvolume` sets the clip volume from 0 to 100.
|
||||
|
||||
Morshu and VOX bypass the SFX splitter because they consume fixed word sets rather than arbitrary speech. Accessibility mode strips emoji so nothing is played as a sound effect.
|
||||
|
||||
## Chatterbox voice cloning
|
||||
|
||||
- `[p]chatterbox addvoice <name>` with an attached `.wav` or `.mp3`, or a direct URL.
|
||||
- Clips shorter than six seconds are looped and clips longer than thirty seconds are trimmed at a nearby silence boundary.
|
||||
- Files are stored on the Chatterbox server as `<user id>_<name>.wav` and the filename is recorded in user config.
|
||||
- The new voice becomes the uploader's active voice.
|
||||
- `[p]chatterbox myvoices` lists them, `[p]ttstoy myvoice <name>` switches.
|
||||
- `[p]chatterbox sharevoice <name> @member` adds the same file to another member's library. The file stays owned by the original uploader, so removing it from the sharer's list does not delete it.
|
||||
- `[p]chatterbox removevoice <name>` removes it from the library and deletes the server file only when the caller owns the file.
|
||||
|
||||
Per-voice tuning is stored against the filename: `temp` for randomness, `exag` for expressiveness, `volume` for a dB offset from -20 to +20, `speed` from 0.25 to 4.0. Each is set per voice per user and cleared with `reset`. `[p]chatterbox reset` clears all four for the current voice.
|
||||
|
||||
Tuning values for temperature and exaggeration are documented with ranges but are not range checked by the cog; the Chatterbox server decides what it accepts. Volume and speed are validated.
|
||||
|
||||
The Chatterbox model can be switched between `turbo` and `original` by the owner. The command writes the model id through `/save_settings` and then triggers a hot swap through `/restart_server`, which can take a minute or more.
|
||||
|
||||
## Queue and music handling
|
||||
|
||||
Each guild has its own TTS queue and processor. When a clip starts, the processor pauses any music, saves the current track, position and queue, clears the Lavalink queue, plays the clip, then restores the queue and seeks back.
|
||||
|
||||
Consequences:
|
||||
|
||||
- Music resumes from where it stopped, not from where it would have been.
|
||||
- Tracks queued in Lavalink during the clip can be lost when the saved queue is restored.
|
||||
- A guild with a stuck player stalls its own queue only.
|
||||
- Generated files live in the cog data directory and are deleted by an hourly cleanup loop, which removes the whole directory.
|
||||
|
||||
## Web UI
|
||||
|
||||
`[p]ttstoy webui` returns the public URL. `[p]ttstoy login` requests a one-time key from the web UI service and DMs it; the key is valid for five minutes and signs the member in across the Scrapyard sites.
|
||||
|
||||
The web UI can change a member's voice, tuning values, and voice library. It cannot run arbitrary bot commands. Changes arrive as queued actions in a shared JSON state file that the cog polls every three seconds.
|
||||
|
||||
`[p]ttstoy webuichannel` sets the channel where web UI generated audio is posted in the current server. Without it, the cog uses the global setting, the `TTSTOY_WEBUI_CHANNEL_ID` environment variable, or the first channel named `tts`, `ttstoy` or `tts-toy`.
|
||||
|
||||
## Health endpoint
|
||||
|
||||
On load the cog starts an HTTP server on port 8097 answering `GET /health` with a small JSON status object. Every other path returns 404. It is intended for external monitoring and is not used by the bot.
|
||||
|
||||
## Limits and known issues
|
||||
|
||||
- Mode is global. A guild cannot choose its own engine.
|
||||
- No cooldowns, so a member can flood the queue and the engine servers.
|
||||
- No permission checks on `[p]tts` or `[p]disconnect`.
|
||||
- The accessibility voice pool for Piper is fixed at five models to bound GPU memory.
|
||||
- Concatenation assumes the same codec parameters across segments. Mixed engines can produce audible seams.
|
||||
- `[p]ttstoy info` still describes an older default Chatterbox port and older command names. Trust `[p]ttstoy mode` and `[p]chatterbox url`.
|
||||
- Voice assignments and library entries are not removed by Red's user data deletion.
|
||||
- `ttstoy/stack.json` is a deployment specific file of website paths and a shared session secret. The cog does not read it.
|
||||
|
||||
## Stored data
|
||||
|
||||
Global config under identifier `0x0A0A0A0A`:
|
||||
|
||||
| Key | Default |
|
||||
|---|---|
|
||||
| `minimax_api_key` | `null` |
|
||||
| `minimax_model` | `speech-01-turbo` |
|
||||
| `minimax_voice` | One built-in voice id |
|
||||
| `sfx_volume` | `100` |
|
||||
| `tts_mode` | `minimax` |
|
||||
| `chatterbox_api_url` | `http://127.0.0.1:8099` |
|
||||
| `dectalk_api_url` | `http://127.0.0.1:33001` |
|
||||
| `piper_api_url` | `http://127.0.0.1:5006` |
|
||||
| `piper_voice` | `null` |
|
||||
| `accessibility_mode` | `false` |
|
||||
| `accessibility_engine` | `dectalk` |
|
||||
| `accessibility_announce_names` | `true` |
|
||||
| `vox_pack` | `vox` |
|
||||
| `webui_tts_channel_id` | `null` |
|
||||
| `webui_public_url` | Deployment URL |
|
||||
|
||||
Guild config: `webui_tts_channel_id`.
|
||||
|
||||
Member config: `access_voice`, a map of engine to voice and whether the member chose it explicitly.
|
||||
|
||||
User config: `minimax_voice`, `chatterbox_voices`, `chatterbox_temperature_offsets`, `chatterbox_exaggeration_offsets`, `chatterbox_volume_offsets`, `chatterbox_speed_offsets`, plus two deprecated single-value tuning keys kept for migration.
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
# TtsToy Servers
|
||||
|
||||
TtsToy talks to five optional services over HTTP. Four of them run as independent processes, normally under systemd, and are not started or stopped by the cog. The cog only needs their addresses.
|
||||
|
||||
The repository includes server code for DECTalk, Morshu and VOX under `ttstoy/dectalk-server`, `ttstoy/morshu-server` and `ttstoy/vox-server`. Chatterbox and Piper are separate projects.
|
||||
|
||||
## Port and endpoint summary
|
||||
|
||||
| Service | Default address | Endpoints used |
|
||||
|---|---|---|
|
||||
| DECTalk | `http://127.0.0.1:33001` | `GET /health`, `POST /v1/t2a_v2` |
|
||||
| Morshu | `http://127.0.0.1:33002` | `GET /say?text=...` |
|
||||
| VOX | port 33003 declared, generation is in process | none currently |
|
||||
| Piper | `http://127.0.0.1:5006` | `POST /synthesize`, `GET /voices`, `GET /` |
|
||||
| Chatterbox | `http://127.0.0.1:8099` | See below |
|
||||
| TtsToy web UI | port 8098, behind a public URL | `POST /api/register_token` |
|
||||
| TtsToy health | port 8097 | `GET /health` |
|
||||
|
||||
## DECTalk server
|
||||
|
||||
The DECTalk service exposes a MiniMax-shaped synthesis API so the cog can use one request builder for both engines.
|
||||
|
||||
Request to `/v1/t2a_v2`:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "<model>",
|
||||
"text": "<text with [:xx] voice tags>",
|
||||
"stream": false,
|
||||
"language_boost": "auto",
|
||||
"output_format": "hex",
|
||||
"voice_setting": {"voice_id": "paul", "speed": 1, "vol": 1, "pitch": 0},
|
||||
"audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "mp3", "channel": 1}
|
||||
}
|
||||
```
|
||||
|
||||
The response must contain `base_resp.status_code` equal to 0 and a hex encoded MP3 in `data.audio`. `GET /health` must answer 200 for the preflight check in `[p]tts`.
|
||||
|
||||
The bundled server is a Node.js application. It requires Node.js 14 or newer, npm, and ffmpeg. The `npm install` step pulls `express` and the `dectalk` package, which ships the original DECTalk binaries and works on Linux.
|
||||
|
||||
The server listens on port 3000 by default; the deployment convention for this cog is `PORT=33001`. `OUTPUT_DIR` changes where generated files are kept. Endpoints beyond the two the cog calls are `GET /engine`, which returns the engine type and version, `GET /say?text=...`, which returns MP3 bytes for quick tests, and `GET /voices`, which lists the nine voices.
|
||||
|
||||
Generated audio is mono, 32 kHz, 128 kbps MP3, matching what the cog expects. On Debian derivatives the DECTalk binaries may need `libasound2`. The service is expected to be managed with systemd under the unit name `dectalk-tts-server`, which is the name the cog prints in its mode confirmation.
|
||||
|
||||
DECTalk accepts synthesis commands in the text:
|
||||
|
||||
| Command | Effect |
|
||||
|---|---|
|
||||
| `[:phoneme on]` | Switches to phoneme input |
|
||||
| `[:rate 200]` | Sets speech rate, default 180 |
|
||||
| `[:dv ap 100]` | Sets voice parameters |
|
||||
|
||||
Example: `[p]tts [:rate 200] speaking very fast`.
|
||||
|
||||
Because the cog no longer manages the process, the commands `dectalkinstall`, `dectalkstart`, `dectalkstop`, `dectalkstatus` and `dectalkautotoggle` from older releases are gone. Use systemctl or an equivalent service manager.
|
||||
|
||||
## Morshu server
|
||||
|
||||
`GET /say?text=<url encoded text>` returns MP3 bytes. The cog requests it with a 60 second timeout. When the request fails for any reason, the cog falls back to the in-process engine from `morshutalk_engine.py`, which needs `g2p_en`, `numpy` and `pydub`.
|
||||
|
||||
There is no health endpoint. The preflight in `[p]tts` checks only whether the engine imported, not whether the server is up.
|
||||
|
||||
The Morshu voice is fixed. Voice selection commands explain this and point at the mode itself.
|
||||
|
||||
## VOX
|
||||
|
||||
The VOX engine is implemented in `vox_engine.py` and runs inside the bot process. It synthesises speech by concatenating samples for known words, so unknown words are skipped and the output can be unintelligible for unusual text.
|
||||
|
||||
`[p]ttstoy voxpack` switches between the `vox` and `vox2` packs detected on disk. `[p]ttstoy voxwords` lists the current vocabulary, split across messages to stay under the limit.
|
||||
|
||||
The cog declares `vox_port = 33003` but does not use it. A `vox-server` directory exists in the repository for a standalone service, which the current renderer does not call.
|
||||
|
||||
## Piper server
|
||||
|
||||
`POST /synthesize` with:
|
||||
|
||||
```json
|
||||
{"text": "...", "voice": "en_US-ryan-medium"}
|
||||
```
|
||||
|
||||
`voice` is omitted when the cog has no model configured, in which case the server's default is used. The response must be audio; the cog treats fewer than 100 bytes as a failure.
|
||||
|
||||
`GET /voices` is used only for the listing in `[p]ttstoy pipervoice`. It may return a mapping of ids or a list of objects with `key` or `name`; the cog handles both.
|
||||
|
||||
`GET /` is the reachability preflight. It must answer 200.
|
||||
|
||||
The accessibility voice pool uses five model ids: `en_US-kristin-medium`, `en_US-hfc_female-medium`, `en_US-hfc_male-medium`, `en_US-john-medium` and `en_US-lessac-high`. Each must exist in the server's data directory.
|
||||
|
||||
Piper models are `.onnx` files in the server's data directory. The model id is the filename without the extension.
|
||||
|
||||
## Chatterbox server
|
||||
|
||||
Required endpoints:
|
||||
|
||||
| Method and path | Purpose |
|
||||
|---|---|
|
||||
| `POST /tts` | Synthesis, returns WAV bytes |
|
||||
| `POST /upload_predefined_voice` | Multipart upload of a reference clip |
|
||||
| `DELETE /delete_predefined_voice/<filename>` | Removes a reference clip |
|
||||
| `GET /api/ui/initial-data` | Reachability check |
|
||||
| `GET /openapi.json` | Confirms a `/tts` route exists |
|
||||
| `GET /api/model-info` | Reports model type, class and loaded state |
|
||||
| `POST /save_settings` | Sets `model.repo_id` |
|
||||
| `POST /restart_server` | Hot swaps the model |
|
||||
|
||||
The last three are used only by `[p]chatterbox model` and may not exist on every build. The cog reports the failure rather than hiding it.
|
||||
|
||||
Synthesis payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"text": "...",
|
||||
"voice_mode": "predefined",
|
||||
"predefined_voice_id": "<user id>_<name>.wav",
|
||||
"output_format": "wav",
|
||||
"split_text": false,
|
||||
"temperature": 0.8,
|
||||
"exaggeration": 1.2,
|
||||
"speed_factor": 1.1
|
||||
}
|
||||
```
|
||||
|
||||
The tuning keys are omitted when unset. A 500 response whose body contains "failed to synthesize" is translated into advice about the reference clip's length and format.
|
||||
|
||||
Reference clips live in the server's voice directory. The cog owns their filenames and the per-user lists, but not the bytes.
|
||||
|
||||
## TtsToy web UI service
|
||||
|
||||
The web UI is a separate service, not a bot subprocess. It shares state with the cog through a JSON file.
|
||||
|
||||
Paths and environment:
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
|---|---|---|
|
||||
| `TTSTOY_SHARED_STATE` | `/tmp/ttstoy_webui_state.json` | Shared state file |
|
||||
| `TTSTOY_SHARED_STATE_LOCK` | `/tmp/ttstoy_webui_state.lock` | Lock file for cross-process updates |
|
||||
| `WEBUI_PORT` | `8098` | Port the cog calls for internal API requests |
|
||||
| `WEBUI_URL` | `https://ttstoy.kingstons-scrapyard.net` | Public URL shown to members |
|
||||
| `TTSTOY_WEBUI_CHANNEL_ID` | unset | Fallback channel for web UI audio |
|
||||
|
||||
The state file holds `internal_secret`, `webui_url`, `users`, `pending_commands` and `pending_posts`. The cog polls every three seconds, takes the pending arrays under a file lock, refreshes member profile fields from every guild, and writes the file back.
|
||||
|
||||
### Login flow
|
||||
|
||||
1. `[p]ttstoy login` reads `internal_secret` from the state file. If it is missing, the command refuses.
|
||||
2. The cog posts to `<internal URL>/api/register_token` with the header `X-Internal-Secret` and a body containing the user id, Discord name, avatar URL, owner flag, guild id and guild name.
|
||||
3. The service returns a token.
|
||||
4. The bot DMs a login URL and the token, valid for five minutes.
|
||||
5. The member logs in once on the homepage and the session cookie is shared across the Scrapyard subdomains.
|
||||
|
||||
### Queued actions
|
||||
|
||||
The web UI can queue `set_voice`, `set_mode`, `set_chatterbox_params`, `add_voice` and `remove_voice`. The cog validates the user, checks owner status for `set_mode`, and applies the change to config.
|
||||
|
||||
Queued posts carry a generated audio path, text, the user's display name, engine, guild and user ids, and a `play_vc` flag. If `play_vc` is set and the member is in a voice channel with a connected node, the file is queued for playback. The transcript and file are then posted to the configured channel.
|
||||
|
||||
The shared state file is readable by any local user on a default temporary directory and contains the internal secret. Restrict its permissions or move it with `TTSTOY_SHARED_STATE`.
|
||||
|
||||
## Deployment checklist
|
||||
|
||||
1. Start Lavalink and confirm port 2333.
|
||||
2. Start the engine services you intend to use and confirm their health endpoints.
|
||||
3. Load YTAudio, then TtsToy.
|
||||
4. Set the engine with `[p]ttstoy mode` and verify with `[p]tts`.
|
||||
5. For the web UI, start the service, confirm it writes the shared state file, then run `[p]ttstoy login`.
|
||||
6. Set `[p]ttstoy webuichannel` per guild where web UI audio should appear.
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# YTAudio
|
||||
|
||||
Plays YouTube audio in voice channels through a Lavalink node. The cog resolves a query with yt-dlp, streams the audio into a growing file, and asks Lavalink's `local` source to play that file while yt-dlp keeps filling it.
|
||||
|
||||
YTAudio also owns the process-wide Lavalink client for the whole bot. TtsToy depends on that connection.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Lavalink node on `localhost:2333` with password `youshallnotpass`, defined in the source as `LL_HOST`, `LL_PORT`, `LL_PASSWORD`.
|
||||
- The `local` source enabled on the node.
|
||||
- A shared filesystem between the bot and the node, because Lavalink opens a path the bot creates.
|
||||
- `yt-dlp` installed in the bot's Python environment, plus `ffmpeg` on the PATH for the fallback conversion.
|
||||
- Python 3.9 or newer for `asyncio` usage, though the bot baseline is 3.11.
|
||||
|
||||
## Commands
|
||||
|
||||
All commands are guild only and none of them have a permission check. Any member can control playback, change the volume, or disconnect the bot.
|
||||
|
||||
| Command | Aliases | Arguments | Behavior |
|
||||
|---|---|---|---|
|
||||
| `[p]play` | none | `<query>` | Joins your voice channel and queues a URL or search |
|
||||
| `[p]skip` | none | none | Skips the current track |
|
||||
| `[p]stop` | none | none | Stops playback and clears the queue |
|
||||
| `[p]pause` | none | none | Pauses the current track |
|
||||
| `[p]resume` | none | none | Resumes playback |
|
||||
| `[p]queue` | `q` | none | Shows the current track and what is next |
|
||||
| `[p]nowplaying` | `np` | none | Shows the current track |
|
||||
| `[p]volume` | none | `<0-150>` | Sets and saves the guild volume |
|
||||
| `[p]summon` | `ytjoin` | none | Joins your voice channel |
|
||||
| `[p]ytleave` | `ytdc` | none | Stops, disconnects and clears state |
|
||||
|
||||
`play` accepts a full URL, a `www.` address, or a search phrase. Searches are resolved as `ytsearch1:<query>`, so the first result is used. Playlists are disabled by yt-dlp options.
|
||||
|
||||
When something is already playing, `play` replies with the queue position. When the queue was empty, the track starts immediately and progress is reported through status messages in the invoking channel.
|
||||
|
||||
`volume` clamps to 0 through 150 and stores the value per guild. It applies to the active player and to the next track.
|
||||
|
||||
`skip` aborts any in-flight resolution for the current track by setting its skip event, then stops the Lavalink player. The track end event advances the queue, so the cog does not signal the queue directly, which would skip two tracks.
|
||||
|
||||
`stop` and `ytleave` also clear pending tracks and delete their temporary files. `ytleave` additionally disconnects the Lavalink player.
|
||||
|
||||
`queue` truncates its output at 1900 characters.
|
||||
|
||||
## Playback pipeline
|
||||
|
||||
1. `play` ensures the bot has a Lavalink player and is connected to the author's voice channel. If the bot is in a different channel, the player is moved rather than reconnected.
|
||||
2. A `QueuedTrack` is appended to the guild's pending list. The player loop wakes.
|
||||
3. The loop takes the first pending track, sets it as current, and calls `_play_track`.
|
||||
4. `_play_track` posts "Loading: <query>" and sets the guild volume.
|
||||
5. The streaming path resolves metadata with yt-dlp using `download=False`, which returns the direct media URL and title without downloading, subject to a 30 second resolver timeout.
|
||||
6. A regular file is created under the cog data directory, and `python -m yt_dlp -f bestaudio/best -o - <target>` is started with its stdout writing directly into that file. The file must be a regular file because this Lavalink build's local loader rejects FIFOs.
|
||||
7. The cog waits until the file reaches 64 KiB or the process exits, up to 15 seconds. A process that exits early counts as a stream failure.
|
||||
8. Lavalink loads the path through its local source. On success the track plays while yt-dlp continues to write.
|
||||
9. When the track ends, is skipped, or fails, the yt-dlp process is killed and the file is deleted.
|
||||
|
||||
The stream path avoids Lavalink's own YouTube source and avoids a full download before playback. Tracks generally start within a few seconds, and a skip is immediate because it only requires killing a process.
|
||||
|
||||
### Fallback path
|
||||
|
||||
If streaming fails, the cog edits the status to "Stream unavailable, downloading: <query>" and downloads the audio through yt-dlp with an `FFmpegExtractAudio` postprocessor at 192 kbps, writing `<video id>.mp3` into `mp3cache`. Progress hooks edit the status message at most once per second and only when the whole percent changes. The mp3 is then played through the same local source.
|
||||
|
||||
If the fallback also fails, the status becomes "Failed to load: <query>" and the queue advances.
|
||||
|
||||
## Queue model
|
||||
|
||||
Each guild has a `GuildPlayer` with:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `pending` | Tracks waiting, index 0 plays next |
|
||||
| `current` | The track playing now, or `None` |
|
||||
| `volume` | Cached guild volume |
|
||||
| `task` | The player loop task |
|
||||
| `next_event` | Set when the current track should end |
|
||||
| `wakeup` | Set when a track is added |
|
||||
|
||||
Commands read `pending` and `current` directly, so `queue` and `nowplaying` reflect real state rather than a separate model.
|
||||
|
||||
Lavalink track end, exception and stuck events set `next_event` for the guild. That is the only signal that moves the loop to the next track.
|
||||
|
||||
## Lavalink ownership
|
||||
|
||||
On setup, `start_up_task` creates a background task that waits for Red to be ready, then:
|
||||
|
||||
1. Checks `lavalink.get_all_nodes()`. If a node is already connected, it marks itself ready and shares it.
|
||||
2. Otherwise calls `lavalink.initialize` with a 30 second timeout, up to five attempts, waiting two seconds between timeouts.
|
||||
3. Registers a track event listener on success.
|
||||
|
||||
On unload it cancels the connect task, cancels every player loop, unregisters the listener, closes the Lavalink client, kills spawned yt-dlp processes, and deletes and recreates `mp3cache` and `streams`.
|
||||
|
||||
Because the client is a process singleton, only one cog should call `initialize` and `close`. If the built-in Audio cog is loaded and already connected, YTAudio shares that node. If YTAudio is unloaded while TtsToy is still loaded, TtsToy loses its player connection.
|
||||
|
||||
## Interaction with TtsToy
|
||||
|
||||
TtsToy plays generated audio through the same Lavalink player. Its queue processor pauses music, saves the current track, position and queue, clears the queue, plays the TTS clip, then restores the queue and seeks back to the saved position.
|
||||
|
||||
That restoration relies on YTAudio's queue objects being present in the Lavalink player when TTS finishes. A track added during a TTS clip is appended to the player, not to YTAudio's `pending` list, so it can be lost when the saved state is restored.
|
||||
|
||||
## Limits and failure modes
|
||||
|
||||
- No permission checks, as noted above.
|
||||
- The queue is in memory. A reload or restart loses pending tracks.
|
||||
- Age restricted, members only, or region blocked videos fail in both paths and report "Failed to load".
|
||||
- yt-dlp must be current. Sites change their player frequently and an old binary fails to resolve.
|
||||
- The Lavalink node must be able to read the path written by the bot. Containers and separate hosts break the streaming path.
|
||||
- Downloads and streams count against disk space until the track ends or the cog unloads.
|
||||
- The resolver timeout is 30 seconds; a slow search is treated as a skip.
|
||||
- A `play` invoked while the bot is not connected still requires the author to be in a voice channel.
|
||||
- Volume 0 does not pause playback; the player keeps decoding silently.
|
||||
|
||||
## Configuration and stored data
|
||||
|
||||
Guild config under identifier `0x5954415544494F` holds one key, `volume`, defaulting to 100.
|
||||
|
||||
Generated files:
|
||||
|
||||
- `<cog data>/mp3cache` for fallback downloads, named by video id.
|
||||
- `<cog data>/streams` for in-progress streams, named by UUID with the source extension.
|
||||
|
||||
Both are wiped on unload. No user data is stored. The Lavalink password is in the source and should be treated as public within the deployment.
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
**Scrapyard Cogworks**
|
||||
|
||||
- [Home](Home)
|
||||
- [Installation](Installation)
|
||||
- [Cog Catalog](Cog-Catalog)
|
||||
- [Local Services](Local-Services)
|
||||
- [Data and Privacy](Data-and-Privacy)
|
||||
- [Troubleshooting](Troubleshooting)
|
||||
- [Development](Development)
|
||||
|
||||
**Cogs**
|
||||
|
||||
- [AlbumOfTheDay](AlbumOfTheDay)
|
||||
- [Assistant](Assistant)
|
||||
- [AutoRoom Overview](AutoRoom-Overview)
|
||||
- [AutoRoom Commands](AutoRoom-Commands)
|
||||
- [AutoRoom Templates](AutoRoom-Templates)
|
||||
- [Deadman](Deadman)
|
||||
- [ImageGrab](ImageGrab)
|
||||
- [PlayitStatus](PlayitStatus)
|
||||
- [Renamer](Renamer)
|
||||
- [Transcribe](Transcribe)
|
||||
- [TtsToy Overview](TtsToy-Overview)
|
||||
- [TtsToy Commands](TtsToy-Commands)
|
||||
- [TtsToy Accessibility](TtsToy-Accessibility)
|
||||
- [TtsToy Servers](TtsToy-Servers)
|
||||
- [YTAudio](YTAudio)
|
||||
Reference in New Issue
Block a user