Compare commits

...
Author SHA1 Message Date
FernandoJVideiraandClaude Sonnet 5.5 694d262c8c Help: compact inline columns, wide instead of long, with a link to the docs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 11:38:45 +01:00
FernandoJVideira 85bd89a3f6 Merge pull request 'Every dashboard feature is also a command' (#30) from ft/commands-parity into dev
Reviewed-on: #30
2026-10-23 01:12:37 +00:00
FernandoJVideiraandClaude Sonnet 5.5 30cbd9a798 Help and docs for the new commands
- /help is sent as a few messages (Discord caps an embed at 6000 characters), with a test for the limits
- command reference, features, self-hosting, beta and getting-started pages describe the commands; the SQL section is gone
- development and contributing: every setting needs a command

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 02:11:44 +01:00
FernandoJVideiraandClaude Sonnet 5.5 132a2cd986 Commands for everything a dashboard can do
- /music skip, pause, resume, stop, repeat, remove, move (DJ role)
- /config view, clear, toggletwitch, streamers, beta-features (server owner)
- /slvl status, remove-reward; /moderation bans, timeouts; /security history
- /beta is now the bot owner's DM-only command: set, off, servers, remove-server, status
- betasettings service and repo methods, with integration tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 02:10:05 +01:00
FernandoJVideiraandClaude Sonnet 5.5 acdb5ead35 Tickets: settings, category edit and ticket list from Discord; NOTIFY triggers in schema.sql
- /tickets settings (on or off, panel title and text, open tickets per member), /tickets category edit, /tickets list
- schema.sql now creates the NOTIFY triggers, so the integration tests run on a database built from it, and two stale expectations (tickets start off) are fixed

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 02:05:45 +01:00
FernandoJVideiraandClaude Sonnet 5.5 d95ebf473e Security: tune the Join Gate, raid mode, anti-nuke and heat with commands
- /security settings, joingate check|account-age, words add|remove|list, raid, antinuke set|limit, heat, alert-dms
- Same rule as the rest of the configuration: owner or trusted, validated in the engine
- schema.sql was missing security_settings.alert_dm, so the bot couldn't read security settings on a database built from it. Fixed, with an ALTER for existing installs
- A test checks every command against Discord's limits

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 02:03:03 +01:00
FernandoJVideira 5657d0789a Merge pull request 'Prepare for open source: license, contributing, self-hosting guide, fix Close()' (#29) from ft/open-source into dev
Reviewed-on: #29
2026-10-23 00:54:45 +00:00
FernandoJVideiraandClaude Sonnet 5.5 02b7db1813 Docs: say plainly that only the bot is open source; the dashboard and API are proprietary
- README, license section and architecture no longer point to the dashboard repositories
- schema.sql is the schema for contributors; database changes only need schema.sql and a note in the PR
- self-hosting: settings without a dashboard (SQL for security thresholds, beta settings, opted-in servers)
- beta features, deployment and troubleshooting reworded for people who don't have the dashboard

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 01:54:08 +01:00
FernandoJVideiraandClaude Sonnet 5.5 1fbc38ca56 Prepare for open source: Apache-2.0 license, contributing guide, self-hosting guide, fix Close()
- LICENSE (Apache-2.0), NOTICE, CONTRIBUTING.md
- docs/self-hosting.md and README sections for hosting and contributing
- Close() no longer crashes: it only disconnects and leaves the slash commands registered, so they keep their IDs across restarts
- Tests use a neutral server ID

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 01:47:24 +01:00
FernandoJVideira 279607183a Merge pull request 'Beta in other servers (still 3.5.2)' (#27) from ft/beta-servers into dev
Reviewed-on: #27
2026-10-23 00:32:50 +00:00
FernandoJVideiraandClaude Sonnet 5.5 9839bba50e Beta: clean up servers that opted out while the bot was offline
The bot remembers where it registered beta commands (beta_registered) and
removes them from servers that are no longer in the beta at the next start.
Failed cleanups are retried; a server the bot has left is forgotten.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 01:32:20 +01:00
FernandoJVideiraandClaude Sonnet 5.5 fcf4f3ccbd Beta servers: testers can use beta features in servers whose owner opted in
- beta.Configure takes the opted-in servers; testers are looked up in the beta server
- beta commands registered per opted-in server and removed when it opts out
- beta.ServerEnabled for behaviour that no person triggers
- docs updated

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 01:25:50 +01:00
FernandoJVideira e2fe30b524 Merge pull request 'v3.5.2: multiple meeting lobbies and beta features' (#25) from ft/lobbies-and-beta into dev
Reviewed-on: #25
2026-10-23 00:08:28 +00:00
FernandoJVideiraandClaude Sonnet 5.5 fefa74e045 Docs: wiki-style documentation in docs/, README as the front page
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 01:07:17 +01:00
FernandoJVideiraandClaude Sonnet 5.5 1ee6280d91 Beta server and role come from the dashboard
The owner sets them on the admin page; the bot polls the shared beta_settings
row (30s) and moves the beta commands if the server changes. BETA_* env vars
are gone.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 00:55:09 +01:00
FernandoJVideiraandClaude Sonnet 5.5 a364435bab Multiple meeting lobbies and beta-gated features (3.5.2)
- /meeting add-lobby, remove-lobby, lobbies: up to 10 lobbies per server, capped in the database
- Deleted voice channels are dropped from the lobbies
- Beta features: registered only in the beta server and usable only with the Beta Tester role (BETA_GUILD_ID, BETA_ROLE_ID); fails closed
- /beta (bot owner only) shows how beta access is set up

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-23 00:38:48 +01:00
FernandoJVideira 136377d81a Merge pull request 'Start Twitch alerts and tickets off on new servers' (#23) from fix/modules-default-off into dev
Reviewed-on: #23
2026-10-21 22:10:37 +00:00
FernandoJVideiraandClaude Opus 5.5 0218676e2d Start Twitch alerts and tickets off on new servers
Every module that can be switched on or off now starts off. A server
with no settings yet reads as off; setting the Twitch alert channel or
running /tickets setup for the first time turns that module on, and
existing settings are left as they are. schema.sql mirrors the API's
migration 000019.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:56:26 +01:00
FernandoJVideira f285367511 Merge pull request 'Ticket panel: dropdown, Create ticket button, orange' (#21) from fix/ticket-panel into dev
Reviewed-on: #21
2026-10-21 10:58:52 +00:00
FernandoJVideiraandClaude Opus 5.5 e10e1f7a86 Use a dropdown and a Create ticket button on the ticket panel, in orange
The panel is now one category dropdown and a Create ticket button
instead of a button per category. Discord doesn't send the dropdown's
value with a button click, so each member's pick is remembered in
memory for 15 minutes (per guild and member, capped). Panels posted
before keep working until they're reposted. Every ticket embed is
orange, closed tickets included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 11:58:19 +01:00
FernandoJVideira e453a9ba94 Merge pull request 'Add anti-raid and anti-nuke protection' (#19) from ft/antiraid into dev
Reviewed-on: #19
2026-10-20 21:04:12 +00:00
FernandoJVideira 95072fcd53 Merge pull request 'Add support tickets with private threads' (#18) from ft/tickets into dev
Reviewed-on: #18
2026-10-20 21:03:04 +00:00
FernandoJVideiraandClaude Opus 5.5 3f87e68a2c Add anti-raid and anti-nuke protection
Join Gate (account age, avatar, advertising and username filters, bot
checks), raid detection with invite pausing, anti-nuke quarantine of
admins who mass delete, manual and automatic lockdowns, a decaying heat
score against spam, role and channel snapshots with restore, and alert
DMs to the owner and trusted users. Everything that weakens protection
is limited to the owner and the trusted list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 21:59:52 +01:00
FernandoJVideiraandClaude Opus 5.5 d294b3463b Add support tickets that work with private threads
Members open a ticket from a panel in the ticket channel: one button per
category (a dropdown past five), then a short form. Each ticket is a private
thread named after the category, number and opener, with a first message
that mentions the category's staff role so its members join, and Claim and
Close buttons.

- Claim: staff (the category's role, or Manage Threads / Manage Server)
  take a ticket; the first message shows who has it.
- Close: the opener or staff close it, with an optional reason. The thread
  is locked and archived, and the log channel gets a summary and a .txt
  transcript of the whole thread.
- /ticket add|remove|claim|close inside a ticket; /tickets setup,
  /tickets category add|remove|list and /tickets panel for admins.
- Per-member limit on open tickets (default 1), per-server ticket numbers
  handed out atomically, a deleted thread closes its ticket.
- The dashboard asks the bot to post or refresh the panel through
  ticket_commands (LISTEN/NOTIFY, like music); the listener reconnects if
  the database connection drops.
- Setup warns about missing bot permissions in the ticket and log channels.

The flows live in internal/tickets behind small Discord and store
interfaces, with unit tests on fakes; the repo and the listener have
integration tests (-tags integration, TICKETS_TEST_DB).

Needs the ticket tables (velox-dashboard-api migration 000016_tickets).
.gitignore gains the /tldr benchmark rules so private chat exports and
benchmark results on disk can't be committed from this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 19:31:52 +01:00
FernandoJVideira b1ea5f17e3 Merge branch 'master' into dev 2026-08-29 18:53:18 +00:00
FernandoJVideira 23d417ef27 Merge pull request 'Ft/music command listener' (#16) from ft/music-command-listener into dev
Reviewed-on: #16
2026-08-29 18:52:50 +00:00
FernandoJVideira 52dfe859ee feat(music): add a stop command
Clears the whole queue and disconnects, mirrors the existing Stop
Manager function, just wires it up to the outbox like every other
dashboard command.
2026-08-29 19:48:43 +01:00
FernandoJVideira da66eb8dd5 feat(music): let the dashboard add songs, starting a session if needed
New AddToQueue appends to an already-active session without touching
voice (the dashboard can't join a channel on its own), and add_song's
dispatch case now branches: a voice_channel_id in the payload means
"start fresh", so it goes through EnqueueAndPlay (join + play) instead.
Query normalization (plain text -> YouTube search, stripping
autoplay/radio params off pasted YouTube URLs) moves out of /play's
handler into a shared NormalizeQuery, both entry points need it, not
just one.

Starting playback from the dashboard also posts the now-playing embed
into the voice channel's own built-in text chat, matching what /play
already does, instead of leaving it with nowhere to show up.
2026-08-29 19:44:24 +01:00
FernandoJVideira fcc7c9c66a feat(music): consume playback commands via LISTEN/NOTIFY
The dashboard has been writing skip/pause/volume/etc. requests into
music_commands with nothing on this end reading them. Adds a
dedicated LISTEN connection (can't use the pooled *sql.DB for this,
LISTEN has to stay bound to one specific connection) that wakes on
NOTIFY, drains unprocessed rows, and dispatches each to the matching
Manager function. A command's error is logged, not fatal, and every
row gets marked processed regardless of outcome so a permanently
broken command doesn't retry forever.
2026-08-29 19:22:16 +01:00
FernandoJVideira 7a17c55774 feat(music): stable queue identity, remove/reorder, and repeat commands
TrackEntry gets a QueueID generated once when a track is queued and
kept for its whole life there, and musicrepo.ReplaceQueue now upserts
by that ID instead of deleting and reinserting the whole queue on
every sync (which churned every track's database id constantly, even
ones that hadn't moved, and would've made remove/reorder commands
target the wrong track). RemoveFromQueue and Reorder are new Manager
functions built on top of that stable identity. Also adds repeat_song/
repeat_queue to the persisted now-playing state, and makes the two
existing toggle functions actually sync it, they never did before.
2026-08-29 19:22:02 +01:00
FernandoJVideira 39962457b3 Merge pull request 'v3.3.0' (#15) from dev into master
Reviewed-on: #15
2026-08-29 15:39:18 +00:00
FernandoJVideira 539c0a69af Merge pull request 'feat(music): persist live playback state to postgres' (#14) from ft/music-live-state into dev
Reviewed-on: #14
2026-08-29 15:35:05 +00:00
FernandoJVideira d6687879dd feat(music): persist live playback state to postgres
The queue and now-playing state only ever lived in the bot's memory,
so the dashboard had nothing real to show and a restart silently
wiped whatever was queued. Adds a musicrepo package and a syncState
call after every queue-changing action (play, skip, pause, volume,
stop, track end) that mirrors the current track and queue into
music_now_playing and music_queue.

No user-visible change yet, this is groundwork for the dashboard
queue/now-playing view.
2026-08-29 15:48:27 +01:00
FernandoJVideira e507225cae Merge pull request 'v3.2.0' (#13) from dev into master
Reviewed-on: #13
2026-08-29 03:14:33 +00:00
FernandoJVideira c7b960e14a Merge pull request 'feat(music): add /music toggle and gate playback behind it' (#12) from ft/music-toggle into dev
Reviewed-on: #12
2026-08-29 02:53:57 +00:00
FernandoJVideira 691b505175 feat(music): add /music toggle and gate playback behind it
Music could be started and controlled with no way to turn it off for
a server. Adds a music_settings table (mirrors the same one
velox-dashboard-api's dashboard toggle reads/writes), a /music toggle
command gated to Manage Server, and checks in /play, /queue, and
/volume so they refuse to run when a server has music turned off.
2026-08-29 03:49:52 +01:00
FernandoJVideira 95ba434194 Merge pull request 'Feat/schedule rework' (#11) from feat/schedule_rework into dev
Reviewed-on: #11
2026-08-26 14:05:52 +00:00
FernandoJVideira 5f4e893971 chore .gitignore 2026-08-26 15:05:06 +01:00
FernandoJVideira 01dbb98450 Command rework 2026-08-18 21:20:31 +01:00
FernandoJVideira 5024af2789 feat: schedule rework 2026-08-18 19:22:21 +01:00
FernandoJVideira 483dc666d1 Merge pull request 'feat: update Docker configuration and environment handling' (#10) from dev into master
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/10
2026-03-18 14:14:27 +00:00
FernandoJVideira 3585fa0658 Merge branch 'master' into dev 2026-03-18 14:14:21 +00:00
FernandoJVideira d1be60e201 Merge pull request 'dev' (#9) from dev into master
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/9
2026-03-18 14:11:39 +00:00
FernandoJVideira 26e1d9b094 feat: update Docker configuration and environment handling
- Added PostgreSQL service to docker-compose.yml with health checks and persistent storage.
- Updated bot service to use environment variable substitution for database connection string.
- Upgraded Go version in Dockerfile to 1.26.1-alpine.
- Modified config loading to ignore missing .env file for better compatibility with Docker.
2026-03-18 14:08:21 +00:00
FernandoJVideira 461f8435c0 feat: add Docker support and bot configuration
- Introduced Dockerfile for building the bot application using Go.
- Added .dockerignore to exclude unnecessary files from the Docker context.
- Updated docker-compose.yml to define the bot service and its dependencies, including environment variables for database and Lavalink configuration.
- Modified internal configuration to streamline environment variable handling.
2026-03-18 13:39:31 +00:00
FernandoJVideira 1b47bd13a3 Merge pull request 'ft/mod' (#8) from ft/mod into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/8
2026-03-18 13:22:26 +00:00
FernandoJVideira 035e383db2 feat: implement server logging functionality
- Added a logging service to manage server event logs including message edits, deletions, member joins/leaves, and moderation actions.
- Introduced commands to configure logging settings, including setting the log channel and enabling/disabling logging.
- Updated the README to document the new logging features and commands.
- Enhanced moderation commands to log actions taken on members.
2026-03-18 13:18:12 +00:00
FernandoJVideira 2b14079e50 feat: add moderation commands and update README
- Introduced a new set of moderation commands including `/moderation purge`, `/moderation timeout`, `/moderation kick`, `/moderation ban`, `/moderation unban`, `/moderation untimeout`, and `/moderation slowmode`.
- Updated README to include details about the new moderation features and commands.
- Enhanced help command to display moderation tools and their usage.
2026-03-18 13:00:30 +00:00
FernandoJVideira a92c4131db Merge pull request 'ft/welcome_message' (#7) from ft/welcome_message into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/7
2026-03-18 05:16:08 +00:00
FernandoJVideira 397a8a459a chore: readme & help update 2026-03-18 05:15:12 +00:00
FernandoJVideira 4080ce8aec feat: add default role management functionality
- Introduced a new default role service and repository for managing default roles assigned to new members.
- Added command to set the default role through the bot's configuration.
- Implemented event handling to assign the default role to new guild members upon joining.
- Updated main application to include the new default role service in the bot's services.
2026-03-18 05:12:40 +00:00
FernandoJVideira e6aa5def96 feat: add welcome message functionality
- Introduced a new welcome service and repository for managing welcome messages, channels, and GIFs.
- Added commands to set welcome channel, message, DM, and GIF through the bot's configuration.
- Implemented event handling for new guild members to send welcome messages and DMs based on configuration.
- Updated main application to include the new welcome service in the bot's services.
2026-03-18 05:07:11 +00:00
FernandoJVideira 6410619662 Merge pull request 'feat: twitch notifications' (#6) from ft/twitch_notifications into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/6
2026-03-18 04:42:54 +00:00
FernandoJVideira df656ca12d feat: twitch notifications 2026-03-18 04:42:02 +00:00
FernandoJVideira 076e616b9c feat: readme 2026-03-18 04:02:11 +00:00
FernandoJVideira 891f3f6ad2 Merge pull request 'feat: integrate music commands with Lavalink support' (#5) from ft/music into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/5
2026-03-18 03:55:06 +00:00
FernandoJVideira ded31409e2 Merge branch 'dev' into ft/music 2026-03-18 03:52:53 +00:00
FernandoJVideira ae3d574c68 Merge pull request 'ft/schedule' (#4) from ft/schedule into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/4
2026-03-18 03:48:14 +00:00
FernandoJVideira d7edfea45e feat: integrate music commands with Lavalink support
- Added new music commands: play, queue, and volume.
- Implemented music management using disgolink for Lavalink integration.
- Updated bot initialization to include Lavalink host and password.
- Enhanced interaction handling for music commands, requiring DJ role for usage.
- Introduced now playing message with interactive buttons for controlling playback.
- Updated dependencies in go.mod for disgolink and snowflake.
2026-03-18 03:47:42 +00:00
FernandoJVideira db5d23c2ac feat: timezone awarenwss 2026-03-18 01:35:09 +00:00
FernandoJVideira a85ac23a6b feat: basic schedule 2026-03-18 01:11:53 +00:00
FernandoJVideira d177114ddb Merge pull request 'feat: project add & list' (#3) from ft/projects into dev
Reviewed-on: https://gitea.fernandovideira.com/FernandoJVideira/velox-bot/pulls/3
2026-03-18 00:41:04 +00:00
132 changed files with 21960 additions and 271 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
.git
.gitignore
.env
*.md
Dockerfile
docker-compose*.yml
.dockerignore
+8 -1
View File
@@ -1,3 +1,10 @@
.env
*.env
.cursor
tmp/
# Local /tldr benchmark: chat dumps and results never get committed.
bench-out/
internal/tldr/tldrbench/private/
# Real chat dumps used by the benchmark never get committed.
internal/tldr/tldrbench/testdata/private/
+64
View File
@@ -0,0 +1,64 @@
# Contributing to Velox Bot
Thanks for wanting to help. This page is the short version of how to do it well. The longer technical material is in the [Development guide](docs/development.md).
## Ways to help
- **Report a bug.** Say what you did, what you expected and what happened. Include the bot's log lines around the problem and whether it happens in more than one server. Never paste a bot token, a database password or a `.env` file.
- **Suggest a feature.** Explain the problem it solves for a server, not only the command you imagine.
- **Improve the documentation.** Wrong or missing docs are bugs. A fix to `docs/` is always welcome.
- **Fix something or build something.** Pick an issue, or open one first (see below).
## Security problems
If you find a way to get around a permission check, make the bot act for someone who shouldn't be able to ask, or leak a token, **do not open a public issue**. Contact the maintainer privately, using the contact details on the repository's profile, and give them time to fix it before you share it.
## Before you write code
1. **Open an issue for anything big**: a new module, a change to how permissions or security work, a change to the database. It saves you from writing something that can't be merged.
2. Read [Architecture](docs/architecture.md) so you know the layers, and the [Development guide](docs/development.md) for the recipe that matches your change.
3. For anything that touches the database, read [Database](docs/database.md#changing-the-schema). A schema change has to keep a bot that is one version behind working for a short while.
## Making the change
1. Fork the repository and create a branch **from `dev`**: `git checkout -b my-change dev`. `master` only holds releases.
2. Keep the change focused. One pull request, one purpose. Unrelated cleanup goes in its own pull request.
3. Follow the code around you: naming, comment density, error handling. Comments explain why, not what.
4. Add tests. At minimum, test the permission check (does the wrong person get refused?), limits, and anything that parses input. See [Testing](docs/development.md#testing).
5. Update the documentation that your change makes wrong: `/help` (`internal/commands/help/help.go`), [Command reference](docs/commands.md) and [Features](docs/features.md).
Before you push:
```bash
gofmt -l . # format the files you touched
go build ./... && go vet ./... && go test -race ./...
```
Some older files are not `gofmt`-clean. Format the files you change, and leave the rest alone so the diff stays readable.
## The rules that matter most
These are the things a reviewer will check first. The reasons are in the [Development guide](docs/development.md#style-and-safety-rules).
- **Fail closed.** If you can't tell whether someone is allowed, they are not.
- **Check permissions in the handler.** `DefaultMemberPermissions` only hides a command from the menu.
- **No SQL outside repos.** Always use query parameters (`$1`), never string formatting.
- **A module that acts on a server starts off.** An admin turns it on.
- **Every setting has a command.** The bot works fully without a dashboard, so a setting must be visible and changeable with slash commands.
- **Escape user text and set `AllowedMentions`** so a message can't ping people.
- **Validate everything that comes from users or from other programs writing to the database**: options, custom IDs, command payloads.
- **No secrets** in code, logs, tests or commit messages.
## Commit messages and pull requests
- Write the commit subject in the imperative and keep it short ("Add a limit of 10 meeting lobbies"). Use the body to explain why, when it isn't obvious.
- In the pull request, say what changed and why, how you tested it, and whether it needs a database change or a deploy in a particular order.
- Keep the pull request open to review comments. Small follow-up commits are fine, there is no need to squash them yourself.
## Behaviour
Be kind and be specific. Disagree with the code, not the person. Harassment, personal attacks and discrimination are not tolerated, and the maintainer may remove comments, close discussions or block people who do it.
## License
By contributing, you agree that your contribution is licensed under the [Apache License 2.0](LICENSE), the same as the project (section 5 of the license covers this). You keep the copyright on your own work.
+21
View File
@@ -0,0 +1,21 @@
# Build stage
FROM golang:1.26.1-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /velox-bot .
# Run stage
FROM alpine:3.19
RUN apk add --no-cache ca-certificates tzdata
WORKDIR /app
COPY --from=builder /velox-bot .
ENTRYPOINT ["./velox-bot"]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
Velox Bot
Copyright 2026 Fernando Videira
This product includes software developed by the authors of its dependencies,
each under its own license (see go.mod).
+87
View File
@@ -0,0 +1,87 @@
# Velox Bot
Velox is a Discord bot written in Go, backed by PostgreSQL. It covers server security (anti-raid and anti-nuke), support tickets, moderation, leveling, music, meeting rooms, scheduling, Twitch alerts and a few games. Every module is off until a server turns it on.
**This repository is the bot, and it is the only open source part of Velox.** The web dashboard and its API, which the hosted Velox uses, are separate proprietary software and are not part of this repository or its license. The bot does not need them. Every setting and every action is a slash command (see the [command reference](docs/commands.md)), with PostgreSQL as its only dependency.
The dashboard and the bot meet in the database. The dashboard writes settings and requests into tables, and the bot reads them (and is woken through Postgres `NOTIFY` where it has to react at once). Those tables are documented, so you can change the same settings with SQL, or build your own tool on top. See [Architecture](docs/architecture.md) and [Database](docs/database.md).
## Documentation
This README is the front page. The rest of the documentation lives in [`docs/`](docs/), organised like a wiki:
| Page | What is in it |
| --- | --- |
| [Getting started](docs/getting-started.md) | Requirements, creating the Discord application, configuration, database, running locally |
| [Host your own bot](docs/self-hosting.md) | A step-by-step guide to running your own copy on a server, with Docker Compose |
| [Deployment](docs/deployment.md) | Docker, Compose, upgrade order, backups |
| [Architecture](docs/architecture.md) | How the code is laid out, how an interaction flows through it, background loops, how a dashboard talks to the bot |
| [Features](docs/features.md) | What each module does and how it behaves |
| [Command reference](docs/commands.md) | Every slash command, its options and who may run it |
| [Database](docs/database.md) | Who owns the schema, the tables, the `NOTIFY` channels, how to change them |
| [Development guide](docs/development.md) | How to add commands, subcommands, buttons, events, background jobs, settings and tables; testing; code style |
| [Beta features](docs/beta-features.md) | How features are tried by a few testers before release |
| [Troubleshooting](docs/troubleshooting.md) | Common problems and what they mean |
## Quick start
You need Go (the version in `go.mod`), PostgreSQL 16 or newer, and a Discord application with a bot token.
```bash
git clone <this repository>
cd velox-bot
# create .env with BOT_TOKEN, APP_ID, GUILD_ID, DB_HOST and TWITCH_CLIENT_ID (see docs/getting-started.md)
docker compose up -d db # PostgreSQL on localhost:5432
psql "postgres://velox:velox_pwd@localhost:5432/velox?sslmode=disable" -f schema.sql
go run .
```
On start the bot registers its slash commands in the server named by `GUILD_ID` (or globally if that is empty). The full walkthrough, including the Discord side, is in [Getting started](docs/getting-started.md).
## What it does
- **Security**: Join Gate, raid mode, anti-nuke with quarantine, lockdowns, snapshots and restore, and a spam "heat" system, modelled on Wick.
- **Tickets**: a panel with categories, a private thread per ticket, claim and close, transcripts to a log channel.
- **Moderation**: purge, timeout, kick, ban, unban, slowmode, plus server logs for edits, deletes, joins, leaves, role changes, bans and mod actions.
- **Leveling**: XP per message, level cards, leaderboard, role rewards.
- **Music**: Lavalink-powered playback with a queue, controlled from Discord.
- **Meeting rooms**: join a lobby voice channel and get a temporary room you can lock and invite people to.
- **Scheduling and projects**: 1:1 sessions with DM invites and reminders, and a simple project list.
- **Twitch alerts, welcome messages, default role**: per-server setup through `/config`.
- **Fun**: `/ping`, `/joke`, `/coinflip`, `/dice`, `/rps` with stats and a leaderboard.
When the bot joins a server for the first time, toggleable systems start **disabled** and the person who invited it gets a DM with setup instructions.
## Repository layout
```
main.go wiring: config, database, repos, services, bot
internal/config environment variables
internal/bot Discord session, intents, event registration, startup
internal/commands slash commands, one package per feature, plus the dispatcher
internal/events handlers for gateway events and background loops
internal/db connection, repos (SQL), services (rules)
internal/security anti-raid and anti-nuke engine
internal/tickets ticket flows
internal/music Lavalink player, queue, buttons
internal/beta beta access gate
internal/modlog, rankcard small shared helpers
schema.sql mirror of the tables the bot reads and writes
```
## Host your own bot
You can run your own copy under your own Discord application. [Host your own bot](docs/self-hosting.md) walks through it on a fresh server with Docker Compose: creating the application and the invite link, configuring the bot, loading the database, optional music and Twitch, backups and updates.
## Contributing
Contributions are welcome: bug reports, fixes, documentation and new features.
- Read [CONTRIBUTING.md](CONTRIBUTING.md) first. It covers how to report a problem, how to propose a change, and what a good pull request looks like.
- The [Development guide](docs/development.md) shows how to add a command, a button, an event handler, a setting or a table, and how to test them.
- For anything big, open an issue to talk about it before you write the code.
- Pull requests go to the `dev` branch. Before opening one, run `gofmt` on the files you touched and `go build ./... && go vet ./... && go test -race ./...`.
## License
Velox Bot, the code in this repository, is released under the [Apache License 2.0](LICENSE). Copyright 2026 Fernando Videira. See [NOTICE](NOTICE). The license does not cover the proprietary Velox dashboard and API, or the Velox name and logo as used by the hosted service. The libraries the bot uses are under their own permissive licenses (see `go.mod`).
+15 -2
View File
@@ -1,5 +1,3 @@
version: "3.9"
services:
db:
image: postgres:16
@@ -19,5 +17,20 @@ services:
timeout: 5s
retries: 5
bot:
build: .
container_name: velox-bot
restart: unless-stopped
env_file: .env
environment:
DB_HOST: ${DB_HOST:-postgres://velox:velox_pwd@db:5432/velox?sslmode=disable}
LAVALINK_HOST: ${LAVALINK_HOST:-ws://lavalink:2333}
LAVALINK_PASSWORD: ${LAVALINK_PASSWORD:-youshallnotpass}
depends_on:
db:
condition: service_healthy
networks:
- default
volumes:
velox_pgdata:
+131
View File
@@ -0,0 +1,131 @@
# Architecture
This page explains how the bot is put together, so you know where to look and where to make a change.
## The big picture
```
Discord gateway (websocket)
|
discordgo session
|
+--------------------------+---------------------------+
| | |
interactions gateway events background loops
(slash commands, (messages, joins, bans, (Twitch, reminders,
buttons, modals) voice, audit log, ...) raid watch, snapshots)
| | |
internal/commands internal/events internal/events, security
| | |
+----------- services (rules) <------ repos (SQL) -----+
|
PostgreSQL <----> a dashboard (the hosted Velox has a proprietary one)
```
The bot is one Go process. It keeps one websocket connection to Discord and one connection pool to PostgreSQL. It has no HTTP server of its own.
## Startup
`main.go` wires everything in this order:
1. **Config**: `config.LoadConfig()` reads the environment (and `.env`).
2. **Database**: `db.NewDB()` opens a `database/sql` pool using the pgx driver.
3. **Repos**: one repo per area (`levelrepo`, `settingsrepo`, `ticketrepo`, ...). A repo is the only place that writes SQL.
4. **Services**: small structs holding the rules for one area (`level`, `meeting`, `welcome`, ...), built on top of repos, collected in `services.Services`.
5. **Singletons for the bigger modules**: tickets and security get their repo with `cmdtickets.Init(...)` and `security.Configure(...)`, and are reached later through `tickets.Default()` and `security.Default()`.
6. **Bot**: `bot.NewBot()` creates the Discord session and chooses the gateway intents.
7. **`bot.Start()`** opens the connection and then:
- starts the music player (if Lavalink is configured) and its command listener,
- starts the ticket and security engines and their command listeners (each reconnects every 10 seconds if its database connection drops),
- registers every slash command in `GUILD_ID` (or globally),
- registers the gateway event handlers,
- starts the Twitch and schedule-reminder loops.
8. **`bot.WatchBeta()`** reads the beta settings from the database and keeps them fresh every 30 seconds. See [Beta features](beta-features.md).
9. The process waits for `SIGINT` or `SIGTERM`.
## Layers
The code follows one direction: commands and events call services, services call repos, repos run SQL.
| Layer | Where | Responsibility |
| --- | --- | --- |
| Commands | `internal/commands/<feature>` | Describe the slash command, check who is allowed, read the options, answer the user. No SQL. |
| Events | `internal/events` | React to gateway events and run background loops. |
| Engines | `internal/security`, `internal/tickets`, `internal/music` | The bigger modules, with their own state and flows. |
| Services | `internal/db/services/<area>` | Rules and orchestration (for example the XP rules in `level`). |
| Repos | `internal/db/repos/<area>repo` | SQL, and nothing else. |
Commands reach services through the package-level `services.Global`, set by `services.NewServices()`. A shared helper in each command package (for example `RequireMeetingService`) answers "service not available" if it is nil. Event handlers receive the services as an argument.
## How a slash command runs
1. Discord sends an interaction. discordgo calls `commands.HandleInteraction` (`internal/commands/commands.go`).
2. For a slash command, the dispatcher looks the command's name up in the `handlers` map and calls the handler.
3. The handler checks the context (server only? permissions?), finds the subcommand in `i.ApplicationCommandData().Options`, reads the options, calls a service, and responds with `s.InteractionRespond`.
Buttons, select menus and modals do not have a command name. They carry a **custom ID**, and the dispatcher sends them to a feature by its **prefix**: `music:`, `schedule:`, `projects:`, `tickets:` or `security:`. A feature owns everything after its prefix.
Some commands have a response that takes longer than three seconds (anything that calls Discord several times). Those answer with a deferred response first, then edit it when done. Search the code for `InteractionResponseDeferredChannelMessageWithSource` for examples.
## How a gateway event runs
`bot.Start()` registers one handler per event with `Session.AddHandler`. Most of them hand the event to a function in `internal/events`, together with the services. A few go to the security engine first, because it must decide before anything else happens:
- **Member joins**: the security engine runs first. If it removes the member (join lock, Join Gate, raid mode) there is no welcome message or default role. Otherwise the welcome, default role and join log run.
- **Messages**: the security engine's heat check runs, then the leveling handler.
- **Audit log entries**: only the security engine (anti-nuke, unauthorised bots).
- **Voice state changes**: meeting rooms and the music player.
## Background loops
| Loop | Where | Interval | What it does |
| --- | --- | --- | --- |
| Twitch live check | `events/twitch_live.go` | 30 s | Checks configured streamers and posts when one goes live |
| Schedule reminders | `events/schedule_reminders.go` | 1 min | DMs participants 10 minutes before a session |
| Raid watch | `security` | 30 s | Ends raid mode after a quiet period |
| Snapshots | `security` | 6 h | Saves roles and channels while anti-nuke is on (keeps three) |
| Beta settings | `bot/bot.go` (`WatchBeta`) | 30 s | Re-reads who the beta testers are and which servers opted in, and adds or removes beta commands to match |
| Command listeners | music, tickets, security | on `NOTIFY` | Carry out requests written to the `*_commands` tables |
## How a dashboard talks to the bot
The bot has no HTTP server and no API of its own. A web dashboard, such as the proprietary one the hosted Velox uses (not part of this repository), meets the bot in PostgreSQL, in two ways. This is the whole contract, so you can drive the bot the same way with SQL or write your own tool:
1. **Settings tables.** A dashboard writes settings (log channel, security thresholds, ticket categories, beta role). The bot reads them when it needs them. Hot paths cache them for a short time, so a raid of thousands of joins does not become thousands of queries.
2. **Command tables with `NOTIFY`.** When a dashboard needs the bot to *do* something (skip a song, post the ticket panel, release a quarantined member), it inserts a row in `music_commands`, `ticket_commands` or `security_commands` and issues `NOTIFY` on that channel. The bot has a long-lived connection that runs `LISTEN`, picks up the row, validates it again and carries it out. Never trust a row just because it is in the table: the listeners re-check permissions themselves.
Both directions are described table by table in [Database](database.md).
## Gateway intents
Set in `internal/bot/bot.go`:
| Intent | Why |
| --- | --- |
| Guilds | slash commands, channel and role events |
| Guild Moderation (bans, audit log) | ban logs, anti-nuke |
| Guild Members (privileged) | joins, leaves, member updates |
| Guild Messages and Message Content (privileged) | leveling, spam heat, message logs |
| Guild Voice States | meeting rooms, music |
| Direct Messages | direct messages sent to the bot |
If you add a feature that needs another event, add its intent here too, and enable it in the developer portal if it is privileged.
## Concurrency and safety notes
- discordgo calls event handlers on goroutines, so handlers must not share unsynchronised state. The engines use mutexes, and per-server memory is bounded.
- Security-sensitive actions do not rely on Discord's command permissions, because server admins can change those. The handlers check the owner and the trusted list themselves (see the [Security](features.md#security) section).
- User-controlled text (usernames, reasons) is escaped or kept out of mentions. Messages only ping roles that are configured for it.
- Settings that decide who has access (the beta role) fail closed: if they cannot be read, nobody gets access.
## Where things live
| I want to find... | Look in |
| --- | --- |
| The definition and handler of `/foo` | `internal/commands/foo/public/` (the `registry.go` next to it re-exports it) |
| The list of all commands and the dispatcher | `internal/commands/commands.go` |
| What happens on a gateway event | `internal/bot/bot.go`, then `internal/events/` |
| The SQL behind a feature | `internal/db/repos/<area>repo/repo.go` |
| The rules behind a feature | `internal/db/services/<area>/` |
| The table definitions | `schema.sql` and [Database](database.md) |
| Environment variables | `internal/config/config.go` |
+80
View File
@@ -0,0 +1,80 @@
# Beta features
A beta feature is one that is still being tried out, so only chosen people can use it, and only where the server agreed. Two things must both be true:
1. **The person is a beta tester**: a member of the beta server who holds the Beta Tester role.
2. **Beta features are on in the server they use it in**: the beta server itself, or any other server whose owner opted in.
The rule is the same on the bot and on the hosted Velox dashboard. The dashboard is proprietary and not part of this repository, so this page is about the bot, and mentions the dashboard only where it explains how the settings get into the database.
## Who the testers are
- The **beta server** and the **Beta Tester role** are chosen by the bot's owner (the owner of the Discord application) with `/beta set`, in a direct message with the bot. They are stored in the `beta_settings` table, one row. `/beta status` shows them and `/beta off` clears the role, which turns beta features off for everyone.
- Giving someone the role in Discord makes them a tester. Taking it away removes their access, within about 30 seconds on the bot (a few seconds if the bot has them cached).
- Until a role is chosen, **nobody** has beta access.
- Being a tester is about the person, so it is always checked in the **beta server**, also when they use a feature somewhere else. Having a role with the same ID in another server means nothing.
## Which servers have beta features
- The beta server always has them.
- Any other server gets them only when its **owner** runs `/config beta-features enabled:true` there. Beta features can act on a whole server (anti-raid behaviour, for example), so the people who answer for the server decide. A server's admins who are not its owner cannot switch it on.
- The bot's owner can take a server out with `/beta remove-server` (and see them with `/beta servers`), but cannot put one in.
- The servers are the `beta_guilds` table. The bot polls it every 30 seconds, together with the beta settings.
Beta never replaces a feature's own permission checks. A beta command that needs Manage Server still needs it, a music command still needs the DJ role, and anything for the owner or trusted users still needs that.
## What a tester sees
- **Bot:** beta commands appear only in the beta server and in opted-in servers, and run only for testers. When a server opts in, the commands show up within about 30 seconds. When it opts out, they are removed.
- **On the hosted Velox dashboard** (proprietary, not in this repository): beta pages and links show a **Beta** badge, only to testers and only for servers where beta features are on.
## On the bot
Code: `internal/beta` (the rules), `internal/commands/commands.go` (`RegisterBeta`), `internal/bot/bot.go` (`WatchBeta`, `syncBetaCommands`), `internal/commands/betacmd` (`/beta`).
- Beta commands are registered in each server where beta features are on, and only there. `/beta` is only in the beta server.
- Each beta handler is wrapped in `beta.Gate`. It checks that beta is on in the server of the interaction and that the person is a tester, and otherwise answers "This feature is in beta and isn't available to you or this server yet." (Autocomplete requests get an empty list.) Hiding the command is never the only protection.
- For a person using a command in another server, the bot looks up their roles in the beta server: first in its gateway cache, otherwise it asks Discord (remembered for 30 seconds). If anything fails, the answer is no.
- If the beta server changes, the beta commands move within 30 seconds. In the beta server, commands this bot left there that no longer exist are removed too. If the beta server is also `GUILD_ID`, the regular commands are kept.
- `/beta` is registered globally but works only in a direct message with the bot, so it is in no server's menu, and only the owner of the Discord application can use it.
- The bot remembers the servers where it registered beta commands (`beta_registered` table). A server that opted out while the bot was **offline** is cleaned up on the next start, and a cleanup that fails is retried every 30 seconds. A server the bot has left is forgotten.
### Add a beta command
Write the command like any other (see the [Development guide](development.md#add-a-simple-command)), but instead of adding it to `AllCommands` and `handlers`, register it from `commands.go`:
```go
func init() {
RegisterBeta(mything.MyThing, mything.MyThingHandler)
}
```
`RegisterBeta` adds the definition to `BetaCommands` and the handler, wrapped in `beta.Gate`, to the dispatcher. Buttons and forms that belong to a beta command need the same care: call `beta.Guard(s, i)` at the top of their handlers, because a custom ID can be reached from an old message.
### Add beta behaviour that no one runs
Event handlers and background jobs have no person to check. Gate them on the server only:
```go
if !beta.ServerEnabled(guildID) {
return // beta features are off here
}
```
Do not use this for anything that should only be for testers as people. It means "this server agreed to try beta features", and every member of the server is affected.
### Release it
Move the definition into `AllCommands` and the handler into the `handlers` map, and delete the `RegisterBeta` call. On the next start the command appears everywhere, and the beta servers drop it from their own lists because it is now a regular command.
## On the dashboard
The hosted Velox has a proprietary dashboard and API that apply the same rule to their own pages: a beta page is only shown, and its API routes only answer, for a tester in a server where beta features are on. Their code is not part of this repository. If you build your own tool on the same tables, apply the rule on your server side too: never rely on hiding a page.
## Why it works this way
- The role in Discord is the single list of testers, so there is no second list to keep in step with it.
- Servers choose to take part, because a beta feature can affect everyone in them.
- Access is decided on the server, never in the browser.
- Beta commands do not exist outside the beta server, and the gate checks again when they run.
- The settings are in the database and changed with commands, not in the environment, so they change without a deploy.
+211
View File
@@ -0,0 +1,211 @@
# Command reference
Every slash command the bot registers. Options marked with `*` are required. "Needs" is what the handler checks, not just what Discord shows in its menu. Commands that need a server cannot be used in DMs.
This page is written by hand from the command definitions in `internal/commands/*/public`. If you change a command, update it here and in `/help` (`internal/commands/help/help.go`). The [Features](features.md) page explains the behaviour behind them.
- [Fun](#fun)
- [Help](#help)
- [Leveling](#leveling)
- [Music](#music)
- [Meeting rooms](#meeting-rooms)
- [Moderation](#moderation)
- [Timezone and scheduling](#timezone-and-scheduling)
- [Projects](#projects)
- [Server setup (`/config`)](#server-setup-config)
- [Tickets](#tickets)
- [Security](#security)
- [Beta](#beta)
## Fun
Anyone can use these. `/rps`, `/rpsstats` and `/rpsleaderboard` work in servers only.
| Command | Options | What it does |
| --- | --- | --- |
| `/ping` | | Replies "Pong!" |
| `/joke` | `type` | A random joke, optionally of a type |
| `/coinflip` | | Heads or tails |
| `/dice` | `expr`* | Rolls a dice expression: `d20`, `2d20+1`, `2#d20+1` |
| `/rps` | `hand`* | Rock paper scissors against the bot |
| `/rpsstats` | | Your rock-paper-scissors record |
| `/rpsleaderboard` | | The server's leaderboard |
## Help
| Command | What it does |
| --- | --- |
| `/help` | DMs you a command reference |
## Leveling
| Command | Options | Needs | What it does |
| --- | --- | --- | --- |
| `/slvl toggle` | | Manage Server | Turns leveling on or off |
| `/slvl set` | `user`*, `level`* | Manage Server, leveling on | Sets a member's level |
| `/slvl set-channel` | `channel`* | Manage Server, leveling on | Where level-up messages go |
| `/slvl set-message` | `message`* | Manage Server, leveling on | The level-up message. Variables: `{user}`, `{level}` |
| `/slvl set-reward` | `level`*, `role`* | Manage Server, leveling on | Role granted at a level |
| `/slvl remove-reward` | `level`* | Manage Server, leveling on | Removes a level's role reward |
| `/slvl status` | | Manage Server | Shows the leveling settings |
| `/rank` | `user` | Leveling on | A rank card for you or another member |
| `/leaderboard` | | Leveling on | Top 10 in the server |
| `/rewards` | | Leveling on | The role rewards |
## Music
| Command | Options | Needs | What it does |
| --- | --- | --- | --- |
| `/play` | `query`* | **DJ** role | Plays a song by name or URL |
| `/queue` | | **DJ** role | Shows the queue |
| `/volume` | `value`* (0 to 150) | **DJ** role | Sets the volume |
| `/music toggle` | | Manage Server | Turns music on or off in this server |
| `/music skip` | | **DJ** role | Skips the current song |
| `/music pause`, `/music resume` | | **DJ** role | Pauses or resumes |
| `/music stop` | | **DJ** role | Stops and clears the queue |
| `/music repeat` | `mode`* (off, song, queue) | **DJ** role | Repeats the song, the queue, or nothing |
| `/music remove` | `position`* (its number in `/queue`) | **DJ** role | Removes a queued song |
| `/music move` | `from`*, `to`* | **DJ** role | Moves a queued song |
Requires Lavalink. See [Getting started](getting-started.md#optional-music-with-lavalink).
## Meeting rooms
Every subcommand needs **Manage Server** and works in servers only.
| Command | Options | What it does |
| --- | --- | --- |
| `/meeting add-lobby` | `channel`* (voice) | Makes a voice channel a lobby (up to 10 per server) |
| `/meeting remove-lobby` | `channel`* (voice) | Stops using it as a lobby |
| `/meeting lobbies` | | Lists the lobbies |
| `/meeting lock` | | Locks the room you are in |
| `/meeting lock-private` | | Locks it and hides it |
| `/meeting unlock` | | Unlocks it |
| `/meeting invite` | `user`* | Lets a user into a locked room |
| `/meeting uninvite` | `user`* | Removes that access |
## Moderation
Each subcommand checks the Discord permission in its "Needs" column.
| Command | Options | Needs | What it does |
| --- | --- | --- | --- |
| `/moderation purge` | `amount`* (1 to 100) | Manage Messages | Deletes recent messages in the channel |
| `/moderation timeout` | `user`*, `duration`* (`10m`, `1h`, `2h30m`, up to 28d), `reason` | Moderate Members | Times a member out |
| `/moderation untimeout` | `user`*, `reason` | Moderate Members | Removes a timeout |
| `/moderation kick` | `user`*, `reason` | Kick Members | Kicks a member |
| `/moderation ban` | `user`*, `delete_days` (0 to 7), `reason` | Ban Members | Bans a member |
| `/moderation unban` | `user_id`*, `reason` | Ban Members | Unbans by ID |
| `/moderation slowmode` | `channel`*, `seconds`* (0 to 21600) | Manage Channels | Sets slowmode, 0 turns it off |
| `/moderation bans` | | Ban Members | Lists banned users, with their IDs |
| `/moderation timeouts` | | Moderate Members | Lists members who are timed out now |
## Timezone and scheduling
Anyone can use these.
| Command | Options | What it does |
| --- | --- | --- |
| `/timezone set` | `zone`* (IANA name, such as `Europe/Lisbon`) | Saves your timezone |
| `/timezone show` | | Shows it |
| `/schedule create` | | Opens a form (date, time, description) to request a session with a member |
| `/schedule list` | | Your upcoming sessions |
| `/schedule reschedule` | `id`* (from `/schedule list`), `datetime`* (UTC, `2006-01-02 15:04`) | Proposes a new time |
## Projects
| Command | Needs | What it does |
| --- | --- | --- |
| `/projects list` | | Active projects with creators and helpers |
| `/projects create` | Manage Server | Opens a form to create a project |
| `/projects add-helper` | Manage Server | Adds a helper to a project |
| `/projects close` | Manage Server | Closes a project |
## Server setup (`/config`)
Every subcommand needs **Manage Server**.
| Command | Options | What it does |
| --- | --- | --- |
| `/config setwelcomechannel` | `channel`* | Where welcome messages go |
| `/config setwelcomemessage` | `message`* | Welcome template. `{user}` is a mention, `{server}` the server name |
| `/config setwelcomedm` | `message`* | The welcome DM template |
| `/config setwelcomegif` | `url`* | Image or GIF for the welcome embed |
| `/config setdefaultrole` | `role`* | Role given on join |
| `/config setlogchannel` | `channel`* | Where logs go |
| `/config enablelogging` | | Turns logging on |
| `/config disablelogging` | | Turns it off |
| `/config view` | | Shows the welcome, default role, logging and Twitch settings |
| `/config clear` | `setting`* (welcome-channel, welcome-message, welcome-dm, welcome-gif, default-role, log-channel) | Clears one |
| `/config toggletwitch` | `enabled`* | Turns Twitch live notifications on or off |
| `/config streamers` | | Lists the watched streamers |
| `/config beta-features` | `enabled` | Lets testers use beta features here. Only the **server owner** can change it. Leave out `enabled` to see the state |
| `/config addstreamer` | `username`* | Adds a Twitch streamer to watch |
| `/config removestreamer` | `username`* | Removes one |
| `/config settwitchnotificationchannel` | `channel`* | Where live alerts go |
## Tickets
| Command | Options | Needs | What it does |
| --- | --- | --- | --- |
| `/tickets setup` | `channel`*, `log-channel`, `staff-role` | Manage Server | Where tickets open and where closed ones are logged. `staff-role` creates a Support category if there are none yet |
| `/tickets category add` | `name`*, `staff-role`, `emoji`, `description` | Manage Server | Adds a category to the panel's dropdown |
| `/tickets category remove` | `name`* | Manage Server | Removes a category |
| `/tickets category list` | | Manage Server | Lists categories |
| `/tickets category edit` | `name`*, `new-name`, `staff-role`, `clear-staff-role`, `emoji`, `description` | Manage Server | Changes a category (`-` removes the emoji or description) |
| `/tickets panel` | | Manage Server | Posts the panel, or updates it after changing categories |
| `/tickets settings` | `enabled`, `panel-title`, `panel-description`, `max-open` | Manage Server | Shows the settings, or changes the ones you give |
| `/tickets list` | `status` (open or closed) | Manage Server | Lists recent tickets |
| `/ticket add` | `user`* | The opener or staff | Adds someone to the ticket |
| `/ticket remove` | `user`* | Staff | Removes someone |
| `/ticket claim` | | Staff | Takes the ticket |
| `/ticket close` | `reason` | The opener or staff | Closes it and posts a transcript |
## Security
All of these are hidden from members without Manage Server (and `/lockdown` from those without Manage Channels), but **hiding is not the check**. The handlers check again, and some need the **server owner or someone on the trusted list** whatever Discord permissions a person has.
In this table "Manage Server" also lets Administrators and trusted members through.
| Command | Options | Needs | What it does |
| --- | --- | --- | --- |
| `/security status` | | Manage Server | What is on, and who is trusted |
| `/security toggle` | `feature`* (Join Gate, Raid mode, Anti-nuke, Heat), `on`* | Manage Server to turn on; owner or trusted to turn off | Turns a protection on or off |
| `/security alerts` | `channel`*, `role` | Owner or trusted | Alert channel and the role to ping |
| `/security quarantine-role` | `role` | Owner or trusted | Role given to quarantined members (empty for none) |
| `/security trust add` | `user` or `role` | Owner only | Exempts a user or role from anti-nuke |
| `/security trust remove` | `user` or `role` | Owner only | Removes that exemption |
| `/security quarantined` | | Manage Server | Lists quarantined members |
| `/security release` | `user`* | Owner or trusted | Releases a member and gives their roles back |
| `/security end-raid` | | Owner or trusted | Ends raid mode now |
| `/security settings` | | Manage Server | Shows every setting |
| `/security history` | | Manage Server | Shows the latest security events |
| `/security joingate check` | `check`* (no-avatar, new-account, invite-in-name, blocked-names, unverified-bot, unauthorized-bot), `action`* | Owner or trusted | What happens when a check catches a new member |
| `/security joingate account-age` | `days`* (1 to 365) | Owner or trusted | How old an account must be |
| `/security words add`, `remove` | `list`* (username or chat), `word`* | Owner or trusted | Blocked words for new members' names (Join Gate) or messages (heat) |
| `/security words list` | `list`* | Manage Server | Shows a list |
| `/security raid` | `join-count`, `join-seconds`, `action`, `pause-invites`, `quiet-minutes` | Owner or trusted | Tunes raid mode |
| `/security antinuke set` | `window-seconds`, `lock-server`, `auto-restore` | Owner or trusted | Tunes anti-nuke |
| `/security antinuke limit` | `action`*, `count`* (0 to 100) | Owner or trusted | How many times someone may do an action in the window (0: never) |
| `/security heat` | `strictness`, `action`, `timeout-minutes`, `escalate`, `panic-members`, `mention-lockdown` | Owner or trusted | Tunes the spam heat system |
| `/security alert-dms` | `on`* | Owner or trusted | DM critical alerts to the owner and trusted users |
| `/security snapshot` | | Manage Server | Saves roles and channels |
| `/security restore` | | Owner or trusted | Recreates deleted roles and channels from the latest snapshot |
| `/lockdown channel` | `channel` (default: this one) | Manage Channels | Locks a channel |
| `/lockdown server` | | Manage Channels | Locks every channel |
| `/lockdown joins` | `action`* (Kick or Ban) | Manage Channels | Kicks or bans new members until unlocked |
| `/unlock channel` | `channel` | Owner or trusted | Unlocks a channel |
| `/unlock server` | | Owner or trusted | Unlocks every channel |
| `/unlock joins` | | Owner or trusted | Lets people join again |
## Beta
| Command | Needs | What it does |
| --- | --- | --- |
| `/beta status` | The bot's owner, **in a DM with the bot** | Shows how beta access is set up |
| `/beta set` | The bot's owner, in a DM | `server-id`* and `role-id`*: chooses the beta server and the Beta Tester role |
| `/beta off` | The bot's owner, in a DM | Turns beta features off for everyone |
| `/beta servers` | The bot's owner, in a DM | Lists the servers that opted in |
| `/beta remove-server` | The bot's owner, in a DM | `server-id`*: takes a server out of the beta |
`/beta` is registered globally but only works in a direct message with the bot, so it is in no server's menu. A server opts itself in with `/config beta-features` (its owner). Other beta commands appear only in the beta server and in servers that opted in, and only testers can run them. See [Beta features](beta-features.md).
+57
View File
@@ -0,0 +1,57 @@
# Database
The bot uses PostgreSQL through `database/sql` with the pgx driver. All SQL lives in repos under `internal/db/repos`.
## Who owns the schema
**`schema.sql`** in this repository is the schema. It describes every table the bot reads and writes, and it is enough to run the bot. It is safe to run more than once (`CREATE TABLE IF NOT EXISTS`). The bot never runs migrations itself.
The hosted Velox also has a proprietary dashboard API that keeps its own migrations for the same tables. That is the maintainer's concern: if your change adds or alters a table, update `schema.sql` and say so in your pull request, and the maintainer ports it. You never need the API to develop or run the bot.
`schema.sql` also creates the `NOTIFY` triggers on the three `*_commands` tables (see [below](#dashboard-to-bot-settings-and-requests)), so anything that inserts a request wakes the bot, with no `NOTIFY` of its own.
## Tables
| Area | Tables | Notes |
| --- | --- | --- |
| Leveling | `levels`, `levelsettings`, `levelrewards`, `levelup` | XP and level per member, settings, role rewards, the level-up channel |
| Welcome | `welcome`, `defaultrole` | Welcome channel, templates, GIF, default role |
| Logging | `logsettings` | Log channel and on/off |
| Twitch | `twitch`, `twitch_config` | Streamers and the notification channel |
| Fun | `rps` | Rock-paper-scissors stats |
| Meeting rooms | `meeting_lobbies`, `meeting_temp_channels`, `meeting_settings` | Lobbies (10 per server, enforced by a trigger), the temporary rooms and who created them. `meeting_settings.lobby_channel_id` is the old single lobby column and is no longer read |
| Projects | `projects`, `project_members` | |
| Scheduling | `schedules`, `schedule_messages`, `user_settings` | Sessions, the DM messages to update, and each member's timezone |
| Music | `music_settings`, `music_now_playing`, `music_queue`, `music_commands` | State a dashboard can show, plus requests to the bot |
| Tickets | `ticket_settings`, `ticket_categories`, `tickets`, `ticket_commands` | |
| Security | `security_settings`, `security_trusted`, `security_quarantines`, `security_lockdowns`, `security_raids`, `security_raid_caught`, `security_snapshots`, `security_events`, `security_commands` | Settings, who is trusted, quarantines (with the roles to give back), locked channels (with the permission to restore), raids in progress, snapshots, an event history, and dashboard requests |
| Beta | `beta_settings`, `beta_guilds` | `beta_settings` is one row: the beta server and the Beta Tester role. `beta_guilds` lists servers whose owner opted in to beta features. Both are written by the dashboard and read by the bot. `beta_registered` is the bot's own note of where it registered beta commands |
Discord IDs are `BIGINT` (snowflakes fit in 64 bits). In Go they are `int64`; Discord's own API gives them to you as strings, so convert at the edge.
## Dashboard to bot: settings and requests
There are two kinds of traffic from a dashboard to the bot, and the difference matters.
**Settings.** A dashboard writes a row, and the bot reads it when it next needs it. Nothing wakes the bot up. Hot paths cache settings for a short time. The bot's beta settings are polled every 30 seconds.
**Requests that need the bot to act.** `music_commands`, `ticket_commands` and `security_commands` work as a small queue:
1. A dashboard inserts a row (`command_type`, a JSON `payload`, `requested_by`, `processed_at` empty).
2. A trigger in the database runs `pg_notify('<table>', id)`.
3. The bot holds one connection that ran `LISTEN <table>`. It wakes, loads **every** unprocessed row, carries each out, and sets `processed_at`.
Because the bot loads all unprocessed rows (also when it starts), nothing is lost if it was down when a request arrived. A command that fails is logged and marked processed anyway, since retrying would fail the same way.
Every listener **validates the request again**. The dashboard should check that the requester is allowed, and the bot checks too, because it should not trust a row just because it exists. The listeners live in `internal/music/listener.go`, `internal/tickets/listener.go` and `internal/security/listener.go`, and each reconnects after 10 seconds if its connection drops.
## Changing the schema
1. Update `schema.sql`. Use `CREATE TABLE IF NOT EXISTS`, and for a new column on an existing table also add `ALTER TABLE ... ADD COLUMN IF NOT EXISTS ...` right after it, so servers set up earlier get the column when they run the file again. Avoid destructive changes: a bot that is a version behind (or a tool reading the same tables) must keep working against the new schema for a moment. Add a column or table first, and remove old ones in a later release.
2. Add or change the repo method in `internal/db/repos/<area>repo`.
3. If something outside the bot must make it do something, add a `command_type` to the `CHECK` in the right `*_commands` table and handle it in the listener.
4. In your pull request, say that the schema changed and whether an existing table is affected, so the maintainer can port the change to the dashboard's migrations.
## Connection settings
`internal/db/db.go` opens the pool with up to 100 open and 10 idle connections, and recycles them after an hour. The listeners use their own separate connections, because `LISTEN` needs one that stays open.
+56
View File
@@ -0,0 +1,56 @@
# Deployment
## Docker
The `Dockerfile` is a two-stage build: it compiles a static binary with Go, then copies it into a small Alpine image (with CA certificates and timezone data, which `/timezone` and scheduling need).
```bash
docker build -t velox-bot .
docker run --env-file .env velox-bot
```
The container reads its configuration from environment variables, exactly like a local run. See [Getting started](getting-started.md#2-configure-the-environment).
## Docker Compose
`docker-compose.yml` defines two services:
- `db`: PostgreSQL 16 with a named volume (`velox_pgdata`) and a health check.
- `bot`: the bot, built from this directory, started after the database is healthy. It takes `.env` through `env_file`, and defaults `DB_HOST` to the `db` service and `LAVALINK_HOST` to `ws://lavalink:2333` if you have not set them.
```bash
docker compose up -d # database and bot
docker compose logs -f bot
```
Compose does not include Lavalink. Run it separately (or add a service) if you want music.
Change the default database password (`velox_pwd`) before exposing PostgreSQL to anything other than your own machine, and remove the published `5432` port if only the bot needs it.
## Database changes
The bot does not run migrations. When a release adds tables, load `schema.sql` again before restarting the bot (it only creates what is missing, and is safe to repeat). A release that changes an existing table says so in its notes.
## Updating
```bash
git pull
docker compose build bot
docker compose up -d bot
```
Slash commands are re-registered on every start, so new and changed commands appear after a restart. Commands you removed from the code are not deleted from Discord automatically, except for the beta server (see [Beta features](beta-features.md)).
## Backups
All state is in PostgreSQL. Back it up with `pg_dump`:
```bash
pg_dump "postgres://velox:velox_pwd@localhost:5432/velox" > velox-backup.sql
```
Raid mode, quarantines, lockdowns and ticket state live in the database, so the bot picks them up again after a restart.
## Shutting down
Send `SIGINT` or `SIGTERM` (Docker does on `docker stop`). Slash commands stay registered in Discord while the bot is down, and are registered again (updated in place) on the next start.
+300
View File
@@ -0,0 +1,300 @@
# Development guide
How to change the bot and how to add to it. Read [Architecture](architecture.md) first if you have not: it explains the layers this page keeps referring to.
- [Daily workflow](#daily-workflow)
- [Add a simple command](#add-a-simple-command)
- [Add a subcommand](#add-a-subcommand)
- [Command options and permissions](#command-options-and-permissions)
- [Buttons, select menus and forms](#buttons-select-menus-and-forms)
- [Add a feature that stores settings](#add-a-feature-that-stores-settings)
- [React to a gateway event](#react-to-a-gateway-event)
- [Add a background job](#add-a-background-job)
- [Add an environment variable](#add-an-environment-variable)
- [Make a command beta](#make-a-command-beta)
- [Testing](#testing)
- [Style and safety rules](#style-and-safety-rules)
- [Checklist before a pull request](#checklist-before-a-pull-request)
## Daily workflow
```bash
docker compose up -d db # PostgreSQL
air # rebuild and restart on every change
```
Set `GUILD_ID` to a test server in `.env`, so commands update within seconds. Before pushing:
```bash
gofmt -l .
go build ./... && go vet ./... && go test ./...
```
Some older files are not gofmt-clean. Format the files you touch, and leave the others alone so reviews stay readable.
## Add a simple command
A command is a definition (what Discord shows) plus a handler (what runs). Each feature has a package under `internal/commands/<feature>`, with this shape:
```
internal/commands/fun/
registry.go re-exports the commands and handlers of the feature
public/ the definitions and handlers
ping.go
shared/ helpers used by several commands of the feature
```
Example: a `/hello` command in the `fun` feature.
**1. The definition and handler**, in `internal/commands/fun/public/hello.go`:
```go
package public
import "github.com/bwmarrin/discordgo"
var Hello = &discordgo.ApplicationCommand{
Name: "hello",
Description: "Say hello",
}
func HelloHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Content: "Hello!"},
})
}
```
**2. Re-export it**, in `internal/commands/fun/registry.go`:
```go
var Hello *discordgo.ApplicationCommand = public.Hello
func HelloHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.HelloHandler(s, i) }
```
**3. Register it**, in `internal/commands/commands.go`: add `fun.Hello` to `AllCommands`, and `"hello": fun.HelloHandler` to the `handlers` map. The key is the command's name. A command that is in `AllCommands` but not in `handlers` is shown in Discord and then does nothing.
**4. Restart the bot.** It re-registers all commands on start.
**5. Document it:** add it to `/help` (`internal/commands/help/help.go`) and to the [Command reference](commands.md).
Names must be lowercase, up to 32 characters, and unique. Descriptions are required and limited to 100 characters.
For an entirely new feature, create a new package with the same shape, and import it in `commands.go`.
## Add a subcommand
A command with subcommands (like `/meeting`) lists them in `Options`, and its handler switches on the name of the first option. Add the subcommand to the definition:
```go
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "lobbies",
Description: "List this server's meeting lobbies",
},
```
and a case to the handler's switch:
```go
switch data.Options[0].Name {
case "lobbies":
handleListLobbies(s, i)
// ...
default:
shared.RespondEphemeral(s, i, "Unknown subcommand.")
}
```
Keep one `handleX` function per subcommand. For a group (`/tickets category add`), the first option is the group and its first option is the subcommand.
## Command options and permissions
**Options** go in the definition's `Options` (or in a subcommand's). Types are `String`, `Integer`, `Boolean`, `User`, `Channel`, `Role`, `Number`, and others. A channel option can be limited with `ChannelTypes`. A string can offer fixed `Choices`.
Inside a subcommand, `shared.SubcommandOptionMap(i)` (in the meeting, level and other `shared` packages) turns the options into a map by name:
```go
opts := shared.SubcommandOptionMap(i)
channel := opts["channel"].ChannelValue(s) // *discordgo.Channel
```
**Where a command may be used.** `Contexts` lists where Discord offers it (`InteractionContextGuild`, `InteractionContextBotDM`, `InteractionContextPrivateChannel`). A server-only command should also refuse politely if `i.GuildID == ""`: the shared packages have `RequireGuild` for this.
**Who may use it.** There are two layers, and you need both:
1. `DefaultMemberPermissions` on the definition only decides who **sees** the command in Discord's menu. Server admins can change it in their settings, so it is not security.
2. The handler must check again, using `i.Member.Permissions`. The shared packages have helpers such as `RequireManageGuild`. Moderation uses `hasPerm(i, discordgo.PermissionKickMembers)` and so on.
For anything where a mistake hurts (security settings, anything destructive), check the **owner or trusted list** as well, as `internal/commands/security` does with `allowedOrTrusted`. Do not rely on Discord's permissions alone.
**Responses.**
- Answer within three seconds. If a command takes longer, respond with `InteractionResponseDeferredChannelMessageWithSource` first, then edit the response with `InteractionResponseEdit`.
- Use `Flags: discordgo.MessageFlagsEphemeral` for replies only the user should see (errors, settings). `shared.RespondEphemeral` does this.
- When the message contains user-controlled text, set `AllowedMentions: &discordgo.MessageAllowedMentions{}` so it cannot ping anyone.
## Buttons, select menus and forms
Components and modals carry a **custom ID**, and the dispatcher routes them by prefix (`internal/commands/commands.go`, `HandleInteraction`). To add one to a feature:
1. Use the feature's prefix when you build the component: `CustomID: "projects:close:" + id`. Put whatever you need in the ID after the prefix, split with `:`.
2. The dispatcher already sends `music:`, `schedule:`, `projects:`, `tickets:` and `security:` to that feature's `HandleComponent`, and `schedule:`, `projects:`, `tickets:` modals to its `HandleModalSubmit`.
3. In `HandleComponent`, parse the rest of the ID, check permissions **again** (the button may be clicked by anyone who can see the message), and respond.
For a **new prefix**, add a case to the `switch` in `HandleInteraction`, and write `HandleComponent` and/or `HandleModalSubmit` in your feature.
Custom IDs are limited to 100 characters, and a modal can have up to five inputs.
Never trust the contents of a custom ID. A user cannot edit it, but old messages stay around with old IDs, and IDs may refer to things that no longer exist.
## Add a feature that stores settings
The usual path is table, repo, service, command. The meeting-room lobbies are a complete small example (`/meeting add-lobby`).
**1. The table.** Add it to `schema.sql` (see [Database](database.md#changing-the-schema)).
**2. The repo**, in `internal/db/repos/<area>repo/repo.go`. SQL only, returning plain Go values:
```go
func (r *Repo) ListMeetingLobbies(ctx context.Context, guildID int64) ([]int64, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT channel_id FROM meeting_lobbies WHERE guild_id = $1 ORDER BY created_at`, guildID)
// ...
}
```
Always pass values as parameters (`$1`), never build SQL with string formatting.
**3. The service**, in `internal/db/services/<area>/service.go`. It wraps the repo and holds the rules (limits, defaults, validation):
```go
type Service struct{ settings *settingsrepo.Repo }
func New(settings *settingsrepo.Repo) *Service { return &Service{settings: settings} }
```
**4. Wire it up.** Add a field to `services.Services` and the constructor in `internal/db/services/services.go`, and build the repo and service in `main.go` next to the others.
**5. Use it from the command**, through `services.Global`:
```go
if services.Global == nil || services.Global.Meeting == nil {
shared.RespondEphemeral(s, i, "Meeting service is not available.")
return
}
added, err := services.Global.Meeting.AddLobby(ctx, guildID, channelID)
```
**6. Enforce limits in the database when you can.** The 10-lobby limit is a trigger, so the bot and anything else writing to the table cannot disagree and two simultaneous requests cannot both slip through.
**7. Give it commands.** Every setting must be visible and changeable from Discord (a slash command to set it, and a way to see it). The bot has to work completely without a dashboard, so never add a setting that only a dashboard or SQL can change. Put the options in the command definition, and `internal/commands/limits_test.go` will tell you if it goes over Discord's limits.
**8. Default to off.** A module that does something to a server without being asked (posts messages, moderates, grants roles) must start disabled and be turned on by an admin.
## React to a gateway event
1. Write the function in `internal/events/`, taking the session, the event and the services:
```go
func HandleChannelDelete(_ *discordgo.Session, c *discordgo.ChannelDelete, svc *services.Services) { ... }
```
2. Register it in `bot.Start()` (`internal/bot/bot.go`):
```go
b.Session.AddHandler(func(s *discordgo.Session, c *discordgo.ChannelDelete) {
events.HandleChannelDelete(s, c, b.Services)
})
```
3. Check that the **intent** for that event is enabled in `NewBot`. Events from an intent you did not ask for never arrive. Privileged intents must also be enabled in the developer portal.
Handlers run concurrently on goroutines. Do not share unsynchronised state, and do not block: slow work belongs in its own goroutine.
If the event is something security cares about (joins, messages, audit log), look at how `bot.go` calls the security engine **before** your handler.
## Add a background job
Follow `StartScheduleReminderLoop` in `internal/events/schedule_reminders.go`: a function that returns immediately and starts a goroutine with a ticker.
```go
func StartMyLoop(s *discordgo.Session, svc *services.Services) {
if svc == nil || svc.Thing == nil || s == nil {
return
}
go func() {
time.Sleep(10 * time.Second) // let the bot finish starting
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for range ticker.C {
// check, act, log errors, never panic
}
}()
}
```
Call it at the end of `bot.Start()`. Log errors instead of returning them, and make one failing server not stop the loop for the others.
## Add an environment variable
1. Add a field to `Config` and read it in `LoadConfig()` (`internal/config/config.go`). Return an error if the bot cannot work without it.
2. Document it in [Getting started](getting-started.md#2-configure-the-environment).
3. Pass it where it is needed from `main.go`.
Never log a secret, and never put one in a message to a user.
Use an environment variable for deployment settings (tokens, hosts). Settings an admin or owner should change at runtime belong in the database instead (set with a command, or by a dashboard). That is how the beta settings work.
## Make a command beta
Register it with `commands.RegisterBeta` instead of adding it to `AllCommands` and `handlers`. See [Beta features](beta-features.md).
## Testing
```bash
go test ./... # unit tests, no database needed
go test -race ./... # recommended before a pull request
```
Where the code allows it, the Discord and database calls go through small interfaces, so flows can be tested with fakes. `internal/tickets` and `internal/security` are the models: look at their `fakes_test.go`.
Tests that need a real PostgreSQL are behind the `integration` build tag and skip themselves when their environment variable is missing:
| Package | Variable |
| --- | --- |
| `internal/db/repos/settingsrepo` | `TEST_DB` |
| `internal/db/repos/ticketrepo`, `internal/tickets` | `TICKETS_TEST_DB` |
| `internal/db/repos/securityrepo` | `SECURITY_TEST_DB` |
```bash
TEST_DB="postgres://velox:velox_pwd@localhost:5432/velox?sslmode=disable" \
go test -tags integration ./internal/db/repos/settingsrepo
```
Use a throwaway database for these, not one with real data. The tables must already exist (load `schema.sql`).
Good things to test: permission checks (does the wrong person get refused?), limits, anything that parses user input, and "what if the service or the database fails".
## Style and safety rules
- **One feature per package, SQL only in repos, rules in services.** Commands never contain SQL.
- **Match the code around you**: naming, comment density, error handling. Comments explain *why*, not *what*.
- **Fail closed.** If you cannot tell whether someone is allowed, they are not.
- **Validate everything that comes from a user or from another program writing to the database**: option values, custom IDs, `payload` JSON in command rows.
- **Escape user text** in messages, and set `AllowedMentions` so it cannot ping.
- **Bound everything per server**: caches, lists, loops. One server must not be able to use unlimited memory.
- **Do not leak internals** to users: reply with a short message, log the detail.
- **Idempotent writes**: use `ON CONFLICT` for "add" operations, so double clicks and retries are harmless.
- Handle the bot being **restarted at any time**. State that must survive (raid mode, quarantines) lives in the database.
## Checklist before a pull request
- [ ] `gofmt` on the files you touched, `go build ./...`, `go vet ./...`, `go test -race ./...`
- [ ] Commands: in `AllCommands` and `handlers`, permission check in the handler, ephemeral errors
- [ ] New table or column: in `schema.sql`, and mentioned in the pull request
- [ ] Module that acts on a server: off by default
- [ ] `/help`, [Command reference](commands.md) and [Features](features.md) updated
- [ ] No secrets, tokens or personal IDs in code, logs or tests
+120
View File
@@ -0,0 +1,120 @@
# Features
What each module does and how it behaves. For the exact options of every command, see the [Command reference](commands.md). To change how a module works, see the [Development guide](development.md).
Unless a section says otherwise, a module is **off** in a new server and a server admin turns it on.
## Security
Anti-raid and anti-nuke, modelled on Wick. Code: `internal/security`, commands in `internal/commands/security`.
**Join Gate** checks every new member: no avatar, account too new, invite links or blocked words in the name, unverified bots. Each check has its own action. It also removes bots added by anyone who is not trusted.
**Raid mode** starts when many members join in a short time. Raiders are timed out, kicked or banned, invites can be paused, staff are alerted, and raid mode ends after a quiet period or when staff end it with `/security end-raid`. It survives a bot restart: the quiet timer carries on and the summary still lists everyone caught.
**Anti-nuke** counts destructive actions per person from the audit log: deleting channels or roles, mass bans and kicks, creating webhooks, granting dangerous permissions. Someone who is not the owner or trusted and goes over a limit is **quarantined**: their roles are removed and saved, and they are timed out. `/security release` gives every role back.
**Lockdown** (`/lockdown`, `/unlock`) locks one channel, every channel, or joins. Unlocking puts back exactly the permission overwrite that was there before.
**Snapshots** save the server's roles and channels. They are taken every 6 hours while anti-nuke is on (the last three are kept) and on request with `/security snapshot`. `/security restore` recreates deleted roles and channels and reverts dangerous permission changes. It can also run automatically after a stopped nuke.
**Heat** is the anti-spam system. Each member has a score that rises with messages and cools over time. Spam, repeats, mass mentions and invite links max it, which deletes the message and times the member out (the timeout doubles for repeat offences). A wave of spammers turns on *heat panic* (newcomers are timed out on sight for 10 minutes), and a mention flood can lock the server. Members with Manage Messages and trusted members are exempt.
**Alerts** go to a channel you choose, and critical ones (raids, stopped nukes, restores, spam waves, removed bots) are also DMed to the owner and trusted users, because the alert channel may be the first thing a nuker deletes. One setting turns the DMs off.
Rules that hold everywhere in this module:
- Turning protection off, changing limits, releasing a quarantine and unlocking need the **server owner or someone on the trusted list**. Editing the trusted list needs the owner. Discord's own command permissions are never relied on, because admins can change them.
- The owner and the bot are never punished.
- Roles that are configured (such as the quarantine role) are checked when they are used, not only when saved. A quarantine role that gained dangerous permissions is not assigned.
- Messages ping only the configured alert role, and names are escaped.
Every threshold, filter and action is a command: `/security settings` shows them all, and `/security joingate`, `words`, `raid`, `antinuke`, `heat` and `alert-dms` change them (owner or trusted users only). `/security history` shows what the system has done. The bot's role must be above the roles it protects against: it can only quarantine members whose highest role is below its own.
## Tickets
Support tickets in private threads. Code: `internal/tickets`, commands in `internal/commands/tickets`.
1. An admin runs `/tickets setup`, adds categories with `/tickets category add` (each with its own staff role), and posts the panel with `/tickets panel`. `/tickets settings` changes the panel text and the open ticket limit and turns tickets on or off, `/tickets category edit` changes a category, and `/tickets list` shows tickets.
2. The panel has a category dropdown and a **Create ticket** button. A short form asks what the ticket is about.
3. A **private thread** is created in the ticket channel. The opener and the category's staff role can see it.
4. Staff can `/ticket claim`. Anyone involved can `/ticket add` someone, staff can `/ticket remove`, and the opener or staff can `/ticket close [reason]`.
5. Closing locks and archives the thread and posts a **transcript** to the log channel.
The bot needs View Channel, Send Messages, Embed Links, Create Private Threads, Send Messages in Threads and Manage Threads in the ticket channel, and Attach Files in the log channel. Give the staff role Manage Threads there too, so staff see every ticket.
The flows go through small interfaces for Discord and the database, so they are tested without either. The slash commands and buttons only translate interactions into those calls.
## Moderation
`/moderation` with `purge`, `timeout`, `kick`, `ban`, `unban`, `untimeout` and `slowmode`. Each subcommand checks the matching Discord permission in the handler (Manage Messages, Moderate Members, Kick Members, Ban Members, Manage Channels). Durations accept `10m`, `1h`, `2h30m` and so on, up to 28 days. Actions are written to the log channel if logging is on.
## Logging
When enabled with `/config enablelogging` and a channel set with `/config setlogchannel`, the bot logs edited and deleted messages, joins and leaves, member and role updates, bans and unbans, and moderation actions. Code: `internal/events/logging.go` and `internal/modlog`.
## Leveling
Opt in per server with `/slvl toggle`. Code: `internal/db/services/level` (the rules) and `internal/events/event_handlers.go` (the message handler).
- Every message may give 1 to 3 XP. Below level 5 every message counts. From level 5 on, a message counts with a chance of 1 in `level / 4`, so leveling slows down.
- 100 XP makes a level, and XP resets to 0.
- A level-up posts the level-up message (set with `/slvl set-message`, variables `{user}` and `{level}`) in the channel chosen with `/slvl set-channel`, or in the channel of the message.
- `/slvl set-reward` gives a role at a level. `/rank` draws a rank card (`internal/rankcard`), `/leaderboard` shows the top 10 and `/rewards` lists role rewards.
## Music
Lavalink-powered playback. Code: `internal/music`, commands in `internal/commands/music`.
- `/play` takes a name or a URL, `/queue` shows the queue, `/volume` sets 0 to 150 percent. These need a role called **DJ**.
- The now-playing message has buttons for playback and repeat. Buttons also check for the DJ role.
- `/music toggle` (Manage Server) turns music on or off in a server. `/music skip`, `pause`, `resume`, `stop`, `repeat`, `remove` and `move` control playback and the queue (DJ role).
- The queue and now-playing state are kept in the database, and playback can also be controlled by writing to the `music_commands` table. The hosted Velox dashboard uses this (see [Database](database.md)); you never need it, the commands above do the same.
- Music needs a Lavalink server. Without `LAVALINK_HOST` the rest of the bot works and music does not.
## Meeting rooms
Join a **lobby** voice channel and get your own temporary room. Code: `internal/events/meeting_voice.go`, commands in `internal/commands/meeting`.
- A server can have up to **10 lobbies** (`/meeting add-lobby`, `remove-lobby`, `lobbies`). The limit is enforced by a database trigger, so the bot and the dashboard obey the same rule.
- When someone joins a lobby, the bot creates a voice channel in the same category with the lobby's user limit and bitrate, named after the lobby and the time, and moves the member in.
- When the temporary room is empty, it is deleted.
- If a lobby channel is deleted in Discord, it is dropped from the lobbies.
- `/meeting lock`, `lock-private` (also hides the room), `unlock`, `invite` and `uninvite` act on the room you are in. Every `/meeting` subcommand, including these, currently needs **Manage Server**.
## Scheduling and timezones
1:1 sessions between two members. Code: `internal/commands/schedule`, `internal/db/services/schedule`, reminders in `internal/events/schedule_reminders.go`.
- Each member sets a timezone with `/timezone set` (an IANA name such as `Europe/Lisbon`).
- `/schedule create` opens a form (date, time in your timezone, optional description) and DMs the other member a request with **Accept**, **Decline** and **Propose different time** buttons.
- `/schedule list` shows your upcoming sessions, and `/schedule reschedule` proposes a new time (in UTC, `2006-01-02 15:04`). The other side can accept or decline the proposal.
- Every minute, a loop DMs the participants of sessions starting within 10 minutes.
## Projects
A simple list of ongoing projects. `/projects create` opens a form (name, optional description), `/projects list` shows active projects with creators and helpers, `/projects add-helper` and `/projects close` manage them. Creating, adding helpers and closing need Manage Server.
## Welcome messages and default role
Set up with `/config` (Manage Server). Code: `internal/events/welcome.go`.
- A welcome message in a channel, and an optional DM, both templates where `{user}` becomes a mention and `{server}` the server name. An optional GIF or image URL goes in the welcome embed.
- A default role is granted when a member joins.
- Bots are skipped, and members the security engine removes get nothing.
## Twitch alerts
`/config addstreamer`, `removestreamer` and `settwitchnotificationchannel` (Manage Server). Every 30 seconds a loop checks each configured streamer and posts in the notification channel when one goes live. Code: `internal/events/twitch_live.go`. It needs `TWITCH_CLIENT_ID`.
## Onboarding
When the bot is added to a server, it applies safe defaults (modules off) and DMs setup instructions to the person who invited it, falling back to the server owner. Code: `internal/events/onboarding.go`.
## Fun
`/ping`, `/joke [type]`, `/coinflip`, `/dice` (expressions like `d20`, `2d20+1`, `2#d20+1`, parsed in `internal/diceexpr`), and `/rps` with `/rpsstats` and `/rpsleaderboard`.
## Help
`/help` DMs a command reference. The text is hand-written in `internal/commands/help/help.go`, so update it when you add or change a command.
+122
View File
@@ -0,0 +1,122 @@
# Getting started
This page takes you from nothing to a bot running on your machine.
## Requirements
- **Go**: the version in `go.mod` (the Dockerfile builds with the same one).
- **PostgreSQL 16 or newer**: the included `docker-compose.yml` starts one for you.
- **A Discord application** with a bot user (see below).
- Optional: [Air](https://github.com/air-verse/air) for live reload, [Just](https://github.com/casey/just) for shortcuts, and a [Lavalink](https://github.com/lavalink-devs/Lavalink) server if you want music.
## 1. Create the Discord application
1. Open the [Discord developer portal](https://discord.com/developers/applications) and create an application. Copy its **Application ID**: this is `APP_ID`.
2. Under **Bot**, create the bot user and copy its token: this is `BOT_TOKEN`. Keep it secret.
3. Under **Bot**, switch on these **privileged gateway intents**: **Server Members Intent** (welcome messages, security) and **Message Content Intent** (leveling and spam detection). The bot also uses the non-privileged Guilds, Guild Moderation (bans and the audit log), Guild Messages, Guild Voice States and Direct Messages intents. You do not need to enable those by hand.
4. Invite the bot with the `bot` and `applications.commands` scopes. It needs these permissions, depending on which modules you use:
| Permission | Used by |
| --- | --- |
| View Channels, Send Messages, Embed Links, Attach Files | everything that posts, ticket transcripts |
| Read Message History, Manage Messages | moderation purge, spam heat |
| Use External Emojis | embeds that use custom emojis |
| Manage Roles | default role, level rewards, quarantine |
| Manage Channels | lockdown, slowmode, meeting rooms, snapshot restore |
| Manage Server | pausing invites during a raid |
| Kick Members, Ban Members, Moderate Members | moderation commands, Join Gate, raid mode, anti-nuke |
| View Audit Log | anti-nuke, unauthorised bot detection |
| Create Private Threads, Send Messages in Threads, Manage Threads | tickets |
| Connect, Speak, Move Members | music, meeting rooms |
The bot's role must sit **above** the roles it manages or protects against. Discord does not let a bot change members whose highest role is higher than its own.
## 2. Configure the environment
The bot reads environment variables, and loads a `.env` file from the working directory if there is one (`internal/config/config.go`).
| Variable | Required | Meaning |
| --- | --- | --- |
| `BOT_TOKEN` | yes | The bot token. |
| `APP_ID` | yes | The application ID. |
| `GUILD_ID` | no | If set, slash commands are registered in this server only, and appear within seconds. If empty they are registered globally, which Discord can take up to an hour to show. Use a test server while developing. |
| `DB_HOST` | yes | A pgx connection string, for example `postgres://velox:velox_pwd@localhost:5432/velox?sslmode=disable`. |
| `TWITCH_CLIENT_ID` | yes | A Twitch client ID, used to check who is live. The bot refuses to start without it, even if you never use Twitch alerts. Any non-empty value works if you do not use them. |
| `LAVALINK_HOST` | no | Lavalink address, for example `ws://localhost:2333`. Leave empty to run without music. |
| `LAVALINK_PASSWORD` | no | Lavalink password. |
A minimal `.env` for local development:
```bash
BOT_TOKEN=your-bot-token
APP_ID=123456789012345678
GUILD_ID=123456789012345678
DB_HOST=postgres://velox:velox_pwd@localhost:5432/velox?sslmode=disable
TWITCH_CLIENT_ID=unused
```
`.env` is ignored by git. Never commit it.
Who the beta testers are is **not** an environment variable. It is stored in the database. See [Beta features](beta-features.md).
## 3. Set up the database
Start PostgreSQL with Compose:
```bash
docker compose up -d db
```
Then load the schema:
```bash
psql "postgres://velox:velox_pwd@localhost:5432/velox?sslmode=disable" -f schema.sql
```
`schema.sql` is written with `CREATE TABLE IF NOT EXISTS`, so running it again is safe. It is the schema of every table the bot uses. Read [Database](database.md) before changing a table.
## 4. Run
```bash
go run .
```
You should see the bot connect, and the slash commands appear in your test server. Type `/ping`.
With live reload:
```bash
air
```
With Just (`Justfile`):
```bash
just up # start PostgreSQL
just start # start PostgreSQL and run Air
just down # stop PostgreSQL
```
## 5. Turn modules on
Nothing is on by default. In your server:
- `/security toggle` to enable Join Gate, raid mode, anti-nuke or heat.
- `/tickets setup`, then `/tickets category add` and `/tickets panel`.
- `/slvl toggle` for leveling.
- `/config setlogchannel` and `/config enablelogging` for logs.
- `/music toggle` for music (needs Lavalink).
- `/config toggletwitch` and `/config addstreamer` for Twitch alerts.
`/security settings`, `/tickets settings`, `/slvl status` and `/config view` show what is set.
The [Features](features.md) page explains each module, and the [Command reference](commands.md) lists every option.
## Optional: music with Lavalink
Music needs a running Lavalink server and `LAVALINK_HOST` / `LAVALINK_PASSWORD`. Without them the bot starts normally and music simply does not work. Members need a role named exactly **DJ** to use `/play`, `/queue` and `/volume`.
## Next steps
- Running it for real: [Deployment](deployment.md).
- Changing or adding things: [Development guide](development.md).
+184
View File
@@ -0,0 +1,184 @@
# Host your own bot
This guide takes you from a clean server to your own Velox running under your own Discord application. It uses Docker Compose, which is the simplest way. For the Discord side in more detail, see [Getting started](getting-started.md). For a short run on your own machine while developing, see that page too.
You will run:
- **The bot** (this repository). It needs PostgreSQL.
- **PostgreSQL**, started by the same Compose file.
- Optionally **Lavalink**, if you want music.
The hosted Velox also has a web dashboard. It is proprietary and not part of this repository, so it is not something you can host, and you do not need it: everything it does is also a command. See [Everything is a command](#everything-is-a-command).
## Before you start
You need:
- A Linux server (or any machine that is always on) with [Docker and Docker Compose](https://docs.docker.com/engine/install/). The bot itself is a small static Go binary and needs little. Lavalink is a Java program and needs noticeably more memory, so size the server for it if you want music.
- A Discord account that can create an application.
- A way to reach the server over SSH, and a firewall that does not expose PostgreSQL.
You do not need a domain name or an open port. The bot only makes outgoing connections to Discord (and to Lavalink and Twitch if you use them).
## 1. Create your Discord application
Follow [step 1 of Getting started](getting-started.md#1-create-the-discord-application). You end up with:
- an **application ID** (`APP_ID`),
- a **bot token** (`BOT_TOKEN`), which is a password: never commit it or paste it anywhere public,
- the **Server Members** and **Message Content** privileged intents switched on.
### The invite link
Invite your bot with this link, replacing `YOUR_APP_ID`:
```
https://discord.com/oauth2/authorize?client_id=YOUR_APP_ID&scope=bot%20applications.commands&permissions=1460577627318
```
The number is the set of permissions the bot uses across all its modules: View Channels, Send Messages, Embed Links, Attach Files, Read Message History, Use External Emojis, Manage Messages, Manage Roles, Manage Channels, Manage Server, Kick Members, Ban Members, Moderate Members, View Audit Log, Create Private Threads, Send Messages in Threads, Manage Threads, Connect, Speak and Move Members. If you never use a module you can leave its permissions out. The [permission table](getting-started.md#1-create-the-discord-application) says which module needs which.
After inviting, drag the bot's role **above** the roles it should manage and the members it should moderate. Discord does not let a bot change anyone whose highest role is above its own.
## 2. Get the code
```bash
git clone <this repository> velox-bot
cd velox-bot
```
## 3. Configure
Create a file called `.env` next to `docker-compose.yml`:
```bash
BOT_TOKEN=paste-your-bot-token
APP_ID=paste-your-application-id
# Register commands in one server (appear at once). Leave empty to register
# them globally, which Discord can take up to an hour to show.
GUILD_ID=paste-a-server-id
# Used for Twitch live alerts. Required to start, even if you never use them
# (any value works then). See "Twitch" below.
TWITCH_CLIENT_ID=unused
```
You do not set `DB_HOST` here: the Compose file points the bot at its own database. **Change the database password**, though. In `docker-compose.yml`, replace `velox_pwd` in two places (the `db` service's `POSTGRES_PASSWORD` and the default `DB_HOST` of the `bot` service), or set `DB_HOST` in `.env` yourself:
```bash
DB_HOST=postgres://velox:A-LONG-RANDOM-PASSWORD@db:5432/velox?sslmode=disable
```
and set the same password for `POSTGRES_PASSWORD`. Then remove the `ports: - "5432:5432"` lines of the `db` service so the database is only reachable from the bot.
`.env` holds secrets. Keep it out of version control (it is already in `.gitignore`) and readable only by you: `chmod 600 .env`.
## 4. Start the database and load the schema
```bash
docker compose up -d db
docker compose exec -T db psql -U velox -d velox < schema.sql
```
The schema file can be run again at any time, it only creates what is missing.
## 5. Start the bot
```bash
docker compose up -d --build bot
docker compose logs -f bot
```
You should see the bot connect and no errors. In your server, type `/ping`. If the commands do not appear, see [Troubleshooting](troubleshooting.md#slash-commands-do-not-appear).
The Compose file restarts the bot automatically (`restart: unless-stopped`), including after a reboot of the server, as long as Docker starts at boot (`sudo systemctl enable docker`).
## 6. Turn modules on
Nothing is on by default. Follow [Turn modules on](getting-started.md#5-turn-modules-on).
## Music (optional)
Music needs a [Lavalink](https://github.com/lavalink-devs/Lavalink) server. Add it to `docker-compose.yml`:
```yaml
lavalink:
image: ghcr.io/lavalink-devs/lavalink:4
container_name: velox-lavalink
restart: unless-stopped
environment:
LAVALINK_SERVER_PASSWORD: ${LAVALINK_PASSWORD}
# Not published: only the bot, on the same Compose network, needs it.
```
and put the password in `.env`:
```bash
LAVALINK_PASSWORD=another-long-random-password
```
The Compose file already defaults `LAVALINK_HOST` to `ws://lavalink:2333` for the bot, so the two find each other. Restart with `docker compose up -d`.
Two things to know:
- Lavalink 4 does not play from every source out of the box. Playing from YouTube needs a source plugin configured in Lavalink. See Lavalink's own documentation for what is current, since it changes.
- Members need a role named exactly **DJ** to use the music commands.
## Twitch alerts (optional)
Twitch live alerts check streamers every 30 seconds, using Twitch's web GraphQL endpoint with the client ID you set in `TWITCH_CLIENT_ID`. That is not Twitch's official API and Twitch can change or block it without notice. If you do not use alerts, leave the value as is and never set a notification channel.
## Keeping it running
**Updates.**
```bash
git pull
docker compose up -d --build bot
```
Read the release notes first. Releases that add tables need `schema.sql` run again (it only creates what is missing, and is safe to repeat) before the bot restarts, and a release that changes an existing table says so in its notes. Slash commands update themselves when the bot starts.
**Backups.** Everything the bot stores is in PostgreSQL:
```bash
docker compose exec -T db pg_dump -U velox velox > velox-backup-$(date +%F).sql
```
Run it on a schedule and keep copies off the server. To restore into an empty database, load the file with `psql`.
**Logs.** `docker compose logs -f bot`. Docker keeps logs without limit by default. Set a log size limit for the `bot` service (`logging` options in Compose) if the server is small.
**Rotating the token.** If the bot token ever leaks, reset it in the developer portal at once, put the new one in `.env` and run `docker compose up -d bot`.
## Growing past 100 servers
Discord requires you to **verify** your application once the bot is in 100 servers, and to be approved for the privileged intents (Server Members, Message Content). Plan for that if you intend to run a public bot. For a bot in a few servers you manage yourself, nothing is needed.
## Everything is a command
The bot is complete on its own: every setting and every action is a slash command, and nothing needs a web dashboard. The [Command reference](commands.md) lists them all. The ones you will want first:
- **Modules:** `/security toggle`, `/tickets setup`, `/slvl toggle`, `/music toggle`, `/config enablelogging`, `/config toggletwitch`.
- **Seeing what is set:** `/security settings`, `/tickets settings`, `/slvl status`, `/config view`.
- **Tuning security:** `/security joingate`, `words`, `raid`, `antinuke` and `heat` change every threshold, filter and action (owner or trusted users only).
- **The beta program:** the bot's owner sets it up in a direct message with the bot, see below.
### Setting up beta features
Beta features are off until you choose a beta server and a Beta Tester role. As the owner of the Discord application, open a **direct message** with your bot and run:
```
/beta set server-id:<the server's ID> role-id:<the role's ID>
```
(In Discord, turn on Developer Mode, then right-click the server or role and choose Copy ID.) `/beta status` shows the result, `/beta off` turns the beta off, `/beta servers` lists the servers that opted in. A server's owner opts the server in with `/config beta-features`. The bot reads the change within 30 seconds. See [Beta features](beta-features.md).
## Making it your own
- Change the bot's name and avatar in the developer portal.
- `/help` is hand-written text in `internal/commands/help/help.go`. Its author link points at the original project, so change it to your own repository.
- The name "Velox" in this code is just a name. You may rename it, and under the license you must keep the copyright notices (`LICENSE`, `NOTICE`) and say what you changed. Please do not present your fork as the original project.
## Something went wrong
[Troubleshooting](troubleshooting.md) covers the usual problems: the bot not starting, commands not appearing, permissions, and music.
+57
View File
@@ -0,0 +1,57 @@
# Troubleshooting
## The bot does not start
| Message | Cause |
| --- | --- |
| `BOT_TOKEN is not set`, `APP_ID is not set`, `DB_HOST is not set` | A required variable is missing. See [Getting started](getting-started.md#2-configure-the-environment). |
| `TWITCH_CLIENT_ID is not set` | It is required even if you do not use Twitch alerts. Set any non-empty value. |
| `Error creating database` | `DB_HOST` is wrong, or PostgreSQL is not running or not reachable. Try the connection string with `psql`. |
| `Error starting bot` | The token is wrong, or a privileged intent is not enabled in the developer portal. |
| `Disallowed intents` | Enable **Server Members Intent** and **Message Content Intent** in the developer portal, under Bot. |
## Slash commands do not appear
- With `GUILD_ID` set, commands appear in that server within seconds. If it is empty they are global and can take up to an hour.
- The bot must be invited with the `applications.commands` scope.
- If a command is defined but not in the `handlers` map in `internal/commands/commands.go`, it shows up and does nothing.
- If the bot logs `Cannot create '<name>' command`, read the error. A name or description that is too long, or an invalid option, makes Discord reject that one command.
- Commands that you removed from the code stay in Discord until you delete them (in the developer portal or through the API).
## A command says "You don't have permission"
Many commands need **Manage Server** (see the [Command reference](commands.md)), and the music commands need a role called exactly **DJ**. Security actions such as turning protection off need the **server owner or a trusted user**, whatever permissions you have.
## The bot cannot do something in a server
Most failures are about the bot's role:
- The bot's role must be **above** the roles it manages and the members it moderates or quarantines.
- It needs the permissions listed in [Getting started](getting-started.md#1-create-the-discord-application). Check the channel's own permission overrides too: a channel can deny what the server role allows.
- Security messages say "Check that Velox's role is high enough and has the permissions it needs" for this reason.
## Music does not play
- `LAVALINK_HOST` and `LAVALINK_PASSWORD` must match your Lavalink server, and Lavalink must be running and reachable from the bot (in Compose, use the service name, not `localhost`).
- You need the **DJ** role.
- A server admin can turn music off with `/music toggle`.
## Level-ups, logs or welcome messages do nothing
They are off until enabled: `/slvl toggle`, `/config enablelogging` with `/config setlogchannel`, and `/config setwelcomechannel`. Leveling and spam detection read message text, so the **Message Content Intent** must be on. Welcome messages and security need the **Server Members Intent**.
## A dashboard or tool's requests have no effect
A dashboard (the hosted Velox has a proprietary one) or any tool of yours talks to the bot through the database (see [Database](database.md#dashboard-to-bot-settings-and-requests)).
- Check that the tool and the bot use the **same database**.
- For a request such as skipping a song or ending a raid, look in the matching `*_commands` table. A row with an empty `processed_at` is waiting. If many are waiting, the bot's listener is down: look for `command listener stopped` in its log. It reconnects every 10 seconds.
- Settings are read when needed and may be cached briefly (the beta settings are polled every 30 seconds).
## Beta features are not available to a tester
Go through [Beta features](beta-features.md): has the bot's owner set the Beta Tester role (`/beta status` in a DM with the bot shows it)? Is the person in the **beta server**, and do they have the role there? Is the server where they use it the beta server, or has its owner run `/config beta-features enabled:true`? Has 30 seconds passed?
## Getting more detail
The bot logs to standard output. Run `docker compose logs -f bot`, or just `go run .`, and reproduce the problem. Errors from Discord calls are logged with the server and channel IDs involved.
+5 -1
View File
@@ -4,6 +4,8 @@ go 1.26.1
require (
github.com/bwmarrin/discordgo v0.29.0
github.com/disgoorg/disgolink/v3 v3.1.0
github.com/disgoorg/snowflake/v2 v2.0.3
github.com/fogleman/gg v1.3.0
github.com/jackc/pgx/v5 v5.8.0
github.com/joho/godotenv v1.5.1
@@ -11,8 +13,10 @@ require (
)
require (
github.com/disgoorg/json v1.2.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
+10 -1
View File
@@ -3,12 +3,21 @@ github.com/bwmarrin/discordgo v0.29.0/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disgoorg/disgolink/v3 v3.1.0 h1:IwhycUfvw87VbvvNSwBcdGMQNSFvNQ7/AQofmbp1NS8=
github.com/disgoorg/disgolink/v3 v3.1.0/go.mod h1:UjHfrC4NT4vzibG3GyqtY5l3aMzFwfkU+B3RiW3AQQ8=
github.com/disgoorg/json v1.2.0 h1:6e/j4BCfSHIvucG1cd7tJPAOp1RgnnMFSqkvZUtEd1Y=
github.com/disgoorg/json v1.2.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA=
github.com/disgoorg/snowflake/v2 v2.0.3 h1:3B+PpFjr7j4ad7oeJu4RlQ+nYOTadsKapJIzgvSI2Ro=
github.com/disgoorg/snowflake/v2 v2.0.3/go.mod h1:W6r7NUA7DwfZLwr00km6G4UnZ0zcoLBRufhkFWgAc4c=
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+215
View File
@@ -0,0 +1,215 @@
// Package beta gates features that are still being tried out.
//
// A beta feature works for a beta tester, in a server where beta features are
// on:
//
// - A beta tester is a member of the beta server who has the Beta Tester
// role. Both are chosen by the bot's owner on the dashboard.
// - Beta features are on in the beta server itself, and in every other
// server whose owner opted in on the dashboard. A feature that can act on
// a whole server never reaches a server that didn't ask for it.
//
// Being a tester is about the person, so it is looked up in the beta server
// even when they use a feature somewhere else (see SetRolesLookup). Beta
// never replaces a feature's own permission checks: a beta command that needs
// Manage Server still needs it.
//
// Features that act without anyone running a command (an event handler, a
// background job) have no person to check, so they use ServerEnabled only.
//
// Everything fails closed. With no role configured, an ID that isn't a
// Discord ID, or a lookup that fails, nobody gets access.
package beta
import (
"log"
"regexp"
"slices"
"strings"
"sync/atomic"
"github.com/bwmarrin/discordgo"
)
// Handler is a slash command handler.
type Handler = func(s *discordgo.Session, i *discordgo.InteractionCreate)
type settings struct {
guildID, roleID string
servers map[string]bool // opted-in servers, besides the beta server
}
var current atomic.Pointer[settings]
var snowflake = regexp.MustCompile(`^[0-9]{1,20}$`)
// idOrEmpty keeps a Discord ID and drops anything else, so a bad value turns
// beta features off instead of matching something odd.
func idOrEmpty(name, v string) string {
v = strings.TrimSpace(v)
if v == "" {
return ""
}
if !snowflake.MatchString(v) {
log.Printf("beta: %s %q isn't a Discord ID; ignoring it", name, v)
return ""
}
return v
}
// Configure sets the beta server, the Beta Tester role and the servers that
// opted in. It replaces everything set before, so call it with the full
// picture each time.
func Configure(guildID, roleID string, servers []string) {
set := make(map[string]bool, len(servers))
for _, id := range servers {
if id = idOrEmpty("beta server", id); id != "" {
set[id] = true
}
}
current.Store(&settings{
guildID: idOrEmpty("beta server", guildID),
roleID: idOrEmpty("beta role", roleID),
servers: set,
})
}
func get() settings {
if s := current.Load(); s != nil {
return *s
}
return settings{}
}
// RolesFunc returns a member's role IDs in a server, as Discord has them now,
// or an error (including "not in that server").
type RolesFunc func(guildID, userID string) ([]string, error)
var lookup atomic.Pointer[RolesFunc]
// SetRolesLookup tells the package how to find someone's roles in the beta
// server when they use a feature in another server. Without it, testers only
// qualify in the beta server itself.
func SetRolesLookup(f RolesFunc) { lookup.Store(&f) }
// GuildID is the beta server, or "" when it isn't set.
func GuildID() string { return get().guildID }
// Servers lists the servers that opted in, besides the beta server, in a
// stable order.
func Servers() []string {
c := get()
out := make([]string, 0, len(c.servers))
for id := range c.servers {
if id != c.guildID {
out = append(out, id)
}
}
slices.Sort(out)
return out
}
// ServerEnabled reports whether beta features are on in a server: the beta
// server, or one whose owner opted in. Use it alone for anything no person
// triggers.
func ServerEnabled(guildID string) bool {
c := get()
return guildID != "" && (guildID == c.guildID || c.servers[guildID])
}
// Status describes where a member stands, for the /beta command.
type Status struct {
ServerEnabled bool // beta features are on in this server
RoleConfigured bool // the owner has set a Beta Tester role
HasRole bool // the member is a tester
}
// StatusOf reports a member's standing in the server they're acting in.
func StatusOf(guildID string, member *discordgo.Member) Status {
c := get()
st := Status{
ServerEnabled: ServerEnabled(guildID),
RoleConfigured: c.roleID != "",
}
if st.ServerEnabled && st.RoleConfigured && member != nil {
st.HasRole = isTester(c, guildID, member)
}
return st
}
// isTester checks the Beta Tester role in the beta server. In the beta server
// the roles come with the interaction. Anywhere else they are looked up.
func isTester(c settings, guildID string, member *discordgo.Member) bool {
if guildID == c.guildID {
return slices.Contains(member.Roles, c.roleID)
}
f := lookup.Load()
if f == nil || *f == nil || member.User == nil || member.User.ID == "" {
return false
}
roles, err := (*f)(c.guildID, member.User.ID)
if err != nil {
return false
}
return slices.Contains(roles, c.roleID)
}
// Allowed reports whether a member may use beta features in guildID: beta
// features have to be on there, and the member has to be a tester. Use it for
// anything a person triggers that isn't a command, such as a button.
func Allowed(guildID string, member *discordgo.Member) bool {
st := StatusOf(guildID, member)
return st.ServerEnabled && st.RoleConfigured && st.HasRole
}
// AllowedInteraction is Allowed for an interaction. A DM has no member, so it
// never qualifies. The member comes from Discord with the interaction, not
// from anything the user typed.
func AllowedInteraction(i *discordgo.InteractionCreate) bool {
return i != nil && i.Interaction != nil && Allowed(i.GuildID, i.Member)
}
// respond is how a refusal is sent; tests replace it.
var respond = func(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
if i.Type == discordgo.InteractionApplicationCommandAutocomplete {
// Nothing to suggest, and a message isn't a valid reply here.
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionApplicationCommandAutocompleteResult,
Data: &discordgo.InteractionResponseData{Choices: []*discordgo.ApplicationCommandOptionChoice{}},
})
return
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
AllowedMentions: &discordgo.MessageAllowedMentions{},
},
})
}
const denied = "This feature is in beta and isn't available to you or this server yet."
// Guard is for the start of a beta feature's handler, and for its component,
// modal and autocomplete handlers too (the command's gate doesn't cover
// those). It answers the user and returns false when they aren't allowed:
//
// if !beta.Guard(s, i) { return }
func Guard(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if AllowedInteraction(i) {
return true
}
respond(s, i, denied)
return false
}
// Gate wraps a command handler so it only runs for beta testers.
func Gate(h Handler) Handler {
return func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !Guard(s, i) {
return
}
h(s, i)
}
}
+240
View File
@@ -0,0 +1,240 @@
package beta
import (
"errors"
"testing"
"github.com/bwmarrin/discordgo"
)
const (
betaGuild = "700000000000000001"
otherGuild = "999000000000000001"
testerRol = "555000000000000001"
testerID = "777000000000000001"
)
func member(roles ...string) *discordgo.Member {
return &discordgo.Member{Roles: roles, User: &discordgo.User{ID: testerID}}
}
func interaction(guildID string, m *discordgo.Member) *discordgo.InteractionCreate {
return &discordgo.InteractionCreate{Interaction: &discordgo.Interaction{GuildID: guildID, Member: m}}
}
// useLookup makes the beta server say who holds which roles, as Discord would.
func useLookup(t *testing.T, rolesByUser map[string][]string, err error) *int {
t.Helper()
calls := 0
SetRolesLookup(func(guildID, userID string) ([]string, error) {
calls++
if guildID != betaGuild {
t.Errorf("the lookup must ask the beta server, asked %q", guildID)
}
return rolesByUser[userID], err
})
t.Cleanup(func() { lookup.Store(nil) })
return &calls
}
func TestAllowedInTheBetaServer(t *testing.T) {
cases := []struct {
name string
guild, role string // configuration
inGuild string
member *discordgo.Member
want bool
on, hasRole bool
}{
{"tester in the beta server", betaGuild, testerRol, betaGuild, member("1", testerRol), true, true, true},
{"member without the role", betaGuild, testerRol, betaGuild, member("1", "2"), false, true, false},
{"member with no roles at all", betaGuild, testerRol, betaGuild, member(), false, true, false},
{"a DM has no member", betaGuild, testerRol, "", nil, false, false, false},
{"a nil member in the beta server", betaGuild, testerRol, betaGuild, nil, false, true, false},
{"no role configured: nobody", betaGuild, "", betaGuild, member(testerRol, ""), false, true, false},
{"no beta server configured: nobody", "", testerRol, betaGuild, member(testerRol), false, false, false},
{"a role ID that isn't a number is dropped", betaGuild, "tester-role", betaGuild, member("tester-role"), false, true, false},
{"a server ID that isn't a number is dropped", "my-server", testerRol, "my-server", member(testerRol), false, false, false},
{"a role that only contains the ID isn't a match", betaGuild, testerRol, betaGuild, member(testerRol + "9"), false, true, false},
{"stray spaces in the configuration are ignored", " " + betaGuild + " ", " " + testerRol + "\n", betaGuild, member(testerRol), true, true, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
Configure(tc.guild, tc.role, nil)
if got := Allowed(tc.inGuild, tc.member); got != tc.want {
t.Errorf("Allowed = %v, want %v", got, tc.want)
}
if got := AllowedInteraction(interaction(tc.inGuild, tc.member)); got != tc.want {
t.Errorf("AllowedInteraction = %v, want %v", got, tc.want)
}
st := StatusOf(tc.inGuild, tc.member)
if st.ServerEnabled != tc.on || st.HasRole != tc.hasRole {
t.Errorf("StatusOf = %+v, want server on %v, tester %v", st, tc.on, tc.hasRole)
}
})
}
}
func TestOptedInServers(t *testing.T) {
roles := map[string][]string{testerID: {"1", testerRol}}
t.Run("a tester in an opted-in server is allowed", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
calls := useLookup(t, roles, nil)
if !Allowed(otherGuild, member()) { // roles in this server don't matter
t.Error("tester in an opted-in server should be allowed")
}
if *calls != 1 {
t.Errorf("the beta server should be asked once, was asked %d times", *calls)
}
})
t.Run("the role in the other server doesn't count", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
useLookup(t, map[string][]string{}, nil)
if Allowed(otherGuild, member(testerRol)) {
t.Error("holding a role with that ID in another server must not make anyone a tester")
}
})
t.Run("a server that didn't opt in is refused, and nothing is looked up", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
calls := useLookup(t, roles, nil)
if Allowed("123000000000000001", member()) {
t.Error("a server that didn't opt in must be refused")
}
if *calls != 0 {
t.Error("no lookup for a server where beta is off")
}
})
t.Run("a failing lookup fails closed", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
useLookup(t, roles, errors.New("Unknown Member"))
if Allowed(otherGuild, member()) {
t.Error("an error from Discord must mean no")
}
})
t.Run("no lookup set: testers only qualify in the beta server", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
lookup.Store(nil)
if Allowed(otherGuild, member()) {
t.Error("without a lookup there is no way to know")
}
if !Allowed(betaGuild, member(testerRol)) {
t.Error("the beta server doesn't need the lookup")
}
})
t.Run("a user without an ID can't be looked up", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
useLookup(t, roles, nil)
if Allowed(otherGuild, &discordgo.Member{}) || Allowed(otherGuild, &discordgo.Member{User: &discordgo.User{}}) {
t.Error("no user, no access")
}
})
t.Run("no role configured: nobody, even when the server opted in", func(t *testing.T) {
Configure(betaGuild, "", []string{otherGuild})
useLookup(t, map[string][]string{testerID: {""}}, nil)
if Allowed(otherGuild, member()) {
t.Error("without a role there are no testers")
}
})
t.Run("bad IDs in the list are dropped", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild, "not-an-id", "", " 5 "})
got := Servers()
if len(got) != 2 || got[0] != "5" || got[1] != otherGuild {
t.Errorf("Servers = %v", got)
}
})
t.Run("the beta server isn't listed twice", func(t *testing.T) {
Configure(betaGuild, testerRol, []string{betaGuild, otherGuild})
if got := Servers(); len(got) != 1 || got[0] != otherGuild {
t.Errorf("Servers = %v", got)
}
})
}
func TestServerEnabledNeedsNoPerson(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
for guild, want := range map[string]bool{betaGuild: true, otherGuild: true, "123": false, "": false} {
if got := ServerEnabled(guild); got != want {
t.Errorf("ServerEnabled(%q) = %v, want %v", guild, got, want)
}
}
current.Store(nil)
if ServerEnabled(betaGuild) {
t.Error("before Configure nothing is on")
}
}
func TestNotConfiguredAtAll(t *testing.T) {
current.Store(nil)
if Allowed(betaGuild, member(testerRol)) || GuildID() != "" || len(Servers()) != 0 {
t.Error("before Configure nothing is allowed and there's no beta server")
}
if AllowedInteraction(nil) || AllowedInteraction(&discordgo.InteractionCreate{}) {
t.Error("a missing interaction is never allowed")
}
}
func TestGateRunsTheHandlerOnlyForTesters(t *testing.T) {
Configure(betaGuild, testerRol, []string{otherGuild})
useLookup(t, map[string][]string{}, nil) // nobody holds the role in the beta server
var answered []string
orig := respond
respond = func(_ *discordgo.Session, _ *discordgo.InteractionCreate, msg string) {
answered = append(answered, msg)
}
t.Cleanup(func() { respond = orig })
ran := 0
h := Gate(func(*discordgo.Session, *discordgo.InteractionCreate) { ran++ })
h(nil, interaction(betaGuild, member(testerRol)))
if ran != 1 || len(answered) != 0 {
t.Fatalf("a tester runs the handler without being refused: ran=%d answered=%v", ran, answered)
}
for name, i := range map[string]*discordgo.InteractionCreate{
"no role": interaction(betaGuild, member("1")),
"opted-in, not a tester": interaction(otherGuild, member(testerRol)),
"server not opted in": interaction("123000000000000001", member(testerRol)),
"DM": interaction("", nil),
} {
before := ran
h(nil, i)
if ran != before {
t.Errorf("%s: the handler must not run", name)
}
}
if len(answered) != 4 || answered[0] != denied {
t.Errorf("each refusal is answered with the beta message: %v", answered)
}
useLookup(t, map[string][]string{testerID: {testerRol}}, nil)
before := ran
h(nil, interaction(otherGuild, member()))
if ran != before+1 {
t.Error("a tester in an opted-in server runs the handler")
}
}
func TestGuardOnItsOwn(t *testing.T) {
Configure(betaGuild, testerRol, nil)
n := 0
orig := respond
respond = func(*discordgo.Session, *discordgo.InteractionCreate, string) { n++ }
t.Cleanup(func() { respond = orig })
if !Guard(nil, interaction(betaGuild, member(testerRol))) || n != 0 {
t.Error("a tester passes without a reply")
}
if Guard(nil, interaction(betaGuild, member())) || n != 1 {
t.Error("someone else is refused with a reply")
}
}
+240
View File
@@ -0,0 +1,240 @@
package bot
import (
"context"
"encoding/json"
"io"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"testing"
"velox-bot/internal/beta"
"velox-bot/internal/commands"
"github.com/bwmarrin/discordgo"
)
const (
appID = "100"
betaServer = "700000000000000001"
optedIn = "222"
leftServer = "333"
)
// fakeDiscord answers the application-command calls the beta sync makes, from
// memory, and records what it was asked to change.
var registerOnce sync.Once
type fakeDiscord struct {
mu sync.Mutex
cmds map[string][]*discordgo.ApplicationCommand // guild -> commands
failures map[string]int // guild -> status for every call
nextID int
created []string // "guild/name"
deleted []string // "guild/name"
}
var cmdPath = regexp.MustCompile(`/applications/` + appID + `/guilds/(\d+)/commands(?:/(\d+))?$`)
func (f *fakeDiscord) RoundTrip(r *http.Request) (*http.Response, error) {
f.mu.Lock()
defer f.mu.Unlock()
reply := func(code int, v any) (*http.Response, error) {
b, _ := json.Marshal(v)
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(string(b))), Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil
}
m := cmdPath.FindStringSubmatch(r.URL.Path)
if m == nil {
return reply(404, map[string]any{"message": "unknown route"})
}
guild, id := m[1], m[2]
if code := f.failures[guild]; code != 0 {
return reply(code, map[string]any{"message": "failure", "code": 0})
}
switch r.Method {
case http.MethodGet:
return reply(200, f.cmds[guild])
case http.MethodPost:
var c discordgo.ApplicationCommand
_ = json.NewDecoder(r.Body).Decode(&c)
f.nextID++
c.ID = strconv.Itoa(1000 + f.nextID)
f.cmds[guild] = append(f.cmds[guild], &c)
f.created = append(f.created, guild+"/"+c.Name)
return reply(200, c)
case http.MethodDelete:
kept := f.cmds[guild][:0]
for _, c := range f.cmds[guild] {
if c.ID == id {
f.deleted = append(f.deleted, guild+"/"+c.Name)
continue
}
kept = append(kept, c)
}
f.cmds[guild] = kept
return reply(204, nil)
}
return reply(405, nil)
}
func (f *fakeDiscord) names(guild string) []string {
f.mu.Lock()
defer f.mu.Unlock()
var out []string
for _, c := range f.cmds[guild] {
out = append(out, c.Name)
}
sort.Strings(out)
return out
}
type fakeStore struct {
registered map[string]bool
servers []string
failWrite bool
}
func (s *fakeStore) GetBetaSettings(context.Context) (string, string, error) {
return betaServer, "555", nil
}
func (s *fakeStore) ListBetaGuilds(context.Context) ([]string, error) { return s.servers, nil }
func (s *fakeStore) ListBetaRegistered(context.Context) ([]string, error) {
var out []string
for id := range s.registered {
out = append(out, id)
}
return out, nil
}
func (s *fakeStore) SetBetaRegistered(_ context.Context, id string, on bool) error {
if s.failWrite {
return io.ErrUnexpectedEOF
}
if on {
s.registered[id] = true
} else {
delete(s.registered, id)
}
return nil
}
func newTestBot(t *testing.T, d *fakeDiscord) *Bot {
t.Helper()
sess, err := discordgo.New("Bot x")
if err != nil {
t.Fatal(err)
}
sess.Client = &http.Client{Transport: d}
sess.MaxRestRetries = 0
return &Bot{
Session: sess,
AppID: appID,
betaRegistered: map[string]bool{},
betaKnown: map[string]bool{},
}
}
func contains(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}
func TestBetaCommandsFollowTheServers(t *testing.T) {
registerOnce.Do(func() {
commands.RegisterBeta(&discordgo.ApplicationCommand{Name: "betatest", Description: "test"}, func(*discordgo.Session, *discordgo.InteractionCreate) {})
})
d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{
// A server that opted out while the bot was offline still has them,
// next to a command that isn't a beta one.
leftServer: {{ID: "1", Name: "betatest"}, {ID: "2", Name: "ping"}},
// A stale command in the beta server, which the bot cleans up.
betaServer: {{ID: "3", Name: "oldthing"}},
}, failures: map[string]int{}}
store := &fakeStore{registered: map[string]bool{leftServer: true}, servers: []string{optedIn}}
b := newTestBot(t, d)
ctx := context.Background()
beta.Configure(betaServer, "555", store.servers)
b.syncBetaCommands(ctx, store)
if got := d.names(leftServer); len(got) != 1 || got[0] != "ping" {
t.Errorf("the beta command is removed from the server that left, nothing else: %v", got)
}
if got := d.names(optedIn); len(got) != 1 || got[0] != "betatest" {
t.Errorf("an opted-in server gets the beta commands but not /beta: %v", got)
}
got := d.names(betaServer)
if !contains(got, "betatest") || contains(got, "oldthing") || contains(got, "beta") {
t.Errorf("the beta server gets the beta commands (not /beta, which lives in DMs) and loses stale ones: %v", got)
}
if store.registered[leftServer] || !store.registered[optedIn] || !store.registered[betaServer] {
t.Errorf("the database remembers where the commands are now: %v", store.registered)
}
// The server opts out.
store.servers = nil
beta.Configure(betaServer, "555", store.servers)
b.syncBetaCommands(ctx, store)
if got := d.names(optedIn); len(got) != 0 {
t.Errorf("an opted-out server loses them within one round: %v", got)
}
if store.registered[optedIn] || !store.registered[betaServer] {
t.Errorf("only the beta server stays remembered: %v", store.registered)
}
}
func TestBetaCleanupIsRetriedAndGivesUpWhenTheBotIsGone(t *testing.T) {
d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{
leftServer: {{ID: "1", Name: "betatest"}},
}, failures: map[string]int{leftServer: 500}}
store := &fakeStore{registered: map[string]bool{leftServer: true}}
b := newTestBot(t, d)
ctx := context.Background()
beta.Configure(betaServer, "555", nil)
b.syncBetaCommands(ctx, store)
if !store.registered[leftServer] {
t.Fatal("a failed cleanup is remembered so it is tried again")
}
d.failures[leftServer] = 0
b.syncBetaCommands(ctx, store)
if store.registered[leftServer] || len(d.names(leftServer)) != 0 {
t.Errorf("the retry cleans up: %v, %v", store.registered, d.names(leftServer))
}
// The bot was removed from a server: nothing to clean, don't try forever.
store.registered["444"] = true
b.betaKnown["444"] = true
d.failures["444"] = 403
b.syncBetaCommands(ctx, store)
if store.registered["444"] {
t.Error("a server the bot can't reach any more is forgotten")
}
}
// Close used to loop over a list that started with empty entries and read
// their IDs, so shutting down crashed. It must just disconnect, and must not
// touch the registered commands.
func TestCloseDoesNotTouchCommands(t *testing.T) {
d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{
"1": {{ID: "7", Name: "ping"}},
}, failures: map[string]int{}}
b := newTestBot(t, d)
b.GuildID = "1"
b.Commands = []*discordgo.ApplicationCommand{{Name: "ping"}}
if err := b.Close(); err != nil {
t.Fatalf("Close on a bot that never connected: %v", err)
}
if len(d.deleted) != 0 {
t.Errorf("Close must not delete commands: %v", d.deleted)
}
}
+372 -13
View File
@@ -1,10 +1,20 @@
package bot
import (
"context"
"errors"
"log"
"net/http"
"sync"
"time"
"velox-bot/internal/beta"
"velox-bot/internal/commands"
"velox-bot/internal/db/repos/musicrepo"
"velox-bot/internal/db/services"
"velox-bot/internal/events"
"velox-bot/internal/music"
"velox-bot/internal/security"
"velox-bot/internal/tickets"
"github.com/bwmarrin/discordgo"
)
@@ -14,11 +24,18 @@ type Bot struct {
AppID string
GuildID string
Commands []*discordgo.ApplicationCommand
registeredCommands []*discordgo.ApplicationCommand
Services *services.Services
MusicRepo *musicrepo.Repo
DBHost string
LavalinkHost string
LavalinkPass string
betaRegistered map[string]bool // servers where this run registered the beta commands
betaKnown map[string]bool // servers where they were registered, now or in an earlier run
betaLoaded bool
betaRoles sync.Map // "guild:user" -> cachedRoles
}
func NewBot(token, appID, guildID string, cmds []*discordgo.ApplicationCommand, services *services.Services) (*Bot, error) {
func NewBot(token, appID, guildID, lavalinkHost, lavalinkPass string, cmds []*discordgo.ApplicationCommand, services *services.Services, musicRepo *musicrepo.Repo, dbHost string) (*Bot, error) {
session, err := discordgo.New("Bot " + token)
if err != nil {
return nil, err
@@ -27,15 +44,28 @@ func NewBot(token, appID, guildID string, cmds []*discordgo.ApplicationCommand,
// Intents needed for:
// - InteractionCreate (slash commands): Guilds
// - MessageCreate (leveling): GuildMessages
// - GuildMemberAdd (welcome messages): GuildMembers
// - VoiceStateUpdate (meeting lobby): GuildVoiceStates
session.Identify.Intents = discordgo.IntentsGuilds | discordgo.IntentsGuildMessages | discordgo.IntentsGuildVoiceStates
session.Identify.Intents = discordgo.IntentsGuilds |
discordgo.IntentsGuildBans |
discordgo.IntentsGuildMembers |
discordgo.IntentsGuildMessages |
discordgo.IntentsMessageContent |
discordgo.IntentsGuildVoiceStates |
discordgo.IntentsDirectMessages
return &Bot{
betaRegistered: map[string]bool{},
betaKnown: map[string]bool{},
Session: session,
AppID: appID,
GuildID: guildID,
Commands: cmds,
Services: services,
MusicRepo: musicRepo,
DBHost: dbHost,
LavalinkHost: lavalinkHost,
LavalinkPass: lavalinkPass,
}, nil
}
@@ -44,34 +74,363 @@ func (b *Bot) Start() error {
return err
}
b.registeredCommands = make([]*discordgo.ApplicationCommand, len(b.Commands))
_ = music.Init(b.Session, b.MusicRepo, b.AppID, b.LavalinkHost, b.LavalinkPass)
go func() {
if err := music.StartCommandListener(context.Background(), b.DBHost, b.MusicRepo); err != nil {
log.Printf("music: command listener stopped: %v", err)
}
}()
if st := tickets.Default(); st != nil {
go func() {
// The connection can drop (database restart, network blip):
// reconnect instead of silently ignoring the dashboard from then on.
for {
err := tickets.StartCommandListener(context.Background(), b.DBHost, b.Session, st)
log.Printf("tickets: command listener stopped: %v (retrying in 10s)", err)
time.Sleep(10 * time.Second)
}
}()
}
if eng := security.Start(b.Session, b.Session.State.User.ID); eng != nil {
// Moderators are exempt from heat; their permissions come from the
// gateway cache so a message never costs an API call.
eng.ChannelPerms = b.Session.State.UserChannelPermissions
eng.ResumeRaids(context.Background())
go eng.WatchRaids(context.Background(), 30*time.Second)
go eng.WatchSnapshots(context.Background())
go func() {
// Reconnect if the database connection drops, instead of
// silently ignoring the dashboard from then on.
for {
err := eng.StartCommandListener(context.Background(), b.DBHost)
log.Printf("security: command listener stopped: %v (retrying in 10s)", err)
time.Sleep(10 * time.Second)
}
}()
}
// Registering is an upsert by name: existing commands are updated in
// place and keep their IDs (links like </help:ID> keep working).
for _, cmd := range b.Commands {
created, err := b.Session.ApplicationCommandCreate(b.AppID, b.GuildID, cmd)
if err != nil {
if _, err := b.Session.ApplicationCommandCreate(b.AppID, b.GuildID, cmd); err != nil {
log.Printf("Cannot create '%v' command: %v", cmd.Name, err)
continue
}
}
// The owner's commands live in direct messages with the bot, not in a server.
for _, cmd := range commands.OwnerCommands {
if _, err := b.Session.ApplicationCommandCreate(b.AppID, "", cmd); err != nil {
log.Printf("Cannot create '%v' command: %v", cmd.Name, err)
}
b.registeredCommands = append(b.registeredCommands, created)
}
b.Session.AddHandler(commands.HandleInteraction)
b.Session.AddHandler(func(s *discordgo.Session, c *discordgo.ChannelDelete) {
events.HandleChannelDelete(s, c, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
if eng := security.Default(); eng != nil {
eng.OnMessage(context.Background(), m)
}
events.HandleMessageCreate(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.GuildMemberAdd) {
events.HandleBotAddedOnGuild(s, m, b.Services)
// Security runs first: someone it removes (join lock, Join Gate,
// raid) gets no welcome message or default role.
if eng := security.Default(); eng != nil && m != nil && m.Member != nil {
if eng.OnMemberJoin(context.Background(), m.GuildID, m.Member) {
events.HandleGuildMemberAddLog(s, m, b.Services)
return
}
}
// Ignore bot members for welcome/log onboarding of normal users.
if m != nil && m.Member != nil && m.User != nil && m.User.Bot {
return
}
events.HandleGuildMemberAdd(s, m, b.Services)
events.HandleGuildMemberAddLog(s, m, b.Services)
})
// Anti-nuke and unauthorized bot additions read the audit log as it
// happens (needs the Guild Moderation intent and View Audit Log).
b.Session.AddHandler(func(s *discordgo.Session, ev *discordgo.GuildAuditLogEntryCreate) {
if eng := security.Default(); eng != nil && ev.AuditLogEntry != nil {
eng.OnAuditLogEntry(context.Background(), ev.GuildID, ev.AuditLogEntry)
}
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.GuildMemberRemove) {
events.HandleGuildMemberRemoveLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {
events.HandleGuildMemberUpdateLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageUpdate) {
events.HandleMessageUpdateLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageDelete) {
events.HandleMessageDeleteLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.GuildBanAdd) {
events.HandleGuildBanAddLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, m *discordgo.GuildBanRemove) {
events.HandleGuildBanRemoveLog(s, m, b.Services)
})
b.Session.AddHandler(func(s *discordgo.Session, t *discordgo.ThreadDelete) {
if st := tickets.Default(); st != nil && t.Channel != nil {
tickets.ThreadDeleted(context.Background(), st, t.ID)
}
})
b.Session.AddHandler(func(s *discordgo.Session, vs *discordgo.VoiceStateUpdate) {
events.HandleVoiceStateUpdate(s, vs, b.Services)
music.OnVoiceStateUpdate(vs)
})
b.Session.AddHandler(func(s *discordgo.Session, ev *discordgo.VoiceServerUpdate) {
music.OnVoiceServerUpdate(ev)
})
events.StartScheduleReminderLoop(b.Session, b.Services)
events.StartTwitchLiveLoop(b.Session, b.Services)
return nil
}
// betaPollEvery is how often the bot looks for a change to the beta settings
// made on the dashboard.
const betaPollEvery = 30 * time.Second
// BetaStore is where the bot reads the beta settings the dashboard writes,
// and remembers which servers it registered beta commands in.
type BetaStore interface {
GetBetaSettings(ctx context.Context) (guildID, roleID string, err error)
ListBetaGuilds(ctx context.Context) ([]string, error)
ListBetaRegistered(ctx context.Context) ([]string, error)
SetBetaRegistered(ctx context.Context, guildID string, registered bool) error
}
// WatchBeta keeps the bot's idea of who the beta testers are, and which
// servers opted in, in step with the dashboard. When the list of servers
// changes, the beta commands follow: they appear in servers that opted in and
// are removed from servers that opted out, also if that happened while the bot
// was offline (it remembers where it registered them). If the settings can't
// be read, the last known ones stay in force (and before the first read, beta
// stays off).
func (b *Bot) WatchBeta(ctx context.Context, store BetaStore) {
beta.SetRolesLookup(b.betaMemberRoles)
sync := func() {
guildID, roleID, err := store.GetBetaSettings(ctx)
if err != nil {
log.Printf("beta: cannot read settings, keeping the last ones: %v", err)
return
}
servers, err := store.ListBetaGuilds(ctx)
if err != nil {
log.Printf("beta: cannot read the opted-in servers, keeping the last ones: %v", err)
return
}
beta.Configure(guildID, roleID, servers)
b.syncBetaCommands(ctx, store)
}
sync()
go func() {
t := time.NewTicker(betaPollEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
sync()
}
}
}()
}
type cachedRoles struct {
roles []string
at time.Time
}
// betaRolesTTL is how long a member's roles in the beta server are remembered
// when they had to be fetched from Discord.
const betaRolesTTL = 30 * time.Second
// betaMemberRoles answers beta.SetRolesLookup: someone's roles in the beta
// server. The gateway cache is used when it has them (it is kept current by
// member updates), otherwise Discord is asked, at most once per
// betaRolesTTL per person.
func (b *Bot) betaMemberRoles(guildID, userID string) ([]string, error) {
if m, err := b.Session.State.Member(guildID, userID); err == nil && m != nil {
return m.Roles, nil
}
key := guildID + ":" + userID
if v, ok := b.betaRoles.Load(key); ok {
if c := v.(cachedRoles); time.Since(c.at) < betaRolesTTL {
return c.roles, nil
}
}
m, err := b.Session.GuildMember(guildID, userID)
if err != nil {
return nil, err
}
b.betaRoles.Store(key, cachedRoles{roles: m.Roles, at: time.Now()})
return m.Roles, nil
}
// syncBetaCommands makes the beta commands exist in exactly the servers where
// beta features are on (the beta server and the ones that opted in), and
// nowhere else. The servers it registered them in are remembered in the
// database, so a server that opted out while the bot was offline is cleaned up
// at the next start. A step that failed is retried on the next round.
func (b *Bot) syncBetaCommands(ctx context.Context, store BetaStore) {
if !b.betaLoaded {
known, err := store.ListBetaRegistered(ctx)
if err != nil {
log.Printf("beta: cannot read where beta commands were registered: %v", err)
return
}
for _, id := range known {
b.betaKnown[id] = true
}
b.betaLoaded = true
}
want := map[string]bool{}
if g := beta.GuildID(); g != "" {
want[g] = true
}
for _, id := range beta.Servers() {
want[id] = true
}
for id := range b.betaKnown {
if want[id] {
continue
}
if !b.removeBetaCommands(id) {
continue
}
if err := store.SetBetaRegistered(ctx, id, false); err != nil {
log.Printf("beta: cannot forget server %s: %v", id, err)
continue
}
delete(b.betaKnown, id)
delete(b.betaRegistered, id)
}
for id := range want {
if b.betaRegistered[id] || !b.addBetaCommands(id) {
continue
}
b.betaRegistered[id] = true
if err := store.SetBetaRegistered(ctx, id, true); err != nil {
log.Printf("beta: cannot remember server %s: %v", id, err)
continue
}
b.betaKnown[id] = true
}
}
// addBetaCommands registers the beta commands in a server. In the beta server
// it also removes commands this bot left there that no longer exist (when the
// beta server is also the bot's main server, its regular commands are kept).
// /beta is for the bot's owner and is only registered in the beta server. It
// reports whether everything was registered.
func (b *Bot) addBetaCommands(guildID string) bool {
isBetaServer := guildID == beta.GuildID()
keep := map[string]bool{}
for _, cmd := range b.Commands {
if b.GuildID == guildID {
keep[cmd.Name] = true
}
}
ok := true
for _, cmd := range commands.BetaCommands {
keep[cmd.Name] = true
if _, err := b.Session.ApplicationCommandCreate(b.AppID, guildID, cmd); err != nil {
log.Printf("beta: cannot create '%v' command in %s: %v", cmd.Name, guildID, err)
ok = false
}
}
if !isBetaServer {
return ok
}
existing, err := b.Session.ApplicationCommands(b.AppID, guildID)
if err != nil {
log.Printf("beta: cannot list commands, leaving stale ones alone: %v", err)
return ok
}
for _, cmd := range existing {
if keep[cmd.Name] {
continue
}
if err := b.Session.ApplicationCommandDelete(b.AppID, guildID, cmd.ID); err != nil {
log.Printf("beta: cannot remove stale '%v' command: %v", cmd.Name, err)
}
}
return ok
}
// goneFromServer reports whether an error from Discord means the bot isn't in
// that server any more (or it no longer exists), so there is nothing left to
// clean up there.
func goneFromServer(err error) bool {
var rest *discordgo.RESTError
if errors.As(err, &rest) && rest.Response != nil {
return rest.Response.StatusCode == http.StatusForbidden || rest.Response.StatusCode == http.StatusNotFound
}
return false
}
// removeBetaCommands takes the beta commands out of a server that is no longer
// part of the beta, and leaves everything else there alone. It reports whether
// the server is clean (or out of reach for good).
func (b *Bot) removeBetaCommands(guildID string) bool {
isBeta := map[string]bool{}
for _, cmd := range commands.BetaCommands {
isBeta[cmd.Name] = true
}
existing, err := b.Session.ApplicationCommands(b.AppID, guildID)
if err != nil {
if goneFromServer(err) {
return true
}
log.Printf("beta: cannot list commands in %s: %v", guildID, err)
return false
}
clean := true
for _, cmd := range existing {
if !isBeta[cmd.Name] {
continue
}
if err := b.Session.ApplicationCommandDelete(b.AppID, guildID, cmd.ID); err != nil && !goneFromServer(err) {
log.Printf("beta: cannot remove '%v' from %s: %v", cmd.Name, guildID, err)
clean = false
}
}
return clean
}
// Close disconnects from Discord. The slash commands are left registered on
// purpose: deleting them on every shutdown would make them disappear during a
// restart, and registering them again would give them new IDs.
func (b *Bot) Close() error {
for _, cmd := range b.registeredCommands {
if err := b.Session.ApplicationCommandDelete(b.AppID, b.GuildID, cmd.ID); err != nil {
log.Printf("cannot delete '%s' command: %v", cmd.Name, err)
}
}
return b.Session.Close()
}
+240
View File
@@ -0,0 +1,240 @@
// Package betacmd is /beta, the bot owner's control over the beta program.
// It is a command you use in a direct message with the bot, so it exists in no
// server's command menu, and only the owner of the Discord application can run
// it (the owner is looked up from the application, so there is nothing to
// configure). It chooses the beta server and the Beta Tester role, and
// removes servers from the beta; a server's own owner opts it in with
// /config beta-features. Nothing about the beta needs a dashboard.
package betacmd
import (
"context"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"sync"
"time"
"velox-bot/internal/beta"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var (
ownerIDs sync.Map // user ID -> struct{}, filled once from the application
loadOnce sync.Mutex
loaded bool
snowflake = regexp.MustCompile(`^[0-9]{1,20}$`)
dmOnly = &[]discordgo.InteractionContextType{discordgo.InteractionContextBotDM}
)
var Beta = &discordgo.ApplicationCommand{
Name: "beta",
Description: "Manage the beta program (bot owner, in a DM with the bot)",
Contexts: dmOnly,
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "status", Description: "Show how beta access is set up"},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "set", Description: "Choose the beta server and the Beta Tester role",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "server-id", Description: "The beta server's ID (the bot must be in it)", Required: true, MaxLength: 20},
{Type: discordgo.ApplicationCommandOptionString, Name: "role-id", Description: "The Beta Tester role's ID in that server", Required: true, MaxLength: 20},
},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "off", Description: "Turn beta features off for everyone (clears the role)"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "servers", Description: "List the servers that opted in to beta features"},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "remove-server", Description: "Take a server out of the beta",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "server-id", Description: "The server's ID", Required: true, MaxLength: 20},
},
},
},
}
// isOwner reports whether the user owns the bot's Discord application (or is
// on its team). If the application can't be read, nobody is the owner.
func isOwner(s *discordgo.Session, userID string) bool {
if userID == "" {
return false
}
loadOnce.Lock()
if !loaded {
app, err := s.Application("@me")
if err == nil && app != nil {
if app.Owner != nil {
ownerIDs.Store(app.Owner.ID, struct{}{})
}
if app.Team != nil {
ownerIDs.Store(app.Team.OwnerID, struct{}{})
for _, m := range app.Team.Members {
if m != nil && m.User != nil {
ownerIDs.Store(m.User.ID, struct{}{})
}
}
}
loaded = true
}
}
loadOnce.Unlock()
_, ok := ownerIDs.Load(userID)
return ok
}
func reply(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Content: msg, AllowedMentions: &discordgo.MessageAllowedMentions{}},
})
}
func guildName(s *discordgo.Session, id string) string {
if g, err := s.State.Guild(id); err == nil && g != nil && g.Name != "" {
return g.Name
}
if g, err := s.Guild(id); err == nil && g != nil {
return g.Name
}
return "unknown server"
}
func Handler(s *discordgo.Session, i *discordgo.InteractionCreate) {
userID := ""
switch {
case i.User != nil:
userID = i.User.ID
case i.Member != nil && i.Member.User != nil:
userID = i.Member.User.ID
}
if !isOwner(s, userID) {
reply(s, i, "Only the bot's owner can use this command.")
return
}
if i.GuildID != "" {
reply(s, i, "Use this command in a direct message with me, not in a server.")
return
}
svc := services.Global
if svc == nil || svc.BetaSettings == nil {
reply(s, i, "Beta settings aren't available right now.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
args := map[string]*discordgo.ApplicationCommandInteractionDataOption{}
for _, o := range sub.Options {
args[o.Name] = o
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
fail := func(err error) {
reply(s, i, "Something went wrong. Try again in a moment.")
log.Printf("beta %s: %v", sub.Name, err)
}
switch sub.Name {
case "status":
guildID, roleID, err := svc.BetaSettings.Get(ctx)
if err != nil {
fail(err)
return
}
opted, _ := svc.BetaSettings.OptedIn(ctx)
var b strings.Builder
switch {
case guildID == "":
b.WriteString("No beta server is set. Choose one with `/beta set`.\n")
case roleID == "":
fmt.Fprintf(&b, "Beta server: **%s** (`%s`).\nNo Beta Tester role is set, so beta features are locked for everyone. Set one with `/beta set`.\n", guildName(s, guildID), guildID)
default:
fmt.Fprintf(&b, "Beta server: **%s** (`%s`).\nBeta Tester role: `%s`. Members of the beta server who have it are testers.\n", guildName(s, guildID), guildID, roleID)
}
fmt.Fprintf(&b, "%d other server(s) opted in. The bot is using: server `%s`, %d opted-in server(s).", len(opted), beta.GuildID(), len(beta.Servers()))
reply(s, i, b.String())
case "set":
guildArg, roleArg := strings.TrimSpace(args["server-id"].StringValue()), strings.TrimSpace(args["role-id"].StringValue())
if !snowflake.MatchString(guildArg) || !snowflake.MatchString(roleArg) {
reply(s, i, "Both IDs must be numbers. In Discord, turn on Developer Mode, then right-click the server or role and choose Copy ID.")
return
}
roles, err := s.GuildRoles(guildArg)
if err != nil {
reply(s, i, "I couldn't read that server. Check the ID, and that I'm in it.")
return
}
found := false
for _, r := range roles {
if r.ID == roleArg && r.ID != guildArg && !r.Managed {
found = true
}
}
if !found {
reply(s, i, "That role isn't a normal role of that server.")
return
}
g, _ := strconv.ParseInt(guildArg, 10, 64)
r, _ := strconv.ParseInt(roleArg, 10, 64)
by, _ := strconv.ParseInt(userID, 10, 64)
if err := svc.BetaSettings.SetServer(ctx, g, r, by); err != nil {
fail(err)
return
}
reply(s, i, fmt.Sprintf("Saved. **%s** is the beta server, and members with the role `%s` are beta testers. The bot picks this up within 30 seconds.", guildName(s, guildArg), roleArg))
case "off":
guildID, _, err := svc.BetaSettings.Get(ctx)
if err != nil {
fail(err)
return
}
if guildID == "" {
reply(s, i, "No beta server is set, so beta features are already off.")
return
}
g, _ := strconv.ParseInt(guildID, 10, 64)
by, _ := strconv.ParseInt(userID, 10, 64)
if err := svc.BetaSettings.SetServer(ctx, g, 0, by); err != nil {
fail(err)
return
}
reply(s, i, "Beta features are off for everyone. Choose a role again with `/beta set` to turn them back on.")
case "servers":
opted, err := svc.BetaSettings.OptedIn(ctx)
if err != nil {
fail(err)
return
}
if len(opted) == 0 {
reply(s, i, "No other server has opted in. A server's owner does that with `/config beta-features`.")
return
}
var b strings.Builder
for _, id := range opted {
fmt.Fprintf(&b, "• %s (`%s`)\n", guildName(s, id), id)
}
out := b.String()
if r := []rune(out); len(r) > 1900 {
out = string(r[:1899]) + "…"
}
reply(s, i, "**Servers in the beta**\n"+out)
case "remove-server":
id := strings.TrimSpace(args["server-id"].StringValue())
if !snowflake.MatchString(id) {
reply(s, i, "The ID must be a number.")
return
}
g, _ := strconv.ParseInt(id, 10, 64)
by, _ := strconv.ParseInt(userID, 10, 64)
if err := svc.BetaSettings.SetOptedIn(ctx, g, by, false); err != nil {
fail(err)
return
}
reply(s, i, "Removed. Its beta commands disappear within a minute. Only that server's owner can put it back.")
}
}
+87
View File
@@ -1,11 +1,22 @@
package commands
import (
"strings"
"velox-bot/internal/beta"
"velox-bot/internal/commands/betacmd"
"velox-bot/internal/commands/config"
"velox-bot/internal/commands/fun"
"velox-bot/internal/commands/help"
cmdlevel "velox-bot/internal/commands/level"
"velox-bot/internal/commands/meeting"
"velox-bot/internal/commands/moderation"
cmdmusic "velox-bot/internal/commands/music"
"velox-bot/internal/commands/projects"
"velox-bot/internal/commands/schedule"
cmdsecurity "velox-bot/internal/commands/security"
cmdtickets "velox-bot/internal/commands/tickets"
"velox-bot/internal/commands/timezone"
"velox-bot/internal/music"
"github.com/bwmarrin/discordgo"
)
@@ -23,8 +34,21 @@ var AllCommands = []*discordgo.ApplicationCommand{
cmdlevel.Rank,
cmdlevel.Leaderboard,
cmdlevel.Rewards,
cmdmusic.Play,
cmdmusic.Queue,
cmdmusic.Volume,
cmdmusic.Music,
meeting.Meeting,
moderation.Moderation,
timezone.Timezone,
schedule.Schedule,
projects.Projects,
config.Config,
cmdtickets.Tickets,
cmdtickets.Ticket,
cmdsecurity.Security,
cmdsecurity.Lockdown,
cmdsecurity.Unlock,
}
var handlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
@@ -41,11 +65,74 @@ var handlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCre
"leaderboard": cmdlevel.LeaderboardHandler,
"rewards": cmdlevel.RewardsHandler,
"meeting": meeting.MeetingHandler,
"moderation": moderation.ModerationHandler,
"timezone": timezone.TimezoneHandler,
"schedule": schedule.ScheduleHandler,
"projects": projects.ProjectsHandler,
"play": cmdmusic.PlayHandler,
"queue": cmdmusic.QueueHandler,
"volume": cmdmusic.VolumeHandler,
"music": cmdmusic.MusicHandler,
"config": config.ConfigHandler,
"tickets": cmdtickets.TicketsHandler,
"ticket": cmdtickets.TicketHandler,
"security": cmdsecurity.SecurityHandler,
"lockdown": cmdsecurity.LockdownHandler,
"unlock": cmdsecurity.UnlockHandler,
}
// BetaCommands are the beta features' slash commands. They're registered in
// the beta server only, so nobody else even sees them, and each handler is
// wrapped so it runs only for members with the Beta Tester role (see the beta
// package). To put a feature in beta, add it with RegisterBeta instead of to
// AllCommands and handlers; to release it, move it there.
var BetaCommands = []*discordgo.ApplicationCommand{}
// OwnerCommands are registered globally but can only be used in a direct
// message with the bot, so they are in no server's menu. /beta is the bot
// owner's control over the beta program (see betacmd).
var OwnerCommands = []*discordgo.ApplicationCommand{betacmd.Beta}
func init() {
handlers[betacmd.Beta.Name] = betacmd.Handler
}
// RegisterBeta adds a slash command that only beta testers can use.
func RegisterBeta(cmd *discordgo.ApplicationCommand, h func(s *discordgo.Session, i *discordgo.InteractionCreate)) {
BetaCommands = append(BetaCommands, cmd)
handlers[cmd.Name] = beta.Gate(h)
}
func HandleInteraction(s *discordgo.Session, i *discordgo.InteractionCreate) {
switch i.Type {
case discordgo.InteractionApplicationCommand:
if h, ok := handlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
case discordgo.InteractionMessageComponent:
data := i.MessageComponentData()
switch {
case strings.HasPrefix(data.CustomID, "music:"):
music.HandleComponent(s, i)
case strings.HasPrefix(data.CustomID, "schedule:"):
schedule.HandleComponent(s, i)
case strings.HasPrefix(data.CustomID, "projects:"):
projects.HandleComponent(s, i)
case strings.HasPrefix(data.CustomID, "tickets:"):
cmdtickets.HandleComponent(s, i)
case strings.HasPrefix(data.CustomID, "security:"):
cmdsecurity.HandleComponent(s, i)
}
case discordgo.InteractionModalSubmit:
data := i.ModalSubmitData()
switch {
case strings.HasPrefix(data.CustomID, "schedule:"):
schedule.HandleModalSubmit(s, i)
case strings.HasPrefix(data.CustomID, "projects:"):
projects.HandleModalSubmit(s, i)
case strings.HasPrefix(data.CustomID, "tickets:"):
cmdtickets.HandleModalSubmit(s, i)
}
}
}
+582
View File
@@ -0,0 +1,582 @@
package public
import (
"context"
"log"
"strconv"
"strings"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var Config = &discordgo.ApplicationCommand{
Name: "config",
Description: "Server configuration",
Options: append([]*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "addstreamer",
Description: "Add a Twitch streamer for live notifications",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "username",
Description: "Twitch username (without https://)",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "removestreamer",
Description: "Remove a Twitch streamer from live notifications",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "username",
Description: "Twitch username to remove",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "settwitchnotificationchannel",
Description: "Set the channel for Twitch live notifications",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Text channel for notifications",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setwelcomechannel",
Description: "Set the channel for welcome messages",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Text channel for welcomes",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setwelcomemessage",
Description: "Set the welcome message template shown in the server",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "message",
Description: "Use {user} where the new member mention should appear",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setwelcomedm",
Description: "Set the welcome DM template sent to new members",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "message",
Description: "Use {user} where the new member mention should appear",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setwelcomegif",
Description: "Set the GIF/image URL used in welcome messages",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "url",
Description: "Direct image or GIF URL",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setdefaultrole",
Description: "Set the default role given to new members",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionRole,
Name: "role",
Description: "Role to assign on join",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setlogchannel",
Description: "Set the moderation log channel",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Text channel for logs",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "enablelogging",
Description: "Enable server logging events",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "disablelogging",
Description: "Disable server logging events",
},
}, extraOptions()...),
}
func ConfigHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.GuildID == "" {
respondEphemeral(s, i, "This command can only be used in a server.")
return
}
if i.Member == nil || (i.Member.Permissions&discordgo.PermissionManageGuild) == 0 {
respondEphemeral(s, i, "You need the **Manage Server** permission to use this.")
return
}
if services.Global == nil {
respondEphemeral(s, i, "Configuration services are not available.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
respondEphemeral(s, i, "Missing subcommand.")
return
}
if handleExtra(s, i, data.Options[0]) {
return
}
switch data.Options[0].Name {
case "addstreamer":
log.Printf("twitch: /config addstreamer invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleAddStreamer(s, i)
case "removestreamer":
log.Printf("twitch: /config removestreamer invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleRemoveStreamer(s, i)
case "settwitchnotificationchannel":
log.Printf("twitch: /config settwitchnotificationchannel invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetChannel(s, i)
case "setwelcomechannel":
log.Printf("welcome: /config setwelcomechannel invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetWelcomeChannel(s, i)
case "setwelcomemessage":
log.Printf("welcome: /config setwelcomemessage invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetWelcomeMessage(s, i)
case "setwelcomedm":
log.Printf("welcome: /config setwelcomedm invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetWelcomeDM(s, i)
case "setwelcomegif":
log.Printf("welcome: /config setwelcomegif invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetWelcomeGIF(s, i)
case "setdefaultrole":
log.Printf("defaultrole: /config setdefaultrole invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetDefaultRole(s, i)
case "setlogchannel":
log.Printf("log: /config setlogchannel invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetLogChannel(s, i)
case "enablelogging":
log.Printf("log: /config enablelogging invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetLoggingEnabled(s, i, true)
case "disablelogging":
log.Printf("log: /config disablelogging invoked by %s in guild %s", i.Member.User.ID, i.GuildID)
handleSetLoggingEnabled(s, i, false)
default:
respondEphemeral(s, i, "Unknown subcommand.")
}
}
func handleAddStreamer(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var username string
for _, o := range opt.Options {
if o.Name == "username" {
username = strings.TrimSpace(o.StringValue())
}
}
username = strings.TrimPrefix(username, "https://www.twitch.tv/")
username = strings.TrimPrefix(username, "http://www.twitch.tv/")
username = strings.TrimPrefix(username, "twitch.tv/")
username = strings.TrimSpace(username)
if username == "" {
respondEphemeral(s, i, "Username cannot be empty.")
return
}
if err := services.Global.Twitch.UpsertStreamer(context.Background(), guildID, username); err != nil {
respondEphemeral(s, i, "Failed to add streamer.")
return
}
respondEphemeral(s, i, "Added `"+username+"` for Twitch live notifications.")
}
func handleRemoveStreamer(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var username string
for _, o := range opt.Options {
if o.Name == "username" {
username = strings.TrimSpace(o.StringValue())
}
}
username = strings.TrimSpace(username)
if username == "" {
respondEphemeral(s, i, "Username cannot be empty.")
return
}
if err := services.Global.Twitch.RemoveStreamer(context.Background(), guildID, username); err != nil {
respondEphemeral(s, i, "Failed to remove streamer.")
return
}
respondEphemeral(s, i, "Removed `"+username+"` from Twitch live notifications.")
}
func handleSetChannel(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var chOpt *discordgo.ApplicationCommandInteractionDataOption
for _, o := range opt.Options {
if o.Name == "channel" {
chOpt = o
break
}
}
if chOpt == nil {
respondEphemeral(s, i, "Missing channel option.")
return
}
ch := chOpt.ChannelValue(s)
if ch == nil {
respondEphemeral(s, i, "Invalid channel.")
return
}
chID, err := strconv.ParseInt(ch.ID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid channel ID.")
return
}
if err := services.Global.Twitch.SetNotificationChannel(context.Background(), guildID, chID); err != nil {
respondEphemeral(s, i, "Failed to set notification channel.")
return
}
respondEphemeral(s, i, "Twitch notifications will be sent to "+ch.Mention()+".")
}
func handleSetWelcomeChannel(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.Welcome == nil {
respondEphemeral(s, i, "Welcome configuration is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var chOpt *discordgo.ApplicationCommandInteractionDataOption
for _, o := range opt.Options {
if o.Name == "channel" {
chOpt = o
break
}
}
if chOpt == nil {
respondEphemeral(s, i, "Missing channel option.")
return
}
ch := chOpt.ChannelValue(s)
if ch == nil {
respondEphemeral(s, i, "Invalid channel.")
return
}
chID, err := strconv.ParseInt(ch.ID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid channel ID.")
return
}
if err := services.Global.Welcome.SetChannel(context.Background(), guildID, chID); err != nil {
respondEphemeral(s, i, "Failed to set welcome channel.")
return
}
respondEphemeral(s, i, "Welcome messages will be sent to "+ch.Mention()+".")
}
func handleSetWelcomeMessage(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.Welcome == nil {
respondEphemeral(s, i, "Welcome configuration is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var msg string
for _, o := range opt.Options {
if o.Name == "message" {
msg = strings.TrimSpace(o.StringValue())
}
}
if msg == "" {
respondEphemeral(s, i, "Message cannot be empty.")
return
}
if err := services.Global.Welcome.SetMessage(context.Background(), guildID, msg); err != nil {
respondEphemeral(s, i, "Failed to set welcome message.")
return
}
respondEphemeral(s, i, "Welcome message updated.")
}
func handleSetWelcomeDM(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.Welcome == nil {
respondEphemeral(s, i, "Welcome configuration is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var msg string
for _, o := range opt.Options {
if o.Name == "message" {
msg = strings.TrimSpace(o.StringValue())
}
}
if msg == "" {
respondEphemeral(s, i, "DM message cannot be empty.")
return
}
if err := services.Global.Welcome.SetDM(context.Background(), guildID, msg); err != nil {
respondEphemeral(s, i, "Failed to set welcome DM.")
return
}
respondEphemeral(s, i, "Welcome DM updated.")
}
func handleSetWelcomeGIF(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.Welcome == nil {
respondEphemeral(s, i, "Welcome configuration is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var url string
for _, o := range opt.Options {
if o.Name == "url" {
url = strings.TrimSpace(o.StringValue())
}
}
if url == "" {
respondEphemeral(s, i, "URL cannot be empty.")
return
}
if err := services.Global.Welcome.SetGIF(context.Background(), guildID, url); err != nil {
respondEphemeral(s, i, "Failed to set welcome GIF.")
return
}
respondEphemeral(s, i, "Welcome GIF updated.")
}
func handleSetDefaultRole(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.DefaultRole == nil {
respondEphemeral(s, i, "Default role configuration is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var roleOpt *discordgo.ApplicationCommandInteractionDataOption
for _, o := range opt.Options {
if o.Name == "role" {
roleOpt = o
break
}
}
if roleOpt == nil {
respondEphemeral(s, i, "Missing role option.")
return
}
role := roleOpt.RoleValue(s, i.GuildID)
if role == nil {
respondEphemeral(s, i, "Invalid role.")
return
}
roleID, err := strconv.ParseInt(role.ID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid role ID.")
return
}
if err := services.Global.DefaultRole.SetRole(context.Background(), guildID, roleID); err != nil {
respondEphemeral(s, i, "Failed to set default role.")
return
}
respondEphemeral(s, i, "Default role set to "+role.Mention()+".")
}
func handleSetLogChannel(s *discordgo.Session, i *discordgo.InteractionCreate) {
if services.Global.LogSettings == nil {
respondEphemeral(s, i, "Log settings service is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
opt := i.ApplicationCommandData().Options[0]
var chOpt *discordgo.ApplicationCommandInteractionDataOption
for _, o := range opt.Options {
if o.Name == "channel" {
chOpt = o
break
}
}
if chOpt == nil {
respondEphemeral(s, i, "Missing channel option.")
return
}
ch := chOpt.ChannelValue(s)
if ch == nil {
respondEphemeral(s, i, "Invalid channel.")
return
}
channelID, err := strconv.ParseInt(ch.ID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid channel ID.")
return
}
if err := services.Global.LogSettings.SetChannel(context.Background(), guildID, channelID); err != nil {
respondEphemeral(s, i, "Failed to set log channel.")
return
}
if err := services.Global.LogSettings.SetEnabled(context.Background(), guildID, true); err != nil {
respondEphemeral(s, i, "Log channel set, but failed to enable logging.")
return
}
respondEphemeral(s, i, "Logging enabled in "+ch.Mention()+".")
}
func handleSetLoggingEnabled(s *discordgo.Session, i *discordgo.InteractionCreate, enabled bool) {
if services.Global.LogSettings == nil {
respondEphemeral(s, i, "Log settings service is not available.")
return
}
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
respondEphemeral(s, i, "Invalid guild ID.")
return
}
if err := services.Global.LogSettings.SetEnabled(context.Background(), guildID, enabled); err != nil {
respondEphemeral(s, i, "Failed to update logging state.")
return
}
if enabled {
respondEphemeral(s, i, "Logging is now enabled.")
return
}
respondEphemeral(s, i, "Logging is now disabled.")
}
func respondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
+214
View File
@@ -0,0 +1,214 @@
package public
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// Everything else /config needs so that no setting depends on a dashboard:
// seeing the settings, clearing one, switching Twitch alerts on and off,
// listing streamers, and the server owner's beta features switch.
var clearChoices = []string{"welcome-channel", "welcome-message", "welcome-dm", "welcome-gif", "default-role", "log-channel"}
func extraOptions() []*discordgo.ApplicationCommandOption {
clear := &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionString, Name: "setting", Description: "What to clear", Required: true,
}
for _, c := range clearChoices {
clear.Choices = append(clear.Choices, &discordgo.ApplicationCommandOptionChoice{Name: c, Value: c})
}
return []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "view", Description: "Show the welcome, role, logging and Twitch settings"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "clear", Description: "Clear a welcome, role or log setting", Options: []*discordgo.ApplicationCommandOption{clear}},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "toggletwitch", Description: "Turn Twitch live notifications on or off",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionBoolean, Name: "enabled", Description: "On or off", Required: true}},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "streamers", Description: "List the Twitch streamers being watched"},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "beta-features",
Description: "Let testers use beta features here. Only the server owner can change it",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionBoolean, Name: "enabled", Description: "On or off. Leave out to see the state"}},
},
}
}
func guildInt(i *discordgo.InteractionCreate) int64 {
n, _ := strconv.ParseInt(i.GuildID, 10, 64)
return n
}
func ownerOf(s *discordgo.Session, guildID string) (string, error) {
if g, err := s.State.Guild(guildID); err == nil && g != nil && g.OwnerID != "" {
return g.OwnerID, nil
}
g, err := s.Guild(guildID)
if err != nil {
return "", err
}
return g.OwnerID, nil
}
// handleExtra runs the subcommands above. It reports whether it handled name.
func handleExtra(s *discordgo.Session, i *discordgo.InteractionCreate, sub *discordgo.ApplicationCommandInteractionDataOption) bool {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
g := guildInt(i)
svc := services.Global
args := map[string]*discordgo.ApplicationCommandInteractionDataOption{}
for _, o := range sub.Options {
args[o.Name] = o
}
fail := func(err error) {
respondEphemeral(s, i, "Something went wrong. Try again in a moment.")
log.Printf("config %s: %v", sub.Name, err)
}
switch sub.Name {
case "view":
var b strings.Builder
if w, err := svc.Welcome.GetSettings(ctx, g); err == nil {
fmt.Fprintf(&b, "**Welcome**\nChannel: %s\nMessage: %s\nDM: %s\nGIF: %s\n", mention("#", w.ChannelID), textOr(w.WelcomeMessage), textOr(w.WelcomeDM), textOr(w.WelcomeGIFURL))
}
if r, err := svc.DefaultRole.GetRole(ctx, g); err == nil {
fmt.Fprintf(&b, "**Default role:** %s\n", mention("@&", r))
}
if l, err := svc.LogSettings.GetSettings(ctx, g); err == nil && l != nil {
state := "off"
if l.IsEnabled {
state = "on"
}
fmt.Fprintf(&b, "**Logging:** %s, channel %s\n", state, mention("#", l.ChannelID))
} else {
b.WriteString("**Logging:** off\n")
}
if on, err := svc.Twitch.IsEnabled(ctx, g); err == nil {
ch, _, _ := svc.Twitch.GetNotificationChannel(ctx, g)
users, _ := svc.Twitch.ListUsersForGuild(ctx, g)
state := "off"
if on {
state = "on"
}
fmt.Fprintf(&b, "**Twitch alerts:** %s, channel %s, %d streamer(s)\n", state, mention("#", ch), len(users))
}
respondEphemeral(s, i, clipConfig(b.String(), 1900))
case "clear":
var err error
setting := args["setting"].StringValue()
switch setting {
case "welcome-channel":
err = svc.Welcome.SetChannel(ctx, g, 0)
case "welcome-message":
err = svc.Welcome.SetMessage(ctx, g, "")
case "welcome-dm":
err = svc.Welcome.SetDM(ctx, g, "")
case "welcome-gif":
err = svc.Welcome.SetGIF(ctx, g, "")
case "default-role":
err = svc.DefaultRole.SetRole(ctx, g, 0)
case "log-channel":
err = svc.LogSettings.SetChannel(ctx, g, 0)
default:
respondEphemeral(s, i, "Unknown setting.")
return true
}
if err != nil {
fail(err)
return true
}
respondEphemeral(s, i, "Cleared **"+setting+"**.")
case "toggletwitch":
on := args["enabled"].BoolValue()
if err := svc.Twitch.SetEnabled(ctx, g, on); err != nil {
fail(err)
return true
}
if on {
if ch, ok, _ := svc.Twitch.GetNotificationChannel(ctx, g); !ok || ch == 0 {
respondEphemeral(s, i, "Twitch alerts are **on**, but there is no channel yet. Set one with `/config settwitchnotificationchannel`.")
return true
}
respondEphemeral(s, i, "Twitch alerts are **on**.")
} else {
respondEphemeral(s, i, "Twitch alerts are **off**.")
}
case "streamers":
users, err := svc.Twitch.ListUsersForGuild(ctx, g)
if err != nil {
fail(err)
return true
}
if len(users) == 0 {
respondEphemeral(s, i, "No streamers yet. Add one with `/config addstreamer`.")
return true
}
respondEphemeral(s, i, clipConfig("Watching: "+strings.Join(users, ", "), 1900))
case "beta-features":
on, err := svc.BetaSettings.IsOptedIn(ctx, g)
if err != nil {
fail(err)
return true
}
state := "off"
if on {
state = "on"
}
want, ok := args["enabled"]
if !ok {
respondEphemeral(s, i, "Beta features are **"+state+"** in this server. Testers can use them here when this is on. Only the server owner can change it.")
return true
}
owner, err := ownerOf(s, i.GuildID)
if err != nil {
fail(err)
return true
}
if i.Member == nil || i.Member.User == nil || i.Member.User.ID != owner {
respondEphemeral(s, i, "Only the server owner can change this. Beta features can act on the whole server.")
return true
}
by, _ := strconv.ParseInt(owner, 10, 64)
if err := svc.BetaSettings.SetOptedIn(ctx, g, by, want.BoolValue()); err != nil {
fail(err)
return true
}
if want.BoolValue() {
respondEphemeral(s, i, "Beta features are **on**. Beta commands appear here within a minute, for testers only.")
} else {
respondEphemeral(s, i, "Beta features are **off**. Beta commands disappear from this server within a minute.")
}
default:
return false
}
return true
}
func mention(prefix string, id int64) string {
if id == 0 {
return "not set"
}
return fmt.Sprintf("<%s%d>", prefix, id)
}
func textOr(v string) string {
if strings.TrimSpace(v) == "" {
return "not set"
}
return "`" + clipConfig(v, 120) + "`"
}
func clipConfig(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n-1]) + "…"
}
return s
}
+14
View File
@@ -0,0 +1,14 @@
package config
import (
"velox-bot/internal/commands/config/public"
"github.com/bwmarrin/discordgo"
)
var (
Config *discordgo.ApplicationCommand = public.Config
)
func ConfigHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.ConfigHandler(s, i) }
+91 -81
View File
@@ -2,6 +2,7 @@ package help
import (
"log"
"unicode/utf8"
"github.com/bwmarrin/discordgo"
)
@@ -11,6 +12,91 @@ var Help = &discordgo.ApplicationCommand{
Description: "Get help with the bot",
}
// A message's embeds share a limit of 6000 characters, and one embed holds at
// most 25 fields of 1024 characters. The reference is longer than that, so it
// is sent as a few messages.
const (
maxEmbedChars = 5000
maxFieldChars = 1024
)
// docsURL is where each command is explained in full, with its options and
// who may use it.
const docsURL = "https://velox.fernandovideira.com/docs/commands"
// col is one short column of the help: a list of commands, no descriptions.
// Fields are inline, so Discord lays three of them side by side and the help
// is wide and short instead of narrow and long.
func col(name string, lines ...string) *discordgo.MessageEmbedField {
v := ""
for i, l := range lines {
if i > 0 {
v += "\n"
}
v += l
}
return &discordgo.MessageEmbedField{Name: name, Value: v, Inline: true}
}
func fields() []*discordgo.MessageEmbedField {
return []*discordgo.MessageEmbedField{
col("Fun",
"`/ping` `/joke` `/coinflip`", "`/dice` `/rps` `/rpsstats`", "`/rpsleaderboard`"),
col("Music (DJ role)",
"`/play` `/queue` `/volume`", "`/music skip` `pause` `resume`", "`/music stop` `repeat`", "`/music remove` `move`", "`/music toggle` (Manage Server)"),
col("Sessions and time",
"`/schedule create`", "`/schedule list`", "`/schedule reschedule`", "`/timezone set` `show`"),
col("Tickets",
"Open one from the panel.", "`/ticket add` `close`", "`/ticket claim` `remove` (staff)", "`/tickets setup` `settings`", "`/tickets category` `panel` `list`"),
col("Security",
"`/security status` `settings` `history`", "`/security toggle`", "`/security joingate` `words` `raid`", "`/security antinuke` `heat` `alert-dms`", "`/security trust` `release` `end-raid`", "`/security alerts` `quarantine-role`", "`/security snapshot` `restore`", "`/lockdown` `/unlock`"),
col("Moderation",
"`/moderation purge`", "`/moderation timeout` `untimeout`", "`/moderation kick` `ban` `unban`", "`/moderation slowmode`", "`/moderation bans` `timeouts`"),
col("Meeting rooms",
"`/meeting add-lobby`", "`/meeting remove-lobby` `lobbies`", "`/meeting lock` `lock-private`", "`/meeting unlock`", "`/meeting invite` `uninvite`"),
col("Leveling",
"`/rank` `/leaderboard` `/rewards`", "`/slvl toggle` `status`", "`/slvl set` `set-channel`", "`/slvl set-message`", "`/slvl set-reward` `remove-reward`"),
col("Projects",
"`/projects list`", "`/projects create`", "`/projects add-helper`", "`/projects close`"),
col("Welcome and roles",
"`/config setwelcomechannel`", "`/config setwelcomemessage`", "`/config setwelcomedm`", "`/config setwelcomegif`", "`/config setdefaultrole`"),
col("Logging and Twitch",
"`/config setlogchannel`", "`/config enablelogging` `disablelogging`", "`/config addstreamer` `removestreamer`", "`/config streamers`", "`/config toggletwitch`", "`/config settwitchnotificationchannel`"),
col("Settings and beta",
"`/config view` `clear`", "`/config beta-features` (server owner)", "Bot owner, in a DM with me:", "`/beta set` `off` `status`"),
{
Name: "Everything in detail",
Value: "Options, permissions and what each command does: " + docsURL + "\nMost setup commands need **Manage Server**. `/help` shows this list again.",
},
}
}
func fieldSize(f *discordgo.MessageEmbedField) int {
return utf8.RuneCountInString(f.Name) + utf8.RuneCountInString(f.Value)
}
// embeds splits the reference into embeds that fit Discord's limits.
func embeds(author *discordgo.MessageEmbedAuthor) []*discordgo.MessageEmbed {
var out []*discordgo.MessageEmbed
cur := &discordgo.MessageEmbed{
Title: "Velox Bot Help",
Description: "Every command, by area. Some need server permissions or a role.",
Color: 0xFFA500,
Author: author,
}
size := utf8.RuneCountInString(cur.Title) + utf8.RuneCountInString(cur.Description) + utf8.RuneCountInString(author.Name)
for _, f := range fields() {
if size+fieldSize(f) > maxEmbedChars || len(cur.Fields) >= 25 {
out = append(out, cur)
cur = &discordgo.MessageEmbed{Title: "Velox Bot Help (continued)", Color: 0xFFA500}
size = utf8.RuneCountInString(cur.Title)
}
cur.Fields = append(cur.Fields, f)
size += fieldSize(f)
}
return append(out, cur)
}
func HelpHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
@@ -40,86 +126,10 @@ func HelpHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
URL: "https://gitea.fernandovideira.com/FernandoJVideira/velox-bot",
}
embed := &discordgo.MessageEmbed{
Title: "Velox Bot Help",
Description: "Here is the help for the bot.",
Color: 0xFFA500,
Fields: []*discordgo.MessageEmbedField{
{
Name: "Fun Commands",
Value: "Small utility + games.",
},
{
Name: "/ping",
Value: "Pong!",
},
{
Name: "/joke [type]",
Value: "Get a random joke (optional category).",
},
{
Name: "/coinflip",
Value: "Flip a coin.",
},
{
Name: "/dice <expr>",
Value: "Roll dice expressions (e.g. `d20`, `2d20+1`, `2#d20+1`).",
},
{
Name: "/rps <hand>",
Value: "Play Rock Paper Scissors (server only).",
},
{
Name: "/rpsstats",
Value: "Show your RPS score (server only).",
},
{
Name: "/rpsleaderboard",
Value: "Show top RPS scores (server only).",
},
{
Name: "/help",
Value: "Get help with the bot.",
},
{
Name: "Leveling System",
Value: `The leveling system is a system that allows users to gain XP and level up. The system is based on the amount of messages sent in a server. The more messages you send, the more XP you gain. The more XP you gain, the higher your level will be. The leveling system is disabled by default, however you can enable/disable it by using the /slvl toggle command. You can also configure the leveling system by using the /slvl command.`,
},
{
Name: "/slvl toggle",
Value: "Toggle the leveling system.",
},
{
Name: "/slvl set",
Value: "Set the level of a user.",
},
{
Name: "/slvl set-channel",
Value: "Set the channel for level-up messages.",
},
{
Name: "/slvl set-message",
Value: "Set the custom level-up message.",
},
{
Name: "/slvl set-reward",
Value: "Set a role reward for a level.",
},
{
Name: "/rank [user]",
Value: "Show a rank card (server only).",
},
{
Name: "/leaderboard",
Value: "Show top levels (server only).",
},
{
Name: "/rewards",
Value: "List configured level rewards (server only).",
},
},
Author: &author,
for _, e := range embeds(&author) {
if _, err := s.ChannelMessageSendEmbed(dmChannel.ID, e); err != nil {
log.Printf("Error sending help: %v", err)
return
}
}
s.ChannelMessageSendEmbed(dmChannel.ID, embed)
}
+57
View File
@@ -0,0 +1,57 @@
package help
import (
"testing"
"unicode/utf8"
"github.com/bwmarrin/discordgo"
)
// Discord refuses an embed that is over its limits, and then /help would send
// nothing. This catches it when a command is added to the text.
func TestHelpFitsDiscordsLimits(t *testing.T) {
list := embeds(&discordgo.MessageEmbedAuthor{Name: "Velox Bot"})
if len(list) == 0 {
t.Fatal("no help")
}
seen := 0
for n, e := range list {
total := utf8.RuneCountInString(e.Title) + utf8.RuneCountInString(e.Description)
if len(e.Fields) > 25 {
t.Errorf("embed %d has %d fields, at most 25", n, len(e.Fields))
}
for _, f := range e.Fields {
seen++
if l := utf8.RuneCountInString(f.Value); l == 0 || l > maxFieldChars {
t.Errorf("field %q has %d characters, must be 1 to %d", f.Name, l, maxFieldChars)
}
if l := utf8.RuneCountInString(f.Name); l == 0 || l > 256 {
t.Errorf("field name %q has %d characters, at most 256", f.Name, l)
}
total += fieldSize(f)
}
if total > 6000 {
t.Errorf("embed %d has %d characters, Discord allows 6000", n, total)
}
}
if seen != len(fields()) {
t.Errorf("%d fields shown of %d", seen, len(fields()))
}
}
// The help is meant to be wide and short: inline fields, so Discord puts
// three side by side, and it should fit in one message.
func TestHelpIsCompactAndInline(t *testing.T) {
if n := len(embeds(&discordgo.MessageEmbedAuthor{Name: "Velox Bot"})); n != 1 {
t.Errorf("the help should fit in one message, it takes %d", n)
}
inline := 0
for _, f := range fields() {
if f.Inline {
inline++
}
}
if inline < len(fields())-2 {
t.Errorf("only %d of %d fields are inline", inline, len(fields()))
}
}
@@ -15,6 +15,8 @@ var Slvl = &discordgo.ApplicationCommand{
slvlSetChannelOption(),
slvlSetMessageOption(),
slvlSetRewardOption(),
slvlRemoveRewardOption(),
slvlStatusOption(),
},
}
@@ -34,6 +36,10 @@ func SlvlHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
slvlSetMessageHandler(s, i)
case "set-reward":
slvlSetRewardHandler(s, i)
case "remove-reward":
slvlRemoveRewardHandler(s, i)
case "status":
slvlStatusHandler(s, i)
default:
shared.RespondEphemeral(s, i, "Invalid subcommand.")
}
+99
View File
@@ -0,0 +1,99 @@
package config
import (
"context"
"fmt"
"strconv"
"strings"
"velox-bot/internal/commands/level/shared"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// Looking at the leveling settings and removing a role reward, so nothing
// about leveling needs a dashboard.
func slvlRemoveRewardOption() *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "remove-reward", Description: "Remove the role reward of a level",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionInteger, Name: "level", Description: "The level", Required: true},
},
}
}
func slvlStatusOption() *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "status", Description: "Show the leveling settings",
}
}
func slvlRemoveRewardHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) || !shared.RequireLevelSystemEnabled(s, i) || !shared.RequireLevelSettingsService(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
level := int(shared.SubcommandOptionMap(i)["level"].IntValue())
removed, err := services.Global.LevelSettings.DeleteRoleRewardForLevel(context.Background(), guildID, level)
switch {
case err != nil:
shared.RespondEphemeral(s, i, "Failed to remove the reward.")
case !removed:
shared.RespondEphemeral(s, i, "Level "+strconv.Itoa(level)+" has no role reward.")
default:
shared.RespondEphemeral(s, i, "Removed the reward for level "+strconv.Itoa(level)+".")
}
}
func slvlStatusHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) || !shared.RequireLevelSettingsService(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
ctx := context.Background()
ls := services.Global.LevelSettings
enabled, err := ls.IsLevelSystemEnabled(ctx, guildID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load the settings.")
return
}
state := "off"
if enabled {
state = "on"
}
var b strings.Builder
fmt.Fprintf(&b, "**Leveling:** %s\n", state)
if ch, ok, _ := ls.GetLevelUpChannelID(ctx, guildID); ok && ch != 0 {
fmt.Fprintf(&b, "**Level-up channel:** <#%d>\n", ch)
} else {
b.WriteString("**Level-up channel:** the channel of the message\n")
}
if msg, err := ls.GetLevelUpMessage(ctx, guildID); err == nil {
fmt.Fprintf(&b, "**Level-up message:** %s\n", msg)
}
rewards, _ := ls.ListRoleRewards(ctx, guildID, 25)
if len(rewards) == 0 {
b.WriteString("**Role rewards:** none")
} else {
b.WriteString("**Role rewards:** ")
for n, r := range rewards {
if n > 0 {
b.WriteString(", ")
}
fmt.Fprintf(&b, "level %d → <@&%d>", r.Level, r.RoleID)
}
}
out := b.String()
if r := []rune(out); len(r) > 1900 {
out = string(r[:1899]) + "…"
}
shared.RespondEphemeral(s, i, out)
}
+106
View File
@@ -0,0 +1,106 @@
package commands
import (
"regexp"
"testing"
"unicode/utf8"
"github.com/bwmarrin/discordgo"
)
// Discord refuses a command that is over its limits, and then the whole
// command silently doesn't exist. These checks catch that in a test instead
// of after a deploy. See
// https://discord.com/developers/docs/interactions/application-commands
var commandName = regexp.MustCompile(`^[-_\p{L}\p{N}]{1,32}$`)
func checkOptions(t *testing.T, path string, options []*discordgo.ApplicationCommandOption, size *int) {
t.Helper()
if len(options) > 25 {
t.Errorf("%s: %d options, at most 25 allowed", path, len(options))
}
seen := map[string]bool{}
sawOptional := false
for _, o := range options {
where := path + " " + o.Name
if !commandName.MatchString(o.Name) || o.Name != lower(o.Name) {
t.Errorf("%s: option names are 1 to 32 lowercase letters, digits, - or _", where)
}
if seen[o.Name] {
t.Errorf("%s: duplicate option name", where)
}
seen[o.Name] = true
if n := utf8.RuneCountInString(o.Description); n < 1 || n > 100 {
t.Errorf("%s: description is %d characters, must be 1 to 100", where, n)
}
*size += utf8.RuneCountInString(o.Name) + utf8.RuneCountInString(o.Description)
if len(o.Choices) > 25 {
t.Errorf("%s: %d choices, at most 25", where, len(o.Choices))
}
for _, c := range o.Choices {
*size += utf8.RuneCountInString(c.Name)
if s, ok := c.Value.(string); ok {
*size += utf8.RuneCountInString(s)
if utf8.RuneCountInString(s) > 100 || utf8.RuneCountInString(c.Name) > 100 {
t.Errorf("%s: a choice is over 100 characters", where)
}
}
}
switch o.Type {
case discordgo.ApplicationCommandOptionSubCommand, discordgo.ApplicationCommandOptionSubCommandGroup:
if len(o.Options) == 0 && o.Type == discordgo.ApplicationCommandOptionSubCommandGroup {
t.Errorf("%s: a group needs subcommands", where)
}
checkOptions(t, where, o.Options, size)
default:
// Required options come before optional ones.
if o.Required && sawOptional {
t.Errorf("%s: a required option after an optional one", where)
}
if !o.Required {
sawOptional = true
}
}
}
}
func lower(s string) string {
out := []rune(s)
for i, r := range out {
if r >= 'A' && r <= 'Z' {
out[i] = r + 32
}
}
return string(out)
}
func TestCommandsStayWithinDiscordLimits(t *testing.T) {
all := append(append(append([]*discordgo.ApplicationCommand{}, AllCommands...), BetaCommands...), OwnerCommands...)
names := map[string]bool{}
for _, c := range all {
if names[c.Name] {
t.Errorf("/%s is defined twice", c.Name)
}
names[c.Name] = true
if !commandName.MatchString(c.Name) || c.Name != lower(c.Name) {
t.Errorf("/%s: names are 1 to 32 lowercase letters, digits, - or _", c.Name)
}
if n := utf8.RuneCountInString(c.Description); n < 1 || n > 100 {
t.Errorf("/%s: description is %d characters, must be 1 to 100", c.Name, n)
}
size := utf8.RuneCountInString(c.Name) + utf8.RuneCountInString(c.Description)
checkOptions(t, "/"+c.Name, c.Options, &size)
if size > 8000 {
t.Errorf("/%s: %d characters in total, Discord allows 8000", c.Name, size)
}
if _, ok := handlers[c.Name]; !ok {
t.Errorf("/%s has no handler", c.Name)
}
}
for name := range handlers {
if !names[name] {
t.Errorf("a handler for /%s exists but the command is never registered", name)
}
}
}
+102 -16
View File
@@ -2,11 +2,14 @@ package public
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"velox-bot/internal/commands/meeting/shared"
"velox-bot/internal/db/services"
meetingsvc "velox-bot/internal/db/services/meeting"
"github.com/bwmarrin/discordgo"
)
@@ -17,18 +20,37 @@ var Meeting = &discordgo.ApplicationCommand{
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "set-lobby",
Description: "Set the voice lobby channel used to create meetings",
Name: "add-lobby",
Description: "Add a voice lobby: joining it creates a meeting room",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Voice channel lobby",
Description: "Voice channel to use as a lobby",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildVoice},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "remove-lobby",
Description: "Stop using a voice channel as a lobby",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "The lobby to remove",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildVoice},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "lobbies",
Description: "List this server's meeting lobbies",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "lock",
@@ -85,8 +107,12 @@ func MeetingHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
}
switch data.Options[0].Name {
case "set-lobby":
handleSetLobby(s, i)
case "add-lobby":
handleAddLobby(s, i)
case "remove-lobby":
handleRemoveLobby(s, i)
case "lobbies":
handleListLobbies(s, i)
case "lock":
handleLock(s, i)
case "lock-private":
@@ -102,37 +128,97 @@ func MeetingHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
}
}
func handleSetLobby(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
// lobbyChannelOption reads the "channel" option of add-lobby and
// remove-lobby, answering the user itself if it's missing or not a voice
// channel.
func lobbyChannelOption(s *discordgo.Session, i *discordgo.InteractionCreate) (*discordgo.Channel, int64, bool) {
optMap := shared.SubcommandOptionMap(i)
channelOpt, ok := optMap["channel"]
if !ok {
shared.RespondEphemeral(s, i, "Missing channel option.")
return
return nil, 0, false
}
ch := channelOpt.ChannelValue(s)
if ch == nil || ch.Type != discordgo.ChannelTypeGuildVoice {
shared.RespondEphemeral(s, i, "Invalid voice channel.")
return
return nil, 0, false
}
channelID, err := strconv.ParseInt(ch.ID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid channel ID.")
return nil, 0, false
}
return ch, channelID, true
}
func handleAddLobby(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
ch, channelID, ok := lobbyChannelOption(s, i)
if !ok {
return
}
if err := services.Global.Meeting.SetLobbyChannel(context.Background(), guildID, channelID); err != nil {
shared.RespondEphemeral(s, i, "Failed to set meeting lobby.")
added, err := services.Global.Meeting.AddLobby(context.Background(), guildID, channelID)
switch {
case errors.Is(err, meetingsvc.ErrLobbyLimit):
shared.RespondEphemeral(s, i, fmt.Sprintf("This server already has %d lobbies. Remove one with `/meeting remove-lobby` first.", meetingsvc.MaxLobbies))
case err != nil:
shared.RespondEphemeral(s, i, "Failed to add the meeting lobby.")
case !added:
shared.RespondEphemeral(s, i, ch.Mention()+" is already a meeting lobby.")
default:
shared.RespondEphemeral(s, i, ch.Mention()+" is now a meeting lobby.")
}
}
func handleRemoveLobby(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
ch, channelID, ok := lobbyChannelOption(s, i)
if !ok {
return
}
shared.RespondEphemeral(s, i, "Meeting lobby set to "+ch.Mention()+".")
removed, err := services.Global.Meeting.RemoveLobby(context.Background(), guildID, channelID)
switch {
case err != nil:
shared.RespondEphemeral(s, i, "Failed to remove the meeting lobby.")
case !removed:
shared.RespondEphemeral(s, i, ch.Mention()+" isn't a meeting lobby.")
default:
shared.RespondEphemeral(s, i, ch.Mention()+" is no longer a meeting lobby.")
}
}
func handleListLobbies(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
ids, err := services.Global.Meeting.ListLobbies(context.Background(), guildID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to list the meeting lobbies.")
return
}
if len(ids) == 0 {
shared.RespondEphemeral(s, i, "No meeting lobbies yet. Add one with `/meeting add-lobby`.")
return
}
var b strings.Builder
fmt.Fprintf(&b, "Meeting lobbies (%d of %d):\n", len(ids), meetingsvc.MaxLobbies)
for _, id := range ids {
fmt.Fprintf(&b, "<#%d>\n", id)
}
shared.RespondEphemeral(s, i, b.String())
}
func handleLock(s *discordgo.Session, i *discordgo.InteractionCreate) {
@@ -0,0 +1,106 @@
package public
import (
"context"
"fmt"
"strings"
"time"
"github.com/bwmarrin/discordgo"
)
// Looking at who is banned and who is timed out, so unbanning and ending a
// timeout never needs a dashboard to find the person first.
func listOptions() []*discordgo.ApplicationCommandOption {
return []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "bans", Description: "List banned users, to use with /moderation unban"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "timeouts", Description: "List members who are timed out right now"},
}
}
const listShown = 20
func handleBans(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionBanMembers) {
respondEphemeral(s, i, "You need **Ban Members** for this command.")
return
}
bans, err := s.GuildBans(i.GuildID, 1000, "", "")
if err != nil {
respondEphemeral(s, i, "I couldn't read the ban list. I need the **Ban Members** permission.")
return
}
if len(bans) == 0 {
respondEphemeral(s, i, "Nobody is banned.")
return
}
var b strings.Builder
fmt.Fprintf(&b, "**Banned users (%d)**\n", len(bans))
for n, ban := range bans {
if n == listShown {
fmt.Fprintf(&b, "…and %d more.\n", len(bans)-listShown)
break
}
name := "unknown"
id := ""
if ban.User != nil {
name, id = ban.User.Username, ban.User.ID
}
reason := strings.TrimSpace(ban.Reason)
if reason == "" {
reason = "no reason"
}
fmt.Fprintf(&b, "• %s (`%s`): %s\n", escape(name), id, escape(clip(reason, 80)))
}
b.WriteString("Unban with `/moderation unban user_id:<id>`.")
respondEphemeral(s, i, clip(b.String(), 1950))
}
func handleTimeouts(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionModerateMembers) {
respondEphemeral(s, i, "You need **Moderate Members** for this command.")
return
}
_, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
members, err := s.GuildMembers(i.GuildID, "", 1000)
if err != nil {
respondEphemeral(s, i, "I couldn't read the member list.")
return
}
now := time.Now()
var out []*discordgo.Member
for _, m := range members {
if m.CommunicationDisabledUntil != nil && m.CommunicationDisabledUntil.After(now) {
out = append(out, m)
}
}
if len(out) == 0 {
respondEphemeral(s, i, "Nobody is timed out (among the first 1000 members).")
return
}
var b strings.Builder
fmt.Fprintf(&b, "**Timed out (%d)**\n", len(out))
for n, m := range out {
if n == listShown {
fmt.Fprintf(&b, "…and %d more.\n", len(out)-listShown)
break
}
fmt.Fprintf(&b, "• <@%s> until <t:%d:f>\n", m.User.ID, m.CommunicationDisabledUntil.Unix())
}
b.WriteString("End one with `/moderation untimeout`.")
respondEphemeral(s, i, clip(b.String(), 1950))
}
func clip(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n-1]) + "…"
}
return s
}
// escape keeps names and reasons from becoming markdown or mentions.
func escape(s string) string {
return strings.NewReplacer("`", "'", "*", "", "_", " ", "~", "", "@", "@​", "|", "/").Replace(s)
}
@@ -0,0 +1,582 @@
package public
import (
"fmt"
"strings"
"time"
"velox-bot/internal/db/services"
"velox-bot/internal/modlog"
"github.com/bwmarrin/discordgo"
)
var Moderation = &discordgo.ApplicationCommand{
Name: "moderation",
Description: "High-value moderation tools",
Options: append([]*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "purge",
Description: "Delete recent messages in this channel (max 100)",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "amount",
Description: "How many recent messages to delete (1-100)",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "timeout",
Description: "Temporarily timeout a member",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user",
Description: "User to timeout",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "duration",
Description: "Duration like 10m, 1h, 2h30m (max 28d)",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "Optional reason",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "kick",
Description: "Kick a member from the server",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user",
Description: "User to kick",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "Optional reason",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "ban",
Description: "Ban a member from the server",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user",
Description: "User to ban",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "delete_days",
Description: "Delete message history (0-7 days)",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "Optional reason",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "unban",
Description: "Unban a user by ID",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "user_id",
Description: "User ID to unban",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "Optional reason",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "untimeout",
Description: "Remove timeout from a member",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user",
Description: "User to untimeout",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "Optional reason",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "slowmode",
Description: "Set channel slowmode (0 disables)",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Text channel to update",
Required: true,
ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews},
},
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "seconds",
Description: "Slowmode delay in seconds (0-21600)",
Required: true,
},
},
},
}, listOptions()...),
}
func ModerationHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.GuildID == "" {
respondEphemeral(s, i, "This command can only be used in a server.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
respondEphemeral(s, i, "Missing subcommand.")
return
}
switch data.Options[0].Name {
case "purge":
handlePurge(s, i)
case "timeout":
handleTimeout(s, i)
case "kick":
handleKick(s, i)
case "ban":
handleBan(s, i)
case "unban":
handleUnban(s, i)
case "untimeout":
handleUntimeout(s, i)
case "slowmode":
handleSlowmode(s, i)
case "bans":
handleBans(s, i)
case "timeouts":
handleTimeouts(s, i)
default:
respondEphemeral(s, i, "Unknown subcommand.")
}
}
func handlePurge(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionManageMessages) {
respondEphemeral(s, i, "You need **Manage Messages** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var amount int64
for _, o := range opt.Options {
if o.Name == "amount" {
amount = o.IntValue()
break
}
}
if amount < 1 || amount > 100 {
respondEphemeral(s, i, "Amount must be between 1 and 100.")
return
}
msgs, err := s.ChannelMessages(i.ChannelID, int(amount), "", "", "")
if err != nil {
respondEphemeral(s, i, "Failed to fetch messages.")
return
}
if len(msgs) == 0 {
respondEphemeral(s, i, "No messages found to delete.")
return
}
tooOldCutoff := time.Now().Add(-14 * 24 * time.Hour)
ids := make([]string, 0, len(msgs))
for _, m := range msgs {
if m == nil {
continue
}
if m.Timestamp.Before(tooOldCutoff) {
continue
}
ids = append(ids, m.ID)
}
if len(ids) == 0 {
respondEphemeral(s, i, "No messages can be bulk deleted (older than 14 days).")
return
}
if len(ids) == 1 {
if err := s.ChannelMessageDelete(i.ChannelID, ids[0]); err != nil {
respondEphemeral(s, i, "Failed to delete message.")
return
}
respondEphemeral(s, i, "Deleted 1 message.")
sendModerationActionLog(s, i, "Purge", fmt.Sprintf("Deleted 1 message in <#%s>.", i.ChannelID), "")
return
}
if err := s.ChannelMessagesBulkDelete(i.ChannelID, ids); err != nil {
respondEphemeral(s, i, "Failed to bulk delete messages.")
return
}
respondEphemeral(s, i, fmt.Sprintf("Deleted %d messages.", len(ids)))
sendModerationActionLog(s, i, "Purge", fmt.Sprintf("Deleted %d messages in <#%s>.", len(ids), i.ChannelID), "")
}
func handleTimeout(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionModerateMembers) {
respondEphemeral(s, i, "You need **Moderate Members** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var userOpt *discordgo.ApplicationCommandInteractionDataOption
var durationInput string
var reason string
for _, o := range opt.Options {
switch o.Name {
case "user":
userOpt = o
case "duration":
durationInput = strings.TrimSpace(o.StringValue())
case "reason":
reason = strings.TrimSpace(o.StringValue())
}
}
if userOpt == nil {
respondEphemeral(s, i, "Missing user option.")
return
}
target := userOpt.UserValue(s)
if target == nil {
respondEphemeral(s, i, "Invalid user.")
return
}
dur, err := time.ParseDuration(durationInput)
if err != nil || dur <= 0 {
respondEphemeral(s, i, "Invalid duration. Examples: `10m`, `1h`, `2h30m`.")
return
}
maxTimeout := 28 * 24 * time.Hour
if dur > maxTimeout {
respondEphemeral(s, i, "Duration cannot exceed 28 days.")
return
}
until := time.Now().UTC().Add(dur)
if err := s.GuildMemberTimeout(i.GuildID, target.ID, &until); err != nil {
respondEphemeral(s, i, "Failed to timeout user. Check role hierarchy and permissions.")
return
}
if reason == "" {
respondEphemeral(s, i, fmt.Sprintf("Timed out %s for `%s`.", target.Mention(), dur.String()))
sendModerationActionLog(s, i, "Timeout", fmt.Sprintf("Target: %s\nDuration: `%s`", target.Mention(), dur.String()), "")
return
}
respondEphemeral(s, i, fmt.Sprintf("Timed out %s for `%s`. Reason: %s", target.Mention(), dur.String(), reason))
sendModerationActionLog(s, i, "Timeout", fmt.Sprintf("Target: %s\nDuration: `%s`", target.Mention(), dur.String()), reason)
}
func handleKick(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionKickMembers) {
respondEphemeral(s, i, "You need **Kick Members** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var userOpt *discordgo.ApplicationCommandInteractionDataOption
var reason string
for _, o := range opt.Options {
switch o.Name {
case "user":
userOpt = o
case "reason":
reason = strings.TrimSpace(o.StringValue())
}
}
if userOpt == nil {
respondEphemeral(s, i, "Missing user option.")
return
}
target := userOpt.UserValue(s)
if target == nil {
respondEphemeral(s, i, "Invalid user.")
return
}
if i.Member != nil && i.Member.User != nil && target.ID == i.Member.User.ID {
respondEphemeral(s, i, "You cannot kick yourself.")
return
}
if s != nil && s.State != nil && s.State.User != nil && target.ID == s.State.User.ID {
respondEphemeral(s, i, "I can't kick myself.")
return
}
if err := s.GuildMemberDeleteWithReason(i.GuildID, target.ID, reason); err != nil {
respondEphemeral(s, i, "Failed to kick user. Check role hierarchy and permissions.")
return
}
if reason == "" {
respondEphemeral(s, i, "Kicked "+target.Mention()+".")
sendModerationActionLog(s, i, "Kick", "Target: "+target.Mention(), "")
return
}
respondEphemeral(s, i, "Kicked "+target.Mention()+". Reason: "+reason)
sendModerationActionLog(s, i, "Kick", "Target: "+target.Mention(), reason)
}
func handleBan(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionBanMembers) {
respondEphemeral(s, i, "You need **Ban Members** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var userOpt *discordgo.ApplicationCommandInteractionDataOption
var deleteDays int64
var reason string
for _, o := range opt.Options {
switch o.Name {
case "user":
userOpt = o
case "delete_days":
deleteDays = o.IntValue()
case "reason":
reason = strings.TrimSpace(o.StringValue())
}
}
if userOpt == nil {
respondEphemeral(s, i, "Missing user option.")
return
}
target := userOpt.UserValue(s)
if target == nil {
respondEphemeral(s, i, "Invalid user.")
return
}
if deleteDays < 0 || deleteDays > 7 {
respondEphemeral(s, i, "delete_days must be between 0 and 7.")
return
}
if i.Member != nil && i.Member.User != nil && target.ID == i.Member.User.ID {
respondEphemeral(s, i, "You cannot ban yourself.")
return
}
if s != nil && s.State != nil && s.State.User != nil && target.ID == s.State.User.ID {
respondEphemeral(s, i, "I can't ban myself.")
return
}
if err := s.GuildBanCreateWithReason(i.GuildID, target.ID, reason, int(deleteDays)); err != nil {
respondEphemeral(s, i, "Failed to ban user. Check role hierarchy and permissions.")
return
}
if reason == "" {
respondEphemeral(s, i, fmt.Sprintf("Banned %s (deleted %d days of messages).", target.Mention(), deleteDays))
sendModerationActionLog(s, i, "Ban", fmt.Sprintf("Target: %s\nDeleted message days: %d", target.Mention(), deleteDays), "")
return
}
respondEphemeral(s, i, fmt.Sprintf("Banned %s (deleted %d days of messages). Reason: %s", target.Mention(), deleteDays, reason))
sendModerationActionLog(s, i, "Ban", fmt.Sprintf("Target: %s\nDeleted message days: %d", target.Mention(), deleteDays), reason)
}
func handleUnban(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionBanMembers) {
respondEphemeral(s, i, "You need **Ban Members** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var userID string
var reason string
for _, o := range opt.Options {
switch o.Name {
case "user_id":
userID = strings.TrimSpace(o.StringValue())
case "reason":
reason = strings.TrimSpace(o.StringValue())
}
}
if userID == "" {
respondEphemeral(s, i, "Missing user ID.")
return
}
if err := s.GuildBanDelete(i.GuildID, userID); err != nil {
respondEphemeral(s, i, "Failed to unban user. Make sure the user ID is valid and banned.")
return
}
if reason == "" {
respondEphemeral(s, i, "Unbanned user ID `"+userID+"`.")
sendModerationActionLog(s, i, "Unban", "Target user ID: `"+userID+"`", "")
return
}
respondEphemeral(s, i, "Unbanned user ID `"+userID+"`. Reason: "+reason)
sendModerationActionLog(s, i, "Unban", "Target user ID: `"+userID+"`", reason)
}
func handleUntimeout(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionModerateMembers) {
respondEphemeral(s, i, "You need **Moderate Members** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var userOpt *discordgo.ApplicationCommandInteractionDataOption
var reason string
for _, o := range opt.Options {
switch o.Name {
case "user":
userOpt = o
case "reason":
reason = strings.TrimSpace(o.StringValue())
}
}
if userOpt == nil {
respondEphemeral(s, i, "Missing user option.")
return
}
target := userOpt.UserValue(s)
if target == nil {
respondEphemeral(s, i, "Invalid user.")
return
}
if err := s.GuildMemberTimeout(i.GuildID, target.ID, nil); err != nil {
respondEphemeral(s, i, "Failed to remove timeout. Check role hierarchy and permissions.")
return
}
if reason == "" {
respondEphemeral(s, i, "Removed timeout from "+target.Mention()+".")
sendModerationActionLog(s, i, "Timeout Removed", "Target: "+target.Mention(), "")
return
}
respondEphemeral(s, i, "Removed timeout from "+target.Mention()+". Reason: "+reason)
sendModerationActionLog(s, i, "Timeout Removed", "Target: "+target.Mention(), reason)
}
func handleSlowmode(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !hasPerm(i, discordgo.PermissionManageChannels) {
respondEphemeral(s, i, "You need **Manage Channels** for this command.")
return
}
opt := i.ApplicationCommandData().Options[0]
var chOpt *discordgo.ApplicationCommandInteractionDataOption
var seconds int64
for _, o := range opt.Options {
switch o.Name {
case "channel":
chOpt = o
case "seconds":
seconds = o.IntValue()
}
}
if chOpt == nil {
respondEphemeral(s, i, "Missing channel option.")
return
}
if seconds < 0 || seconds > 21600 {
respondEphemeral(s, i, "Seconds must be between 0 and 21600.")
return
}
ch := chOpt.ChannelValue(s)
if ch == nil {
respondEphemeral(s, i, "Invalid channel.")
return
}
secondsInt := int(seconds)
_, err := s.ChannelEditComplex(ch.ID, &discordgo.ChannelEdit{
RateLimitPerUser: &secondsInt,
})
if err != nil {
respondEphemeral(s, i, "Failed to update slowmode.")
return
}
if seconds == 0 {
respondEphemeral(s, i, "Disabled slowmode in "+ch.Mention()+".")
sendModerationActionLog(s, i, "Slowmode", "Channel: "+ch.Mention()+"\nSet to: `0s`", "")
return
}
respondEphemeral(s, i, fmt.Sprintf("Set slowmode in %s to %d seconds.", ch.Mention(), seconds))
sendModerationActionLog(s, i, "Slowmode", fmt.Sprintf("Channel: %s\nSet to: `%ds`", ch.Mention(), seconds), "")
}
func hasPerm(i *discordgo.InteractionCreate, perm int64) bool {
return i.Member != nil && (i.Member.Permissions&perm) == perm
}
func respondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
func sendModerationActionLog(s *discordgo.Session, i *discordgo.InteractionCreate, action, details, reason string) {
if services.Global == nil {
return
}
moderator := "Unknown"
if i != nil && i.Member != nil && i.Member.User != nil {
moderator = i.Member.User.Mention()
}
desc := "Moderator: " + moderator + "\n" + details
if strings.TrimSpace(reason) != "" {
desc += "\nReason: " + reason
}
embed := &discordgo.MessageEmbed{
Title: "Moderation Action: " + action,
Color: 0x5865F2,
Description: desc,
Timestamp: time.Now().Format(time.RFC3339),
}
_ = modlog.Send(s, services.Global, i.GuildID, embed)
}
+16
View File
@@ -0,0 +1,16 @@
package moderation
import (
"velox-bot/internal/commands/moderation/public"
"github.com/bwmarrin/discordgo"
)
var (
Moderation *discordgo.ApplicationCommand = public.Moderation
)
func ModerationHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.ModerationHandler(s, i)
}
@@ -0,0 +1,36 @@
package public
import "github.com/bwmarrin/discordgo"
func memberHasDJRole(s *discordgo.Session, guildID string, m *discordgo.Member) bool {
if s == nil || guildID == "" || m == nil {
return false
}
if len(m.Roles) == 0 {
return false
}
roles, err := s.GuildRoles(guildID)
if err != nil {
return false
}
djRoleID := ""
for _, r := range roles {
if r != nil && r.Name == "DJ" {
djRoleID = r.ID
break
}
}
if djRoleID == "" {
return false
}
for _, rid := range m.Roles {
if rid == djRoleID {
return true
}
}
return false
}
+95
View File
@@ -0,0 +1,95 @@
package public
import (
"fmt"
"velox-bot/internal/commands/music/shared"
"velox-bot/internal/music"
"github.com/bwmarrin/discordgo"
)
var Play = &discordgo.ApplicationCommand{
Name: "play",
Description: "Play a song via Lavalink",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "query",
Description: "Song name or URL",
Required: true,
},
},
}
func PlayHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireMusicEnabled(s, i) {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
query := data.Options[0].StringValue()
// Always acknowledge quickly to avoid "application did not respond".
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Searching...",
},
})
if !memberHasDJRole(s, i.GuildID, i.Member) {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr("You need the **DJ** role to use music commands."),
})
return
}
vs, err := findUserVoiceState(s, i.GuildID, i.Member.User.ID)
if err != nil {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Error: %v", err)),
})
return
}
entry, started, err := music.EnqueueAndPlay(i.GuildID, vs.ChannelID, i.ChannelID, query, i.Member.User.Username, i.Member.User.ID)
if err != nil {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Error: %v", err)),
})
return
}
title := entry.Track.Info.Title
author := entry.Track.Info.Author
length := entry.Track.Info.Length
if started {
// manager will post now-playing message & manage invalidating old buttons
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Starting: **%s** by **%s** `[%ds]`", title, author, length/1000)),
})
} else {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Added to queue: **%s** by **%s** `[%ds]`", title, author, length/1000)),
})
}
}
func ptr[T any](v T) *T { return new(v) }
func findUserVoiceState(s *discordgo.Session, guildID, userID string) (*discordgo.VoiceState, error) {
g, err := s.State.Guild(guildID)
if err != nil {
return nil, fmt.Errorf("cannot find guild voice state")
}
for _, vs := range g.VoiceStates {
if vs.UserID == userID {
return vs, nil
}
}
return nil, fmt.Errorf("you must be in a voice channel")
}
+126
View File
@@ -0,0 +1,126 @@
package public
import (
"fmt"
"strings"
"velox-bot/internal/commands/music/shared"
"velox-bot/internal/music"
"github.com/bwmarrin/discordgo"
)
// The player controls. Everything a dashboard can do to the queue (skip, pause,
// resume, stop, repeat, remove and move a track) is also a command, so a
// server never needs one. They need the DJ role, like /play, /queue and
// /volume. Turning music on or off needs Manage Server.
func positionOption(name, desc string) *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionInteger, Name: name, Description: desc,
Required: true, MinValue: ptrFloat(1), MaxValue: 1000,
}
}
func playerOptions() []*discordgo.ApplicationCommandOption {
sub := func(name, desc string, o ...*discordgo.ApplicationCommandOption) *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionSubCommand, Name: name, Description: desc, Options: o}
}
return []*discordgo.ApplicationCommandOption{
sub("skip", "Skip the current song (DJ)"),
sub("pause", "Pause playback (DJ)"),
sub("resume", "Resume playback (DJ)"),
sub("stop", "Stop playback and clear the queue (DJ)"),
sub("repeat", "Repeat the current song, the whole queue, or nothing (DJ)",
&discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionString, Name: "mode", Description: "What repeats", Required: true,
Choices: []*discordgo.ApplicationCommandOptionChoice{{Name: "off", Value: "off"}, {Name: "song", Value: "song"}, {Name: "queue", Value: "queue"}},
}),
sub("remove", "Remove a song from the queue (DJ)", positionOption("position", "Its number in /queue")),
sub("move", "Move a song to another place in the queue (DJ)",
positionOption("from", "Its number in /queue"), positionOption("to", "The number it should have")),
}
}
// queueEntry returns the queued song at position n (1 is the first one after
// the song that is playing), as /queue numbers them.
func queueEntry(guildID string, n int) (*music.TrackEntry, int) {
_, rest := music.GetQueue(guildID)
if n < 1 || n > len(rest) {
return nil, len(rest)
}
e := rest[n-1]
return &e, len(rest)
}
func title(e *music.TrackEntry) string {
return strings.TrimSpace(e.Track.Info.Title)
}
// handlePlayer runs a player subcommand. The caller has checked that music is
// on and that the member has the DJ role.
func handlePlayer(s *discordgo.Session, i *discordgo.InteractionCreate, sub *discordgo.ApplicationCommandInteractionDataOption) {
g := i.GuildID
args := map[string]*discordgo.ApplicationCommandInteractionDataOption{}
for _, o := range sub.Options {
args[o.Name] = o
}
current, _ := music.GetQueue(g)
needsPlayer := sub.Name != "repeat" && sub.Name != "remove" && sub.Name != "move"
if needsPlayer && current == nil {
shared.RespondEphemeral(s, i, "Nothing is playing.")
return
}
var err error
var msg string
switch sub.Name {
case "skip":
err, msg = music.Skip(g), "Skipped."
case "pause":
err, msg = music.Pause(g, true), "Paused. `/music resume` continues."
case "resume":
err, msg = music.Pause(g, false), "Resumed."
case "stop":
err, msg = music.Stop(g), "Stopped, and the queue is cleared."
case "repeat":
switch args["mode"].StringValue() {
case "song":
music.SetRepeat(g, true, false)
msg = "The current song repeats."
case "queue":
music.SetRepeat(g, false, true)
msg = "The whole queue repeats."
default:
music.SetRepeat(g, false, false)
msg = "Nothing repeats."
}
case "remove":
n := int(args["position"].IntValue())
e, size := queueEntry(g, n)
if e == nil {
shared.RespondEphemeral(s, i, fmt.Sprintf("There is no song number %d in the queue (it has %d).", n, size))
return
}
err, msg = music.RemoveFromQueue(g, e.QueueID), fmt.Sprintf("Removed **%s**.", title(e))
case "move":
from, to := int(args["from"].IntValue()), int(args["to"].IntValue())
e, size := queueEntry(g, from)
if e == nil {
shared.RespondEphemeral(s, i, fmt.Sprintf("There is no song number %d in the queue (it has %d).", from, size))
return
}
if to > size {
to = size
}
err, msg = music.Reorder(g, e.QueueID, to), fmt.Sprintf("Moved **%s** to number %d.", title(e), to)
default:
shared.RespondEphemeral(s, i, "Unknown subcommand.")
return
}
if err != nil {
shared.RespondEphemeral(s, i, "That didn't work: "+err.Error())
return
}
shared.RespondEphemeral(s, i, msg)
}
+80
View File
@@ -0,0 +1,80 @@
package public
import (
"fmt"
"strings"
"velox-bot/internal/commands/music/shared"
"velox-bot/internal/music"
"github.com/bwmarrin/discordgo"
)
var Queue = &discordgo.ApplicationCommand{
Name: "queue",
Description: "Show the current music queue",
}
func QueueHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireMusicEnabled(s, i) {
return
}
if !memberHasDJRole(s, i.GuildID, i.Member) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You need the **DJ** role to use music commands.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
current, rest := music.GetQueue(i.GuildID)
if current == nil {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "The queue is currently empty.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
nowPlaying := fmt.Sprintf("%s — %s", current.Track.Info.Title, current.Track.Info.Author)
var descBuilder strings.Builder
if len(rest) > 0 {
limit := len(rest)
if limit > 10 {
limit = 10
}
for idx, entry := range rest[:limit] {
fmt.Fprintf(&descBuilder, "%d. %s — %s (requested by %s)\n", idx+1, entry.Track.Info.Title, entry.Track.Info.Author, entry.RequestedBy)
}
if len(rest) > limit {
fmt.Fprintf(&descBuilder, "...and %d more.", len(rest)-limit)
}
} else {
descBuilder.WriteString("Nothing else in the queue.")
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "Music Queue",
Description: descBuilder.String(),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Now Playing",
Value: nowPlaying,
},
},
},
},
},
})
}
+75
View File
@@ -0,0 +1,75 @@
package public
import (
"context"
"velox-bot/internal/commands/music/shared"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var Music = &discordgo.ApplicationCommand{
Name: "music",
Description: "Music settings and player controls",
Options: append([]*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "toggle",
Description: "Turn the music player on or off for this server (Manage Server)",
},
}, playerOptions()...),
}
func MusicHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.GuildID == "" {
shared.RespondEphemeral(s, i, "This command can only be used in a server.")
return
}
if !shared.RequireMusicService(s, i) {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
shared.RespondEphemeral(s, i, "Missing subcommand.")
return
}
sub := data.Options[0]
if sub.Name == "toggle" {
if !shared.RequireManageGuild(s, i) {
return
}
handleToggle(s, i)
return
}
// Every other subcommand controls the player: music has to be on and the
// member needs the DJ role, like /play, /queue and /volume.
if !shared.RequireMusicEnabled(s, i) {
return
}
if !memberHasDJRole(s, i.GuildID, i.Member) {
shared.RespondEphemeral(s, i, "You need the **DJ** role to use music commands.")
return
}
handlePlayer(s, i, sub)
}
func handleToggle(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
enabled, err := services.Global.MusicSettings.ToggleMusic(context.Background(), guildID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to toggle music playback.")
return
}
status := "disabled"
if enabled {
status = "enabled"
}
shared.RespondEphemeral(s, i, "Music playback "+status+" for this server.")
}
+66
View File
@@ -0,0 +1,66 @@
package public
import (
"fmt"
"velox-bot/internal/commands/music/shared"
"velox-bot/internal/music"
"github.com/bwmarrin/discordgo"
)
var Volume = &discordgo.ApplicationCommand{
Name: "volume",
Description: "Set playback volume (0-150)",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "value",
Description: "Volume percent (0-150)",
Required: true,
MinValue: ptrFloat(0),
MaxValue: 150,
},
},
}
func VolumeHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireMusicEnabled(s, i) {
return
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Updating volume...",
Flags: discordgo.MessageFlagsEphemeral,
},
})
if !memberHasDJRole(s, i.GuildID, i.Member) {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr("You need the **DJ** role to use music commands."),
})
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr("Missing volume value."),
})
return
}
vol := int(data.Options[0].IntValue())
if err := music.SetVolume(i.GuildID, vol); err != nil {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Error: %v", err)),
})
return
}
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: ptr(fmt.Sprintf("Volume set to **%d%%**.", vol)),
})
}
func ptrFloat(v float64) *float64 { return &v }
+21
View File
@@ -0,0 +1,21 @@
package music
import (
"velox-bot/internal/commands/music/public"
"github.com/bwmarrin/discordgo"
)
var (
Play *discordgo.ApplicationCommand = public.Play
Queue *discordgo.ApplicationCommand = public.Queue
Volume *discordgo.ApplicationCommand = public.Volume
Music *discordgo.ApplicationCommand = public.Music
)
func PlayHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.PlayHandler(s, i) }
func QueueHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.QueueHandler(s, i)
}
func VolumeHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.VolumeHandler(s, i) }
func MusicHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.MusicHandler(s, i) }
+61
View File
@@ -0,0 +1,61 @@
package shared
import (
"context"
"strconv"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
func RequireMusicEnabled(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
guildID, ok := ParseGuildID(s, i)
if !ok {
return false
}
enabled, err := services.Global.MusicSettings.IsMusicEnabled(context.Background(), guildID)
if err != nil {
RespondEphemeral(s, i, "Failed to load music settings.")
return false
}
if !enabled {
RespondEphemeral(s, i, "Music is disabled on this server. Use /music toggle to enable it.")
return false
}
return true
}
func RequireManageGuild(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if i.Member == nil || (i.Member.Permissions&discordgo.PermissionManageGuild) == 0 {
RespondEphemeral(s, i, "You need the **Manage Server** permission to use this.")
return false
}
return true
}
func RequireMusicService(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if services.Global == nil || services.Global.MusicSettings == nil {
RespondEphemeral(s, i, "Music service is not available.")
return false
}
return true
}
func ParseGuildID(s *discordgo.Session, i *discordgo.InteractionCreate) (int64, bool) {
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
RespondEphemeral(s, i, "Invalid guild ID.")
return 0, false
}
return guildID, true
}
func RespondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
@@ -0,0 +1,222 @@
package public
import (
"context"
"strconv"
"strings"
"velox-bot/internal/commands/projects/shared"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// HandleComponent routes the select menus shown after /projects add-helper
// and /projects close.
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
parts := strings.Split(i.MessageComponentData().CustomID, ":")
if len(parts) < 2 {
return
}
switch parts[1] {
case "add_helper_project_select":
handleAddHelperProjectSelect(s, i)
case "add_helper_user_select":
handleAddHelperUserSelect(s, i, parts)
case "close_select":
handleCloseSelect(s, i)
}
}
// handleAddHelperProjectSelect is step 1: a project was picked, now show a
// native Discord user-select to pick who helps - the actual AddHelper call
// happens in handleAddHelperUserSelect once both are known.
func handleAddHelperProjectSelect(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) {
return
}
values := i.MessageComponentData().Values
if len(values) == 0 {
return
}
projectID := values[0]
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "Who should help with this project?",
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
MenuType: discordgo.UserSelectMenu,
CustomID: "projects:add_helper_user_select:" + projectID,
Placeholder: "Select a user",
},
},
},
},
},
})
}
// handleAddHelperUserSelect is step 2: a user was picked from the native
// select menu, so both the project (carried in the CustomID) and the user
// (the selected value) are now known - perform the actual AddHelper call.
func handleAddHelperUserSelect(s *discordgo.Session, i *discordgo.InteractionCreate, parts []string) {
if !shared.RequireManageGuild(s, i) {
return
}
if len(parts) < 3 {
return
}
projectID, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
values := i.MessageComponentData().Values
if len(values) == 0 {
return
}
userID := values[0]
userID64, err := strconv.ParseInt(userID, 10, 64)
if err != nil {
return
}
ctx := context.Background()
project, err := services.Global.Projects.GetProject(ctx, guildID, projectID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load project.")
return
}
if project == nil {
shared.RespondEphemeral(s, i, "That project no longer exists in this server.")
return
}
if err := services.Global.Projects.AddHelper(ctx, projectID, userID64); err != nil {
shared.RespondEphemeral(s, i, "Failed to add helper to project.")
return
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "Added <@" + userID + "> as helper to project **" + project.Name + "**.",
Components: []discordgo.MessageComponent{},
},
})
}
func handleCloseSelect(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
values := i.MessageComponentData().Values
if len(values) == 0 {
return
}
projectID, err := strconv.ParseInt(values[0], 10, 64)
if err != nil {
return
}
ctx := context.Background()
project, err := services.Global.Projects.GetProject(ctx, guildID, projectID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load project.")
return
}
if project == nil {
shared.RespondEphemeral(s, i, "That project no longer exists in this server.")
return
}
if err := services.Global.Projects.DeactivateProject(ctx, guildID, projectID); err != nil {
shared.RespondEphemeral(s, i, "Failed to close project.")
return
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "Closed project **" + project.Name + "**.",
Components: []discordgo.MessageComponent{},
},
})
}
// HandleModalSubmit handles the /projects create modal.
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
parts := strings.Split(i.ModalSubmitData().CustomID, ":")
if len(parts) < 2 || parts[1] != "create_modal" {
return
}
if !shared.RequireManageGuild(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
if i.Member == nil || i.Member.User == nil {
shared.RespondEphemeral(s, i, "Missing member info.")
return
}
values := modalTextInputValues(i.ModalSubmitData().Components)
name := strings.TrimSpace(values["name"])
description := strings.TrimSpace(values["description"])
if name == "" {
shared.RespondEphemeral(s, i, "Project name cannot be empty.")
return
}
creatorID, err := strconv.ParseInt(i.Member.User.ID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid user ID.")
return
}
id, err := services.Global.Projects.CreateProject(context.Background(), guildID, creatorID, name, description)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to create project.")
return
}
shared.RespondEphemeral(s, i, "Created project **"+name+"** with ID `"+strconv.FormatInt(id, 10)+"`.")
}
func modalTextInputValues(components []discordgo.MessageComponent) map[string]string {
values := make(map[string]string)
for _, c := range components {
row, ok := c.(*discordgo.ActionsRow)
if !ok {
continue
}
for _, rc := range row.Components {
ti, ok := rc.(*discordgo.TextInput)
if !ok {
continue
}
values[ti.CustomID] = ti.Value
}
}
return values
}
+144 -113
View File
@@ -24,39 +24,16 @@ var Projects = &discordgo.ApplicationCommand{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "create",
Description: "Create a new active project",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "name",
Description: "Project name",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "description",
Description: "Short description (optional)",
Required: false,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "add-helper",
Description: "Add a helper to an existing project",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "project-id",
Description: "ID of the project",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user",
Description: "User to add as helper",
Required: true,
},
},
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "close",
Description: "Close (deactivate) a project",
},
},
}
@@ -79,6 +56,8 @@ func ProjectsHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
handleCreate(s, i)
case "add-helper":
handleAddHelper(s, i)
case "close":
handleClose(s, i)
default:
shared.RespondEphemeral(s, i, "Unknown subcommand.")
}
@@ -154,56 +133,53 @@ func mentionUser(id int64) string {
return "<@" + strconv.FormatInt(id, 10) + ">"
}
// handleCreate just opens the modal - the actual creation happens on
// submit, in HandleModalSubmit (components.go).
func handleCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
if i.Member == nil || i.Member.User == nil {
shared.RespondEphemeral(s, i, "Missing member info.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
shared.RespondEphemeral(s, i, "Missing options.")
return
}
opt := data.Options[0]
var name, description string
for _, o := range opt.Options {
switch o.Name {
case "name":
name = o.StringValue()
case "description":
description = o.StringValue()
}
}
if strings.TrimSpace(name) == "" {
shared.RespondEphemeral(s, i, "Project name cannot be empty.")
return
}
creatorID, err := strconv.ParseInt(i.Member.User.ID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid user ID.")
return
}
id, err := services.Global.Projects.CreateProject(context.Background(), guildID, creatorID, name, description)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to create project.")
return
}
shared.RespondEphemeral(s, i, "Created project **"+name+"** with ID `"+strconv.FormatInt(id, 10)+"`.")
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: "projects:create_modal",
Title: "Create a project",
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "name",
Label: "Project name",
Style: discordgo.TextInputShort,
Required: true,
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "description",
Label: "Description (optional)",
Style: discordgo.TextInputParagraph,
Required: false,
},
},
},
},
},
})
}
// handleAddHelper collects the user via Discord's native user-option (a
// modal can't hold one of these), then responds with a select menu of the
// guild's active projects instead of making the caller remember/type a
// numeric project ID - the actual add-helper call happens on selection, in
// HandleComponent (components.go).
// handleAddHelper is the first of two dropdown steps: pick a project here,
// then HandleComponent (components.go) follows up with a native Discord
// user-select to pick who helps, and performs the actual AddHelper call
// once both are known.
func handleAddHelper(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) {
return
@@ -214,55 +190,110 @@ func handleAddHelper(s *discordgo.Session, i *discordgo.InteractionCreate) {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
shared.RespondEphemeral(s, i, "Missing options.")
return
}
opt := data.Options[0]
var projectID int64
var userID string
for _, o := range opt.Options {
switch o.Name {
case "project-id":
projectID = o.IntValue()
case "user":
if u := o.UserValue(s); u != nil {
userID = u.ID
}
}
}
if projectID <= 0 {
shared.RespondEphemeral(s, i, "Invalid project ID.")
return
}
if userID == "" {
shared.RespondEphemeral(s, i, "Invalid user.")
return
}
exists, err := services.Global.Projects.ProjectExistsInGuild(context.Background(), guildID, projectID)
options, err := activeProjectOptions(context.Background(), guildID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load project.")
shared.RespondEphemeral(s, i, "Failed to load projects.")
return
}
if !exists {
shared.RespondEphemeral(s, i, "Project `"+strconv.FormatInt(projectID, 10)+"` not found in this server.")
if len(options) == 0 {
shared.RespondEphemeral(s, i, "There are no active projects to add a helper to.")
return
}
userID64, err := strconv.ParseInt(userID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid user ID.")
return
}
if err := services.Global.Projects.AddHelper(context.Background(), projectID, userID64); err != nil {
shared.RespondEphemeral(s, i, "Failed to add helper to project. ("+err.Error()+")")
return
}
shared.RespondEphemeral(s, i, "Added <@"+userID+"> as helper to project `"+strconv.FormatInt(projectID, 10)+"`.")
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Which project should get a new helper?",
Flags: discordgo.MessageFlagsEphemeral,
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
CustomID: "projects:add_helper_project_select",
Placeholder: "Select a project",
Options: options,
},
},
},
},
},
})
}
// handleClose responds with a select menu of the guild's active projects -
// same reasoning as handleAddHelper, picking from a live list beats typing
// an ID. The actual deactivation happens on selection, in HandleComponent.
func handleClose(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireManageGuild(s, i) {
return
}
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
options, err := activeProjectOptions(context.Background(), guildID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load projects.")
return
}
if len(options) == 0 {
shared.RespondEphemeral(s, i, "There are no active projects to close.")
return
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Which project should be closed?",
Flags: discordgo.MessageFlagsEphemeral,
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
CustomID: "projects:close_select",
Placeholder: "Select a project",
Options: options,
},
},
},
},
},
})
}
// activeProjectOptions builds select-menu options for the guild's active
// projects, truncating name/description to Discord's option limits
// (label: 100 chars, description: 100 chars).
func activeProjectOptions(ctx context.Context, guildID int64) ([]discordgo.SelectMenuOption, error) {
const limit = 25 // Discord's own cap on select menu options
items, err := services.Global.Projects.ListActive(ctx, guildID, limit)
if err != nil {
return nil, err
}
options := make([]discordgo.SelectMenuOption, 0, len(items))
for _, p := range items {
if p == nil {
continue
}
name := p.Name
if name == "" {
name = "Unnamed project"
}
options = append(options, discordgo.SelectMenuOption{
Label: truncate(name, 100),
Value: strconv.FormatInt(p.ID, 10),
Description: truncate(p.Description, 100),
})
}
return options, nil
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max]
}
+6
View File
@@ -12,3 +12,9 @@ var (
func ProjectsHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.ProjectsHandler(s, i) }
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) { public.HandleComponent(s, i) }
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleModalSubmit(s, i)
}
@@ -0,0 +1,794 @@
package public
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"velox-bot/internal/commands/schedule/shared"
"velox-bot/internal/db/repos/schedulerepo"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
func scheduleActionButtons(scheduleID int64) []discordgo.MessageComponent {
idStr := strconv.FormatInt(scheduleID, 10)
return []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Label: "Accept",
Style: discordgo.SuccessButton,
CustomID: "schedule:accept:" + idStr,
},
discordgo.Button{
Label: "Decline",
Style: discordgo.DangerButton,
CustomID: "schedule:decline:" + idStr,
},
discordgo.Button{
Label: "Reschedule",
Style: discordgo.SecondaryButton,
CustomID: "schedule:reschedule:" + idStr,
},
},
},
}
}
func rescheduleProposalButtons(scheduleID int64) []discordgo.MessageComponent {
idStr := strconv.FormatInt(scheduleID, 10)
return []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Label: "Accept",
Style: discordgo.SuccessButton,
CustomID: "schedule:accept_reschedule:" + idStr,
},
discordgo.Button{
Label: "Decline",
Style: discordgo.DangerButton,
CustomID: "schedule:decline_reschedule:" + idStr,
},
discordgo.Button{
Label: "Propose different time",
Style: discordgo.SecondaryButton,
CustomID: "schedule:reschedule:" + idStr,
},
},
},
}
}
const createUserSelectCustomID = "schedule:create_user_select"
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.MessageComponentData().CustomID == createUserSelectCustomID {
handleCreateUserSelect(s, i)
return
}
ctx := context.Background()
action, scheduleID := parseComponentCustomID(i.MessageComponentData().CustomID)
userIDStr := interactionUserID(i)
userID, err := strconv.ParseInt(userIDStr, 10, 64)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error parsing user ID.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
sch, err := services.Global.Schedule.GetByID(ctx, scheduleID)
if err != nil || sch == nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error retrieving schedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
var status schedulerepo.ScheduleStatus
var message string
switch action {
case "accept":
if userID != sch.InviteeID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if sch.Status != schedulerepo.StatusPending {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "This schedule is no longer pending.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
status = schedulerepo.StatusAccepted
message = "✅ Accepted"
case "decline":
if userID != sch.InviteeID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if sch.Status != schedulerepo.StatusPending {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "This schedule is no longer pending.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
status = schedulerepo.StatusDeclined
message = "❌ Declined"
case "reschedule":
if userID != sch.InviteeID && userID != sch.RequesterID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if sch.Status != schedulerepo.StatusPending && sch.Status != schedulerepo.StatusAccepted {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "This schedule can't be rescheduled right now.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: "schedule:reschedule_modal:" + strconv.FormatInt(scheduleID, 10),
Title: "Propose a new time",
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "date",
Label: "Date (YYYY-MM-DD)",
Style: discordgo.TextInputShort,
Required: true,
Placeholder: "2026-01-02",
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "time",
Label: "Time (HH:MM, your timezone)",
Style: discordgo.TextInputShort,
Required: true,
Placeholder: "15:04",
},
},
},
},
},
})
return
case "accept_reschedule":
if sch.ProposedBy == nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "There is no reschedule proposal to accept.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if (userID != sch.RequesterID && userID != sch.InviteeID) || userID == *sch.ProposedBy {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if sch.Status != schedulerepo.StatusRescheduleRequested {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "There is no reschedule request to accept.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
err = services.Global.Schedule.AcceptReschedule(ctx, scheduleID)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error accepting reschedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "✅ Reschedule accepted",
Components: []discordgo.MessageComponent{},
},
})
newTime := *sch.ProposedAt
utcStr := newTime.UTC().Format("2006-01-02 15:04")
loc, zone, _, err := services.Global.UserSettings.GetTimezone(ctx, *sch.ProposedBy)
if err != nil {
loc = time.UTC
zone = "UTC"
}
localStr := newTime.In(loc).Format("2006-01-02 15:04")
content := "Your proposed time for the session was accepted: " +
utcStr + " UTC (" + localStr + " " + zone + ")."
dmCh, err := s.UserChannelCreate(strconv.FormatInt(*sch.ProposedBy, 10))
if err == nil {
if _, err := s.ChannelMessageSend(dmCh.ID, content); err != nil {
log.Printf("schedule: failed to DM proposer about accepted reschedule: %v", err)
}
}
return
case "decline_reschedule":
if sch.ProposedBy == nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "There is no reschedule proposal to accept.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if (userID != sch.RequesterID && userID != sch.InviteeID) || userID == *sch.ProposedBy {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if sch.Status != schedulerepo.StatusRescheduleRequested {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "There is no reschedule request to accept.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
err = services.Global.Schedule.DeclineReschedule(ctx, scheduleID)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error declining reschedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "❌ Reschedule declined",
Components: []discordgo.MessageComponent{},
},
})
utcStr := sch.ScheduledAt.UTC().Format("2006-01-02 15:04")
loc, zone, _, err := services.Global.UserSettings.GetTimezone(ctx, *sch.ProposedBy)
if err != nil {
loc = time.UTC
zone = "UTC"
}
localStr := sch.ScheduledAt.In(loc).Format("2006-01-02 15:04")
content := "Your proposed new time was declined. The session remains scheduled for " +
utcStr + " UTC (" + localStr + " " + zone + ")."
dmCh, err := s.UserChannelCreate(strconv.FormatInt(*sch.ProposedBy, 10))
if err == nil {
if _, err := s.ChannelMessageSend(dmCh.ID, content); err != nil {
log.Printf("schedule: failed to DM proposer about declined reschedule: %v", err)
}
}
return
default:
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Unknown action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
err = services.Global.Schedule.UpdateStatus(ctx, scheduleID, status)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error updating schedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: message,
Components: []discordgo.MessageComponent{},
},
})
statusText := map[schedulerepo.ScheduleStatus]string{
schedulerepo.StatusAccepted: "accepted ✅",
schedulerepo.StatusDeclined: "declined ❌",
schedulerepo.StatusRescheduleRequested: "requested rescheduling 🔁",
}[status]
utcStr := sch.ScheduledAt.UTC().Format("2006-01-02 15:04")
// Notify requester with local time if configured.
if services.Global.UserSettings != nil {
loc, zone, _, err := services.Global.UserSettings.GetTimezone(ctx, sch.RequesterID)
if err != nil {
loc = sch.ScheduledAt.UTC().Location()
zone = "UTC"
}
localStr := sch.ScheduledAt.In(loc).Format("2006-01-02 15:04")
content := "Your session request with <@" + strconv.FormatInt(sch.InviteeID, 10) + "> for " +
utcStr + " UTC (" + localStr + " " + zone + ") has been " + statusText + "."
requesterID := strconv.FormatInt(sch.RequesterID, 10)
dmCh, err := s.UserChannelCreate(requesterID)
if err == nil {
if _, err := s.ChannelMessageSend(dmCh.ID, content); err != nil {
log.Printf("schedule: failed to DM requester about status change: %v", err)
}
}
}
}
func handleCreateUserSelect(s *discordgo.Session, i *discordgo.InteractionCreate) {
values := i.MessageComponentData().Values
if len(values) == 0 {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "No user selected.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
targetUserID := values[0]
if targetUserID == interactionUserID(i) {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You cannot schedule a session with yourself.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: "schedule:create_modal:" + targetUserID,
Title: "Schedule a session",
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "date",
Label: "Date (YYYY-MM-DD)",
Style: discordgo.TextInputShort,
Required: true,
Placeholder: "2026-01-02",
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "time",
Label: "Time (HH:MM, your timezone)",
Style: discordgo.TextInputShort,
Required: true,
Placeholder: "15:04",
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: "description",
Label: "Description (optional)",
Style: discordgo.TextInputShort,
Required: false,
},
},
},
},
},
})
}
func modalTextInputValues(components []discordgo.MessageComponent) map[string]string {
values := make(map[string]string)
for _, c := range components {
row, ok := c.(*discordgo.ActionsRow)
if !ok {
continue
}
for _, rc := range row.Components {
ti, ok := rc.(*discordgo.TextInput)
if !ok {
continue
}
values[ti.CustomID] = ti.Value
}
}
return values
}
func handleCreateModalSubmit(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, inviteeID int64) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
requesterID, err := strconv.ParseInt(interactionUserID(i), 10, 64)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Invalid user ID.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if requesterID == inviteeID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You cannot schedule a session with yourself.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
values := modalTextInputValues(i.ModalSubmitData().Components)
dateStr := strings.TrimSpace(values["date"])
timeStr := strings.TrimSpace(values["time"])
desc := strings.TrimSpace(values["description"])
loc, zone, _, err := services.Global.UserSettings.GetTimezone(ctx, requesterID)
if err != nil {
loc = time.UTC
zone = "UTC"
}
when, err := shared.ParseScheduleDatetime(dateStr+" "+timeStr, loc)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Invalid date/time. Use YYYY-MM-DD for the date and HH:MM for the time, in your timezone (" + zone + ").",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
when = when.In(time.UTC)
scheduleID, err := services.Global.Schedule.CreateSchedule(ctx, guildID, requesterID, inviteeID, when, desc)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to create schedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
dmCh, err := s.UserChannelCreate(strconv.FormatInt(inviteeID, 10))
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Session created, but failed to DM the invited user (are DMs disabled?).",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
embed := &discordgo.MessageEmbed{
Title: "New session request",
Description: fmt.Sprintf("You have been invited to a session by <@%d>.", requesterID),
Color: 0x4caf50,
}
utcStr := when.Format("2006-01-02 15:04")
locInv, zoneInv, _, err := services.Global.UserSettings.GetTimezone(ctx, inviteeID)
if err != nil {
locInv = time.UTC
zoneInv = "UTC"
}
localInvStr := when.In(locInv).Format("2006-01-02 15:04")
embed.Fields = []*discordgo.MessageEmbedField{
{Name: "When (UTC)", Value: utcStr},
{Name: "When (" + zoneInv + ")", Value: localInvStr},
}
if desc != "" {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Description",
Value: desc,
})
}
_, err = s.ChannelMessageSendComplex(dmCh.ID, &discordgo.MessageSend{
Content: "Respond to this session request:",
Embed: embed,
Components: scheduleActionButtons(scheduleID),
})
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Session created, but failed to DM the invited user.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Session request created and sent to <@" + strconv.FormatInt(inviteeID, 10) + ">.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
ctx := context.Background()
action, idOrUserID := parseComponentCustomID(i.ModalSubmitData().CustomID)
if action == "create_modal" {
handleCreateModalSubmit(ctx, s, i, idOrUserID)
return
}
scheduleID := idOrUserID
if scheduleID == 0 {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Invalid schedule ID.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
modalValues := modalTextInputValues(i.ModalSubmitData().Components)
datetimeInput := strings.TrimSpace(modalValues["date"]) + " " + strings.TrimSpace(modalValues["time"])
sch, err := services.Global.Schedule.GetByID(ctx, scheduleID)
if err != nil || sch == nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error retrieving schedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
userIDStr := interactionUserID(i)
userID, err := strconv.ParseInt(userIDStr, 10, 64)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error parsing user ID.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
if userID != sch.InviteeID && userID != sch.RequesterID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You are not authorized to perform this action.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
loc, _, _, err := services.Global.UserSettings.GetTimezone(ctx, userID)
if err != nil {
loc = sch.ScheduledAt.UTC().Location()
}
newTime, err := shared.ParseScheduleDatetime(datetimeInput, loc)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Invalid date/time. Use YYYY-MM-DD for the date and HH:MM for the time.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
//Convert time to UTC before storing in the database
newTime = newTime.UTC()
err = services.Global.Schedule.ProposeReschedule(ctx, scheduleID, newTime, userID)
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Error proposing reschedule.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
otherID := sch.RequesterID
if userID == sch.RequesterID {
otherID = sch.InviteeID
}
dmCh, err := s.UserChannelCreate(strconv.FormatInt(otherID, 10))
if err != nil {
shared.RespondEphemeral(s, i, "Failed to DM the invited user (are DMs disabled?).")
return
}
embed := &discordgo.MessageEmbed{
Title: "Reschedule Proposal",
Description: fmt.Sprintf("<@%d> has proposed a new time for your session request. Please respond.", userID),
Color: 0x4caf50,
}
// Show both UTC and invitee-local time if available.
utcStr := newTime.Format("2006-01-02 15:04")
locInv, zoneInv, _, err := services.Global.UserSettings.GetTimezone(context.Background(), otherID)
if err != nil {
locInv = time.UTC
zoneInv = "UTC"
}
localInvStr := newTime.In(locInv).Format("2006-01-02 15:04")
embed.Fields = []*discordgo.MessageEmbedField{
{
Name: "When (UTC)",
Value: utcStr,
},
{
Name: "When (" + zoneInv + ")",
Value: localInvStr,
},
}
_, err = s.ChannelMessageSendComplex(dmCh.ID, &discordgo.MessageSend{
Content: "A new time has been proposed for your session:",
Embed: embed,
Components: rescheduleProposalButtons(scheduleID),
})
if err != nil {
shared.RespondEphemeral(s, i, "Failed to DM the other participant.")
return
}
shared.RespondEphemeral(s, i, "Proposed new time sent to <@"+strconv.FormatInt(otherID, 10)+">.")
}
func parseComponentCustomID(customID string) (string, int64) {
parts := strings.Split(customID, ":")
if len(parts) != 3 {
return "", 0
}
action := parts[1]
scheduleID, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
return "", 0
}
return action, scheduleID
}
func interactionUserID(i *discordgo.InteractionCreate) string {
if i.Member != nil && i.Member.User != nil {
return i.Member.User.ID
}
if i.User != nil {
return i.User.ID
}
return ""
}
@@ -0,0 +1,289 @@
package public
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"velox-bot/internal/commands/schedule/shared"
"velox-bot/internal/db/repos/schedulerepo"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var Schedule = &discordgo.ApplicationCommand{
Name: "schedule",
Description: "Schedule 1:1 sessions",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "create",
Description: "Create a new session with a user",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "list",
Description: "List your upcoming sessions",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "reschedule",
Description: "Reschedule an existing session",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "id",
Description: "ID of the session (from /schedule list)",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "datetime",
Description: "New datetime (UTC), format: 2006-01-02 15:04",
Required: true,
},
},
},
},
}
func ScheduleHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireGuild(s, i) || !shared.RequireScheduleService(s, i) {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
handleList(s, i)
return
}
switch data.Options[0].Name {
case "create":
handleCreate(s, i)
case "list":
handleList(s, i)
case "reschedule":
handleReschedule(s, i)
default:
shared.RespondEphemeral(s, i, "Unknown subcommand.")
}
}
func handleCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
if _, ok := shared.ParseGuildID(s, i); !ok {
return
}
if i.Member == nil || i.Member.User == nil {
shared.RespondEphemeral(s, i, "Missing member info.")
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Who do you want to schedule a session with?",
Flags: discordgo.MessageFlagsEphemeral,
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
MenuType: discordgo.UserSelectMenu,
CustomID: createUserSelectCustomID,
Placeholder: "Select a user",
},
},
},
},
},
})
}
func handleList(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
if i.Member == nil || i.Member.User == nil {
shared.RespondEphemeral(s, i, "Missing member info.")
return
}
userID, err := strconv.ParseInt(i.Member.User.ID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid user ID.")
return
}
const limit = 10
items, err := services.Global.Schedule.ListForUser(context.Background(), guildID, userID, limit)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load your sessions.")
return
}
if len(items) == 0 {
shared.RespondEphemeral(s, i, "You have no upcoming sessions.")
return
}
var b strings.Builder
for _, sch := range items {
role := "Requester"
otherID := sch.InviteeID
if sch.InviteeID == userID {
role = "Invitee"
otherID = sch.RequesterID
}
status := string(sch.Status)
whenStr := sch.ScheduledAt.UTC().Format("2006-01-02 15:04")
line := fmt.Sprintf("ID `%d` • %s with <@%d> at %s UTC (%s)\n", sch.ID, role, otherID, whenStr, status)
if sch.Description != "" {
line += " " + sch.Description + "\n"
}
b.WriteString(line)
}
shared.RespondEphemeral(s, i, b.String())
}
func handleReschedule(s *discordgo.Session, i *discordgo.InteractionCreate) {
guildID, ok := shared.ParseGuildID(s, i)
if !ok {
return
}
if i.Member == nil || i.Member.User == nil {
shared.RespondEphemeral(s, i, "Missing member info.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
shared.RespondEphemeral(s, i, "Missing options.")
return
}
opt := data.Options[0]
var (
idVal int64
whenStr string
)
for _, o := range opt.Options {
switch o.Name {
case "id":
idVal = o.IntValue()
case "datetime":
whenStr = o.StringValue()
}
}
if idVal <= 0 {
shared.RespondEphemeral(s, i, "Invalid session ID.")
return
}
whenStr = strings.TrimSpace(whenStr)
if whenStr == "" {
shared.RespondEphemeral(s, i, "Datetime cannot be empty.")
return
}
userID, err := strconv.ParseInt(i.Member.User.ID, 10, 64)
if err != nil {
shared.RespondEphemeral(s, i, "Invalid user ID.")
return
}
ctx := context.Background()
sch, err := services.Global.Schedule.GetByID(ctx, idVal)
if err != nil || sch == nil {
shared.RespondEphemeral(s, i, "Session not found.")
return
}
if sch.GuildID != guildID {
shared.RespondEphemeral(s, i, "This session belongs to another server.")
return
}
if userID != sch.RequesterID && userID != sch.InviteeID {
shared.RespondEphemeral(s, i, "You are not part of this session.")
return
}
if sch.Status != schedulerepo.StatusPending && sch.Status != schedulerepo.StatusAccepted {
shared.RespondEphemeral(s, i, "This session can't be rescheduled right now.")
return
}
// Use rescheduler's timezone for parsing.
loc, zone, _, err := services.Global.UserSettings.GetTimezone(ctx, userID)
if err != nil {
loc = time.UTC
zone = "UTC"
}
// Expect explicit layout "2006-01-02 15:04" in user's timezone.
when, err := shared.ParseScheduleDatetime(whenStr, loc)
if err != nil {
shared.RespondEphemeral(s, i, err.Error()+" (use `2006-01-02 15:04` in your timezone: "+zone+")")
return
}
when = when.In(time.UTC)
if err := services.Global.Schedule.ProposeReschedule(ctx, sch.ID, when, userID); err != nil {
shared.RespondEphemeral(s, i, "Failed to propose reschedule.")
return
}
whenFmt := when.Format("2006-01-02 15:04")
otherID := sch.InviteeID
if userID == sch.InviteeID {
otherID = sch.RequesterID
}
dmCh, err := s.UserChannelCreate(strconv.FormatInt(otherID, 10))
if err != nil {
shared.RespondEphemeral(s, i, "Proposal saved, but failed to DM the other participant (are DMs disabled?).")
return
}
embed := &discordgo.MessageEmbed{
Title: "Reschedule proposed",
Description: fmt.Sprintf("<@%s> has proposed a new time for your session.", i.Member.User.ID),
Color: 0x4caf50,
}
// Show both UTC and the other participant's local time if available.
locOther, zoneOther, _, errTZ := services.Global.UserSettings.GetTimezone(ctx, otherID)
if errTZ != nil {
locOther = time.UTC
zoneOther = "UTC"
}
localOtherStr := when.In(locOther).Format("2006-01-02 15:04")
embed.Fields = []*discordgo.MessageEmbedField{
{
Name: "When (UTC)",
Value: whenFmt,
},
{
Name: "When (" + zoneOther + ")",
Value: localOtherStr,
},
}
if sch.Description != "" {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Description",
Value: sch.Description,
})
}
_, err = s.ChannelMessageSendComplex(dmCh.ID, &discordgo.MessageSend{
Content: "A new time has been proposed for your session:",
Embed: embed,
Components: rescheduleProposalButtons(sch.ID),
})
if err != nil {
shared.RespondEphemeral(s, i, "Proposal saved, but failed to DM the other participant.")
return
}
shared.RespondEphemeral(s, i, "Proposed new time sent to <@"+strconv.FormatInt(otherID, 10)+">.")
}
+22
View File
@@ -0,0 +1,22 @@
package schedule
import (
"velox-bot/internal/commands/schedule/public"
"github.com/bwmarrin/discordgo"
)
var (
Schedule *discordgo.ApplicationCommand = public.Schedule
)
func ScheduleHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.ScheduleHandler(s, i)
}
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleComponent(s, i)
}
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleModalSubmit(s, i)
}
@@ -0,0 +1,62 @@
package shared
import (
"fmt"
"strconv"
"time"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var scheduleDatetimeLayouts = []string{
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02 15:04:05",
"01/02/2006 15:04",
}
func RespondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
func ParseScheduleDatetime(input string, loc *time.Location) (time.Time, error) {
for _, layout := range scheduleDatetimeLayouts {
if t, err := time.ParseInLocation(layout, input, loc); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("invalid schedule datetime format")
}
func RequireGuild(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if i.GuildID == "" {
RespondEphemeral(s, i, "This command can only be used in a server.")
return false
}
return true
}
func RequireScheduleService(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if services.Global == nil || services.Global.Schedule == nil {
RespondEphemeral(s, i, "Scheduling service is not available.")
return false
}
return true
}
func ParseGuildID(s *discordgo.Session, i *discordgo.InteractionCreate) (int64, bool) {
guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
if err != nil {
RespondEphemeral(s, i, "Invalid guild ID.")
return 0, false
}
return guildID, true
}
@@ -0,0 +1,579 @@
package public
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
"velox-bot/internal/db/repos/securityrepo"
"velox-bot/internal/security"
"github.com/bwmarrin/discordgo"
)
// Every handler re-checks permissions through the security engine. The
// DefaultMemberPermissions below only hide commands from the menu; server
// admins can change them, so they are never what keeps anyone out.
var (
manageGuild = int64(discordgo.PermissionManageGuild)
manageChannel = int64(discordgo.PermissionManageChannels)
guildOnly = &[]discordgo.InteractionContextType{discordgo.InteractionContextGuild}
textChannels = []discordgo.ChannelType{discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews}
chatChannels = []discordgo.ChannelType{
discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews, discordgo.ChannelTypeGuildForum,
discordgo.ChannelTypeGuildVoice, discordgo.ChannelTypeGuildStageVoice,
}
opTimeout = 3 * time.Minute
genericFailed = "Something went wrong. Check that Velox's role is high enough and has the permissions it needs, then try again."
)
var featureChoices = []*discordgo.ApplicationCommandOptionChoice{
{Name: "Join Gate", Value: securityrepo.FeatureJoinGate},
{Name: "Raid mode", Value: securityrepo.FeatureAntiRaid},
{Name: "Anti-nuke", Value: securityrepo.FeatureAntiNuke},
{Name: "Heat (anti-spam)", Value: securityrepo.FeatureHeat},
}
var Security = &discordgo.ApplicationCommand{
Name: "security",
Description: "Anti-raid and anti-nuke protection",
DefaultMemberPermissions: &manageGuild,
Contexts: guildOnly,
Options: append([]*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "status", Description: "Show what's on and who is trusted"},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "toggle", Description: "Turn a protection on or off",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "feature", Description: "Which protection", Required: true, Choices: featureChoices},
{Type: discordgo.ApplicationCommandOptionBoolean, Name: "on", Description: "On or off", Required: true},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "alerts", Description: "Where alerts go and which role they ping (owner or trusted)",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionChannel, Name: "channel", Description: "Alert channel", Required: true, ChannelTypes: textChannels},
{Type: discordgo.ApplicationCommandOptionRole, Name: "role", Description: "Role to ping for raids and nukes"},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "quarantine-role", Description: "Role given to quarantined members (owner or trusted)",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionRole, Name: "role", Description: "Leave empty to use none"},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommandGroup, Name: "trust", Description: "Who is exempt from anti-nuke (owner only)",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "add", Description: "Trust a user or a role",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionUser, Name: "user", Description: "A user"},
{Type: discordgo.ApplicationCommandOptionRole, Name: "role", Description: "A role"},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "remove", Description: "Stop trusting a user or a role",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionUser, Name: "user", Description: "A user"},
{Type: discordgo.ApplicationCommandOptionRole, Name: "role", Description: "A role"},
},
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "release", Description: "Release a quarantined member (owner or trusted)",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionUser, Name: "user", Description: "Who to release", Required: true},
},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "quarantined", Description: "List quarantined members"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "end-raid", Description: "End raid mode now (owner or trusted)"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "snapshot", Description: "Save a snapshot of roles and channels to restore from"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "restore", Description: "Recreate deleted roles and channels from the latest snapshot (owner or trusted)"},
}, tuneOptions()...),
}
func lockOptions(unlock bool) []*discordgo.ApplicationCommandOption {
verb := "Lock"
if unlock {
verb = "Unlock"
}
joins := &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "joins", Description: verb + " joins"}
if !unlock {
joins.Description = "Kick or ban everyone who joins until unlocked"
joins.Options = []*discordgo.ApplicationCommandOption{{
Type: discordgo.ApplicationCommandOptionString, Name: "action", Description: "What happens to new members", Required: true,
Choices: []*discordgo.ApplicationCommandOptionChoice{{Name: "Kick", Value: securityrepo.ActionKick}, {Name: "Ban", Value: securityrepo.ActionBan}},
}}
}
return []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "channel", Description: verb + " one channel",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionChannel, Name: "channel", Description: "Defaults to this channel", ChannelTypes: chatChannels}},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "server", Description: verb + " every channel"},
joins,
}
}
var Lockdown = &discordgo.ApplicationCommand{
Name: "lockdown", Description: "Stop members from talking, or from joining", DefaultMemberPermissions: &manageChannel,
Contexts: guildOnly, Options: lockOptions(false),
}
var Unlock = &discordgo.ApplicationCommand{
Name: "unlock", Description: "Undo a lockdown (owner or trusted)", DefaultMemberPermissions: &manageChannel,
Contexts: guildOnly, Options: lockOptions(true),
}
func reply(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Content: msg, Flags: discordgo.MessageFlagsEphemeral, AllowedMentions: &discordgo.MessageAllowedMentions{}},
})
}
func deferReply(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
return s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Flags: discordgo.MessageFlagsEphemeral},
}) == nil
}
func edit(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{Content: &msg, AllowedMentions: &discordgo.MessageAllowedMentions{}})
}
func message(where string, err error) string {
var ue security.UserError
if errors.As(err, &ue) {
return string(ue)
}
log.Printf("security command %s: %v", where, err)
return genericFailed
}
func opts(o []*discordgo.ApplicationCommandInteractionDataOption) map[string]*discordgo.ApplicationCommandInteractionDataOption {
m := map[string]*discordgo.ApplicationCommandInteractionDataOption{}
for _, x := range o {
m[x.Name] = x
}
return m
}
func perms(i *discordgo.InteractionCreate) int64 {
if i.Member == nil {
return 0
}
return i.Member.Permissions
}
func userID(i *discordgo.InteractionCreate) string {
if i.Member == nil || i.Member.User == nil {
return ""
}
return i.Member.User.ID
}
func engine(s *discordgo.Session, i *discordgo.InteractionCreate) *security.Engine {
e := security.Default()
if e == nil || i.GuildID == "" || i.Member == nil {
reply(s, i, "Security isn't available right now.")
return nil
}
return e
}
// allowedOrTrusted lets an action through when the member has one of the
// permissions, or is the owner or trusted.
func allowedOrTrusted(ctx context.Context, e *security.Engine, i *discordgo.InteractionCreate, need int64) bool {
if perms(i)&(need|discordgo.PermissionAdministrator) != 0 {
return true
}
return e.RequireTrusted(ctx, i.GuildID, i.Member) == nil
}
func SecurityHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
e := engine(s, i)
if e == nil {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
args := opts(sub.Options)
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
if handleTune(ctx, s, i, e, sub) {
return
}
switch sub.Name {
case "status":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to see the security settings.")
return
}
reply(s, i, status(ctx, e, i.GuildID))
case "toggle":
feature, on := args["feature"].StringValue(), args["on"].BoolValue()
if err := e.SetFeature(ctx, i.GuildID, i.Member, perms(i), feature, on); err != nil {
reply(s, i, message("toggle", err))
return
}
state := "off"
if on {
state = "on"
}
reply(s, i, fmt.Sprintf("%s is now **%s**.", featureName(feature), state))
case "alerts":
ch := args["channel"].ChannelValue(nil).ID
role := ""
if r, ok := args["role"]; ok {
role = r.RoleValue(nil, i.GuildID).ID
}
if err := e.SetAlerts(ctx, i.GuildID, i.Member, ch, role); err != nil {
reply(s, i, message("alerts", err))
return
}
reply(s, i, fmt.Sprintf("Alerts will go to <#%s>.", ch))
case "quarantine-role":
role := ""
if r, ok := args["role"]; ok {
role = r.RoleValue(nil, i.GuildID).ID
}
if err := e.SetQuarantineRole(ctx, i.GuildID, i.Member, role); err != nil {
reply(s, i, message("quarantine-role", err))
return
}
if role == "" {
reply(s, i, "Quarantined members won't get a role; they still lose their roles and are timed out.")
} else {
reply(s, i, fmt.Sprintf("Quarantined members will get <@&%s>.", role))
}
case "trust":
if len(sub.Options) == 0 {
return
}
handleTrust(ctx, s, i, e, sub.Options[0])
case "release":
if err := e.RequireTrusted(ctx, i.GuildID, i.Member); err != nil {
reply(s, i, message("release", err))
return
}
target := args["user"].UserValue(nil)
if !deferReply(s, i) {
return
}
if err := e.Release(ctx, i.GuildID, target.ID, userID(i)); err != nil {
edit(s, i, message("release", err))
return
}
edit(s, i, fmt.Sprintf("<@%s> was released and got their roles back.", target.ID))
case "quarantined":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to see this.")
return
}
qs, err := e.Quarantines(ctx, i.GuildID)
if err != nil {
reply(s, i, message("quarantined", err))
return
}
if len(qs) == 0 {
reply(s, i, "Nobody is quarantined.")
return
}
var b strings.Builder
for _, q := range qs {
fmt.Fprintf(&b, "• <@%d>, <t:%d:R>: %s\n", q.UserID, q.CreatedAt.Unix(), q.Reason)
}
reply(s, i, clip(b.String(), 1900))
case "end-raid":
endRaid(ctx, s, i, e)
case "snapshot":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to take a snapshot.")
return
}
if !deferReply(s, i) {
return
}
roles, channels, err := e.TakeSnapshot(ctx, i.GuildID, userID(i))
if err != nil {
edit(s, i, message("snapshot", err))
return
}
edit(s, i, fmt.Sprintf("Snapshot saved: %d roles and %d channels. The last three are kept.", roles, channels))
case "restore":
if err := e.RequireTrusted(ctx, i.GuildID, i.Member); err != nil {
reply(s, i, message("restore", err))
return
}
if !deferReply(s, i) {
return
}
// Recreating many channels takes a while under Discord's rate limits.
res, err := e.Restore(ctx, i.GuildID, userID(i))
if err != nil {
edit(s, i, message("restore", err))
return
}
edit(s, i, fmt.Sprintf("Restored from the snapshot of <t:%d:f>: %d roles and %d channels recreated, %d roles had dangerous permissions reverted, %d steps failed.",
res.SnapshotAt.Unix(), res.RolesCreated, res.ChannelsCreated, res.RolesReverted, res.Failed))
}
}
func handleTrust(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, e *security.Engine, sub *discordgo.ApplicationCommandInteractionDataOption) {
args := opts(sub.Options)
kind, target := "", ""
if u, ok := args["user"]; ok {
kind, target = "user", u.UserValue(nil).ID
}
if r, ok := args["role"]; ok {
if target != "" {
reply(s, i, "Pick a user or a role, not both.")
return
}
kind, target = "role", r.RoleValue(nil, i.GuildID).ID
}
if target == "" {
reply(s, i, "Pick a user or a role.")
return
}
mention := "<@" + target + ">"
if kind == "role" {
mention = "<@&" + target + ">"
}
switch sub.Name {
case "add":
if err := e.Trust(ctx, i.GuildID, i.Member, kind, target); err != nil {
reply(s, i, message("trust add", err))
return
}
reply(s, i, mention+" is now trusted: exempt from anti-nuke and able to change security settings.")
case "remove":
if err := e.Untrust(ctx, i.GuildID, i.Member, target); err != nil {
reply(s, i, message("trust remove", err))
return
}
reply(s, i, mention+" is no longer trusted.")
}
}
func endRaid(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, e *security.Engine) {
if err := e.RequireTrusted(ctx, i.GuildID, i.Member); err != nil {
reply(s, i, message("end raid", err))
return
}
if !deferReply(s, i) {
return
}
if err := e.EndRaid(ctx, i.GuildID, userID(i)); err != nil {
edit(s, i, message("end raid", err))
return
}
edit(s, i, "Raid mode is off.")
}
func featureName(f string) string {
switch f {
case securityrepo.FeatureJoinGate:
return "Join Gate"
case securityrepo.FeatureAntiRaid:
return "Raid mode"
case securityrepo.FeatureAntiNuke:
return "Anti-nuke"
case securityrepo.FeatureHeat:
return "Heat"
}
return f
}
func onOff(b bool) string {
if b {
return "✅ on"
}
return "⬜ off"
}
func status(ctx context.Context, e *security.Engine, guildID string) string {
st, trusted, err := e.Settings(ctx, guildID)
if err != nil {
return message("status", err)
}
var b strings.Builder
fmt.Fprintf(&b, "**Join Gate:** %s\n**Raid mode:** %s (%d joins in %ds → %s)\n**Anti-nuke:** %s (auto restore %s)\n**Heat:** %s (%s)\n",
onOff(st.JoinGateEnabled), onOff(st.AntiRaidEnabled), st.RaidJoinCount, st.RaidJoinSeconds, st.RaidAction,
onOff(st.AntiNukeEnabled), onOff(st.AntiNukeAutoRestore), onOff(st.HeatEnabled), st.HeatStrictness)
if e.RaidActive(guildID) {
b.WriteString("🚨 **A raid is in progress.**\n")
}
if st.JoinLock != securityrepo.ActionOff {
fmt.Fprintf(&b, "🔒 Joins are locked (%s).\n", st.JoinLock)
}
if st.AlertChannelID != 0 {
fmt.Fprintf(&b, "**Alerts:** <#%d>", st.AlertChannelID)
if st.AlertRoleID != 0 {
fmt.Fprintf(&b, ", pinging <@&%d>", st.AlertRoleID)
}
b.WriteString("\n")
} else {
b.WriteString("**Alerts:** not set. Use `/security alerts`.\n")
}
if owner, err := e.OwnerID(guildID); err == nil {
fmt.Fprintf(&b, "**Trusted:** <@%s> (owner)", owner)
}
for _, t := range trusted {
if t.Kind == "role" {
fmt.Fprintf(&b, ", <@&%d>", t.TargetID)
} else {
fmt.Fprintf(&b, ", <@%d>", t.TargetID)
}
}
b.WriteString("\nSee every setting with `/security settings`, and change them with `/security joingate`, `words`, `raid`, `antinuke` and `heat`.")
return b.String()
}
func clip(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n-1]) + "…"
}
return s
}
func LockdownHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
e := engine(s, i)
if e == nil {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
args := opts(sub.Options)
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
switch sub.Name {
case "channel":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageChannels) {
reply(s, i, "You need Manage Channels to lock a channel.")
return
}
ch := i.ChannelID
if c, ok := args["channel"]; ok {
ch = c.ChannelValue(nil).ID
}
if err := e.LockChannel(ctx, i.GuildID, ch, userID(i), false); err != nil {
reply(s, i, message("lock channel", err))
return
}
reply(s, i, fmt.Sprintf("🔒 <#%s> is locked. `/unlock channel` puts it back as it was.", ch))
case "server":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to lock the server.")
return
}
if !deferReply(s, i) {
return
}
locked, failed, err := e.LockServer(ctx, i.GuildID, userID(i))
if err != nil {
edit(s, i, message("lock server", err))
return
}
msg := fmt.Sprintf("🔒 Locked %d channels.", locked)
if failed > 0 {
msg += fmt.Sprintf(" %d couldn't be locked (Velox needs Manage Channels there).", failed)
}
edit(s, i, msg+" `/unlock server` puts them back as they were.")
case "joins":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to lock joins.")
return
}
mode := args["action"].StringValue()
if err := e.SetJoinLock(ctx, i.GuildID, mode, userID(i)); err != nil {
reply(s, i, message("lock joins", err))
return
}
reply(s, i, fmt.Sprintf("🔒 Everyone who joins will be %s until `/unlock joins`.", map[string]string{"kick": "kicked", "ban": "banned"}[mode]))
}
}
// UnlockHandler relaxes protection, so it is owner or trusted only.
func UnlockHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
e := engine(s, i)
if e == nil {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
args := opts(sub.Options)
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
if err := e.RequireTrusted(ctx, i.GuildID, i.Member); err != nil {
reply(s, i, message("unlock", err))
return
}
switch sub.Name {
case "channel":
ch := i.ChannelID
if c, ok := args["channel"]; ok {
ch = c.ChannelValue(nil).ID
}
if err := e.UnlockChannel(ctx, i.GuildID, ch, userID(i)); err != nil {
reply(s, i, message("unlock channel", err))
return
}
reply(s, i, fmt.Sprintf("🔓 <#%s> is unlocked.", ch))
case "server":
if !deferReply(s, i) {
return
}
unlocked, failed, err := e.UnlockServer(ctx, i.GuildID, userID(i))
if err != nil {
edit(s, i, message("unlock server", err))
return
}
msg := fmt.Sprintf("🔓 Unlocked %d channels.", unlocked)
if failed > 0 {
msg += fmt.Sprintf(" %d failed; try `/unlock server` again.", failed)
}
edit(s, i, msg)
case "joins":
if err := e.SetJoinLock(ctx, i.GuildID, securityrepo.ActionOff, userID(i)); err != nil {
reply(s, i, message("unlock joins", err))
return
}
reply(s, i, "🔓 Joins are open again.")
}
}
// HandleComponent handles the alert's "End raid" button. Anyone in the alert
// channel can press it, so it checks trust like the command.
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
e := engine(s, i)
if e == nil {
return
}
if i.MessageComponentData().CustomID != security.CustomIDEndRaid {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
endRaid(ctx, s, i, e)
}
+377
View File
@@ -0,0 +1,377 @@
package public
import (
"context"
"fmt"
"sort"
"strings"
"velox-bot/internal/db/repos/securityrepo"
"velox-bot/internal/security"
"github.com/bwmarrin/discordgo"
)
// The commands that tune the Join Gate, raid mode, anti-nuke and heat. They
// reach the same settings a dashboard would, so a server never needs one.
// Changing them needs the server owner or someone on the trusted list; that is
// enforced by the security engine, not by Discord's command permissions.
func intOption(name, desc string, min, max int) *discordgo.ApplicationCommandOption {
lo := float64(min)
return &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionInteger, Name: name, Description: desc,
MinValue: &lo, MaxValue: float64(max),
}
}
func boolOption(name, desc string) *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionBoolean, Name: name, Description: desc}
}
func choiceOption(name, desc string, required bool, choices ...string) *discordgo.ApplicationCommandOption {
o := &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionString, Name: name, Description: desc, Required: required}
for _, c := range choices {
o.Choices = append(o.Choices, &discordgo.ApplicationCommandOptionChoice{Name: c, Value: c})
}
return o
}
func sub(name, desc string, options ...*discordgo.ApplicationCommandOption) *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionSubCommand, Name: name, Description: desc, Options: options}
}
func group(name, desc string, subs ...*discordgo.ApplicationCommandOption) *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionSubCommandGroup, Name: name, Description: desc, Options: subs}
}
func required(o *discordgo.ApplicationCommandOption) *discordgo.ApplicationCommandOption {
o.Required = true
return o
}
var nukeLimitChoices = []string{
securityrepo.LimitChannelDelete, securityrepo.LimitChannelCreate, securityrepo.LimitRoleDelete, securityrepo.LimitRoleCreate,
securityrepo.LimitBan, securityrepo.LimitKick, securityrepo.LimitWebhookCreate,
}
// Which Join Gate check an option name stands for.
var joinGateChecks = []string{"no-avatar", "new-account", "invite-in-name", "blocked-names", "unverified-bot", "unauthorized-bot"}
// tuneOptions are the subcommands added to /security.
func tuneOptions() []*discordgo.ApplicationCommandOption {
acts := []string{securityrepo.ActionOff, securityrepo.ActionTimeout, securityrepo.ActionKick, securityrepo.ActionBan}
lists := []string{string(security.UsernameWords), string(security.ChatWords)}
listOpt := func() *discordgo.ApplicationCommandOption {
return choiceOption("list", "username: new members' names (Join Gate). chat: messages (heat)", true, lists...)
}
wordOpt := func() *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{Type: discordgo.ApplicationCommandOptionString, Name: "word", Description: "A word or phrase, matched as plain text", Required: true, MaxLength: 50}
}
return []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "settings", Description: "Show every security setting"},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "history", Description: "Show the latest security events (raids, quarantines, setting changes)"},
group("joingate", "Tune the Join Gate (owner or trusted)",
sub("check", "Choose what happens when a check catches a new member",
choiceOption("check", "Which check", true, joinGateChecks...),
choiceOption("action", "What to do. Bot checks accept off, kick or ban", true, acts...)),
sub("account-age", "How old an account must be to pass the new-account check",
required(intOption("days", "Days, 1 to 365", 1, 365)))),
group("words", "Blocked words (owner or trusted)",
sub("add", "Block a word", listOpt(), wordOpt()),
sub("remove", "Stop blocking a word", listOpt(), wordOpt()),
sub("list", "Show the blocked words", listOpt())),
sub("raid", "Tune raid mode (owner or trusted). Leave out what you don't change",
intOption("join-count", "Joins that start a raid, 3 to 100", 3, 100),
intOption("join-seconds", "Within this many seconds, 5 to 300", 5, 300),
choiceOption("action", "What happens to raiders", false, securityrepo.ActionAlert, securityrepo.ActionTimeout, securityrepo.ActionKick, securityrepo.ActionBan),
boolOption("pause-invites", "Pause server invites during a raid"),
intOption("quiet-minutes", "Minutes without a join before the raid ends, 1 to 120", 1, 120)),
group("antinuke", "Tune anti-nuke (owner or trusted)",
sub("set", "Leave out what you don't change",
intOption("window-seconds", "Actions are counted within this many seconds, 5 to 300", 5, 300),
boolOption("lock-server", "Also lock every channel when a nuke is stopped"),
boolOption("auto-restore", "Restore deleted roles and channels after a stopped nuke")),
sub("limit", "How many times someone may do an action within the window (0 means never)",
choiceOption("action", "Which action", true, nukeLimitChoices...),
required(intOption("count", "0 to 100", 0, 100)))),
sub("heat", "Tune the spam heat system (owner or trusted). Leave out what you don't change",
choiceOption("strictness", "How fast heat builds", false, "low", "medium", "high"),
choiceOption("action", "What happens at maximum heat", false, securityrepo.ActionTimeout, securityrepo.ActionKick, securityrepo.ActionBan),
intOption("timeout-minutes", "Timeout length, 1 to 10080", 1, 10080),
boolOption("escalate", "Double the timeout for repeat offences"),
intOption("panic-members", "Members maxing out in a minute that start heat panic, 0 (off) to 50", 0, 50),
intOption("mention-lockdown", "Mentions in 30 seconds that lock the server, 0 (off) or 5 to 1000", 0, 1000)),
sub("alert-dms", "Send critical alerts to the owner and trusted users too (owner or trusted)",
required(boolOption("on", "On or off"))),
}
}
func intArg(args map[string]*discordgo.ApplicationCommandInteractionDataOption, name string) *int {
if a, ok := args[name]; ok {
v := int(a.IntValue())
return &v
}
return nil
}
func boolArg(args map[string]*discordgo.ApplicationCommandInteractionDataOption, name string) *bool {
if a, ok := args[name]; ok {
v := a.BoolValue()
return &v
}
return nil
}
func strArg(args map[string]*discordgo.ApplicationCommandInteractionDataOption, name string) *string {
if a, ok := args[name]; ok {
v := a.StringValue()
return &v
}
return nil
}
// handleTune runs the tuning subcommands. It reports whether it handled name.
func handleTune(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, e *security.Engine, subcmd *discordgo.ApplicationCommandInteractionDataOption) bool {
args := opts(subcmd.Options)
switch subcmd.Name {
case "settings":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to see the security settings.")
return true
}
st, _, err := e.Settings(ctx, i.GuildID)
if err != nil {
reply(s, i, message("settings", err))
return true
}
reply(s, i, describeSettings(st))
case "history":
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to see the security history.")
return true
}
events, err := e.Events(ctx, i.GuildID, 15)
if err != nil {
reply(s, i, message("history", err))
return true
}
if len(events) == 0 {
reply(s, i, "Nothing has happened yet.")
return true
}
var b strings.Builder
for _, ev := range events {
fmt.Fprintf(&b, "<t:%d:R> **%s**", ev.CreatedAt.Unix(), ev.Kind)
if ev.ActorID != 0 {
fmt.Fprintf(&b, " by <@%d>", ev.ActorID)
}
if ev.TargetID != 0 {
fmt.Fprintf(&b, " on <@%d>", ev.TargetID)
}
if ev.Detail != "" {
fmt.Fprintf(&b, ": %s", clip(ev.Detail, 120))
}
b.WriteString("\n")
}
reply(s, i, clip(b.String(), 1950))
case "joingate":
if len(subcmd.Options) == 0 {
return true
}
inner := subcmd.Options[0]
innerArgs := opts(inner.Options)
t := securityrepo.Tuning{}
var summary, done string
switch inner.Name {
case "check":
check, action := innerArgs["check"].StringValue(), innerArgs["action"].StringValue()
switch check {
case "no-avatar":
t.NoAvatar = &action
case "new-account":
t.NewAccount = &action
case "invite-in-name":
t.AdvertisingName = &action
case "blocked-names":
t.UsernameFilter = &action
case "unverified-bot":
t.UnverifiedBot = &action
case "unauthorized-bot":
t.UnauthorizedBot = &action
}
summary = "joingate " + check + " " + action
done = fmt.Sprintf("The **%s** check is now **%s**. The Join Gate itself is switched with `/security toggle`.", check, action)
case "account-age":
days := int(innerArgs["days"].IntValue())
t.MinAccountAgeDays = &days
summary = fmt.Sprintf("joingate minimum account age %d days", days)
done = fmt.Sprintf("Accounts younger than **%d days** are caught by the new-account check.", days)
default:
return true
}
finishTune(ctx, s, i, e, t, summary, done)
case "words":
if len(subcmd.Options) == 0 {
return true
}
handleWords(ctx, s, i, e, subcmd.Options[0])
case "raid":
t := securityrepo.Tuning{
RaidJoinCount: intArg(args, "join-count"), RaidJoinSeconds: intArg(args, "join-seconds"), RaidAction: strArg(args, "action"),
RaidPauseInvites: boolArg(args, "pause-invites"), RaidQuietMinutes: intArg(args, "quiet-minutes"),
}
if len(args) == 0 {
reply(s, i, "Say what to change: join-count, join-seconds, action, pause-invites or quiet-minutes.")
return true
}
finishTune(ctx, s, i, e, t, "raid settings changed", "Raid settings saved.\n"+raidLine(ctx, e, i.GuildID, t))
case "antinuke":
if len(subcmd.Options) == 0 {
return true
}
inner := subcmd.Options[0]
innerArgs := opts(inner.Options)
t := securityrepo.Tuning{}
var summary, done string
switch inner.Name {
case "set":
if len(innerArgs) == 0 {
reply(s, i, "Say what to change: window-seconds, lock-server or auto-restore.")
return true
}
t.AntiNukeWindowSeconds, t.AntiNukeLockServer, t.AntiNukeAutoRestore = intArg(innerArgs, "window-seconds"), boolArg(innerArgs, "lock-server"), boolArg(innerArgs, "auto-restore")
summary, done = "antinuke settings changed", "Anti-nuke settings saved. See them with `/security settings`."
case "limit":
action, count := innerArgs["action"].StringValue(), int(innerArgs["count"].IntValue())
t.AntiNukeLimits = map[string]int{action: count}
summary = fmt.Sprintf("antinuke limit %s = %d", action, count)
if count == 0 {
done = fmt.Sprintf("**%s** is never allowed for anyone who isn't the owner or trusted.", action)
} else {
done = fmt.Sprintf("**%s** is limited to **%d** per window.", action, count)
}
default:
return true
}
finishTune(ctx, s, i, e, t, summary, done)
case "heat":
if len(args) == 0 {
reply(s, i, "Say what to change: strictness, action, timeout-minutes, escalate, panic-members or mention-lockdown.")
return true
}
t := securityrepo.Tuning{
HeatStrictness: strArg(args, "strictness"), HeatAction: strArg(args, "action"), HeatTimeoutMinutes: intArg(args, "timeout-minutes"),
HeatEscalate: boolArg(args, "escalate"), HeatPanicMembers: intArg(args, "panic-members"), HeatLockdownMentions: intArg(args, "mention-lockdown"),
}
finishTune(ctx, s, i, e, t, "heat settings changed", "Heat settings saved. See them with `/security settings`.")
case "alert-dms":
on := args["on"].BoolValue()
state := "off"
if on {
state = "on"
}
finishTune(ctx, s, i, e, securityrepo.Tuning{AlertDM: &on}, "alert DMs "+state, "Critical alerts by DM are now **"+state+"**.")
default:
return false
}
return true
}
func finishTune(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, e *security.Engine, t securityrepo.Tuning, summary, done string) {
if err := e.Tune(ctx, i.GuildID, i.Member, t, summary); err != nil {
reply(s, i, message("tune", err))
return
}
reply(s, i, done)
}
func raidLine(ctx context.Context, e *security.Engine, guildID string, _ securityrepo.Tuning) string {
st, _, err := e.Settings(ctx, guildID)
if err != nil {
return ""
}
return fmt.Sprintf("%d joins within %ds start a raid, raiders get **%s**, it ends after %d quiet minutes (invites %s).",
st.RaidJoinCount, st.RaidJoinSeconds, st.RaidAction, st.RaidQuietMinutes, pausedText(st.RaidPauseInvites))
}
func pausedText(on bool) string {
if on {
return "are paused"
}
return "stay open"
}
func handleWords(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, e *security.Engine, inner *discordgo.ApplicationCommandInteractionDataOption) {
args := opts(inner.Options)
list := security.WordList(args["list"].StringValue())
what := map[security.WordList]string{security.UsernameWords: "new members' names", security.ChatWords: "messages"}[list]
switch inner.Name {
case "list":
st, _, err := e.Settings(ctx, i.GuildID)
if err != nil {
reply(s, i, message("words", err))
return
}
words := st.UsernamePatterns
if list == security.ChatWords {
words = st.HeatBlockedWords
}
if !allowedOrTrusted(ctx, e, i, discordgo.PermissionManageGuild) {
reply(s, i, "You need Manage Server to see the blocked words.")
return
}
if len(words) == 0 {
reply(s, i, "No words are blocked in "+what+".")
return
}
reply(s, i, fmt.Sprintf("Blocked in %s (%d): %s", what, len(words), clip("`"+strings.Join(words, "`, `")+"`", 1700)))
case "add", "remove":
word := args["word"].StringValue()
words, err := e.EditWords(ctx, i.GuildID, i.Member, list, inner.Name == "add", word)
if err != nil {
reply(s, i, message("words", err))
return
}
verb := "is now blocked in"
if inner.Name == "remove" {
verb = "is no longer blocked in"
}
reply(s, i, fmt.Sprintf("`%s` %s %s. %d word(s) on the list.", strings.ToLower(strings.TrimSpace(word)), verb, what, len(words)))
}
}
// describeSettings lists every setting, for /security settings.
func describeSettings(st *securityrepo.Settings) string {
var b strings.Builder
fmt.Fprintf(&b, "**Join Gate** %s\n", onOff(st.JoinGateEnabled))
fmt.Fprintf(&b, "No avatar: %s · New account (under %d days): %s · Invite in name: %s · Blocked names: %s (%d words)\n",
st.NoAvatar, st.MinAccountAgeDays, st.NewAccount, st.AdvertisingName, st.UsernameFilter, len(st.UsernamePatterns))
fmt.Fprintf(&b, "Unverified bots: %s · Bots added by someone untrusted: %s\n\n", st.UnverifiedBot, st.UnauthorizedBot)
fmt.Fprintf(&b, "**Raid mode** %s\n%d joins in %ds → %s · ends after %d quiet minutes · invites %s\n\n",
onOff(st.AntiRaidEnabled), st.RaidJoinCount, st.RaidJoinSeconds, st.RaidAction, st.RaidQuietMinutes, pausedText(st.RaidPauseInvites))
fmt.Fprintf(&b, "**Anti-nuke** %s\nWindow %ds · lock server on a nuke: %s · auto restore: %s\n",
onOff(st.AntiNukeEnabled), st.AntiNukeWindowSeconds, onOff(st.AntiNukeLockServer), onOff(st.AntiNukeAutoRestore))
keys := make([]string, 0, len(st.AntiNukeLimits))
for k := range st.AntiNukeLimits {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s %d", k, st.AntiNukeLimits[k]))
}
fmt.Fprintf(&b, "Limits: %s\n\n", strings.Join(parts, " · "))
mention := "off"
if st.HeatLockdownMentions > 0 {
mention = fmt.Sprintf("%d mentions", st.HeatLockdownMentions)
}
panicMembers := "off"
if st.HeatPanicMembers > 0 {
panicMembers = fmt.Sprintf("%d members", st.HeatPanicMembers)
}
fmt.Fprintf(&b, "**Heat** %s\nStrictness %s · action %s (%d min timeout, escalating %s) · panic at %s · mention flood lockdown at %s · %d blocked words\n\n",
onOff(st.HeatEnabled), st.HeatStrictness, st.HeatAction, st.HeatTimeoutMinutes, onOff(st.HeatEscalate), panicMembers, mention, len(st.HeatBlockedWords))
fmt.Fprintf(&b, "**Alerts** by DM to the owner and trusted: %s", onOff(st.AlertDM))
return clip(b.String(), 1990)
}
+29
View File
@@ -0,0 +1,29 @@
package security
import (
"velox-bot/internal/commands/security/public"
"github.com/bwmarrin/discordgo"
)
var (
Security *discordgo.ApplicationCommand = public.Security
Lockdown *discordgo.ApplicationCommand = public.Lockdown
Unlock *discordgo.ApplicationCommand = public.Unlock
)
func SecurityHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.SecurityHandler(s, i)
}
func LockdownHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.LockdownHandler(s, i)
}
func UnlockHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.UnlockHandler(s, i)
}
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleComponent(s, i)
}
@@ -0,0 +1,247 @@
package public
import (
"context"
"fmt"
"strconv"
"strings"
"unicode/utf8"
"velox-bot/internal/db/repos/ticketrepo"
"github.com/bwmarrin/discordgo"
)
// The rest of the ticket configuration: the on/off switch, the panel's text,
// the open ticket limit, editing a category, and looking at tickets. All of it
// is available from Discord, so a dashboard is never needed.
func ticketSettingsOptions() []*discordgo.ApplicationCommandOption {
lo, hi := 1.0, 10.0
return []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "settings",
Description: "Show the ticket settings, or change them. Leave out what you don't change",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionBoolean, Name: "enabled", Description: "Turn tickets on or off"},
{Type: discordgo.ApplicationCommandOptionString, Name: "panel-title", Description: "The panel's title", MaxLength: 256},
{Type: discordgo.ApplicationCommandOptionString, Name: "panel-description", Description: "The panel's text", MaxLength: 4000},
{Type: discordgo.ApplicationCommandOptionInteger, Name: "max-open", Description: "Open tickets one member can have, 1 to 10", MinValue: &lo, MaxValue: hi},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "list",
Description: "List recent tickets",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString, Name: "status", Description: "Open or closed (default: open)",
Choices: []*discordgo.ApplicationCommandOptionChoice{{Name: "open", Value: ticketrepo.StatusOpen}, {Name: "closed", Value: ticketrepo.StatusClosed}},
},
},
},
}
}
func categoryEditOption() *discordgo.ApplicationCommandOption {
return &discordgo.ApplicationCommandOption{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "edit",
Description: "Change a category. Leave out what you don't change",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "name", Description: "The category to change", Required: true},
{Type: discordgo.ApplicationCommandOptionString, Name: "new-name", Description: "A new name", MaxLength: 40},
{Type: discordgo.ApplicationCommandOptionRole, Name: "staff-role", Description: "Who handles these tickets"},
{Type: discordgo.ApplicationCommandOptionBoolean, Name: "clear-staff-role", Description: "Remove the staff role"},
{Type: discordgo.ApplicationCommandOptionString, Name: "emoji", Description: "Shown on the button. Use - to remove", MaxLength: 64},
{Type: discordgo.ApplicationCommandOptionString, Name: "description", Description: "Shown on the panel. Use - to remove", MaxLength: 200},
},
}
}
func onOff(b bool) string {
if b {
return "on"
}
return "off"
}
func handleSettings(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
args := opts(o)
g := guildID(i)
if len(args) == 0 {
st, err := Repo.GetSettings(ctx, g)
if err != nil {
reply(s, i, message("settings", err))
return
}
where := "not set (use `/tickets setup`)"
if st.ChannelID != 0 {
where = fmt.Sprintf("<#%d>", st.ChannelID)
}
logs := "none"
if st.LogChannelID != 0 {
logs = fmt.Sprintf("<#%d>", st.LogChannelID)
}
reply(s, i, fmt.Sprintf("**Tickets:** %s\n**Channel:** %s · **Log channel:** %s\n**Open tickets per member:** %d\n**Panel title:** %s\n**Panel text:** %s",
onOff(st.Enabled), where, logs, st.MaxOpenPerUser, clipText(st.PanelTitle, 200), clipText(st.PanelDescription, 600)))
return
}
var p ticketrepo.SettingsPatch
if a, ok := args["enabled"]; ok {
v := a.BoolValue()
p.Enabled = &v
}
if a, ok := args["panel-title"]; ok {
v := strings.TrimSpace(a.StringValue())
if v == "" || utf8.RuneCountInString(v) > 256 {
reply(s, i, "The panel title must be between 1 and 256 characters.")
return
}
p.PanelTitle = &v
}
if a, ok := args["panel-description"]; ok {
v := strings.TrimSpace(a.StringValue())
if utf8.RuneCountInString(v) > 4000 {
reply(s, i, "The panel text can be at most 4000 characters.")
return
}
p.PanelDescription = &v
}
if a, ok := args["max-open"]; ok {
v := int(a.IntValue())
if v < 1 || v > 10 {
reply(s, i, "Open tickets per member must be between 1 and 10.")
return
}
p.MaxOpenPerUser = &v
}
if err := Repo.UpdateSettings(ctx, g, p); err != nil {
reply(s, i, message("settings", err))
return
}
msg := "Saved."
if p.PanelTitle != nil || p.PanelDescription != nil {
msg += " Run `/tickets panel` to update the panel with the new text."
}
if p.Enabled != nil {
msg += " Tickets are now **" + onOff(*p.Enabled) + "**."
}
reply(s, i, msg)
}
func clipText(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n-1]) + "…"
}
return s
}
func handleCategoryEdit(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
args := opts(o)
g := guildID(i)
name := strings.TrimSpace(args["name"].StringValue())
cats, err := Repo.ListCategories(ctx, g)
if err != nil {
reply(s, i, message("category edit", err))
return
}
var target *ticketrepo.Category
for idx := range cats {
if strings.EqualFold(cats[idx].Name, name) {
target = &cats[idx]
}
}
if target == nil {
reply(s, i, fmt.Sprintf("There's no category called **%s**.", name))
return
}
var p ticketrepo.CategoryPatch
if a, ok := args["new-name"]; ok {
v := strings.TrimSpace(a.StringValue())
if v == "" || utf8.RuneCountInString(v) > 40 {
reply(s, i, "The category name must be between 1 and 40 characters.")
return
}
for _, c := range cats {
if c.ID != target.ID && strings.EqualFold(c.Name, v) {
reply(s, i, fmt.Sprintf("There's already a category called **%s**.", c.Name))
return
}
}
p.Name = &v
}
if a, ok := args["staff-role"]; ok {
id, _ := strconv.ParseInt(a.RoleValue(nil, i.GuildID).ID, 10, 64)
p.StaffRoleID = &id
}
if a, ok := args["clear-staff-role"]; ok && a.BoolValue() {
if p.StaffRoleID != nil {
reply(s, i, "Choose either a staff role or clearing it, not both.")
return
}
zero := int64(0)
p.StaffRoleID = &zero
}
if a, ok := args["emoji"]; ok {
v := strings.TrimSpace(a.StringValue())
if v == "-" {
v = ""
}
p.Emoji = &v
}
if a, ok := args["description"]; ok {
v := strings.TrimSpace(a.StringValue())
if v == "-" {
v = ""
}
if utf8.RuneCountInString(v) > 200 {
reply(s, i, "The category description can be at most 200 characters.")
return
}
p.Description = &v
}
if p == (ticketrepo.CategoryPatch{}) {
reply(s, i, "Say what to change: new-name, staff-role, clear-staff-role, emoji or description.")
return
}
if _, err := Repo.UpdateCategory(ctx, g, target.ID, p); err != nil {
reply(s, i, message("category edit", err))
return
}
reply(s, i, fmt.Sprintf("Updated **%s**. Run `/tickets panel` to update the panel.", target.Name))
}
func handleList(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
status := ticketrepo.StatusOpen
if a, ok := opts(o)["status"]; ok {
status = a.StringValue()
}
ts, err := Repo.ListTickets(ctx, guildID(i), status, 15)
if err != nil {
reply(s, i, message("list", err))
return
}
if len(ts) == 0 {
reply(s, i, "No "+status+" tickets.")
return
}
var b strings.Builder
fmt.Fprintf(&b, "**Latest %s tickets**\n", status)
for _, t := range ts {
fmt.Fprintf(&b, "• #%d <#%d> %s, by <@%d>", t.Number, t.ThreadID, clipText(t.CategoryName, 30), t.OpenerID)
if t.ClaimedBy != 0 {
fmt.Fprintf(&b, ", claimed by <@%d>", t.ClaimedBy)
}
b.WriteString("\n")
}
reply(s, i, clipText(b.String(), 1900))
}
+549
View File
@@ -0,0 +1,549 @@
package public
import (
"context"
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"
"velox-bot/internal/db/repos/ticketrepo"
"velox-bot/internal/tickets"
"github.com/bwmarrin/discordgo"
)
// The session must provide everything the ticket flows call.
var _ tickets.Discord = (*discordgo.Session)(nil)
// Repo is the full ticket store, including the admin calls that only the
// slash commands make. Set by Init.
var Repo *ticketrepo.Repo
func Init(r *ticketrepo.Repo) {
Repo = r
tickets.Init(r)
}
var (
manageGuild = int64(discordgo.PermissionManageGuild)
guildOnly = &[]discordgo.InteractionContextType{discordgo.InteractionContextGuild}
textChannels = []discordgo.ChannelType{discordgo.ChannelTypeGuildText}
opTimeout = 2 * time.Minute
genericFailed = "Something went wrong. Try again in a moment, and tell an admin if it keeps happening."
)
// Tickets is the admin command for setting the system up.
var Tickets = &discordgo.ApplicationCommand{
Name: "tickets",
Description: "Set up support tickets",
DefaultMemberPermissions: &manageGuild,
Contexts: guildOnly,
Options: append([]*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "setup",
Description: "Choose where tickets are opened and where closed tickets are logged",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionChannel, Name: "channel", Description: "Where the panel goes and ticket threads are created", Required: true, ChannelTypes: textChannels},
{Type: discordgo.ApplicationCommandOptionChannel, Name: "log-channel", Description: "Where closed tickets and their transcripts are posted", ChannelTypes: textChannels},
{Type: discordgo.ApplicationCommandOptionRole, Name: "staff-role", Description: "Creates a Support category handled by this role, if there are no categories yet"},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommandGroup,
Name: "category",
Description: "Manage ticket categories",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "add",
Description: "Add a category (an option in the panel's dropdown)",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "name", Description: "e.g. Support, Report, Appeal", Required: true, MaxLength: 40},
{Type: discordgo.ApplicationCommandOptionRole, Name: "staff-role", Description: "Who handles these tickets"},
{Type: discordgo.ApplicationCommandOptionString, Name: "emoji", Description: "Shown on the button", MaxLength: 64},
{Type: discordgo.ApplicationCommandOptionString, Name: "description", Description: "Shown on the panel", MaxLength: 200},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "remove",
Description: "Remove a category",
Options: []*discordgo.ApplicationCommandOption{
{Type: discordgo.ApplicationCommandOptionString, Name: "name", Description: "The category's name", Required: true},
},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "list", Description: "Show the categories"},
categoryEditOption(),
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "panel",
Description: "Post the ticket panel, or update it after changing categories",
},
}, ticketSettingsOptions()...),
}
// Ticket is used inside a ticket thread.
var Ticket = &discordgo.ApplicationCommand{
Name: "ticket",
Description: "Manage the ticket you're in",
Contexts: guildOnly,
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "add", Description: "Add someone to this ticket",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionUser, Name: "user", Description: "Who to add", Required: true}},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "remove", Description: "Remove someone from this ticket (staff only)",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionUser, Name: "user", Description: "Who to remove", Required: true}},
},
{Type: discordgo.ApplicationCommandOptionSubCommand, Name: "claim", Description: "Take this ticket (staff only)"},
{
Type: discordgo.ApplicationCommandOptionSubCommand, Name: "close", Description: "Close this ticket",
Options: []*discordgo.ApplicationCommandOption{{Type: discordgo.ApplicationCommandOptionString, Name: "reason", Description: "Why it's being closed", MaxLength: 300}},
},
},
}
func reply(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Content: msg, Flags: discordgo.MessageFlagsEphemeral, AllowedMentions: &discordgo.MessageAllowedMentions{}},
})
}
func deferReply(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{Flags: discordgo.MessageFlagsEphemeral},
})
return err == nil
}
func edit(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_, _ = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{Content: &msg, AllowedMentions: &discordgo.MessageAllowedMentions{}})
}
// message turns an error into what the user sees; unexpected ones are logged.
func message(where string, err error) string {
var ue tickets.UserError
if errors.As(err, &ue) {
return string(ue)
}
log.Printf("tickets: %s: %v", where, err)
return genericFailed
}
func actor(i *discordgo.InteractionCreate) tickets.Actor {
a := tickets.Actor{Member: i.Member}
if i.Member != nil {
a.Perms = i.Member.Permissions
}
return a
}
func guildID(i *discordgo.InteractionCreate) int64 {
n, _ := strconv.ParseInt(i.GuildID, 10, 64)
return n
}
func TicketsHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if Repo == nil {
reply(s, i, "Tickets aren't available right now.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
switch sub.Name {
case "setup":
handleSetup(s, i, sub.Options)
case "panel":
handlePanel(s, i)
case "settings":
handleSettings(s, i, sub.Options)
case "list":
handleList(s, i, sub.Options)
case "category":
if len(sub.Options) == 0 {
return
}
switch sub.Options[0].Name {
case "add":
handleCategoryAdd(s, i, sub.Options[0].Options)
case "remove":
handleCategoryRemove(s, i, sub.Options[0].Options)
case "list":
handleCategoryList(s, i)
case "edit":
handleCategoryEdit(s, i, sub.Options[0].Options)
}
}
}
func opts(o []*discordgo.ApplicationCommandInteractionDataOption) map[string]*discordgo.ApplicationCommandInteractionDataOption {
m := map[string]*discordgo.ApplicationCommandInteractionDataOption{}
for _, x := range o {
m[x.Name] = x
}
return m
}
// permissionWarning names what the bot is missing in a channel, or "".
func permissionWarning(s *discordgo.Session, channelID string, need int64, what string) string {
have, err := s.UserChannelPermissions(s.State.User.ID, channelID)
if err != nil {
return ""
}
if missing := tickets.MissingPerms(have, need); len(missing) > 0 {
return fmt.Sprintf("\n⚠️ I'm missing these permissions in <#%s> (%s): %s.", channelID, what, strings.Join(missing, ", "))
}
return ""
}
func handleSetup(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
args := opts(o)
g := guildID(i)
ch := args["channel"].ChannelValue(nil).ID
var logID int64
logMention := "none"
if l, ok := args["log-channel"]; ok {
lc := l.ChannelValue(nil).ID
logID, _ = strconv.ParseInt(lc, 10, 64)
logMention = "<#" + lc + ">"
}
chID, _ := strconv.ParseInt(ch, 10, 64)
if err := Repo.SetChannels(ctx, g, chID, logID); err != nil {
reply(s, i, message("setup", err))
return
}
cats, err := Repo.ListCategories(ctx, g)
if err != nil {
reply(s, i, message("setup", err))
return
}
created := ""
if r, ok := args["staff-role"]; ok && len(cats) == 0 {
role := r.RoleValue(nil, i.GuildID)
roleID, _ := strconv.ParseInt(role.ID, 10, 64)
if _, err := Repo.AddCategory(ctx, ticketrepo.Category{GuildID: g, Name: "Support", Emoji: "🎫", StaffRoleID: roleID}); err != nil {
reply(s, i, message("setup", err))
return
}
created = fmt.Sprintf("\nCreated a **Support** category handled by <@&%s>.", role.ID)
cats = append(cats, ticketrepo.Category{Name: "Support"})
}
msg := fmt.Sprintf("Tickets will open as private threads in <#%s>. Closed tickets are logged to %s.%s", ch, logMention, created)
msg += permissionWarning(s, ch, tickets.NeedTicketChannel, "ticket channel")
if logID != 0 {
msg += permissionWarning(s, strconv.FormatInt(logID, 10), tickets.NeedLogChannel, "log channel")
}
if len(cats) == 0 {
msg += "\nNext: add a category with `/tickets category add`, then post the panel with `/tickets panel`."
} else {
msg += "\nNext: post the panel with `/tickets panel`."
}
msg += "\nTip: give your staff role **Manage Threads** in that channel so they can see every ticket, even ones they weren't pinged in."
reply(s, i, msg)
}
func handlePanel(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !deferReply(s, i) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
msg, err := tickets.PostPanel(ctx, s, Repo, guildID(i))
if err != nil {
edit(s, i, message("panel", err))
return
}
edit(s, i, fmt.Sprintf("The ticket panel is up: https://discord.com/channels/%s/%s/%s", i.GuildID, msg.ChannelID, msg.ID))
}
func handleCategoryAdd(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
args := opts(o)
g := guildID(i)
cats, err := Repo.ListCategories(ctx, g)
if err != nil {
reply(s, i, message("category add", err))
return
}
name := strings.TrimSpace(args["name"].StringValue())
for _, c := range cats {
if strings.EqualFold(c.Name, name) {
reply(s, i, fmt.Sprintf("There's already a category called **%s**.", c.Name))
return
}
}
if len(cats) >= 25 {
reply(s, i, "A panel can hold at most 25 categories.")
return
}
c := ticketrepo.Category{GuildID: g, Name: name}
if r, ok := args["staff-role"]; ok {
c.StaffRoleID, _ = strconv.ParseInt(r.RoleValue(nil, i.GuildID).ID, 10, 64)
}
if e, ok := args["emoji"]; ok {
c.Emoji = strings.TrimSpace(e.StringValue())
}
if d, ok := args["description"]; ok {
c.Description = strings.TrimSpace(d.StringValue())
}
if _, err := Repo.AddCategory(ctx, c); err != nil {
reply(s, i, message("category add", err))
return
}
reply(s, i, fmt.Sprintf("Added **%s**. Run `/tickets panel` to show it on the panel.", name))
}
func handleCategoryRemove(s *discordgo.Session, i *discordgo.InteractionCreate, o []*discordgo.ApplicationCommandInteractionDataOption) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
name := strings.TrimSpace(opts(o)["name"].StringValue())
ok, err := Repo.DeleteCategoryByName(ctx, guildID(i), name)
switch {
case err != nil:
reply(s, i, message("category remove", err))
case !ok:
reply(s, i, fmt.Sprintf("There's no category called **%s**.", name))
default:
reply(s, i, fmt.Sprintf("Removed **%s**. Open tickets keep working. Run `/tickets panel` to update the panel.", name))
}
}
func handleCategoryList(s *discordgo.Session, i *discordgo.InteractionCreate) {
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
cats, err := Repo.ListCategories(ctx, guildID(i))
if err != nil {
reply(s, i, message("category list", err))
return
}
if len(cats) == 0 {
reply(s, i, "No categories yet. Add one with `/tickets category add`.")
return
}
var b strings.Builder
for _, c := range cats {
line := "• "
if c.Emoji != "" {
line += c.Emoji + " "
}
line += "**" + c.Name + "**"
if c.StaffRoleID != 0 {
line += fmt.Sprintf(" → <@&%d>", c.StaffRoleID)
} else {
line += " → no staff role (only Manage Threads)"
}
if c.Description != "" {
line += ": " + c.Description
}
b.WriteString(line + "\n")
}
reply(s, i, b.String())
}
func TicketHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if Repo == nil {
reply(s, i, "Tickets aren't available right now.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
return
}
sub := data.Options[0]
args := opts(sub.Options)
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
switch sub.Name {
case "add", "remove":
user := args["user"].UserValue(nil)
if user == nil {
return
}
if !deferReply(s, i) {
return
}
var err error
if sub.Name == "add" {
err = tickets.AddMember(ctx, s, Repo, i.ChannelID, actor(i), user.ID)
} else {
err = tickets.RemoveMember(ctx, s, Repo, i.ChannelID, actor(i), user.ID)
}
if err != nil {
edit(s, i, message("ticket "+sub.Name, err))
return
}
edit(s, i, "Done.")
case "claim":
claim(s, i)
case "close":
reason := ""
if r, ok := args["reason"]; ok {
reason = r.StringValue()
}
closeTicket(s, i, reason)
}
}
func claim(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !deferReply(s, i) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
if err := tickets.Claim(ctx, s, Repo, i.ChannelID, actor(i)); err != nil {
edit(s, i, message("claim", err))
return
}
edit(s, i, "You're handling this ticket now.")
}
func closeTicket(s *discordgo.Session, i *discordgo.InteractionCreate, reason string) {
if !deferReply(s, i) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
if err := tickets.Close(ctx, s, Repo, i.ChannelID, actor(i), reason); err != nil {
edit(s, i, message("close", err))
return
}
edit(s, i, "Ticket closed.")
}
// HandleComponent handles the panel dropdown and Create ticket button and the Claim and
// Close buttons in a ticket.
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
if Repo == nil {
reply(s, i, "Tickets aren't available right now.")
return
}
data := i.MessageComponentData()
switch {
case strings.HasPrefix(data.CustomID, "tickets:open:"):
// Panels posted before the dropdown had one button per category.
showOpenForm(s, i, strings.TrimPrefix(data.CustomID, "tickets:open:"))
case data.CustomID == "tickets:select" && len(data.Values) > 0:
rememberPick(s, i, data.Values[0])
case data.CustomID == "tickets:create":
createFromPick(s, i)
case data.CustomID == "tickets:claim":
claim(s, i)
case data.CustomID == "tickets:close":
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
if err := tickets.CheckCanClose(ctx, Repo, i.ChannelID, actor(i)); err != nil {
reply(s, i, message("close", err))
return
}
_ = s.InteractionRespond(i.Interaction, tickets.CloseForm())
}
}
// rememberPick stores the dropdown choice for the Create ticket button and
// acknowledges it without changing the panel, so the choice stays visible.
func rememberPick(s *discordgo.Session, i *discordgo.InteractionCreate, rawCategory string) {
catID, err := strconv.ParseInt(rawCategory, 10, 64)
if err != nil || i.Member == nil || i.Member.User == nil {
return
}
userID, _ := strconv.ParseInt(i.Member.User.ID, 10, 64)
tickets.RememberPick(guildID(i), userID, catID)
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{Type: discordgo.InteractionResponseDeferredMessageUpdate})
}
func createFromPick(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Member == nil || i.Member.User == nil {
return
}
userID, _ := strconv.ParseInt(i.Member.User.ID, 10, 64)
catID, ok := tickets.PickedCategory(guildID(i), userID)
if !ok {
reply(s, i, "Pick a category from the menu first, then press **Create ticket**.")
return
}
showOpenForm(s, i, strconv.FormatInt(catID, 10))
}
func showOpenForm(s *discordgo.Session, i *discordgo.InteractionCreate, rawCategory string) {
catID, err := strconv.ParseInt(rawCategory, 10, 64)
if err != nil || i.Member == nil || i.Member.User == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
userID, _ := strconv.ParseInt(i.Member.User.ID, 10, 64)
_, cat, err := tickets.CheckCanOpen(ctx, Repo, guildID(i), userID, catID)
if err != nil {
reply(s, i, message("open", err))
return
}
_ = s.InteractionRespond(i.Interaction, tickets.OpenForm(cat))
}
func field(data discordgo.ModalSubmitInteractionData, name string) string {
for _, row := range data.Components {
r, ok := row.(*discordgo.ActionsRow)
if !ok {
continue
}
for _, c := range r.Components {
if in, ok := c.(*discordgo.TextInput); ok && in.CustomID == name {
return strings.TrimSpace(in.Value)
}
}
}
return ""
}
// HandleModalSubmit handles the opening and closing forms.
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
if Repo == nil {
reply(s, i, "Tickets aren't available right now.")
return
}
data := i.ModalSubmitData()
switch {
case strings.HasPrefix(data.CustomID, "tickets:openform:"):
catID, err := strconv.ParseInt(strings.TrimPrefix(data.CustomID, "tickets:openform:"), 10, 64)
if err != nil || i.Member == nil || i.Member.User == nil {
return
}
if !deferReply(s, i) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), opTimeout)
defer cancel()
thread, err := tickets.Open(ctx, s, Repo, tickets.OpenRequest{
GuildID: guildID(i), CategoryID: catID, User: i.Member.User,
Subject: field(data, "subject"), Details: field(data, "details"),
})
if err != nil {
edit(s, i, message("open", err))
return
}
edit(s, i, fmt.Sprintf("Your ticket is open: <#%s>. The staff will be with you there.", thread.ID))
case data.CustomID == "tickets:closeform":
closeTicket(s, i, field(data, "reason"))
}
}
+29
View File
@@ -0,0 +1,29 @@
package tickets
import (
"velox-bot/internal/commands/tickets/public"
"velox-bot/internal/db/repos/ticketrepo"
"github.com/bwmarrin/discordgo"
)
var (
Tickets *discordgo.ApplicationCommand = public.Tickets
Ticket *discordgo.ApplicationCommand = public.Ticket
)
func Init(r *ticketrepo.Repo) { public.Init(r) }
func TicketsHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.TicketsHandler(s, i)
}
func TicketHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.TicketHandler(s, i) }
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleComponent(s, i)
}
func HandleModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) {
public.HandleModalSubmit(s, i)
}
@@ -0,0 +1,115 @@
package public
import (
"context"
"time"
"velox-bot/internal/commands/timezone/shared"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
var Timezone = &discordgo.ApplicationCommand{
Name: "timezone",
Description: "Configure and view your timezone",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "set",
Description: "Set your timezone (IANA name, e.g., Europe/Lisbon)",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "zone",
Description: "Timezone (e.g., Europe/Lisbon, America/New_York)",
Required: true,
},
},
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "show",
Description: "Show your current timezone",
},
},
}
func TimezoneHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if !shared.RequireUserSettingsService(s, i) {
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
handleShow(s, i)
return
}
switch data.Options[0].Name {
case "set":
handleSet(s, i)
case "show":
handleShow(s, i)
default:
shared.RespondEphemeral(s, i, "Unknown subcommand.")
}
}
func handleSet(s *discordgo.Session, i *discordgo.InteractionCreate) {
userID, ok := shared.CurrentUserID(i)
if !ok {
shared.RespondEphemeral(s, i, "Could not determine your user ID.")
return
}
data := i.ApplicationCommandData()
if len(data.Options) == 0 {
shared.RespondEphemeral(s, i, "Missing options.")
return
}
opt := data.Options[0]
var zone string
for _, o := range opt.Options {
if o.Name == "zone" {
zone = o.StringValue()
}
}
if zone == "" {
shared.RespondEphemeral(s, i, "Timezone cannot be empty.")
return
}
// Validate via service (which uses time.LoadLocation).
if err := services.Global.UserSettings.SetTimezone(context.Background(), userID, zone); err != nil {
shared.RespondEphemeral(s, i, "Invalid timezone. Use an IANA name like `Europe/Lisbon`.")
return
}
loc, z, _, _ := services.Global.UserSettings.GetTimezone(context.Background(), userID)
now := time.Now().In(loc).Format("2006-01-02 15:04")
shared.RespondEphemeral(s, i, "Your timezone is now set to `"+z+"` (current local time: "+now+").")
}
func handleShow(s *discordgo.Session, i *discordgo.InteractionCreate) {
userID, ok := shared.CurrentUserID(i)
if !ok {
shared.RespondEphemeral(s, i, "Could not determine your user ID.")
return
}
loc, z, userDefined, err := services.Global.UserSettings.GetTimezone(context.Background(), userID)
if err != nil {
shared.RespondEphemeral(s, i, "Failed to load your timezone.")
return
}
now := time.Now().In(loc).Format("2006-01-02 15:04")
if userDefined {
shared.RespondEphemeral(s, i, "Your timezone is `"+z+"` (current local time: "+now+").")
} else {
shared.RespondEphemeral(s, i, "You don't have a timezone set. Using `UTC` (current time: "+now+"). Use `/timezone set` to configure one.")
}
}
+14
View File
@@ -0,0 +1,14 @@
package timezone
import (
"velox-bot/internal/commands/timezone/public"
"github.com/bwmarrin/discordgo"
)
var (
Timezone *discordgo.ApplicationCommand = public.Timezone
)
func TimezoneHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { public.TimezoneHandler(s, i) }
@@ -0,0 +1,45 @@
package shared
import (
"strconv"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
func RespondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
func RequireUserSettingsService(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
if services.Global == nil || services.Global.UserSettings == nil {
RespondEphemeral(s, i, "User settings service is not available.")
return false
}
return true
}
func CurrentUserID(i *discordgo.InteractionCreate) (int64, bool) {
var idStr string
if i.Member != nil && i.Member.User != nil {
idStr = i.Member.User.ID
} else if i.User != nil {
idStr = i.User.ID
}
if idStr == "" {
return 0, false
}
uid, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return 0, false
}
return uid, true
}
+16 -6
View File
@@ -12,12 +12,14 @@ type Config struct {
AppID string
GuildID string
DBHost string
LavalinkHost string
LavalinkPass string
TwitchClientID string
}
func LoadConfig() (*Config, error) {
if err := godotenv.Load(); err != nil {
return nil, err
}
// Load .env if present (e.g. local dev). Ignore if missing (e.g. Docker injects env vars).
_ = godotenv.Load()
token := os.Getenv("BOT_TOKEN")
if token == "" {
@@ -30,19 +32,27 @@ func LoadConfig() (*Config, error) {
}
guildID := os.Getenv("GUILD_ID")
if guildID == "" {
return nil, fmt.Errorf("GUILD_ID is not set")
}
dbHost := os.Getenv("DB_HOST")
if dbHost == "" {
return nil, fmt.Errorf("DB_HOST is not set")
}
lavalinkHost := os.Getenv("LAVALINK_HOST")
lavalinkPass := os.Getenv("LAVALINK_PASSWORD")
twitchClientID := os.Getenv("TWITCH_CLIENT_ID")
if twitchClientID == "" {
return nil, fmt.Errorf("TWITCH_CLIENT_ID is not set")
}
return &Config{
BotToken: token,
AppID: appID,
GuildID: guildID,
DBHost: dbHost,
LavalinkHost: lavalinkHost,
LavalinkPass: lavalinkPass,
TwitchClientID: twitchClientID,
}, nil
}
+47
View File
@@ -0,0 +1,47 @@
package defaultrolerepo
import (
"context"
"database/sql"
)
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
// GetRole returns the configured default role ID for a guild, or 0 if none.
func (r *Repo) GetRole(ctx context.Context, guildID int64) (int64, error) {
const q = `
SELECT role_id
FROM defaultrole
WHERE guild_id = $1
`
var roleID sql.NullInt64
if err := r.db.QueryRowContext(ctx, q, guildID).Scan(&roleID); err != nil {
if err == sql.ErrNoRows {
return 0, nil
}
return 0, err
}
if !roleID.Valid {
return 0, nil
}
return roleID.Int64, nil
}
// SetRole upserts the default role for a guild.
func (r *Repo) SetRole(ctx context.Context, guildID, roleID int64) error {
const q = `
INSERT INTO defaultrole (guild_id, role_id)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET role_id = EXCLUDED.role_id
`
_, err := r.db.ExecContext(ctx, q, guildID, roleID)
return err
}
+144
View File
@@ -0,0 +1,144 @@
package musicrepo
import (
"context"
"database/sql"
"time"
)
type QueueEntry struct {
Title string
URL string
RequestedBy int64
// ClientID is the track's stable identity (set once by the manager
// when a track is first queued), used to upsert this row across
// syncs instead of assigning it a fresh DB id every single time.
ClientID string
}
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) SetNowPlaying(ctx context.Context, guildID int64, title, url string, durationSeconds int, startedAt time.Time, paused bool, volume int, repeatSong, repeatQueue bool) error {
const q = `
INSERT INTO music_now_playing (guild_id, track_title, track_url, duration_seconds, started_at, paused, volume, repeat_song, repeat_queue)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (guild_id) DO UPDATE SET
track_title = $2, track_url = $3, duration_seconds = $4, started_at = $5,
paused = $6, volume = $7, repeat_song = $8, repeat_queue = $9
`
_, err := r.db.ExecContext(ctx, q, guildID, title, url, durationSeconds, startedAt, paused, volume, repeatSong, repeatQueue)
return err
}
func (r *Repo) ClearNowPlaying(ctx context.Context, guildID int64) error {
const q = `DELETE FROM music_now_playing WHERE guild_id = $1`
_, err := r.db.ExecContext(ctx, q, guildID)
return err
}
// ReplaceQueue syncs music_queue with the current in-memory queue by
// upserting each entry on its stable ClientID, rather than deleting and
// recreating every row on every call. That matters because music_queue.id
// is only an internal DB identity, remove/reorder commands target a
// track by ClientID, and that has to survive a track just sitting in the
// queue unchanged across syncs.
func (r *Repo) ReplaceQueue(ctx context.Context, guildID int64, entries []QueueEntry) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
existing := make(map[string]bool)
rows, err := tx.QueryContext(ctx, `SELECT client_id FROM music_queue WHERE guild_id = $1`, guildID)
if err != nil {
return err
}
for rows.Next() {
var clientID string
if err := rows.Scan(&clientID); err != nil {
rows.Close()
return err
}
existing[clientID] = true
}
if err := rows.Err(); err != nil {
rows.Close()
return err
}
rows.Close()
keep := make(map[string]bool, len(entries))
for i, entry := range entries {
keep[entry.ClientID] = true
const q = `
INSERT INTO music_queue (guild_id, position, track_title, track_url, requested_by, client_id)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (guild_id, client_id) DO UPDATE SET
position = EXCLUDED.position,
track_title = EXCLUDED.track_title,
track_url = EXCLUDED.track_url,
requested_by = EXCLUDED.requested_by
`
if _, err := tx.ExecContext(ctx, q, guildID, i, entry.Title, entry.URL, entry.RequestedBy, entry.ClientID); err != nil {
return err
}
}
for clientID := range existing {
if keep[clientID] {
continue
}
const q = `DELETE FROM music_queue WHERE guild_id = $1 AND client_id = $2`
if _, err := tx.ExecContext(ctx, q, guildID, clientID); err != nil {
return err
}
}
return tx.Commit()
}
type MusicCommand struct {
ID int64
GuildID int64
CommandType string
Payload []byte
RequestedBy int64
}
func (r *Repo) ListUnprocessedCommands(ctx context.Context) ([]MusicCommand, error) {
const q = `SELECT id, guild_id, command_type, payload, requested_by FROM music_commands WHERE processed_at IS NULL ORDER BY id ASC`
rows, err := r.db.QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var commands []MusicCommand
for rows.Next() {
var cmd MusicCommand
if err := rows.Scan(&cmd.ID, &cmd.GuildID, &cmd.CommandType, &cmd.Payload, &cmd.RequestedBy); err != nil {
return nil, err
}
commands = append(commands, cmd)
}
if err := rows.Err(); err != nil {
return nil, err
}
return commands, nil
}
func (r *Repo) MarkCommandProcessed(ctx context.Context, id int64) error {
const q = `UPDATE music_commands SET processed_at = NOW() WHERE id = $1`
_, err := r.db.ExecContext(ctx, q, id)
return err
}
+60
View File
@@ -61,6 +61,35 @@ func (r *Repo) AddHelper(ctx context.Context, projectID, userID int64) error {
return err
}
func (r *Repo) DeactivateProject(ctx context.Context, guildID, projectID int64) error {
const q = `
UPDATE projects
SET is_active = FALSE
WHERE id = $1 AND guild_id = $2
`
_, err := r.db.ExecContext(ctx, q, projectID, guildID)
return err
}
// GetProject fetches a single project, scoped to guildID so a project ID
// from one server can't be used to reach into another's data.
func (r *Repo) GetProject(ctx context.Context, guildID, projectID int64) (*Project, error) {
const q = `
SELECT id, name, description, created_by
FROM projects
WHERE id = $1 AND guild_id = $2
`
row := r.db.QueryRowContext(ctx, q, projectID, guildID)
p := &Project{GuildID: guildID, IsActive: true}
if err := row.Scan(&p.ID, &p.Name, &p.Description, &p.CreatedBy); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return p, nil
}
func (r *Repo) ProjectExistsInGuild(ctx context.Context, guildID, projectID int64) (bool, error) {
const q = `
SELECT 1
@@ -79,6 +108,37 @@ func (r *Repo) ProjectExistsInGuild(ctx context.Context, guildID, projectID int6
}
}
// ListActiveProjects is a lighter version of ListActiveProjectsWithMembers,
// without the member-join query - for callers (like building a select menu
// of projects to pick from) that only need name/id, not creator/helpers.
func (r *Repo) ListActiveProjects(ctx context.Context, guildID int64, limit int) ([]*Project, error) {
const q = `
SELECT id, name, description, created_by
FROM projects
WHERE guild_id = $1 AND is_active = TRUE
ORDER BY created_at DESC
LIMIT $2
`
rows, err := r.db.QueryContext(ctx, q, guildID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Project
for rows.Next() {
p := &Project{GuildID: guildID, IsActive: true}
if err := rows.Scan(&p.ID, &p.Name, &p.Description, &p.CreatedBy); err != nil {
return nil, err
}
out = append(out, p)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}
func (r *Repo) ListActiveProjectsWithMembers(ctx context.Context, guildID int64, limit int) ([]*ProjectWithMembers, error) {
const qProjects = `
SELECT id, name, description, created_by
+202
View File
@@ -0,0 +1,202 @@
package schedulerepo
import (
"context"
"database/sql"
"time"
)
type Repo struct {
db *sql.DB
}
type ScheduleStatus string
const (
StatusPending ScheduleStatus = "pending"
StatusAccepted ScheduleStatus = "accepted"
StatusDeclined ScheduleStatus = "declined"
StatusRescheduleRequested ScheduleStatus = "reschedule_requested"
)
type Schedule struct {
ID int64
GuildID int64
RequesterID int64
InviteeID int64
ScheduledAt time.Time
ProposedAt *time.Time
ProposedBy *int64
PreRescheduleStatus *ScheduleStatus
Status ScheduleStatus
Description string
ReminderSent bool
CreatedAt time.Time
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) CreateSchedule(ctx context.Context, guildID, requesterID, inviteeID int64, when time.Time, description string) (int64, error) {
const q = `
INSERT INTO schedules (guild_id, requester_id, invitee_id, scheduled_at, description)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`
var id int64
if err := r.db.QueryRowContext(ctx, q, guildID, requesterID, inviteeID, when, description).Scan(&id); err != nil {
return 0, err
}
return id, nil
}
func (r *Repo) UpdateStatus(ctx context.Context, scheduleID int64, status ScheduleStatus) error {
const q = `
UPDATE schedules
SET status = $1
WHERE id = $2
`
_, err := r.db.ExecContext(ctx, q, status, scheduleID)
return err
}
func (r *Repo) ListForUser(ctx context.Context, guildID, userID int64, limit int) ([]*Schedule, error) {
const q = `
SELECT id, guild_id, requester_id, invitee_id, scheduled_at, status, description, reminder_sent, created_at
FROM schedules
WHERE guild_id = $1
AND (requester_id = $2 OR invitee_id = $2)
AND status IN ('pending', 'accepted', 'reschedule_requested')
ORDER BY scheduled_at ASC
LIMIT $3
`
rows, err := r.db.QueryContext(ctx, q, guildID, userID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Schedule
for rows.Next() {
var sch Schedule
if err := rows.Scan(&sch.ID, &sch.GuildID, &sch.RequesterID, &sch.InviteeID, &sch.ScheduledAt, &sch.Status, &sch.Description, &sch.ReminderSent, &sch.CreatedAt); err != nil {
return nil, err
}
out = append(out, &sch)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}
func (r *Repo) GetByID(ctx context.Context, id int64) (*Schedule, error) {
const q = `
SELECT id, guild_id, requester_id, invitee_id, scheduled_at, proposed_at, proposed_by, pre_reschedule_status, status, description, reminder_sent, created_at
FROM schedules
WHERE id = $1
`
row := r.db.QueryRowContext(ctx, q, id)
var sch Schedule
if err := row.Scan(&sch.ID, &sch.GuildID, &sch.RequesterID, &sch.InviteeID, &sch.ScheduledAt, &sch.ProposedAt, &sch.ProposedBy, &sch.PreRescheduleStatus, &sch.Status, &sch.Description, &sch.ReminderSent, &sch.CreatedAt); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &sch, nil
}
func (r *Repo) Reschedule(ctx context.Context, id int64, when time.Time) error {
const q = `
UPDATE schedules
SET scheduled_at = $1,
status = 'pending',
reminder_sent = FALSE
WHERE id = $2
`
_, err := r.db.ExecContext(ctx, q, when, id)
return err
}
// ListDueForReminder returns sessions starting between now and now+ahead, not yet reminded.
func (r *Repo) ListDueForReminder(ctx context.Context, now time.Time, ahead time.Duration) ([]*Schedule, error) {
const q = `
SELECT id, guild_id, requester_id, invitee_id, scheduled_at, status, description, reminder_sent, created_at
FROM schedules
WHERE reminder_sent = FALSE
AND status IN ('pending', 'accepted', 'reschedule_requested')
AND scheduled_at > $1
AND scheduled_at <= $2
`
rows, err := r.db.QueryContext(ctx, q, now, now.Add(ahead))
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Schedule
for rows.Next() {
var sch Schedule
if err := rows.Scan(&sch.ID, &sch.GuildID, &sch.RequesterID, &sch.InviteeID, &sch.ScheduledAt, &sch.Status, &sch.Description, &sch.ReminderSent, &sch.CreatedAt); err != nil {
return nil, err
}
out = append(out, &sch)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}
func (r *Repo) MarkReminded(ctx context.Context, scheduleID int64) error {
const q = `
UPDATE schedules
SET reminder_sent = TRUE
WHERE id = $1
`
_, err := r.db.ExecContext(ctx, q, scheduleID)
return err
}
func (r *Repo) ProposeReschedule(ctx context.Context, scheduleID int64, newTime time.Time, proposedBy int64) error {
const q = `
UPDATE schedules
SET proposed_at = $1,
proposed_by = $2,
pre_reschedule_status = status,
status = 'reschedule_requested'
WHERE id = $3
`
_, err := r.db.ExecContext(ctx, q, newTime, proposedBy, scheduleID)
return err
}
func (r *Repo) AcceptReschedule(ctx context.Context, scheduleID int64) error {
const q = `
UPDATE schedules
SET scheduled_at = proposed_at,
proposed_at = NULL,
proposed_by = NULL,
pre_reschedule_status = NULL,
status = 'accepted',
reminder_sent = FALSE
WHERE id = $1
`
_, err := r.db.ExecContext(ctx, q, scheduleID)
return err
}
func (r *Repo) DeclineReschedule(ctx context.Context, scheduleID int64) error {
const q = `
UPDATE schedules
SET proposed_at = NULL,
proposed_by = NULL,
status = pre_reschedule_status,
pre_reschedule_status = NULL
WHERE id = $1
`
_, err := r.db.ExecContext(ctx, q, scheduleID)
return err
}
+742
View File
@@ -0,0 +1,742 @@
// Package securityrepo stores the anti-raid and anti-nuke settings, the
// trusted list, quarantines, locked channels, the event history and the
// dashboard's requests. Discord IDs are int64; 0 means "not set".
package securityrepo
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
)
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
// Filter actions.
const (
ActionOff = "off"
ActionAlert = "alert" // raid mode only: alert staff, touch nobody
ActionTimeout = "timeout"
ActionKick = "kick"
ActionBan = "ban"
)
// Anti-nuke limit keys.
const (
LimitChannelDelete = "channel_delete"
LimitChannelCreate = "channel_create"
LimitRoleDelete = "role_delete"
LimitRoleCreate = "role_create"
LimitBan = "ban"
LimitKick = "kick"
LimitWebhookCreate = "webhook_create"
)
// DefaultLimits mirrors the column default in the migration.
func DefaultLimits() map[string]int {
return map[string]int{
LimitChannelDelete: 2, LimitChannelCreate: 5, LimitRoleDelete: 2, LimitRoleCreate: 5,
LimitBan: 3, LimitKick: 5, LimitWebhookCreate: 3,
}
}
type Settings struct {
GuildID int64
AlertChannelID int64
AlertRoleID int64
AlertDM bool
JoinGateEnabled bool
NoAvatar string
NewAccount string
MinAccountAgeDays int
AdvertisingName string
UsernameFilter string
UsernamePatterns []string
UnverifiedBot string
UnauthorizedBot string
AntiRaidEnabled bool
RaidJoinCount int
RaidJoinSeconds int
RaidAction string
RaidPauseInvites bool
RaidQuietMinutes int
AntiNukeEnabled bool
AntiNukeWindowSeconds int
AntiNukeLimits map[string]int
AntiNukeLockServer bool
QuarantineRoleID int64
AntiNukeAutoRestore bool
HeatEnabled bool
HeatStrictness string
HeatAction string
HeatTimeoutMinutes int
HeatEscalate bool
HeatBlockedWords []string
HeatPanicMembers int
HeatLockdownMentions int
JoinLock string
// Configured is false when the guild has no row yet; the fields then
// hold the defaults, with every system off.
Configured bool
}
func Defaults(guildID int64) *Settings {
return &Settings{
GuildID: guildID,
AlertDM: true,
NoAvatar: ActionOff, NewAccount: ActionOff, MinAccountAgeDays: 7, AdvertisingName: ActionOff,
UsernameFilter: ActionOff, UnverifiedBot: ActionOff, UnauthorizedBot: ActionKick,
RaidJoinCount: 10, RaidJoinSeconds: 10, RaidAction: ActionKick, RaidPauseInvites: true, RaidQuietMinutes: 10,
AntiNukeWindowSeconds: 10, AntiNukeLimits: DefaultLimits(),
HeatStrictness: "medium", HeatAction: ActionTimeout, HeatTimeoutMinutes: 10, HeatEscalate: true, HeatPanicMembers: 3,
JoinLock: ActionOff,
}
}
func nullID(v int64) sql.NullInt64 { return sql.NullInt64{Int64: v, Valid: v != 0} }
func (r *Repo) GetSettings(ctx context.Context, guildID int64) (*Settings, error) {
const q = `
SELECT alert_channel_id, alert_role_id, alert_dm,
joingate_enabled, joingate_no_avatar, joingate_new_account, joingate_min_account_age_days,
joingate_advertising_name, joingate_username_filter, to_json(joingate_username_patterns),
joingate_unverified_bot, joingate_unauthorized_bot,
antiraid_enabled, raid_join_count, raid_join_seconds, raid_action, raid_pause_invites, raid_quiet_minutes,
antinuke_enabled, antinuke_window_seconds, antinuke_limits, antinuke_lock_server, quarantine_role_id,
antinuke_auto_restore, heat_enabled, heat_strictness, heat_action, heat_timeout_minutes, heat_escalate,
to_json(heat_blocked_words), heat_panic_members, heat_lockdown_mentions,
join_lock
FROM security_settings WHERE guild_id = $1`
s := &Settings{GuildID: guildID, Configured: true}
var alertCh, alertRole, qRole sql.NullInt64
var patterns, words []byte
var limits []byte
err := r.db.QueryRowContext(ctx, q, guildID).Scan(
&alertCh, &alertRole, &s.AlertDM,
&s.JoinGateEnabled, &s.NoAvatar, &s.NewAccount, &s.MinAccountAgeDays,
&s.AdvertisingName, &s.UsernameFilter, &patterns,
&s.UnverifiedBot, &s.UnauthorizedBot,
&s.AntiRaidEnabled, &s.RaidJoinCount, &s.RaidJoinSeconds, &s.RaidAction, &s.RaidPauseInvites, &s.RaidQuietMinutes,
&s.AntiNukeEnabled, &s.AntiNukeWindowSeconds, &limits, &s.AntiNukeLockServer, &qRole,
&s.AntiNukeAutoRestore, &s.HeatEnabled, &s.HeatStrictness, &s.HeatAction, &s.HeatTimeoutMinutes, &s.HeatEscalate,
&words, &s.HeatPanicMembers, &s.HeatLockdownMentions,
&s.JoinLock,
)
if errors.Is(err, sql.ErrNoRows) {
return Defaults(guildID), nil
}
if err != nil {
return nil, err
}
s.AlertChannelID, s.AlertRoleID, s.QuarantineRoleID = alertCh.Int64, alertRole.Int64, qRole.Int64
_ = json.Unmarshal(patterns, &s.UsernamePatterns)
_ = json.Unmarshal(words, &s.HeatBlockedWords)
s.AntiNukeLimits = DefaultLimits()
if len(limits) > 0 {
// Saved values override the defaults key by key, so a limit added
// in a later version still has a value for older rows.
var saved map[string]int
if err := json.Unmarshal(limits, &saved); err == nil {
for k, v := range saved {
s.AntiNukeLimits[k] = v
}
}
}
return s, nil
}
// ensureRow makes sure the guild has a settings row so single-column updates
// below can be plain UPDATEs.
func (r *Repo) ensureRow(ctx context.Context, guildID int64) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO security_settings (guild_id) VALUES ($1) ON CONFLICT DO NOTHING`, guildID)
return err
}
func (r *Repo) update(ctx context.Context, guildID int64, set string, args ...any) error {
if err := r.ensureRow(ctx, guildID); err != nil {
return err
}
_, err := r.db.ExecContext(ctx, `UPDATE security_settings SET `+set+` WHERE guild_id = $1`, append([]any{guildID}, args...)...)
return err
}
// Feature names accepted by SetEnabled.
const (
FeatureJoinGate = "joingate"
FeatureAntiRaid = "antiraid"
FeatureAntiNuke = "antinuke"
FeatureHeat = "heat"
)
func (r *Repo) SetEnabled(ctx context.Context, guildID int64, feature string, on bool) error {
col := map[string]string{FeatureJoinGate: "joingate_enabled", FeatureAntiRaid: "antiraid_enabled", FeatureAntiNuke: "antinuke_enabled", FeatureHeat: "heat_enabled"}[feature]
if col == "" {
return errors.New("unknown feature " + feature)
}
return r.update(ctx, guildID, col+` = $2`, on)
}
func (r *Repo) SetAlerts(ctx context.Context, guildID, channelID, roleID int64) error {
return r.update(ctx, guildID, `alert_channel_id = $2, alert_role_id = $3`, nullID(channelID), nullID(roleID))
}
func (r *Repo) SetQuarantineRole(ctx context.Context, guildID, roleID int64) error {
return r.update(ctx, guildID, `quarantine_role_id = $2`, nullID(roleID))
}
func (r *Repo) SetJoinLock(ctx context.Context, guildID int64, mode string) error {
return r.update(ctx, guildID, `join_lock = $2`, mode)
}
// Tuning is a partial update of a server's thresholds, filters and actions.
// A nil field is left as it is. The security package validates it before it
// gets here; the column constraints are the last line of defence.
type Tuning struct {
AlertDM *bool
NoAvatar *string
NewAccount *string
MinAccountAgeDays *int
AdvertisingName *string
UsernameFilter *string
UsernamePatterns *[]string
UnverifiedBot *string
UnauthorizedBot *string
RaidJoinCount *int
RaidJoinSeconds *int
RaidAction *string
RaidPauseInvites *bool
RaidQuietMinutes *int
AntiNukeWindowSeconds *int
AntiNukeLimits map[string]int // only the keys present change
AntiNukeLockServer *bool
AntiNukeAutoRestore *bool
HeatStrictness *string
HeatAction *string
HeatTimeoutMinutes *int
HeatEscalate *bool
HeatBlockedWords *[]string
HeatPanicMembers *int
HeatLockdownMentions *int
}
// UpdateTuning applies the fields that are set, in one statement.
func (r *Repo) UpdateTuning(ctx context.Context, guildID int64, t Tuning) error {
var sets []string
args := []any{}
add := func(col string, v any) {
args = append(args, v)
sets = append(sets, col+` = $`+strconv.Itoa(len(args)+1)) // $1 is the guild
}
addList := func(col string, v []string) {
b, _ := json.Marshal(v)
args = append(args, string(b))
sets = append(sets, col+` = ARRAY(SELECT jsonb_array_elements_text($`+strconv.Itoa(len(args)+1)+`::jsonb))`)
}
if t.AlertDM != nil {
add("alert_dm", *t.AlertDM)
}
if t.NoAvatar != nil {
add("joingate_no_avatar", *t.NoAvatar)
}
if t.NewAccount != nil {
add("joingate_new_account", *t.NewAccount)
}
if t.MinAccountAgeDays != nil {
add("joingate_min_account_age_days", *t.MinAccountAgeDays)
}
if t.AdvertisingName != nil {
add("joingate_advertising_name", *t.AdvertisingName)
}
if t.UsernameFilter != nil {
add("joingate_username_filter", *t.UsernameFilter)
}
if t.UsernamePatterns != nil {
addList("joingate_username_patterns", *t.UsernamePatterns)
}
if t.UnverifiedBot != nil {
add("joingate_unverified_bot", *t.UnverifiedBot)
}
if t.UnauthorizedBot != nil {
add("joingate_unauthorized_bot", *t.UnauthorizedBot)
}
if t.RaidJoinCount != nil {
add("raid_join_count", *t.RaidJoinCount)
}
if t.RaidJoinSeconds != nil {
add("raid_join_seconds", *t.RaidJoinSeconds)
}
if t.RaidAction != nil {
add("raid_action", *t.RaidAction)
}
if t.RaidPauseInvites != nil {
add("raid_pause_invites", *t.RaidPauseInvites)
}
if t.RaidQuietMinutes != nil {
add("raid_quiet_minutes", *t.RaidQuietMinutes)
}
if t.AntiNukeWindowSeconds != nil {
add("antinuke_window_seconds", *t.AntiNukeWindowSeconds)
}
if len(t.AntiNukeLimits) > 0 {
b, _ := json.Marshal(t.AntiNukeLimits)
args = append(args, string(b))
// Merge into what is saved, so setting one limit keeps the others.
sets = append(sets, `antinuke_limits = antinuke_limits || $`+strconv.Itoa(len(args)+1)+`::jsonb`)
}
if t.AntiNukeLockServer != nil {
add("antinuke_lock_server", *t.AntiNukeLockServer)
}
if t.AntiNukeAutoRestore != nil {
add("antinuke_auto_restore", *t.AntiNukeAutoRestore)
}
if t.HeatStrictness != nil {
add("heat_strictness", *t.HeatStrictness)
}
if t.HeatAction != nil {
add("heat_action", *t.HeatAction)
}
if t.HeatTimeoutMinutes != nil {
add("heat_timeout_minutes", *t.HeatTimeoutMinutes)
}
if t.HeatEscalate != nil {
add("heat_escalate", *t.HeatEscalate)
}
if t.HeatBlockedWords != nil {
addList("heat_blocked_words", *t.HeatBlockedWords)
}
if t.HeatPanicMembers != nil {
add("heat_panic_members", *t.HeatPanicMembers)
}
if t.HeatLockdownMentions != nil {
add("heat_lockdown_mentions", *t.HeatLockdownMentions)
}
if len(sets) == 0 {
return nil
}
return r.update(ctx, guildID, strings.Join(sets, ", "), args...)
}
// ---- Trusted ----
type Trusted struct {
TargetID int64
Kind string // "user" or "role"
AddedBy int64
}
func (r *Repo) ListTrusted(ctx context.Context, guildID int64) ([]Trusted, error) {
rows, err := r.db.QueryContext(ctx, `SELECT target_id, kind, added_by FROM security_trusted WHERE guild_id = $1 ORDER BY created_at`, guildID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Trusted
for rows.Next() {
var t Trusted
if err := rows.Scan(&t.TargetID, &t.Kind, &t.AddedBy); err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
func (r *Repo) AddTrusted(ctx context.Context, guildID int64, t Trusted) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_trusted (guild_id, target_id, kind, added_by) VALUES ($1, $2, $3, $4)
ON CONFLICT (guild_id, target_id) DO UPDATE SET kind = EXCLUDED.kind`, guildID, t.TargetID, t.Kind, t.AddedBy)
return err
}
func (r *Repo) RemoveTrusted(ctx context.Context, guildID, targetID int64) (bool, error) {
res, err := r.db.ExecContext(ctx, `DELETE FROM security_trusted WHERE guild_id = $1 AND target_id = $2`, guildID, targetID)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
// ---- Quarantine ----
type Quarantine struct {
GuildID int64
UserID int64
PreviousRoleIDs []int64
Reason string
CreatedAt time.Time
}
// SaveQuarantine records a quarantine. If the member is already quarantined
// the first record is kept, since its roles are the ones to give back.
func (r *Repo) SaveQuarantine(ctx context.Context, q Quarantine) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_quarantines (guild_id, user_id, previous_role_ids, reason)
VALUES ($1, $2, COALESCE($3::bigint[], '{}'), $4)
ON CONFLICT (guild_id, user_id) DO NOTHING`, q.GuildID, q.UserID, q.PreviousRoleIDs, q.Reason)
return err
}
func scanQuarantine(row interface{ Scan(...any) error }) (Quarantine, error) {
var q Quarantine
var roles []byte
err := row.Scan(&q.GuildID, &q.UserID, &roles, &q.Reason, &q.CreatedAt)
if err == nil {
err = json.Unmarshal(roles, &q.PreviousRoleIDs)
}
return q, err
}
// GetQuarantine returns nil when the member isn't quarantined.
func (r *Repo) GetQuarantine(ctx context.Context, guildID, userID int64) (*Quarantine, error) {
q, err := scanQuarantine(r.db.QueryRowContext(ctx, `
SELECT guild_id, user_id, to_json(previous_role_ids), reason, created_at FROM security_quarantines
WHERE guild_id = $1 AND user_id = $2`, guildID, userID))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &q, nil
}
func (r *Repo) ListQuarantines(ctx context.Context, guildID int64) ([]Quarantine, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT guild_id, user_id, to_json(previous_role_ids), reason, created_at FROM security_quarantines
WHERE guild_id = $1 ORDER BY created_at DESC`, guildID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Quarantine
for rows.Next() {
q, err := scanQuarantine(rows)
if err != nil {
return nil, err
}
out = append(out, q)
}
return out, rows.Err()
}
func (r *Repo) DeleteQuarantine(ctx context.Context, guildID, userID int64) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM security_quarantines WHERE guild_id = $1 AND user_id = $2`, guildID, userID)
return err
}
// ---- Lockdowns ----
type Lockdown struct {
GuildID int64
ChannelID int64
HadOverwrite bool
PreviousAllow int64
PreviousDeny int64
ServerWide bool
LockedBy int64
}
// SaveLockdown remembers a channel's @everyone overwrite from before it was
// locked. A channel that is already locked keeps its first record, which is
// the state to go back to.
func (r *Repo) SaveLockdown(ctx context.Context, l Lockdown) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_lockdowns (guild_id, channel_id, had_overwrite, previous_allow, previous_deny, server_wide, locked_by)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (guild_id, channel_id) DO NOTHING`,
l.GuildID, l.ChannelID, l.HadOverwrite, l.PreviousAllow, l.PreviousDeny, l.ServerWide, l.LockedBy)
return err
}
// GetLockdown returns nil when the channel isn't locked by the bot.
func (r *Repo) GetLockdown(ctx context.Context, guildID, channelID int64) (*Lockdown, error) {
var l Lockdown
err := r.db.QueryRowContext(ctx, `
SELECT guild_id, channel_id, had_overwrite, previous_allow, previous_deny, server_wide, locked_by
FROM security_lockdowns WHERE guild_id = $1 AND channel_id = $2`, guildID, channelID).
Scan(&l.GuildID, &l.ChannelID, &l.HadOverwrite, &l.PreviousAllow, &l.PreviousDeny, &l.ServerWide, &l.LockedBy)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &l, nil
}
// ListLockdowns lists locked channels; serverWideOnly limits it to the ones a
// server lockdown locked.
func (r *Repo) ListLockdowns(ctx context.Context, guildID int64, serverWideOnly bool) ([]Lockdown, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT guild_id, channel_id, had_overwrite, previous_allow, previous_deny, server_wide, locked_by
FROM security_lockdowns WHERE guild_id = $1 AND (NOT $2 OR server_wide) ORDER BY locked_at`, guildID, serverWideOnly)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Lockdown
for rows.Next() {
var l Lockdown
if err := rows.Scan(&l.GuildID, &l.ChannelID, &l.HadOverwrite, &l.PreviousAllow, &l.PreviousDeny, &l.ServerWide, &l.LockedBy); err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
}
func (r *Repo) DeleteLockdown(ctx context.Context, guildID, channelID int64) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM security_lockdowns WHERE guild_id = $1 AND channel_id = $2`, guildID, channelID)
return err
}
// ---- Events ----
type Event struct {
GuildID int64
Kind string
ActorID int64
TargetID int64
Detail string
CreatedAt time.Time // set when read
}
// Event kinds.
const (
EventJoinGate = "joingate"
EventRaidStarted = "raid_started"
EventRaidEnded = "raid_ended"
EventNuke = "nuke"
EventQuarantined = "quarantined"
EventReleased = "released"
EventUnauthorizedBot = "unauthorized_bot"
EventLocked = "locked"
EventUnlocked = "unlocked"
EventHeat = "heat"
EventHeatPanic = "heat_panic"
EventSnapshot = "snapshot"
EventRestored = "restored"
)
func (r *Repo) AddEvent(ctx context.Context, e Event) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_events (guild_id, kind, actor_id, target_id, detail) VALUES ($1, $2, $3, $4, $5)`,
e.GuildID, e.Kind, nullID(e.ActorID), nullID(e.TargetID), e.Detail)
return err
}
// ---- Dashboard commands ----
type Command struct {
ID int64
GuildID int64
CommandType string
Payload []byte
RequestedBy int64
}
func (r *Repo) ListUnprocessedCommands(ctx context.Context) ([]Command, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT id, guild_id, command_type, COALESCE(payload, '{}'::jsonb), requested_by
FROM security_commands WHERE processed_at IS NULL ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Command
for rows.Next() {
var c Command
if err := rows.Scan(&c.ID, &c.GuildID, &c.CommandType, &c.Payload, &c.RequestedBy); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
func (r *Repo) MarkCommandProcessed(ctx context.Context, id int64) error {
_, err := r.db.ExecContext(ctx, `UPDATE security_commands SET processed_at = NOW() WHERE id = $1`, id)
return err
}
// ---- Raids in progress ----
type Raid struct {
GuildID int64
StartedAt time.Time
LastJoinAt time.Time
InvitesPaused bool
CaughtTotal int
}
func (r *Repo) SaveRaid(ctx context.Context, x Raid) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_raids (guild_id, started_at, last_join_at, invites_paused, caught_total)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (guild_id) DO UPDATE SET
last_join_at = EXCLUDED.last_join_at, invites_paused = EXCLUDED.invites_paused, caught_total = EXCLUDED.caught_total`,
x.GuildID, x.StartedAt, x.LastJoinAt, x.InvitesPaused, x.CaughtTotal)
return err
}
func (r *Repo) ListRaids(ctx context.Context) ([]Raid, error) {
rows, err := r.db.QueryContext(ctx, `SELECT guild_id, started_at, last_join_at, invites_paused, caught_total FROM security_raids`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Raid
for rows.Next() {
var x Raid
if err := rows.Scan(&x.GuildID, &x.StartedAt, &x.LastJoinAt, &x.InvitesPaused, &x.CaughtTotal); err != nil {
return nil, err
}
out = append(out, x)
}
return out, rows.Err()
}
// DeleteRaid ends a raid's record and its caught list.
func (r *Repo) DeleteRaid(ctx context.Context, guildID int64) error {
if _, err := r.db.ExecContext(ctx, `DELETE FROM security_raid_caught WHERE guild_id = $1`, guildID); err != nil {
return err
}
_, err := r.db.ExecContext(ctx, `DELETE FROM security_raids WHERE guild_id = $1`, guildID)
return err
}
type Caught struct {
UserID int64
Action string
Name string
}
func (r *Repo) AddRaidCaught(ctx context.Context, guildID int64, c Caught) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO security_raid_caught (guild_id, user_id, action, name) VALUES ($1, $2, $3, $4)
ON CONFLICT (guild_id, user_id) DO NOTHING`, guildID, c.UserID, c.Action, c.Name)
return err
}
func (r *Repo) ListRaidCaught(ctx context.Context, guildID int64, limit int) ([]Caught, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT user_id, action, name FROM security_raid_caught WHERE guild_id = $1 ORDER BY caught_at LIMIT $2`, guildID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Caught
for rows.Next() {
var c Caught
if err := rows.Scan(&c.UserID, &c.Action, &c.Name); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
// ---- Snapshots ----
const keepSnapshots = 3
type Snapshot struct {
ID int64
GuildID int64
Data []byte
Roles int
Channels int
CreatedAt time.Time
}
// SaveSnapshot stores a snapshot and drops all but the newest three.
func (r *Repo) SaveSnapshot(ctx context.Context, s Snapshot) error {
if _, err := r.db.ExecContext(ctx, `
INSERT INTO security_snapshots (guild_id, data, roles, channels) VALUES ($1, $2, $3, $4)`,
s.GuildID, s.Data, s.Roles, s.Channels); err != nil {
return err
}
_, err := r.db.ExecContext(ctx, `
DELETE FROM security_snapshots WHERE guild_id = $1 AND id NOT IN (
SELECT id FROM security_snapshots WHERE guild_id = $1 ORDER BY created_at DESC, id DESC LIMIT $2)`,
s.GuildID, keepSnapshots)
return err
}
// LatestSnapshot returns nil when the guild has none.
func (r *Repo) LatestSnapshot(ctx context.Context, guildID int64) (*Snapshot, error) {
var s Snapshot
err := r.db.QueryRowContext(ctx, `
SELECT id, guild_id, data, roles, channels, created_at FROM security_snapshots
WHERE guild_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1`, guildID).
Scan(&s.ID, &s.GuildID, &s.Data, &s.Roles, &s.Channels, &s.CreatedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &s, nil
}
// GuildsDueForSnapshot lists guilds with anti-nuke on whose newest snapshot
// is older than maxAge (or that have none).
func (r *Repo) GuildsDueForSnapshot(ctx context.Context, maxAge time.Duration) ([]int64, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT s.guild_id FROM security_settings s
WHERE s.antinuke_enabled AND NOT EXISTS (
SELECT 1 FROM security_snapshots p WHERE p.guild_id = s.guild_id AND p.created_at > NOW() - make_interval(secs => $1))`,
maxAge.Seconds())
if err != nil {
return nil, err
}
defer rows.Close()
var out []int64
for rows.Next() {
var g int64
if err := rows.Scan(&g); err != nil {
return nil, err
}
out = append(out, g)
}
return out, rows.Err()
}
// ListEvents returns a server's most recent security events, newest first.
func (r *Repo) ListEvents(ctx context.Context, guildID int64, limit int) ([]Event, error) {
if limit < 1 || limit > 100 {
limit = 20
}
rows, err := r.db.QueryContext(ctx, `
SELECT kind, COALESCE(actor_id, 0), COALESCE(target_id, 0), detail, created_at
FROM security_events WHERE guild_id = $1 ORDER BY id DESC LIMIT $2`, guildID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Event
for rows.Next() {
e := Event{GuildID: guildID}
if err := rows.Scan(&e.Kind, &e.ActorID, &e.TargetID, &e.Detail, &e.CreatedAt); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}
@@ -0,0 +1,255 @@
//go:build integration
// Runs against a real Postgres with the dashboard API's migrations applied:
//
// SECURITY_TEST_DB=postgres://... go test -tags integration ./internal/db/repos/securityrepo
package securityrepo
import (
"context"
"database/sql"
"os"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func testRepo(t *testing.T) (*Repo, int64) {
t.Helper()
dsn := os.Getenv("SECURITY_TEST_DB")
if dsn == "" {
t.Skip("SECURITY_TEST_DB not set")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
const g = 777
for _, tbl := range []string{"security_settings", "security_trusted", "security_quarantines", "security_lockdowns", "security_events", "security_commands"} {
if _, err := db.Exec(`DELETE FROM `+tbl+` WHERE guild_id = $1`, g); err != nil {
t.Fatal(err)
}
}
return NewRepo(db), g
}
func TestSettings(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
s, err := r.GetSettings(ctx, g)
if err != nil || s.Configured || s.JoinGateEnabled || s.AntiNukeEnabled || s.UnauthorizedBot != ActionKick || s.AntiNukeLimits[LimitChannelDelete] != 2 || !s.AlertDM {
t.Fatalf("defaults wrong: %+v %v", s, err)
}
for _, f := range []string{FeatureJoinGate, FeatureAntiRaid, FeatureAntiNuke} {
if err := r.SetEnabled(ctx, g, f, true); err != nil {
t.Fatal(err)
}
}
if err := r.SetEnabled(ctx, g, "drop table", true); err == nil {
t.Error("unknown features must be refused, never put into SQL")
}
_ = r.SetAlerts(ctx, g, 10, 20)
if _, err := r.db.Exec(`UPDATE security_settings SET alert_dm = false WHERE guild_id = $1`, g); err != nil {
t.Fatal(err)
}
_ = r.SetQuarantineRole(ctx, g, 30)
_ = r.SetJoinLock(ctx, g, ActionBan)
if _, err := r.db.Exec(`UPDATE security_settings SET joingate_username_patterns = '{nitro,free}', antinuke_limits = '{"ban": 0}' WHERE guild_id = $1`, g); err != nil {
t.Fatal(err)
}
s, err = r.GetSettings(ctx, g)
if err != nil {
t.Fatal(err)
}
if !s.Configured || s.AlertDM || !s.JoinGateEnabled || !s.AntiRaidEnabled || !s.AntiNukeEnabled || s.AlertChannelID != 10 || s.AlertRoleID != 20 || s.QuarantineRoleID != 30 || s.JoinLock != ActionBan {
t.Errorf("saved settings wrong: %+v", s)
}
if len(s.UsernamePatterns) != 2 || s.AntiNukeLimits[LimitBan] != 0 || s.AntiNukeLimits[LimitKick] != 5 {
t.Errorf("patterns or limits wrong (saved limits override defaults key by key): %+v %+v", s.UsernamePatterns, s.AntiNukeLimits)
}
if err := r.SetJoinLock(ctx, g, "everyone"); err == nil {
t.Error("the database must refuse unknown join lock modes")
}
}
func TestTrustedQuarantineLockdown(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
_ = r.AddTrusted(ctx, g, Trusted{TargetID: 5, Kind: "user", AddedBy: 1})
_ = r.AddTrusted(ctx, g, Trusted{TargetID: 6, Kind: "role", AddedBy: 1})
if err := r.AddTrusted(ctx, g, Trusted{TargetID: 7, Kind: "everyone", AddedBy: 1}); err == nil {
t.Error("unknown kinds must be refused")
}
list, _ := r.ListTrusted(ctx, g)
if len(list) != 2 {
t.Fatalf("trusted = %+v", list)
}
if ok, _ := r.RemoveTrusted(ctx, g, 5); !ok {
t.Error("remove should report true")
}
_ = r.SaveQuarantine(ctx, Quarantine{GuildID: g, UserID: 9, PreviousRoleIDs: []int64{1, 2}, Reason: "first"})
_ = r.SaveQuarantine(ctx, Quarantine{GuildID: g, UserID: 9, PreviousRoleIDs: nil, Reason: "second"})
q, _ := r.GetQuarantine(ctx, g, 9)
if q == nil || len(q.PreviousRoleIDs) != 2 || q.Reason != "first" {
t.Errorf("the first quarantine record must be kept: %+v", q)
}
qs, _ := r.ListQuarantines(ctx, g)
if len(qs) != 1 {
t.Errorf("list = %+v", qs)
}
_ = r.DeleteQuarantine(ctx, g, 9)
if q, _ := r.GetQuarantine(ctx, g, 9); q != nil {
t.Error("deleted")
}
_ = r.SaveLockdown(ctx, Lockdown{GuildID: g, ChannelID: 50, HadOverwrite: true, PreviousAllow: 1, PreviousDeny: 2, ServerWide: true, LockedBy: 1})
_ = r.SaveLockdown(ctx, Lockdown{GuildID: g, ChannelID: 50, HadOverwrite: false, PreviousAllow: 9, PreviousDeny: 9, LockedBy: 2})
_ = r.SaveLockdown(ctx, Lockdown{GuildID: g, ChannelID: 51, LockedBy: 1})
l, _ := r.GetLockdown(ctx, g, 50)
if l == nil || !l.HadOverwrite || l.PreviousAllow != 1 || !l.ServerWide {
t.Errorf("the first lockdown record must be kept: %+v", l)
}
if all, _ := r.ListLockdowns(ctx, g, false); len(all) != 2 {
t.Errorf("all = %+v", all)
}
if server, _ := r.ListLockdowns(ctx, g, true); len(server) != 1 {
t.Errorf("server-wide = %+v", server)
}
_ = r.DeleteLockdown(ctx, g, 50)
if l, _ := r.GetLockdown(ctx, g, 50); l != nil {
t.Error("deleted")
}
if err := r.AddEvent(ctx, Event{GuildID: g, Kind: EventNuke, ActorID: 3, Detail: "x"}); err != nil {
t.Fatal(err)
}
if _, err := r.db.Exec(`INSERT INTO security_commands (guild_id, command_type, payload, requested_by) VALUES ($1, 'release_quarantine', '{"user_id":"9"}', 1)`, g); err != nil {
t.Fatal(err)
}
if _, err := r.db.Exec(`INSERT INTO security_commands (guild_id, command_type, requested_by) VALUES ($1, 'grant_admin', 1)`, g); err == nil {
t.Error("unknown commands must be refused")
}
cmds, _ := r.ListUnprocessedCommands(ctx)
var mine *Command
for i := range cmds {
if cmds[i].GuildID == g {
mine = &cmds[i]
}
}
if mine == nil || string(mine.Payload) != `{"user_id": "9"}` {
t.Fatalf("command = %+v", mine)
}
_ = r.MarkCommandProcessed(ctx, mine.ID)
}
func TestRaidsSnapshotsAndHeatSettings(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
if _, err := r.db.Exec(`DELETE FROM security_raids WHERE guild_id = $1`, g); err != nil {
t.Fatal(err)
}
_, _ = r.db.Exec(`DELETE FROM security_raid_caught WHERE guild_id = $1`, g)
_, _ = r.db.Exec(`DELETE FROM security_snapshots WHERE guild_id = $1`, g)
s, _ := r.GetSettings(ctx, g)
if s.HeatEnabled || s.HeatStrictness != "medium" || s.HeatTimeoutMinutes != 10 || !s.HeatEscalate || s.HeatPanicMembers != 3 {
t.Errorf("heat defaults wrong: %+v", s)
}
_ = r.SetEnabled(ctx, g, FeatureHeat, true)
if _, err := r.db.Exec(`UPDATE security_settings SET heat_blocked_words = '{scam}', antinuke_auto_restore = true WHERE guild_id = $1`, g); err != nil {
t.Fatal(err)
}
s, _ = r.GetSettings(ctx, g)
if !s.HeatEnabled || !s.AntiNukeAutoRestore || len(s.HeatBlockedWords) != 1 {
t.Errorf("heat settings not read back: %+v", s)
}
if _, err := r.db.Exec(`UPDATE security_settings SET heat_strictness = 'insane' WHERE guild_id = $1`, g); err == nil {
t.Error("unknown strictness must be refused by the database")
}
start := time.Now().Add(-time.Minute).UTC().Truncate(time.Millisecond)
_ = r.SaveRaid(ctx, Raid{GuildID: g, StartedAt: start, LastJoinAt: start, InvitesPaused: true, CaughtTotal: 1})
_ = r.SaveRaid(ctx, Raid{GuildID: g, StartedAt: time.Now(), LastJoinAt: start.Add(time.Second), InvitesPaused: true, CaughtTotal: 2})
_ = r.AddRaidCaught(ctx, g, Caught{UserID: 1, Action: "kick", Name: "a"})
_ = r.AddRaidCaught(ctx, g, Caught{UserID: 1, Action: "ban", Name: "a"})
_ = r.AddRaidCaught(ctx, g, Caught{UserID: 2, Action: "kick", Name: "b"})
raids, _ := r.ListRaids(ctx)
var mine *Raid
for i := range raids {
if raids[i].GuildID == g {
mine = &raids[i]
}
}
if mine == nil || !mine.StartedAt.Equal(start) || mine.CaughtTotal != 2 {
t.Fatalf("raid = %+v (the start time is kept on update)", mine)
}
caught, _ := r.ListRaidCaught(ctx, g, 10)
if len(caught) != 2 || caught[0].Action != "kick" {
t.Errorf("caught = %+v (one row per raider)", caught)
}
_ = r.DeleteRaid(ctx, g)
if c, _ := r.ListRaidCaught(ctx, g, 10); len(c) != 0 {
t.Error("deleting a raid clears its list")
}
for i := 0; i < 5; i++ {
if err := r.SaveSnapshot(ctx, Snapshot{GuildID: g, Data: []byte(`{"roles":[],"channels":[]}`), Roles: i}); err != nil {
t.Fatal(err)
}
}
var n int
_ = r.db.QueryRow(`SELECT COUNT(*) FROM security_snapshots WHERE guild_id = $1`, g).Scan(&n)
if n != 3 {
t.Errorf("only the last three snapshots are kept, have %d", n)
}
latest, _ := r.LatestSnapshot(ctx, g)
if latest == nil || latest.Roles != 4 {
t.Errorf("latest = %+v", latest)
}
_ = r.SetEnabled(ctx, g, FeatureAntiNuke, true)
due, _ := r.GuildsDueForSnapshot(ctx, time.Hour)
for _, d := range due {
if d == g {
t.Error("a guild with a fresh snapshot is not due")
}
}
due, _ = r.GuildsDueForSnapshot(ctx, 0)
found := false
for _, d := range due {
found = found || d == g
}
if !found {
t.Error("with a zero max age every anti-nuke guild is due")
}
}
func TestListEvents(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
for _, kind := range []string{"settings", "raid_started", "quarantine"} {
if err := r.AddEvent(ctx, Event{GuildID: g, Kind: kind, ActorID: 5, Detail: "d"}); err != nil {
t.Fatal(err)
}
}
if err := r.AddEvent(ctx, Event{GuildID: g + 1, Kind: "other server"}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = r.db.Exec(`DELETE FROM security_events WHERE guild_id = $1`, g+1) })
got, err := r.ListEvents(ctx, g, 2)
if err != nil || len(got) != 2 || got[0].Kind != "quarantine" || got[1].Kind != "raid_started" {
t.Fatalf("newest first, limited: %+v %v", got, err)
}
if got[0].CreatedAt.IsZero() || got[0].ActorID != 5 || got[0].TargetID != 0 {
t.Errorf("fields: %+v", got[0])
}
if all, _ := r.ListEvents(ctx, g, 0); len(all) != 3 {
t.Errorf("only this server's events: %v", all)
}
}
@@ -0,0 +1,321 @@
//go:build integration
// Runs against a real Postgres with the dashboard API's migrations applied
// (the lobby limit is a trigger from migration 000020):
//
// TEST_DB=postgres://... go test -tags integration ./internal/db/repos/settingsrepo
package settingsrepo
import (
"context"
"database/sql"
"errors"
"os"
"sync"
"testing"
_ "github.com/jackc/pgx/v5/stdlib"
)
func testRepo(t *testing.T) (*Repo, int64) {
t.Helper()
dsn := os.Getenv("TEST_DB")
if dsn == "" {
t.Skip("TEST_DB not set")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
const guild = 4242
if _, err := db.Exec(`DELETE FROM meeting_lobbies WHERE guild_id IN ($1, $2)`, guild, guild+1); err != nil {
t.Fatal(err)
}
return NewRepo(db), guild
}
func TestMeetingLobbies(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
if ids, err := r.ListMeetingLobbies(ctx, g); err != nil || len(ids) != 0 {
t.Fatalf("a fresh server has no lobbies: %v %v", ids, err)
}
for ch := int64(1); ch <= MaxMeetingLobbies; ch++ {
added, err := r.AddMeetingLobby(ctx, g, ch)
if err != nil || !added {
t.Fatalf("adding lobby %d: added=%v err=%v", ch, added, err)
}
}
if _, err := r.AddMeetingLobby(ctx, g, 99); !errors.Is(err, ErrMeetingLobbyLimit) {
t.Errorf("an 11th lobby must hit the limit, got %v", err)
}
if added, err := r.AddMeetingLobby(ctx, g, 3); err != nil || added {
t.Errorf("adding an existing lobby is a no-op even at the limit: added=%v err=%v", added, err)
}
if added, err := r.AddMeetingLobby(ctx, g+1, 99); err != nil || !added {
t.Errorf("the limit is per server: added=%v err=%v", added, err)
}
if ok, _ := r.IsMeetingLobby(ctx, g, 7); !ok {
t.Error("7 is a lobby")
}
if ok, _ := r.IsMeetingLobby(ctx, g, 99); ok {
t.Error("99 isn't a lobby of this server (it is one of the other server's)")
}
if removed, err := r.RemoveMeetingLobby(ctx, g, 7); err != nil || !removed {
t.Errorf("removing 7: removed=%v err=%v", removed, err)
}
if removed, _ := r.RemoveMeetingLobby(ctx, g, 7); removed {
t.Error("7 was already removed")
}
if ok, _ := r.IsMeetingLobby(ctx, g, 7); ok {
t.Error("7 is no longer a lobby")
}
if added, err := r.AddMeetingLobby(ctx, g, 99); err != nil || !added {
t.Errorf("removing one makes room: added=%v err=%v", added, err)
}
ids, err := r.ListMeetingLobbies(ctx, g)
if err != nil || len(ids) != MaxMeetingLobbies || ids[len(ids)-1] != 99 {
t.Errorf("oldest first, newest last: %v %v", ids, err)
}
}
// Two people adding a lobby at the same moment must not both fit under the limit.
func TestMeetingLobbiesConcurrent(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
for ch := int64(1); ch < MaxMeetingLobbies; ch++ {
if _, err := r.AddMeetingLobby(ctx, g, ch); err != nil {
t.Fatal(err)
}
}
var wg sync.WaitGroup
var mu sync.Mutex
succeeded := 0
for i := 0; i < 8; i++ {
wg.Add(1)
go func(ch int64) {
defer wg.Done()
if added, err := r.AddMeetingLobby(ctx, g, ch); err == nil && added {
mu.Lock()
succeeded++
mu.Unlock()
}
}(int64(100 + i))
}
wg.Wait()
if succeeded != 1 {
t.Errorf("exactly one of the concurrent adds fits, %d did", succeeded)
}
if ids, _ := r.ListMeetingLobbies(ctx, g); len(ids) != MaxMeetingLobbies {
t.Errorf("have %d lobbies, want %d", len(ids), MaxMeetingLobbies)
}
}
func TestGetBetaSettings(t *testing.T) {
r, _ := testRepo(t)
db := r.db
ctx := context.Background()
_, err := db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS beta_settings (
id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (id), guild_id BIGINT, role_id BIGINT, updated_by BIGINT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`)
if err != nil {
t.Fatal(err)
}
var wasG, wasR sql.NullInt64
hadRow := db.QueryRowContext(ctx, `SELECT guild_id, role_id FROM beta_settings WHERE id`).Scan(&wasG, &wasR) == nil
t.Cleanup(func() {
if hadRow {
_, _ = db.ExecContext(ctx, `UPDATE beta_settings SET guild_id=$1, role_id=$2 WHERE id`, wasG, wasR)
} else {
_, _ = db.ExecContext(ctx, `DELETE FROM beta_settings`)
}
})
_, err = db.ExecContext(ctx, `DELETE FROM beta_settings`)
if err != nil {
t.Fatal(err)
}
g, role, err := r.GetBetaSettings(ctx)
if err != nil {
t.Fatal(err)
}
if g != "" {
t.Fatalf("g = %q, want empty", g)
}
if role != "" {
t.Fatalf("role = %q, want empty", role)
}
_, err = db.ExecContext(ctx, `INSERT INTO beta_settings (id, guild_id) VALUES (TRUE, 700000000000000001)`)
if err != nil {
t.Fatal(err)
}
g, role, err = r.GetBetaSettings(ctx)
if err != nil {
t.Fatal(err)
}
if g != "700000000000000001" {
t.Fatalf("g = %q, want %q", g, "700000000000000001")
}
if role != "" {
t.Fatalf("role = %q, want empty", role)
}
_, err = db.ExecContext(ctx, `UPDATE beta_settings SET role_id = 42`)
if err != nil {
t.Fatal(err)
}
_, role, err = r.GetBetaSettings(ctx)
if err != nil {
t.Fatal(err)
}
if role != "42" {
t.Fatalf("role = %q, want %q", role, "42")
}
}
func TestListBetaGuilds(t *testing.T) {
r, _ := testRepo(t)
db := r.db
ctx := context.Background()
if _, err := db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS beta_guilds (
guild_id BIGINT PRIMARY KEY, enabled_by BIGINT NOT NULL, enabled_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
t.Fatal(err)
}
const g = 8800000000000004242
_, _ = db.ExecContext(ctx, `DELETE FROM beta_guilds WHERE guild_id = $1`, g)
t.Cleanup(func() { _, _ = db.ExecContext(ctx, `DELETE FROM beta_guilds WHERE guild_id = $1`, g) })
has := func() bool {
ids, err := r.ListBetaGuilds(ctx)
if err != nil {
t.Fatal(err)
}
for _, id := range ids {
if id == "8800000000000004242" {
return true
}
}
return false
}
if has() {
t.Fatal("not listed before opting in")
}
if _, err := db.ExecContext(ctx, `INSERT INTO beta_guilds (guild_id, enabled_by) VALUES ($1, 1)`, g); err != nil {
t.Fatal(err)
}
if !has() {
t.Fatal("listed after opting in")
}
}
func TestBetaRegistered(t *testing.T) {
r, _ := testRepo(t)
ctx := context.Background()
if _, err := r.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS beta_registered (guild_id BIGINT PRIMARY KEY)`); err != nil {
t.Fatal(err)
}
const g = "8800000000000005151"
_ = r.SetBetaRegistered(ctx, g, false)
t.Cleanup(func() { _ = r.SetBetaRegistered(ctx, g, false) })
has := func() bool {
ids, err := r.ListBetaRegistered(ctx)
if err != nil {
t.Fatal(err)
}
for _, id := range ids {
if id == g {
return true
}
}
return false
}
if has() {
t.Fatal("not remembered at first")
}
for i := 0; i < 2; i++ { // twice: harmless
if err := r.SetBetaRegistered(ctx, g, true); err != nil {
t.Fatal(err)
}
}
if !has() {
t.Fatal("remembered after registering")
}
if err := r.SetBetaRegistered(ctx, g, false); err != nil || has() {
t.Fatalf("forgotten after removing: %v", err)
}
if err := r.SetBetaRegistered(ctx, "not-a-number", true); err == nil {
t.Error("a bad ID is refused")
}
}
func TestBetaSettingsFromCommands(t *testing.T) {
r, _ := testRepo(t)
ctx := context.Background()
var wasG, wasR sql.NullInt64
hadRow := r.db.QueryRowContext(ctx, `SELECT guild_id, role_id FROM beta_settings WHERE id`).Scan(&wasG, &wasR) == nil
t.Cleanup(func() {
if hadRow {
_, _ = r.db.ExecContext(ctx, `UPDATE beta_settings SET guild_id=$1, role_id=$2 WHERE id`, wasG, wasR)
} else {
_, _ = r.db.ExecContext(ctx, `DELETE FROM beta_settings`)
}
_ = r.SetBetaGuild(ctx, 8800000000000007171, 1, false)
})
if err := r.SetBetaServer(ctx, 700000000000000001, 800000000000000002, 5); err != nil {
t.Fatal(err)
}
g, role, err := r.GetBetaSettings(ctx)
if err != nil || g != "700000000000000001" || role != "800000000000000002" {
t.Fatalf("settings: %q %q %v", g, role, err)
}
if err := r.SetBetaServer(ctx, 700000000000000001, 0, 5); err != nil {
t.Fatal(err)
}
if g, role, _ = r.GetBetaSettings(ctx); g != "700000000000000001" || role != "" {
t.Errorf("a zero role clears the role and keeps the server: %q %q", g, role)
}
const guild = 8800000000000007171
for i := 0; i < 2; i++ {
if err := r.SetBetaGuild(ctx, guild, 9, true); err != nil {
t.Fatal(err)
}
}
if on, _ := r.IsBetaGuild(ctx, guild); !on {
t.Error("opted in")
}
if err := r.SetBetaGuild(ctx, guild, 9, false); err != nil {
t.Fatal(err)
}
if on, _ := r.IsBetaGuild(ctx, guild); on {
t.Error("opted out")
}
}
func TestDeleteRoleReward(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
if err := r.SetRoleRewardForLevel(ctx, g, 5, 77); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = r.db.ExecContext(ctx, `DELETE FROM levelrewards WHERE guild_id = $1`, g) })
if removed, err := r.DeleteRoleRewardForLevel(ctx, g, 6); err != nil || removed {
t.Errorf("nothing at level 6: %v %v", removed, err)
}
if removed, err := r.DeleteRoleRewardForLevel(ctx, g, 5); err != nil || !removed {
t.Errorf("remove level 5: %v %v", removed, err)
}
if _, ok, _ := r.GetRoleRewardForLevel(ctx, g, 5); ok {
t.Error("the reward is gone")
}
}
+278 -23
View File
@@ -3,6 +3,10 @@ package settingsrepo
import (
"context"
"database/sql"
"errors"
"strconv"
"github.com/jackc/pgx/v5/pgconn"
)
type Repo struct {
@@ -15,40 +19,85 @@ type LevelReward struct {
RoleID int64
}
type LogSettings struct {
GuildID int64
ChannelID int64
IsEnabled bool
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) SetMeetingLobbyChannel(ctx context.Context, guildID int64, lobbyChannelID int64) error {
// MaxMeetingLobbies is how many lobby channels one server can have. The
// database enforces it too (a trigger from the API's migration 000020), so
// the command and the dashboard can't disagree.
const MaxMeetingLobbies = 10
// ErrMeetingLobbyLimit means the server already has MaxMeetingLobbies.
var ErrMeetingLobbyLimit = errors.New("meeting lobby limit reached")
// pgLimitExceeded is the error code the database raises for one lobby too many.
const pgLimitExceeded = "54000"
// AddMeetingLobby makes channelID a lobby. added is false when it already
// was one; going over the limit is ErrMeetingLobbyLimit.
func (r *Repo) AddMeetingLobby(ctx context.Context, guildID, channelID int64) (added bool, err error) {
const q = `
INSERT INTO meeting_settings (guild_id, lobby_channel_id)
INSERT INTO meeting_lobbies (guild_id, channel_id)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET lobby_channel_id = EXCLUDED.lobby_channel_id
ON CONFLICT DO NOTHING
`
_, err := r.db.ExecContext(ctx, q, guildID, lobbyChannelID)
return err
res, err := r.db.ExecContext(ctx, q, guildID, channelID)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgLimitExceeded {
return false, ErrMeetingLobbyLimit
}
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
func (r *Repo) GetMeetingLobbyChannel(ctx context.Context, guildID int64) (channelID int64, ok bool, err error) {
const q = `
SELECT lobby_channel_id
FROM meeting_settings
WHERE guild_id = $1
`
row := r.db.QueryRowContext(ctx, q, guildID)
var ch sql.NullInt64
switch err := row.Scan(&ch); err {
case nil:
if !ch.Valid {
return 0, false, nil
// RemoveMeetingLobby takes a channel off the lobby list; removed is false
// when it wasn't one.
func (r *Repo) RemoveMeetingLobby(ctx context.Context, guildID, channelID int64) (removed bool, err error) {
const q = `DELETE FROM meeting_lobbies WHERE guild_id = $1 AND channel_id = $2`
res, err := r.db.ExecContext(ctx, q, guildID, channelID)
if err != nil {
return false, err
}
return ch.Int64, true, nil
case sql.ErrNoRows:
return 0, false, nil
default:
return 0, false, err
n, err := res.RowsAffected()
return n > 0, err
}
// ListMeetingLobbies returns a server's lobbies, oldest first.
func (r *Repo) ListMeetingLobbies(ctx context.Context, guildID int64) ([]int64, error) {
const q = `SELECT channel_id FROM meeting_lobbies WHERE guild_id = $1 ORDER BY created_at, channel_id`
rows, err := r.db.QueryContext(ctx, q, guildID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
// IsMeetingLobby reports whether channelID is one of the server's lobbies.
// It runs whenever someone joins a voice channel, so it's one indexed lookup.
func (r *Repo) IsMeetingLobby(ctx context.Context, guildID, channelID int64) (bool, error) {
const q = `SELECT EXISTS (SELECT 1 FROM meeting_lobbies WHERE guild_id = $1 AND channel_id = $2)`
var ok bool
err := r.db.QueryRowContext(ctx, q, guildID, channelID).Scan(&ok)
return ok, err
}
func (r *Repo) AddMeetingTempChannel(ctx context.Context, guildID, channelID, createdBy int64) error {
@@ -240,6 +289,80 @@ func (r *Repo) SetLevelUpMessage(ctx context.Context, guildID int64, message str
return err
}
func (r *Repo) SetLogChannel(ctx context.Context, guildID int64, channelID int64) error {
const q = `
INSERT INTO logsettings (guild_id, log_channel_id, is_enabled)
VALUES ($1, $2, TRUE)
ON CONFLICT (guild_id)
DO UPDATE SET log_channel_id = EXCLUDED.log_channel_id
`
_, err := r.db.ExecContext(ctx, q, guildID, channelID)
return err
}
func (r *Repo) SetLogEnabled(ctx context.Context, guildID int64, enabled bool) error {
const q = `
INSERT INTO logsettings (guild_id, is_enabled)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET is_enabled = EXCLUDED.is_enabled
`
_, err := r.db.ExecContext(ctx, q, guildID, enabled)
return err
}
func (r *Repo) GetLogSettings(ctx context.Context, guildID int64) (*LogSettings, error) {
const q = `
SELECT log_channel_id, is_enabled
FROM logsettings
WHERE guild_id = $1
`
row := r.db.QueryRowContext(ctx, q, guildID)
var channelID sql.NullInt64
var enabled sql.NullBool
switch err := row.Scan(&channelID, &enabled); err {
case nil:
out := &LogSettings{
GuildID: guildID,
ChannelID: 0,
IsEnabled: false,
}
if channelID.Valid {
out.ChannelID = channelID.Int64
}
if enabled.Valid {
out.IsEnabled = enabled.Bool
}
return out, nil
case sql.ErrNoRows:
return &LogSettings{
GuildID: guildID,
ChannelID: 0,
IsEnabled: false,
}, nil
default:
return nil, err
}
}
func (r *Repo) HasLogSettings(ctx context.Context, guildID int64) (bool, error) {
const q = `
SELECT 1
FROM logsettings
WHERE guild_id = $1
`
row := r.db.QueryRowContext(ctx, q, guildID)
var one int
switch err := row.Scan(&one); err {
case nil:
return true, nil
case sql.ErrNoRows:
return false, nil
default:
return false, err
}
}
func (r *Repo) GetLevelUpMessage(ctx context.Context, guildID int64) (string, error) {
const q = `
SELECT message
@@ -260,3 +383,135 @@ func (r *Repo) GetLevelUpMessage(ctx context.Context, guildID int64) (string, er
return "", err
}
}
func (r *Repo) IsMusicEnabled(ctx context.Context, guildID int64) (bool, error) {
const q = `SELECT is_enabled FROM music_settings WHERE guild_id = $1`
var enabled bool
err := r.db.QueryRowContext(ctx, q, guildID).Scan(&enabled)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
return enabled, nil
}
func (r *Repo) SetMusicEnabled(ctx context.Context, guildID int64, enabled bool) error {
const q = `INSERT INTO music_settings (guild_id, is_enabled) VALUES ($1, $2) ON CONFLICT (guild_id) DO UPDATE SET is_enabled = $2`
_, err := r.db.ExecContext(ctx, q, guildID, enabled)
return err
}
// GetBetaSettings returns the beta server and Beta Tester role as set on the
// dashboard. Either is "" when not set (or when there's no row yet).
func (r *Repo) GetBetaSettings(ctx context.Context) (guildID, roleID string, err error) {
var g, role sql.NullInt64
err = r.db.QueryRowContext(ctx, `SELECT guild_id, role_id FROM beta_settings WHERE id = TRUE`).Scan(&g, &role)
if errors.Is(err, sql.ErrNoRows) {
return "", "", nil
}
if err != nil {
return "", "", err
}
if g.Valid {
guildID = strconv.FormatInt(g.Int64, 10)
}
if role.Valid {
roleID = strconv.FormatInt(role.Int64, 10)
}
return guildID, roleID, nil
}
// ListBetaGuilds returns the servers whose owner opted in to beta features
// (set on the dashboard), as ID strings.
func (r *Repo) ListBetaGuilds(ctx context.Context) ([]string, error) {
rows, err := r.db.QueryContext(ctx, `SELECT guild_id FROM beta_guilds ORDER BY enabled_at`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, strconv.FormatInt(id, 10))
}
return out, rows.Err()
}
// ListBetaRegistered returns the servers where the bot registered beta
// commands, so it can clean up after itself even if a server opted out while
// it was offline.
func (r *Repo) ListBetaRegistered(ctx context.Context) ([]string, error) {
rows, err := r.db.QueryContext(ctx, `SELECT guild_id FROM beta_registered`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, strconv.FormatInt(id, 10))
}
return out, rows.Err()
}
// SetBetaRegistered records (or forgets) that beta commands exist in a server.
func (r *Repo) SetBetaRegistered(ctx context.Context, guildID string, registered bool) error {
id, err := strconv.ParseInt(guildID, 10, 64)
if err != nil {
return err
}
if registered {
_, err = r.db.ExecContext(ctx, `INSERT INTO beta_registered (guild_id) VALUES ($1) ON CONFLICT DO NOTHING`, id)
} else {
_, err = r.db.ExecContext(ctx, `DELETE FROM beta_registered WHERE guild_id = $1`, id)
}
return err
}
// SetBetaServer saves the beta server and the Beta Tester role (0 clears the
// role, which turns beta features off for everyone).
func (r *Repo) SetBetaServer(ctx context.Context, guildID, roleID, updatedBy int64) error {
const q = `
INSERT INTO beta_settings (id, guild_id, role_id, updated_by, updated_at)
VALUES (TRUE, $1, $2, $3, NOW())
ON CONFLICT (id) DO UPDATE SET guild_id = EXCLUDED.guild_id, role_id = EXCLUDED.role_id,
updated_by = EXCLUDED.updated_by, updated_at = NOW()`
_, err := r.db.ExecContext(ctx, q, guildID, sql.NullInt64{Int64: roleID, Valid: roleID != 0}, updatedBy)
return err
}
// SetBetaGuild opts a server in or out of beta features.
func (r *Repo) SetBetaGuild(ctx context.Context, guildID, enabledBy int64, enabled bool) error {
if enabled {
_, err := r.db.ExecContext(ctx, `INSERT INTO beta_guilds (guild_id, enabled_by) VALUES ($1, $2) ON CONFLICT (guild_id) DO NOTHING`, guildID, enabledBy)
return err
}
_, err := r.db.ExecContext(ctx, `DELETE FROM beta_guilds WHERE guild_id = $1`, guildID)
return err
}
// IsBetaGuild reports whether a server opted in to beta features.
func (r *Repo) IsBetaGuild(ctx context.Context, guildID int64) (bool, error) {
var on bool
err := r.db.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM beta_guilds WHERE guild_id = $1)`, guildID).Scan(&on)
return on, err
}
// DeleteRoleRewardForLevel removes the role reward of a level and reports
// whether there was one.
func (r *Repo) DeleteRoleRewardForLevel(ctx context.Context, guildID int64, level int) (bool, error) {
res, err := r.db.ExecContext(ctx, `DELETE FROM levelrewards WHERE guild_id = $1 AND levelreq = $2`, guildID, level)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
+412
View File
@@ -0,0 +1,412 @@
// Package ticketrepo stores the ticket system's settings, categories, tickets
// and the dashboard's requests to the bot. Discord IDs are int64; 0 means
// "not set" for optional ones.
package ticketrepo
import (
"context"
"database/sql"
"errors"
"strconv"
"strings"
"time"
)
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
const (
DefaultPanelTitle = "Need help?"
DefaultPanelDescription = "Pick a category below to open a private ticket with the staff team."
DefaultMaxOpenPerUser = 1
StatusOpen = "open"
StatusClosed = "closed"
)
type Settings struct {
GuildID int64
Enabled bool
ChannelID int64
LogChannelID int64
PanelMessageID int64
PanelTitle string
PanelDescription string
MaxOpenPerUser int
// Configured is false when the guild has no settings row yet; the other
// fields then hold the defaults.
Configured bool
}
type Category struct {
ID int64
GuildID int64
Name string
Emoji string
Description string
StaffRoleID int64
Position int
}
type Ticket struct {
ID int64
GuildID int64
Number int
CategoryID int64
CategoryName string
ThreadID int64
IntroMessage int64
OpenerID int64
Subject string
Status string
ClaimedBy int64
ClosedBy int64
CloseReason string
CreatedAt time.Time
ClosedAt time.Time // zero while open
}
type Command struct {
ID int64
GuildID int64
CommandType string
RequestedBy int64
}
func nullID(v int64) sql.NullInt64 {
return sql.NullInt64{Int64: v, Valid: v != 0}
}
func nullText(v string) sql.NullString {
return sql.NullString{String: v, Valid: v != ""}
}
func (r *Repo) GetSettings(ctx context.Context, guildID int64) (*Settings, error) {
const q = `
SELECT enabled, channel_id, log_channel_id, panel_message_id, panel_title, panel_description, max_open_per_user
FROM ticket_settings WHERE guild_id = $1`
var ch, logCh, panel sql.NullInt64
s := &Settings{GuildID: guildID}
err := r.db.QueryRowContext(ctx, q, guildID).Scan(&s.Enabled, &ch, &logCh, &panel, &s.PanelTitle, &s.PanelDescription, &s.MaxOpenPerUser)
switch {
case errors.Is(err, sql.ErrNoRows):
// Modules start off until the server sets them up.
return &Settings{
GuildID: guildID,
Enabled: false,
PanelTitle: DefaultPanelTitle,
PanelDescription: DefaultPanelDescription,
MaxOpenPerUser: DefaultMaxOpenPerUser,
}, nil
case err != nil:
return nil, err
}
s.ChannelID, s.LogChannelID, s.PanelMessageID = ch.Int64, logCh.Int64, panel.Int64
s.Configured = true
return s, nil
}
// SetChannels saves where tickets live and where transcripts go. A zero log
// channel clears it. Setting tickets up for the first time turns them on
// (they start off); after that, the on/off switch is left alone.
func (r *Repo) SetChannels(ctx context.Context, guildID, channelID, logChannelID int64) error {
const q = `
INSERT INTO ticket_settings (guild_id, channel_id, log_channel_id, enabled)
VALUES ($1, $2, $3, TRUE)
ON CONFLICT (guild_id) DO UPDATE SET
channel_id = EXCLUDED.channel_id,
log_channel_id = EXCLUDED.log_channel_id`
_, err := r.db.ExecContext(ctx, q, guildID, nullID(channelID), nullID(logChannelID))
return err
}
func (r *Repo) SetPanelMessage(ctx context.Context, guildID, messageID int64) error {
const q = `
INSERT INTO ticket_settings (guild_id, panel_message_id) VALUES ($1, $2)
ON CONFLICT (guild_id) DO UPDATE SET panel_message_id = EXCLUDED.panel_message_id`
_, err := r.db.ExecContext(ctx, q, guildID, nullID(messageID))
return err
}
// NextNumber hands out the guild's next ticket number. It is a single
// statement, so two tickets opened at the same moment never share a number.
func (r *Repo) NextNumber(ctx context.Context, guildID int64) (int, error) {
const q = `
INSERT INTO ticket_settings (guild_id, next_number) VALUES ($1, 2)
ON CONFLICT (guild_id) DO UPDATE SET next_number = ticket_settings.next_number + 1
RETURNING next_number - 1`
var n int
err := r.db.QueryRowContext(ctx, q, guildID).Scan(&n)
return n, err
}
const categoryCols = `id, guild_id, name, COALESCE(emoji, ''), description, COALESCE(staff_role_id, 0), position`
func scanCategory(row interface{ Scan(...any) error }) (Category, error) {
var c Category
err := row.Scan(&c.ID, &c.GuildID, &c.Name, &c.Emoji, &c.Description, &c.StaffRoleID, &c.Position)
return c, err
}
func (r *Repo) ListCategories(ctx context.Context, guildID int64) ([]Category, error) {
q := `SELECT ` + categoryCols + ` FROM ticket_categories WHERE guild_id = $1 ORDER BY position, id`
rows, err := r.db.QueryContext(ctx, q, guildID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Category
for rows.Next() {
c, err := scanCategory(rows)
if err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
// GetCategory returns nil when the category does not exist in that guild.
func (r *Repo) GetCategory(ctx context.Context, guildID, id int64) (*Category, error) {
q := `SELECT ` + categoryCols + ` FROM ticket_categories WHERE guild_id = $1 AND id = $2`
c, err := scanCategory(r.db.QueryRowContext(ctx, q, guildID, id))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &c, nil
}
// AddCategory appends a category after the existing ones.
func (r *Repo) AddCategory(ctx context.Context, c Category) (*Category, error) {
q := `
INSERT INTO ticket_categories (guild_id, name, emoji, description, staff_role_id, position)
VALUES ($1, $2, $3, $4, $5,
(SELECT COALESCE(MAX(position) + 1, 0) FROM ticket_categories WHERE guild_id = $1))
RETURNING ` + categoryCols
out, err := scanCategory(r.db.QueryRowContext(ctx, q, c.GuildID, c.Name, nullText(c.Emoji), c.Description, nullID(c.StaffRoleID)))
if err != nil {
return nil, err
}
return &out, nil
}
// DeleteCategoryByName removes a category (case-insensitively) and reports
// whether one was found. Tickets keep their copied category name.
func (r *Repo) DeleteCategoryByName(ctx context.Context, guildID int64, name string) (bool, error) {
const q = `DELETE FROM ticket_categories WHERE guild_id = $1 AND lower(name) = lower($2)`
res, err := r.db.ExecContext(ctx, q, guildID, name)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
func (r *Repo) CountOpenByOpener(ctx context.Context, guildID, openerID int64) (int, error) {
const q = `SELECT COUNT(*) FROM tickets WHERE guild_id = $1 AND opener_id = $2 AND status = 'open'`
var n int
err := r.db.QueryRowContext(ctx, q, guildID, openerID).Scan(&n)
return n, err
}
func (r *Repo) CreateTicket(ctx context.Context, t Ticket) (int64, error) {
const q = `
INSERT INTO tickets (guild_id, number, category_id, category_name, thread_id, intro_message_id, opener_id, subject)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id`
var id int64
err := r.db.QueryRowContext(ctx, q, t.GuildID, t.Number, nullID(t.CategoryID), t.CategoryName, t.ThreadID, nullID(t.IntroMessage), t.OpenerID, t.Subject).Scan(&id)
return id, err
}
const ticketCols = `id, guild_id, number, COALESCE(category_id, 0), category_name, thread_id, COALESCE(intro_message_id, 0), opener_id, subject, status,
COALESCE(claimed_by, 0), COALESCE(closed_by, 0), COALESCE(close_reason, ''), created_at, closed_at`
func scanTicket(row interface{ Scan(...any) error }) (Ticket, error) {
var t Ticket
var closedAt sql.NullTime
err := row.Scan(&t.ID, &t.GuildID, &t.Number, &t.CategoryID, &t.CategoryName, &t.ThreadID, &t.IntroMessage, &t.OpenerID, &t.Subject, &t.Status,
&t.ClaimedBy, &t.ClosedBy, &t.CloseReason, &t.CreatedAt, &closedAt)
t.ClosedAt = closedAt.Time
return t, err
}
// GetTicketByThread returns nil when the thread is not a ticket.
func (r *Repo) GetTicketByThread(ctx context.Context, threadID int64) (*Ticket, error) {
q := `SELECT ` + ticketCols + ` FROM tickets WHERE thread_id = $1`
t, err := scanTicket(r.db.QueryRowContext(ctx, q, threadID))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &t, nil
}
// Claim sets the ticket's handler unless someone already has it, and returns
// whoever holds it afterwards (the caller when the claim worked).
func (r *Repo) Claim(ctx context.Context, threadID, staffID int64) (int64, error) {
const q = `
UPDATE tickets SET claimed_by = COALESCE(claimed_by, $2)
WHERE thread_id = $1 AND status = 'open'
RETURNING claimed_by`
var holder int64
err := r.db.QueryRowContext(ctx, q, threadID, staffID).Scan(&holder)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return holder, err
}
// Close marks an open ticket closed and reports whether this call closed it,
// so two people pressing Close at once only produce one transcript.
func (r *Repo) Close(ctx context.Context, threadID, closedBy int64, reason string) (bool, error) {
const q = `
UPDATE tickets SET status = 'closed', closed_by = $2, close_reason = $3, closed_at = NOW()
WHERE thread_id = $1 AND status = 'open'`
res, err := r.db.ExecContext(ctx, q, threadID, nullID(closedBy), nullText(reason))
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
func (r *Repo) ListUnprocessedCommands(ctx context.Context) ([]Command, error) {
const q = `SELECT id, guild_id, command_type, requested_by FROM ticket_commands WHERE processed_at IS NULL ORDER BY id`
rows, err := r.db.QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Command
for rows.Next() {
var c Command
if err := rows.Scan(&c.ID, &c.GuildID, &c.CommandType, &c.RequestedBy); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
func (r *Repo) MarkCommandProcessed(ctx context.Context, id int64) error {
_, err := r.db.ExecContext(ctx, `UPDATE ticket_commands SET processed_at = NOW() WHERE id = $1`, id)
return err
}
// SettingsPatch changes ticket settings. A nil field is left as it is.
type SettingsPatch struct {
Enabled *bool
PanelTitle *string
PanelDescription *string
MaxOpenPerUser *int
}
// UpdateSettings applies the fields that are set. The server gets a settings
// row if it has none yet, with everything else at its default and the system
// still off, until /tickets setup or this turns it on.
func (r *Repo) UpdateSettings(ctx context.Context, guildID int64, p SettingsPatch) error {
if _, err := r.db.ExecContext(ctx, `INSERT INTO ticket_settings (guild_id) VALUES ($1) ON CONFLICT DO NOTHING`, guildID); err != nil {
return err
}
var sets []string
args := []any{guildID}
add := func(col string, v any) {
args = append(args, v)
sets = append(sets, col+` = $`+strconv.Itoa(len(args)))
}
if p.Enabled != nil {
add("enabled", *p.Enabled)
}
if p.PanelTitle != nil {
add("panel_title", *p.PanelTitle)
}
if p.PanelDescription != nil {
add("panel_description", *p.PanelDescription)
}
if p.MaxOpenPerUser != nil {
add("max_open_per_user", *p.MaxOpenPerUser)
}
if len(sets) == 0 {
return nil
}
_, err := r.db.ExecContext(ctx, `UPDATE ticket_settings SET `+strings.Join(sets, ", ")+` WHERE guild_id = $1`, args...)
return err
}
// CategoryPatch changes a category. A nil field is left as it is; an empty
// emoji or description clears it, and a zero StaffRoleID clears the role.
type CategoryPatch struct {
Name *string
Emoji *string
Description *string
StaffRoleID *int64
}
// UpdateCategory applies the fields that are set and returns the category as
// saved, or nil when there is none with that ID in the guild.
func (r *Repo) UpdateCategory(ctx context.Context, guildID, id int64, p CategoryPatch) (*Category, error) {
var sets []string
args := []any{guildID, id}
add := func(col string, v any) {
args = append(args, v)
sets = append(sets, col+` = $`+strconv.Itoa(len(args)))
}
if p.Name != nil {
add("name", *p.Name)
}
if p.Emoji != nil {
add("emoji", nullText(*p.Emoji))
}
if p.Description != nil {
add("description", *p.Description)
}
if p.StaffRoleID != nil {
add("staff_role_id", nullID(*p.StaffRoleID))
}
if len(sets) == 0 {
return r.GetCategory(ctx, guildID, id)
}
q := `UPDATE ticket_categories SET ` + strings.Join(sets, ", ") + ` WHERE guild_id = $1 AND id = $2 RETURNING ` + categoryCols
c, err := scanCategory(r.db.QueryRowContext(ctx, q, args...))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &c, nil
}
// ListTickets returns a guild's most recent tickets with the given status
// ("open" or "closed"), newest first.
func (r *Repo) ListTickets(ctx context.Context, guildID int64, status string, limit int) ([]Ticket, error) {
if limit < 1 || limit > 100 {
limit = 25
}
q := `SELECT ` + ticketCols + ` FROM tickets WHERE guild_id = $1 AND status = $2 ORDER BY number DESC LIMIT $3`
rows, err := r.db.QueryContext(ctx, q, guildID, status, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Ticket
for rows.Next() {
t, err := scanTicket(rows)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
@@ -0,0 +1,287 @@
//go:build integration
// Runs against a real Postgres with schema.sql loaded:
//
// TICKETS_TEST_DB=postgres://... go test -tags integration ./internal/db/repos/ticketrepo
package ticketrepo
import (
"context"
"database/sql"
"os"
"sync"
"testing"
_ "github.com/jackc/pgx/v5/stdlib"
)
func testRepo(t *testing.T) (*Repo, int64) {
t.Helper()
dsn := os.Getenv("TICKETS_TEST_DB")
if dsn == "" {
t.Skip("TICKETS_TEST_DB not set")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
const guild = 424242
for _, q := range []string{
`DELETE FROM tickets WHERE guild_id = $1`,
`DELETE FROM ticket_categories WHERE guild_id = $1`,
`DELETE FROM ticket_settings WHERE guild_id = $1`,
`DELETE FROM ticket_commands WHERE guild_id = $1`,
} {
if _, err := db.Exec(q, guild); err != nil {
t.Fatal(err)
}
}
return NewRepo(db), guild
}
func TestSettingsDefaultsAndChannels(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
s, err := r.GetSettings(ctx, g)
if err != nil || s.Configured || s.Enabled || s.PanelTitle != DefaultPanelTitle || s.MaxOpenPerUser != 1 {
t.Fatalf("defaults wrong: %+v %v", s, err)
}
if err := r.SetChannels(ctx, g, 111, 222); err != nil {
t.Fatal(err)
}
if err := r.SetPanelMessage(ctx, g, 333); err != nil {
t.Fatal(err)
}
s, _ = r.GetSettings(ctx, g)
if !s.Configured || s.ChannelID != 111 || s.LogChannelID != 222 || s.PanelMessageID != 333 {
t.Fatalf("saved settings wrong: %+v", s)
}
// Clearing the log channel.
_ = r.SetChannels(ctx, g, 111, 0)
s, _ = r.GetSettings(ctx, g)
if s.LogChannelID != 0 {
t.Errorf("log channel not cleared: %+v", s)
}
}
func TestNextNumberIsUniqueUnderConcurrency(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
var mu sync.Mutex
seen := map[int]bool{}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
n, err := r.NextNumber(ctx, g)
if err != nil {
t.Error(err)
return
}
mu.Lock()
defer mu.Unlock()
if seen[n] {
t.Errorf("number %d handed out twice", n)
}
seen[n] = true
}()
}
wg.Wait()
for n := 1; n <= 20; n++ {
if !seen[n] {
t.Errorf("number %d missing: numbers should be 1..20", n)
}
}
}
func TestCategories(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
a, err := r.AddCategory(ctx, Category{GuildID: g, Name: "Support", Emoji: "🛟", StaffRoleID: 9})
if err != nil {
t.Fatal(err)
}
b, _ := r.AddCategory(ctx, Category{GuildID: g, Name: "Appeal", Description: "Ban appeals"})
if a.Position != 0 || b.Position != 1 || b.Emoji != "" || b.StaffRoleID != 0 {
t.Fatalf("positions or defaults wrong: %+v %+v", a, b)
}
list, _ := r.ListCategories(ctx, g)
if len(list) != 2 || list[0].Name != "Support" || list[1].Description != "Ban appeals" {
t.Fatalf("list wrong: %+v", list)
}
if c, _ := r.GetCategory(ctx, g, a.ID); c == nil || c.Emoji != "🛟" {
t.Errorf("get wrong: %+v", c)
}
if c, _ := r.GetCategory(ctx, g+1, a.ID); c != nil {
t.Error("a category must not be readable from another guild")
}
if ok, _ := r.DeleteCategoryByName(ctx, g, "support"); !ok {
t.Error("delete should match case-insensitively")
}
if ok, _ := r.DeleteCategoryByName(ctx, g, "nope"); ok {
t.Error("deleting a missing category should report false")
}
}
func TestTicketLifecycle(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
cat, _ := r.AddCategory(ctx, Category{GuildID: g, Name: "Support"})
id, err := r.CreateTicket(ctx, Ticket{GuildID: g, Number: 1, CategoryID: cat.ID, CategoryName: "Support", ThreadID: 5001, IntroMessage: 6001, OpenerID: 77, Subject: "Help"})
if err != nil || id == 0 {
t.Fatal(err)
}
if n, _ := r.CountOpenByOpener(ctx, g, 77); n != 1 {
t.Errorf("open count = %d", n)
}
if holder, _ := r.Claim(ctx, 5001, 10); holder != 10 {
t.Errorf("first claim should win, holder = %d", holder)
}
if holder, _ := r.Claim(ctx, 5001, 11); holder != 10 {
t.Errorf("second claim must not take over, holder = %d", holder)
}
if ok, _ := r.Close(ctx, 5001, 10, "solved"); !ok {
t.Error("first close should succeed")
}
if ok, _ := r.Close(ctx, 5001, 11, ""); ok {
t.Error("closing twice must report false")
}
tk, _ := r.GetTicketByThread(ctx, 5001)
if tk == nil || tk.Status != StatusClosed || tk.ClosedBy != 10 || tk.CloseReason != "solved" || tk.ClosedAt.IsZero() || tk.ClaimedBy != 10 || tk.IntroMessage != 6001 {
t.Fatalf("closed ticket wrong: %+v", tk)
}
if n, _ := r.CountOpenByOpener(ctx, g, 77); n != 0 {
t.Errorf("closed ticket still counted as open")
}
if holder, _ := r.Claim(ctx, 5001, 12); holder != 0 {
t.Error("a closed ticket cannot be claimed")
}
// Deleting the category keeps the ticket and its copied name.
_, _ = r.DeleteCategoryByName(ctx, g, "Support")
tk, _ = r.GetTicketByThread(ctx, 5001)
if tk.CategoryID != 0 || tk.CategoryName != "Support" {
t.Errorf("ticket after category delete: %+v", tk)
}
if tk, _ := r.GetTicketByThread(ctx, 999); tk != nil {
t.Error("unknown thread should return nil")
}
}
func TestCommands(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
if _, err := r.db.Exec(`INSERT INTO ticket_commands (guild_id, command_type, requested_by) VALUES ($1, 'post_panel', 5)`, g); err != nil {
t.Fatal(err)
}
cmds, err := r.ListUnprocessedCommands(ctx)
if err != nil {
t.Fatal(err)
}
var mine *Command
for i := range cmds {
if cmds[i].GuildID == g {
mine = &cmds[i]
}
}
if mine == nil || mine.CommandType != "post_panel" || mine.RequestedBy != 5 {
t.Fatalf("command not listed: %+v", cmds)
}
_ = r.MarkCommandProcessed(ctx, mine.ID)
cmds, _ = r.ListUnprocessedCommands(ctx)
for _, c := range cmds {
if c.ID == mine.ID {
t.Error("processed command still listed")
}
}
}
func TestUpdateSettingsCategoriesAndList(t *testing.T) {
r, g := testRepo(t)
ctx := context.Background()
str := func(v string) *string { return &v }
num := func(v int) *int { return &v }
on := true
// Changing the text of a server that never set tickets up creates its row
// and leaves the system off.
if err := r.UpdateSettings(ctx, g, SettingsPatch{PanelTitle: str("Help desk"), MaxOpenPerUser: num(3)}); err != nil {
t.Fatal(err)
}
st, _ := r.GetSettings(ctx, g)
if st.Enabled || st.PanelTitle != "Help desk" || st.MaxOpenPerUser != 3 || st.PanelDescription != DefaultPanelDescription {
t.Errorf("settings: %+v", st)
}
if err := r.UpdateSettings(ctx, g, SettingsPatch{Enabled: &on}); err != nil {
t.Fatal(err)
}
if st, _ = r.GetSettings(ctx, g); !st.Enabled || st.PanelTitle != "Help desk" {
t.Errorf("enabling keeps the rest: %+v", st)
}
if err := r.UpdateSettings(ctx, g, SettingsPatch{MaxOpenPerUser: num(11)}); err == nil {
t.Error("the database refuses more than 10 open tickets per member")
}
if err := r.UpdateSettings(ctx, g, SettingsPatch{}); err != nil {
t.Errorf("an empty patch is fine: %v", err)
}
cat, err := r.AddCategory(ctx, Category{GuildID: g, Name: "Support", Emoji: "🎫", Description: "Questions", StaffRoleID: 99})
if err != nil {
t.Fatal(err)
}
other, err := r.AddCategory(ctx, Category{GuildID: g, Name: "Report"})
if err != nil {
t.Fatal(err)
}
zero := int64(0)
empty := ""
got, err := r.UpdateCategory(ctx, g, cat.ID, CategoryPatch{Name: str("Help"), Emoji: &empty, StaffRoleID: &zero})
if err != nil || got == nil {
t.Fatalf("update: %v %v", got, err)
}
if got.Name != "Help" || got.Emoji != "" || got.StaffRoleID != 0 || got.Description != "Questions" {
t.Errorf("only the named fields change, and empty clears: %+v", got)
}
if got, _ = r.UpdateCategory(ctx, g, cat.ID, CategoryPatch{StaffRoleID: func() *int64 { v := int64(5); return &v }()}); got.StaffRoleID != 5 {
t.Errorf("setting the role: %+v", got)
}
if gone, err := r.UpdateCategory(ctx, g+1, cat.ID, CategoryPatch{Name: str("x")}); err != nil || gone != nil {
t.Errorf("another server's category can't be edited: %v %v", gone, err)
}
if _, err := r.UpdateCategory(ctx, g, other.ID, CategoryPatch{Name: str("")}); err == nil {
t.Error("the database refuses an empty name")
}
for n, status := range []string{"open", "open", "closed"} {
id, err := r.CreateTicket(ctx, Ticket{GuildID: g, Number: n + 1, CategoryID: cat.ID, CategoryName: "Help", ThreadID: int64(9100 + n), OpenerID: 7, Subject: "x"})
if err != nil {
t.Fatal(err)
}
if status == "closed" {
if _, err := r.Close(ctx, int64(9100+n), 7, "done"); err != nil {
t.Fatal(err)
}
}
_ = id
}
open, err := r.ListTickets(ctx, g, StatusOpen, 10)
if err != nil || len(open) != 2 || open[0].Number != 2 {
t.Errorf("open tickets, newest first: %v %v", open, err)
}
closed, _ := r.ListTickets(ctx, g, StatusClosed, 10)
if len(closed) != 1 {
t.Errorf("closed tickets: %v", closed)
}
if other, _ := r.ListTickets(ctx, g+1, StatusOpen, 10); len(other) != 0 {
t.Error("another server's tickets must not show")
}
}
+145
View File
@@ -0,0 +1,145 @@
package twitchrepo
import (
"context"
"database/sql"
)
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) ListGuilds(ctx context.Context) ([]int64, error) {
const q = `SELECT DISTINCT guild_id FROM twitch`
rows, err := r.db.QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var gid int64
if err := rows.Scan(&gid); err != nil {
return nil, err
}
ids = append(ids, gid)
}
return ids, rows.Err()
}
func (r *Repo) ListUsersForGuild(ctx context.Context, guildID int64) ([]string, error) {
const q = `SELECT twitch_user FROM twitch WHERE guild_id = $1`
rows, err := r.db.QueryContext(ctx, q, guildID)
if err != nil {
return nil, err
}
defer rows.Close()
var users []string
for rows.Next() {
var u string
if err := rows.Scan(&u); err != nil {
return nil, err
}
users = append(users, u)
}
return users, rows.Err()
}
func (r *Repo) GetStatus(ctx context.Context, guildID int64, username string) (string, bool, error) {
const q = `SELECT status FROM twitch WHERE guild_id = $1 AND twitch_user = $2`
var status string
err := r.db.QueryRowContext(ctx, q, guildID, username).Scan(&status)
if err == sql.ErrNoRows {
return "", false, nil
}
if err != nil {
return "", false, err
}
return status, true, nil
}
func (r *Repo) UpsertStreamer(ctx context.Context, guildID int64, username string) error {
const q = `
INSERT INTO twitch (twitch_user, guild_id, status)
VALUES ($1, $2, 'not live')
ON CONFLICT (twitch_user, guild_id)
DO NOTHING
`
_, err := r.db.ExecContext(ctx, q, username, guildID)
return err
}
func (r *Repo) RemoveStreamer(ctx context.Context, guildID int64, username string) error {
const q = `DELETE FROM twitch WHERE guild_id = $1 AND twitch_user = $2`
_, err := r.db.ExecContext(ctx, q, guildID, username)
return err
}
func (r *Repo) UpdateStatus(ctx context.Context, guildID int64, username, status string) error {
const q = `UPDATE twitch SET status = $1 WHERE guild_id = $2 AND twitch_user = $3`
_, err := r.db.ExecContext(ctx, q, status, guildID, username)
return err
}
func (r *Repo) GetNotificationChannel(ctx context.Context, guildID int64) (int64, bool, error) {
const q = `SELECT twitch_channel_id FROM twitch_config WHERE guild_id = $1`
var chID sql.NullInt64
if err := r.db.QueryRowContext(ctx, q, guildID).Scan(&chID); err != nil {
if err == sql.ErrNoRows {
return 0, false, nil
}
return 0, false, err
}
if !chID.Valid {
return 0, false, nil
}
return chID.Int64, true, nil
}
// SetNotificationChannel sets where live alerts go. Setting it for the first
// time turns alerts on (they start off); after that, the on/off switch is
// left alone.
func (r *Repo) SetNotificationChannel(ctx context.Context, guildID, channelID int64) error {
const q = `
INSERT INTO twitch_config (guild_id, twitch_channel_id, enabled)
VALUES ($1, $2, TRUE)
ON CONFLICT (guild_id)
DO UPDATE SET twitch_channel_id = EXCLUDED.twitch_channel_id
`
_, err := r.db.ExecContext(ctx, q, guildID, channelID)
return err
}
// IsEnabled reports whether Twitch notifications are enabled for guildID.
// A guild with no twitch_config row yet is off: modules start off until
// the server sets them up.
func (r *Repo) IsEnabled(ctx context.Context, guildID int64) (bool, error) {
const q = `SELECT enabled FROM twitch_config WHERE guild_id = $1`
var enabled bool
err := r.db.QueryRowContext(ctx, q, guildID).Scan(&enabled)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
return enabled, nil
}
func (r *Repo) SetEnabled(ctx context.Context, guildID int64, enabled bool) error {
const q = `
INSERT INTO twitch_config (guild_id, enabled)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET enabled = EXCLUDED.enabled
`
_, err := r.db.ExecContext(ctx, q, guildID, enabled)
return err
}
@@ -0,0 +1,44 @@
package usersettingsrepo
import (
"context"
"database/sql"
)
type Repo struct {
db *sql.DB
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) SetTimezone(ctx context.Context, userID int64, zone string) error {
const q = `
INSERT INTO user_settings (user_id, timezone)
VALUES ($1, $2)
ON CONFLICT (user_id)
DO UPDATE SET timezone = EXCLUDED.timezone
`
_, err := r.db.ExecContext(ctx, q, userID, zone)
return err
}
func (r *Repo) GetTimezone(ctx context.Context, userID int64) (string, bool, error) {
const q = `
SELECT timezone
FROM user_settings
WHERE user_id = $1
`
row := r.db.QueryRowContext(ctx, q, userID)
var zone string
switch err := row.Scan(&zone); err {
case nil:
return zone, true, nil
case sql.ErrNoRows:
return "", false, nil
default:
return "", false, err
}
}
+111
View File
@@ -0,0 +1,111 @@
package welcomerepo
import (
"context"
"database/sql"
)
type Repo struct {
db *sql.DB
}
type Settings struct {
GuildID int64
ChannelID int64
WelcomeMessage string
WelcomeDM string
WelcomeGIFURL string
HasConfiguration bool
}
func NewRepo(db *sql.DB) *Repo {
return &Repo{db: db}
}
func (r *Repo) GetSettings(ctx context.Context, guildID int64) (*Settings, error) {
const q = `
SELECT welcome_channel_id, welcome_message, welcome_dm, welcome_gif_url
FROM welcome
WHERE guild_id = $1
`
row := r.db.QueryRowContext(ctx, q, guildID)
var ch sql.NullInt64
var msg, dm, gif sql.NullString
switch err := row.Scan(&ch, &msg, &dm, &gif); err {
case nil:
s := &Settings{
GuildID: guildID,
ChannelID: 0,
WelcomeMessage: "",
WelcomeDM: "",
WelcomeGIFURL: "",
HasConfiguration: true,
}
if ch.Valid {
s.ChannelID = ch.Int64
}
if msg.Valid {
s.WelcomeMessage = msg.String
}
if dm.Valid {
s.WelcomeDM = dm.String
}
if gif.Valid {
s.WelcomeGIFURL = gif.String
}
return s, nil
case sql.ErrNoRows:
return &Settings{
GuildID: guildID,
HasConfiguration: false,
}, nil
default:
return nil, err
}
}
func (r *Repo) UpsertChannel(ctx context.Context, guildID, channelID int64) error {
const q = `
INSERT INTO welcome (guild_id, welcome_channel_id)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET welcome_channel_id = EXCLUDED.welcome_channel_id
`
_, err := r.db.ExecContext(ctx, q, guildID, channelID)
return err
}
func (r *Repo) UpsertMessage(ctx context.Context, guildID int64, message string) error {
const q = `
INSERT INTO welcome (guild_id, welcome_message)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET welcome_message = EXCLUDED.welcome_message
`
_, err := r.db.ExecContext(ctx, q, guildID, message)
return err
}
func (r *Repo) UpsertDM(ctx context.Context, guildID int64, dm string) error {
const q = `
INSERT INTO welcome (guild_id, welcome_dm)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET welcome_dm = EXCLUDED.welcome_dm
`
_, err := r.db.ExecContext(ctx, q, guildID, dm)
return err
}
func (r *Repo) UpsertGIF(ctx context.Context, guildID int64, gifURL string) error {
const q = `
INSERT INTO welcome (guild_id, welcome_gif_url)
VALUES ($1, $2)
ON CONFLICT (guild_id)
DO UPDATE SET welcome_gif_url = EXCLUDED.welcome_gif_url
`
_, err := r.db.ExecContext(ctx, q, guildID, gifURL)
return err
}
@@ -0,0 +1,39 @@
// Package betasettings is where the beta server, the Beta Tester role and the
// servers that opted in to beta features are read and changed. The bot polls
// the same tables, so a change here reaches the beta gate within 30 seconds.
package betasettings
import (
"context"
"velox-bot/internal/db/repos/settingsrepo"
)
type Service struct {
settings *settingsrepo.Repo
}
func New(settings *settingsrepo.Repo) *Service {
return &Service{settings: settings}
}
// Get returns the beta server and role as ID strings ("" when not set).
func (s *Service) Get(ctx context.Context) (guildID, roleID string, err error) {
return s.settings.GetBetaSettings(ctx)
}
func (s *Service) SetServer(ctx context.Context, guildID, roleID, updatedBy int64) error {
return s.settings.SetBetaServer(ctx, guildID, roleID, updatedBy)
}
func (s *Service) OptedIn(ctx context.Context) ([]string, error) {
return s.settings.ListBetaGuilds(ctx)
}
func (s *Service) IsOptedIn(ctx context.Context, guildID int64) (bool, error) {
return s.settings.IsBetaGuild(ctx, guildID)
}
func (s *Service) SetOptedIn(ctx context.Context, guildID, by int64, on bool) error {
return s.settings.SetBetaGuild(ctx, guildID, by, on)
}
@@ -0,0 +1,24 @@
package defaultrole
import (
"context"
"velox-bot/internal/db/repos/defaultrolerepo"
)
type Service struct {
repo *defaultrolerepo.Repo
}
func New(repo *defaultrolerepo.Repo) *Service {
return &Service{repo: repo}
}
func (s *Service) GetRole(ctx context.Context, guildID int64) (int64, error) {
return s.repo.GetRole(ctx, guildID)
}
func (s *Service) SetRole(ctx context.Context, guildID, roleID int64) error {
return s.repo.SetRole(ctx, guildID, roleID)
}
@@ -55,3 +55,11 @@ func (s *Service) ListRoleRewards(ctx context.Context, guildID int64, limit int)
func (s *Service) IsLevelSystemEnabled(ctx context.Context, guildID int64) (bool, error) {
return s.settings.IsLevelSystemEnabled(ctx, guildID)
}
func (s *Service) DeleteRoleRewardForLevel(ctx context.Context, guildID int64, level int) (bool, error) {
return s.settings.DeleteRoleRewardForLevel(ctx, guildID, level)
}
func (s *Service) GetLevelUpChannelID(ctx context.Context, guildID int64) (int64, bool, error) {
return s.settings.GetLevelupChannelID(ctx, guildID)
}
@@ -0,0 +1,32 @@
package logsettings
import (
"context"
"velox-bot/internal/db/repos/settingsrepo"
)
type Service struct {
settings *settingsrepo.Repo
}
func New(settings *settingsrepo.Repo) *Service {
return &Service{settings: settings}
}
func (s *Service) SetChannel(ctx context.Context, guildID, channelID int64) error {
return s.settings.SetLogChannel(ctx, guildID, channelID)
}
func (s *Service) SetEnabled(ctx context.Context, guildID int64, enabled bool) error {
return s.settings.SetLogEnabled(ctx, guildID, enabled)
}
func (s *Service) GetSettings(ctx context.Context, guildID int64) (*settingsrepo.LogSettings, error) {
return s.settings.GetLogSettings(ctx, guildID)
}
func (s *Service) HasSettings(ctx context.Context, guildID int64) (bool, error) {
return s.settings.HasLogSettings(ctx, guildID)
}
+18 -4
View File
@@ -14,12 +14,26 @@ func New(settings *settingsrepo.Repo) *Service {
return &Service{settings: settings}
}
func (s *Service) SetLobbyChannel(ctx context.Context, guildID int64, lobbyChannelID int64) error {
return s.settings.SetMeetingLobbyChannel(ctx, guildID, lobbyChannelID)
// MaxLobbies is how many lobbies a server can have.
const MaxLobbies = settingsrepo.MaxMeetingLobbies
// ErrLobbyLimit means the server already has MaxLobbies.
var ErrLobbyLimit = settingsrepo.ErrMeetingLobbyLimit
func (s *Service) AddLobby(ctx context.Context, guildID, channelID int64) (added bool, err error) {
return s.settings.AddMeetingLobby(ctx, guildID, channelID)
}
func (s *Service) GetLobbyChannel(ctx context.Context, guildID int64) (channelID int64, ok bool, err error) {
return s.settings.GetMeetingLobbyChannel(ctx, guildID)
func (s *Service) RemoveLobby(ctx context.Context, guildID, channelID int64) (removed bool, err error) {
return s.settings.RemoveMeetingLobby(ctx, guildID, channelID)
}
func (s *Service) ListLobbies(ctx context.Context, guildID int64) ([]int64, error) {
return s.settings.ListMeetingLobbies(ctx, guildID)
}
func (s *Service) IsLobby(ctx context.Context, guildID, channelID int64) (bool, error) {
return s.settings.IsMeetingLobby(ctx, guildID, channelID)
}
func (s *Service) AddTempChannel(ctx context.Context, guildID, channelID, createdBy int64) error {
@@ -0,0 +1,32 @@
package musicsettings
import (
"context"
"velox-bot/internal/db/repos/settingsrepo"
)
type Service struct {
settings *settingsrepo.Repo
}
func New(settings *settingsrepo.Repo) *Service {
return &Service{settings: settings}
}
func (s *Service) ToggleMusic(ctx context.Context, guildID int64) (bool, error) {
enabled, err := s.settings.IsMusicEnabled(ctx, guildID)
if err != nil {
return false, err
}
newEnabled := !enabled
if err := s.settings.SetMusicEnabled(ctx, guildID, newEnabled); err != nil {
return false, err
}
return newEnabled, nil
}
func (s *Service) IsMusicEnabled(ctx context.Context, guildID int64) (bool, error) {
return s.settings.IsMusicEnabled(ctx, guildID)
}
+12
View File
@@ -26,7 +26,19 @@ func (s *Service) ListActiveWithMembers(ctx context.Context, guildID int64, limi
return s.repo.ListActiveProjectsWithMembers(ctx, guildID, limit)
}
func (s *Service) ListActive(ctx context.Context, guildID int64, limit int) ([]*projectsrepo.Project, error) {
return s.repo.ListActiveProjects(ctx, guildID, limit)
}
func (s *Service) ProjectExistsInGuild(ctx context.Context, guildID, projectID int64) (bool, error) {
return s.repo.ProjectExistsInGuild(ctx, guildID, projectID)
}
func (s *Service) GetProject(ctx context.Context, guildID, projectID int64) (*projectsrepo.Project, error) {
return s.repo.GetProject(ctx, guildID, projectID)
}
func (s *Service) DeactivateProject(ctx context.Context, guildID, projectID int64) error {
return s.repo.DeactivateProject(ctx, guildID, projectID)
}
+56
View File
@@ -0,0 +1,56 @@
package schedule
import (
"context"
"time"
"velox-bot/internal/db/repos/schedulerepo"
)
type Service struct {
repo *schedulerepo.Repo
}
func New(repo *schedulerepo.Repo) *Service {
return &Service{repo: repo}
}
func (s *Service) CreateSchedule(ctx context.Context, guildID, requesterID, inviteeID int64, when time.Time, description string) (int64, error) {
return s.repo.CreateSchedule(ctx, guildID, requesterID, inviteeID, when, description)
}
func (s *Service) UpdateStatus(ctx context.Context, scheduleID int64, status schedulerepo.ScheduleStatus) error {
return s.repo.UpdateStatus(ctx, scheduleID, status)
}
func (s *Service) ListForUser(ctx context.Context, guildID, userID int64, limit int) ([]*schedulerepo.Schedule, error) {
return s.repo.ListForUser(ctx, guildID, userID, limit)
}
func (s *Service) ListDueForReminder(ctx context.Context, now time.Time, ahead time.Duration) ([]*schedulerepo.Schedule, error) {
return s.repo.ListDueForReminder(ctx, now, ahead)
}
func (s *Service) MarkReminded(ctx context.Context, scheduleID int64) error {
return s.repo.MarkReminded(ctx, scheduleID)
}
func (s *Service) GetByID(ctx context.Context, id int64) (*schedulerepo.Schedule, error) {
return s.repo.GetByID(ctx, id)
}
func (s *Service) Reschedule(ctx context.Context, id int64, when time.Time) error {
return s.repo.Reschedule(ctx, id, when)
}
func (s *Service) ProposeReschedule(ctx context.Context, scheduleID int64, newTime time.Time, proposedBy int64) error {
return s.repo.ProposeReschedule(ctx, scheduleID, newTime, proposedBy)
}
func (s *Service) AcceptReschedule(ctx context.Context, id int64) error {
return s.repo.AcceptReschedule(ctx, id)
}
func (s *Service) DeclineReschedule(ctx context.Context, id int64) error {
return s.repo.DeclineReschedule(ctx, id)
}
+25 -1
View File
@@ -1,30 +1,54 @@
package services
import (
"velox-bot/internal/db/services/betasettings"
"velox-bot/internal/db/services/defaultrole"
"velox-bot/internal/db/services/level"
"velox-bot/internal/db/services/levelsettings"
"velox-bot/internal/db/services/logsettings"
"velox-bot/internal/db/services/meeting"
"velox-bot/internal/db/services/musicsettings"
"velox-bot/internal/db/services/projects"
"velox-bot/internal/db/services/rps"
"velox-bot/internal/db/services/schedule"
"velox-bot/internal/db/services/twitch"
"velox-bot/internal/db/services/usersettings"
"velox-bot/internal/db/services/welcome"
)
type Services struct {
Level *level.Service
LevelSettings *levelsettings.Service
Meeting *meeting.Service
Schedule *schedule.Service
UserSettings *usersettings.Service
Projects *projects.Service
RPS *rps.Service
Twitch *twitch.Service
Welcome *welcome.Service
DefaultRole *defaultrole.Service
LogSettings *logsettings.Service
MusicSettings *musicsettings.Service
BetaSettings *betasettings.Service
}
var Global *Services
func NewServices(level *level.Service, levelSettings *levelsettings.Service, meeting *meeting.Service, projects *projects.Service, rps *rps.Service) *Services {
func NewServices(level *level.Service, levelSettings *levelsettings.Service, meeting *meeting.Service, schedule *schedule.Service, userSettings *usersettings.Service, projects *projects.Service, rps *rps.Service, twitchSvc *twitch.Service, welcomeSvc *welcome.Service, defaultRoleSvc *defaultrole.Service, logSettingsSvc *logsettings.Service, musicSvc *musicsettings.Service, betaSvc *betasettings.Service) *Services {
s := &Services{
Level: level,
LevelSettings: levelSettings,
Meeting: meeting,
Schedule: schedule,
UserSettings: userSettings,
Projects: projects,
RPS: rps,
Twitch: twitchSvc,
Welcome: welcomeSvc,
DefaultRole: defaultRoleSvc,
LogSettings: logSettingsSvc,
MusicSettings: musicSvc,
BetaSettings: betaSvc,
}
Global = s
return s
+117
View File
@@ -0,0 +1,117 @@
package twitch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"velox-bot/internal/db/repos/twitchrepo"
)
type Service struct {
repo *twitchrepo.Repo
client *http.Client
twitchClient string
}
func New(repo *twitchrepo.Repo, twitchClientID string) *Service {
return &Service{
repo: repo,
client: &http.Client{
Timeout: 5 * time.Second,
},
twitchClient: twitchClientID,
}
}
func (s *Service) ListGuilds(ctx context.Context) ([]int64, error) {
return s.repo.ListGuilds(ctx)
}
func (s *Service) ListUsersForGuild(ctx context.Context, guildID int64) ([]string, error) {
return s.repo.ListUsersForGuild(ctx, guildID)
}
func (s *Service) GetStatus(ctx context.Context, guildID int64, username string) (string, bool, error) {
return s.repo.GetStatus(ctx, guildID, username)
}
func (s *Service) UpdateStatus(ctx context.Context, guildID int64, username, status string) error {
return s.repo.UpdateStatus(ctx, guildID, username, status)
}
func (s *Service) UpsertStreamer(ctx context.Context, guildID int64, username string) error {
return s.repo.UpsertStreamer(ctx, guildID, username)
}
func (s *Service) RemoveStreamer(ctx context.Context, guildID int64, username string) error {
return s.repo.RemoveStreamer(ctx, guildID, username)
}
func (s *Service) GetNotificationChannel(ctx context.Context, guildID int64) (int64, bool, error) {
return s.repo.GetNotificationChannel(ctx, guildID)
}
func (s *Service) SetNotificationChannel(ctx context.Context, guildID, channelID int64) error {
return s.repo.SetNotificationChannel(ctx, guildID, channelID)
}
func (s *Service) IsEnabled(ctx context.Context, guildID int64) (bool, error) {
return s.repo.IsEnabled(ctx, guildID)
}
func (s *Service) SetEnabled(ctx context.Context, guildID int64, enabled bool) error {
return s.repo.SetEnabled(ctx, guildID, enabled)
}
func (s *Service) IsUserStreaming(ctx context.Context, username string) (bool, error) {
type gqlRequest struct {
Query string `json:"query"`
Variables map[string]any `json:"variables"`
}
type gqlResponse struct {
Data struct {
User *struct {
Stream *struct {
ID string `json:"id"`
} `json:"stream"`
} `json:"user"`
} `json:"data"`
}
q := fmt.Sprintf(`query { user(login: "%s") { stream { id } } }`, username)
body, err := json.Marshal(gqlRequest{
Query: q,
Variables: map[string]any{},
})
if err != nil {
return false, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://gql.twitch.tv/gql", bytes.NewReader(body))
if err != nil {
return false, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Client-Id", s.twitchClient)
resp, err := s.client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
var respBody gqlResponse
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
return false, err
}
if respBody.Data.User == nil {
return false, nil
}
return respBody.Data.User.Stream != nil, nil
}
@@ -0,0 +1,42 @@
package usersettings
import (
"context"
"time"
"velox-bot/internal/db/repos/usersettingsrepo"
)
type Service struct {
repo *usersettingsrepo.Repo
}
func New(repo *usersettingsrepo.Repo) *Service {
return &Service{repo: repo}
}
func (s *Service) SetTimezone(ctx context.Context, userID int64, zone string) error {
// validate zone before storing
if _, err := time.LoadLocation(zone); err != nil {
return err
}
return s.repo.SetTimezone(ctx, userID, zone)
}
// GetTimezone returns the user's location (or UTC) and the zone string and a flag indicating if it was user-defined.
func (s *Service) GetTimezone(ctx context.Context, userID int64) (*time.Location, string, bool, error) {
zone, ok, err := s.repo.GetTimezone(ctx, userID)
if err != nil {
return time.UTC, "UTC", false, err
}
if !ok || zone == "" {
return time.UTC, "UTC", false, nil
}
loc, err := time.LoadLocation(zone)
if err != nil {
// fallback to UTC but indicate not user-defined
return time.UTC, "UTC", false, nil
}
return loc, zone, true, nil
}
+36
View File
@@ -0,0 +1,36 @@
package welcome
import (
"context"
"velox-bot/internal/db/repos/welcomerepo"
)
type Service struct {
repo *welcomerepo.Repo
}
func New(repo *welcomerepo.Repo) *Service {
return &Service{repo: repo}
}
func (s *Service) GetSettings(ctx context.Context, guildID int64) (*welcomerepo.Settings, error) {
return s.repo.GetSettings(ctx, guildID)
}
func (s *Service) SetChannel(ctx context.Context, guildID, channelID int64) error {
return s.repo.UpsertChannel(ctx, guildID, channelID)
}
func (s *Service) SetMessage(ctx context.Context, guildID int64, message string) error {
return s.repo.UpsertMessage(ctx, guildID, message)
}
func (s *Service) SetDM(ctx context.Context, guildID int64, dm string) error {
return s.repo.UpsertDM(ctx, guildID, dm)
}
func (s *Service) SetGIF(ctx context.Context, guildID int64, gifURL string) error {
return s.repo.UpsertGIF(ctx, guildID, gifURL)
}
+2
View File
@@ -11,6 +11,8 @@ import (
)
func HandleMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate, services *services.Services) {
CacheMessageFromCreate(m)
if m.Author.Bot || m.GuildID == "" {
return
}
+376
View File
@@ -0,0 +1,376 @@
package events
import (
"fmt"
"log"
"slices"
"strings"
"sync"
"time"
"velox-bot/internal/db/services"
"velox-bot/internal/modlog"
"github.com/bwmarrin/discordgo"
)
type cachedMessage struct {
Content string
AuthorID string
}
var messageCache sync.Map // map[messageID]cachedMessage
func HandleMessageUpdateLog(s *discordgo.Session, m *discordgo.MessageUpdate, svc *services.Services) {
if s == nil || m == nil || m.Message == nil || m.GuildID == "" || svc == nil {
return
}
if m.Author != nil && m.Author.Bot {
return
}
before := ""
if m.BeforeUpdate != nil {
before = strings.TrimSpace(m.BeforeUpdate.Content)
}
if before == "" {
if prev, ok := getCachedMessage(m.ID); ok {
before = strings.TrimSpace(prev.Content)
}
}
after := strings.TrimSpace(m.Content)
if before == after {
return
}
jumpURL := fmt.Sprintf("https://discord.com/channels/%s/%s/%s", m.GuildID, m.ChannelID, m.ID)
authorMention := "Unknown"
if m.Author != nil {
authorMention = m.Author.Mention()
}
embed := &discordgo.MessageEmbed{
Title: "Message Edited",
Color: 0xF1C40F,
Description: fmt.Sprintf("Author: %s\nChannel: <#%s>\n[Jump to message](%s)", authorMention, m.ChannelID, jumpURL),
Fields: []*discordgo.MessageEmbedField{
{Name: "Before", Value: truncateOrPlaceholder(before), Inline: false},
{Name: "After", Value: truncateOrPlaceholder(after), Inline: false},
},
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send message edit log: %v", err)
}
cacheMessage(m.ID, after, authorIDOrEmpty(m.Author))
}
func HandleMessageDeleteLog(s *discordgo.Session, m *discordgo.MessageDelete, svc *services.Services) {
if s == nil || m == nil || m.Message == nil || m.GuildID == "" || svc == nil {
return
}
authorID := ""
authorLabel := "Unknown"
content := ""
if m.BeforeDelete != nil {
if m.BeforeDelete.Author != nil {
authorID = m.BeforeDelete.Author.ID
authorLabel = m.BeforeDelete.Author.Mention()
}
content = strings.TrimSpace(m.BeforeDelete.Content)
}
if content == "" {
if prev, ok := getCachedMessage(m.ID); ok {
content = strings.TrimSpace(prev.Content)
if authorID == "" && prev.AuthorID != "" {
authorID = prev.AuthorID
authorLabel = "<@" + prev.AuthorID + ">"
}
}
}
if authorID == "" && m.Author != nil {
authorID = m.Author.ID
authorLabel = m.Author.Mention()
}
if authorID == "" {
authorLabel = "Unknown"
}
embed := &discordgo.MessageEmbed{
Title: "Message Deleted",
Color: 0xE74C3C,
Description: fmt.Sprintf("Author: %s\nChannel: <#%s>\nMessage ID: `%s`", authorLabel, m.ChannelID, m.ID),
Fields: []*discordgo.MessageEmbedField{
{Name: "Content", Value: truncateOrPlaceholder(content), Inline: false},
},
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send message delete log: %v", err)
}
deleteCachedMessage(m.ID)
}
func HandleGuildMemberAddLog(s *discordgo.Session, m *discordgo.GuildMemberAdd, svc *services.Services) {
if s == nil || m == nil || m.Member == nil || m.User == nil || m.GuildID == "" || svc == nil {
return
}
embed := &discordgo.MessageEmbed{
Title: "Member Joined",
Color: 0x2ECC71,
Description: fmt.Sprintf("%s joined the server.\nUser ID: `%s`", m.User.Mention(), m.User.ID),
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send member join log: %v", err)
}
}
func HandleGuildMemberRemoveLog(s *discordgo.Session, m *discordgo.GuildMemberRemove, svc *services.Services) {
if s == nil || m == nil || m.Member == nil || m.User == nil || m.GuildID == "" || svc == nil {
return
}
// Try to classify this leave as a kick via recent audit log.
kickEntry, kickMod := findRecentAuditEntryForTarget(s, m.GuildID, m.User.ID, discordgo.AuditLogActionMemberKick)
title := "Member Left"
color := 0x95A5A6
description := fmt.Sprintf("%s left the server.\nUser ID: `%s`", m.User.Mention(), m.User.ID)
if kickEntry != nil {
title = "Member Kicked"
color = 0xE67E22
description = fmt.Sprintf("%s was kicked.\nUser ID: `%s`", m.User.Mention(), m.User.ID)
if kickMod != nil {
description += "\nModerator: " + kickMod.Mention()
}
if strings.TrimSpace(kickEntry.Reason) != "" {
description += "\nReason: " + kickEntry.Reason
}
}
embed := &discordgo.MessageEmbed{
Title: title,
Color: color,
Description: description,
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send member remove log: %v", err)
}
}
func HandleGuildMemberUpdateLog(s *discordgo.Session, m *discordgo.GuildMemberUpdate, svc *services.Services) {
if s == nil || m == nil || m.Member == nil || m.User == nil || m.GuildID == "" || svc == nil || m.BeforeUpdate == nil {
return
}
added := diffRoleIDs(m.BeforeUpdate.Roles, m.Roles)
removed := diffRoleIDs(m.Roles, m.BeforeUpdate.Roles)
if len(added) == 0 && len(removed) == 0 {
return
}
fields := make([]*discordgo.MessageEmbedField, 0, 2)
if len(added) > 0 {
fields = append(fields, &discordgo.MessageEmbedField{
Name: "Roles Added",
Value: joinRoleMentions(added),
Inline: false,
})
}
if len(removed) > 0 {
fields = append(fields, &discordgo.MessageEmbedField{
Name: "Roles Removed",
Value: joinRoleMentions(removed),
Inline: false,
})
}
embed := &discordgo.MessageEmbed{
Title: "Member Roles Updated",
Color: 0x3498DB,
Description: fmt.Sprintf("Member: %s (`%s`)", m.User.Mention(), m.User.ID),
Fields: fields,
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send member update log: %v", err)
}
}
func HandleGuildBanAddLog(s *discordgo.Session, m *discordgo.GuildBanAdd, svc *services.Services) {
if s == nil || m == nil || m.User == nil || m.GuildID == "" || svc == nil {
return
}
entry, moderator := findRecentAuditEntryForTarget(s, m.GuildID, m.User.ID, discordgo.AuditLogActionMemberBanAdd)
desc := fmt.Sprintf("%s was banned.\nUser ID: `%s`", m.User.Mention(), m.User.ID)
if moderator != nil {
desc += "\nModerator: " + moderator.Mention()
}
if entry != nil && strings.TrimSpace(entry.Reason) != "" {
desc += "\nReason: " + entry.Reason
}
embed := &discordgo.MessageEmbed{
Title: "Member Banned",
Color: 0xC0392B,
Description: desc,
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send ban add log: %v", err)
}
}
func HandleGuildBanRemoveLog(s *discordgo.Session, m *discordgo.GuildBanRemove, svc *services.Services) {
if s == nil || m == nil || m.User == nil || m.GuildID == "" || svc == nil {
return
}
entry, moderator := findRecentAuditEntryForTarget(s, m.GuildID, m.User.ID, discordgo.AuditLogActionMemberBanRemove)
desc := fmt.Sprintf("%s was unbanned.\nUser ID: `%s`", m.User.Mention(), m.User.ID)
if moderator != nil {
desc += "\nModerator: " + moderator.Mention()
}
if entry != nil && strings.TrimSpace(entry.Reason) != "" {
desc += "\nReason: " + entry.Reason
}
embed := &discordgo.MessageEmbed{
Title: "Member Unbanned",
Color: 0x27AE60,
Description: desc,
Timestamp: time.Now().Format(time.RFC3339),
}
if err := modlog.Send(s, svc, m.GuildID, embed); err != nil {
log.Printf("log: failed to send ban remove log: %v", err)
}
}
func findRecentAuditEntryForTarget(s *discordgo.Session, guildID, targetID string, action discordgo.AuditLogAction) (*discordgo.AuditLogEntry, *discordgo.User) {
if s == nil || guildID == "" || targetID == "" {
return nil, nil
}
logs, err := s.GuildAuditLog(guildID, "", "", int(action), 10)
if err != nil || logs == nil {
return nil, nil
}
var chosen *discordgo.AuditLogEntry
now := time.Now().UTC()
for _, e := range logs.AuditLogEntries {
if e == nil || e.TargetID != targetID || e.ActionType == nil || *e.ActionType != action {
continue
}
ts, err := discordgo.SnowflakeTimestamp(e.ID)
if err != nil {
continue
}
// Keep only very recent entries to reduce false positives.
if now.Sub(ts) > 2*time.Minute {
continue
}
chosen = e
break
}
if chosen == nil {
return nil, nil
}
for _, u := range logs.Users {
if u != nil && u.ID == chosen.UserID {
return chosen, u
}
}
return chosen, nil
}
func truncateOrPlaceholder(s string) string {
v := strings.TrimSpace(s)
if v == "" {
return "*empty*"
}
if len(v) <= 1000 {
return v
}
return v[:997] + "..."
}
func diffRoleIDs(base, compare []string) []string {
out := make([]string, 0)
for _, id := range base {
if id == "" {
continue
}
if !slices.Contains(compare, id) {
out = append(out, id)
}
}
return out
}
func joinRoleMentions(roleIDs []string) string {
if len(roleIDs) == 0 {
return "*none*"
}
const max = 12
parts := make([]string, 0, len(roleIDs))
for idx, id := range roleIDs {
if idx >= max {
parts = append(parts, fmt.Sprintf("... and %d more", len(roleIDs)-max))
break
}
parts = append(parts, "<@&"+id+">")
}
return strings.Join(parts, ", ")
}
func CacheMessageFromCreate(m *discordgo.MessageCreate) {
if m == nil || m.Message == nil || m.ID == "" {
return
}
cacheMessage(m.ID, strings.TrimSpace(m.Content), authorIDOrEmpty(m.Author))
}
func cacheMessage(messageID, content, authorID string) {
if messageID == "" {
return
}
messageCache.Store(messageID, cachedMessage{
Content: content,
AuthorID: authorID,
})
}
func getCachedMessage(messageID string) (cachedMessage, bool) {
if messageID == "" {
return cachedMessage{}, false
}
raw, ok := messageCache.Load(messageID)
if !ok {
return cachedMessage{}, false
}
msg, ok := raw.(cachedMessage)
if !ok {
return cachedMessage{}, false
}
return msg, true
}
func deleteCachedMessage(messageID string) {
if messageID == "" {
return
}
messageCache.Delete(messageID)
}
func authorIDOrEmpty(u *discordgo.User) string {
if u == nil {
return ""
}
return u.ID
}
+23 -4
View File
@@ -13,7 +13,7 @@ import (
)
// HandleVoiceStateUpdate implements the "meeting lobby" behavior:
// - When a user joins the configured lobby voice channel, create a temporary voice channel
// - When a user joins one of the server's lobby voice channels, create a temporary voice channel
// with the same UserLimit and move the user into it.
// - When a temporary channel becomes empty, delete it.
func HandleVoiceStateUpdate(s *discordgo.Session, vs *discordgo.VoiceStateUpdate, svc *services.Services) {
@@ -40,11 +40,12 @@ func HandleVoiceStateUpdate(s *discordgo.Session, vs *discordgo.VoiceStateUpdate
return
}
lobbyID, ok, err := svc.Meeting.GetLobbyChannel(ctx, guildID64)
if err != nil || !ok || lobbyID == 0 {
joinedID, err := strconv.ParseInt(vs.ChannelID, 10, 64)
if err != nil {
return
}
if vs.ChannelID != strconv.FormatInt(lobbyID, 10) {
isLobby, err := svc.Meeting.IsLobby(ctx, guildID64, joinedID)
if err != nil || !isLobby {
return
}
@@ -114,3 +115,21 @@ func tryCleanupTempChannel(s *discordgo.Session, ctx context.Context, svc *servi
_ = svc.Meeting.RemoveTempChannel(ctx, guildID64, chID64)
}
// HandleChannelDelete drops a deleted voice channel from the meeting lobbies,
// so it doesn't keep using up one of the server's slots.
func HandleChannelDelete(_ *discordgo.Session, c *discordgo.ChannelDelete, svc *services.Services) {
if svc == nil || svc.Meeting == nil || c == nil || c.Channel == nil || c.GuildID == "" {
return
}
if c.Type != discordgo.ChannelTypeGuildVoice {
return
}
guildID, err1 := strconv.ParseInt(c.GuildID, 10, 64)
channelID, err2 := strconv.ParseInt(c.ID, 10, 64)
if err1 != nil || err2 != nil {
return
}
if _, err := svc.Meeting.RemoveLobby(context.Background(), guildID, channelID); err != nil {
log.Printf("meeting: removing deleted lobby guild=%s channel=%s err=%v", c.GuildID, c.ID, err)
}
}
+163
View File
@@ -0,0 +1,163 @@
package events
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// HandleBotAddedOnGuild applies safe defaults when this bot is added to a guild
// and DMs setup instructions to the inviter (or guild owner fallback).
func HandleBotAddedOnGuild(s *discordgo.Session, m *discordgo.GuildMemberAdd, svc *services.Services) {
if s == nil || m == nil || m.Member == nil || m.User == nil || svc == nil {
return
}
if s.State == nil || s.State.User == nil {
return
}
if m.User.ID != s.State.User.ID {
return
}
guildID64, err := strconv.ParseInt(m.GuildID, 10, 64)
if err != nil {
return
}
// Treat an existing logsettings row as "already onboarded once".
alreadyOnboarded := false
if svc.LogSettings != nil {
exists, err := svc.LogSettings.HasSettings(context.Background(), guildID64)
if err == nil {
alreadyOnboarded = exists
}
}
if alreadyOnboarded {
return
}
// Explicitly disable toggleable systems by default.
if svc.LevelSettings != nil {
if err := svc.LevelSettings.SetLevelSystemEnabled(context.Background(), guildID64, false); err != nil {
log.Printf("onboarding: failed to set default level state for guild %s: %v", m.GuildID, err)
}
}
if svc.LogSettings != nil {
if err := svc.LogSettings.SetEnabled(context.Background(), guildID64, false); err != nil {
log.Printf("onboarding: failed to set default log state for guild %s: %v", m.GuildID, err)
}
}
recipientID := findRecentBotAdderID(s, m.GuildID)
if recipientID == "" {
recipientID = guildOwnerID(s, m.GuildID)
}
if recipientID == "" {
log.Printf("onboarding: unable to resolve DM recipient for guild %s", m.GuildID)
return
}
dmCh, err := s.UserChannelCreate(recipientID)
if err != nil {
log.Printf("onboarding: failed creating DM for user %s: %v", recipientID, err)
return
}
guildName := m.GuildID
if g, err := s.State.Guild(m.GuildID); err == nil && g != nil && strings.TrimSpace(g.Name) != "" {
guildName = g.Name
} else if g, err := s.Guild(m.GuildID); err == nil && g != nil && strings.TrimSpace(g.Name) != "" {
guildName = g.Name
}
embed := &discordgo.MessageEmbed{
Title: "Thanks for adding Velox Bot!",
Color: 0x5865F2,
Description: fmt.Sprintf(
"Server: **%s**\n\nFor safety, toggleable systems start **disabled by default**.\nUse these commands in your server to enable features:",
guildName,
),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Level System",
Value: "`/slvl toggle`",
Inline: false,
},
{
Name: "Logging System",
Value: "" +
"`/config setlogchannel channel:#channel`\n" +
"`/config enablelogging`",
Inline: false,
},
{
Name: "Welcome System",
Value: "" +
"`/config setwelcomechannel channel:#channel`\n" +
"`/config setwelcomemessage message:\"...\"`\n" +
"`/config setwelcomedm message:\"...\"`",
Inline: false,
},
},
Footer: &discordgo.MessageEmbedFooter{
Text: "Tip: run /help in any server channel for the full command reference.",
},
Timestamp: time.Now().Format(time.RFC3339),
}
if _, err := s.ChannelMessageSendEmbed(dmCh.ID, embed); err != nil {
log.Printf("onboarding: failed sending setup DM to user %s: %v", recipientID, err)
}
}
func findRecentBotAdderID(s *discordgo.Session, guildID string) string {
if s == nil || s.State == nil || s.State.User == nil {
return ""
}
logs, err := s.GuildAuditLog(guildID, "", "", int(discordgo.AuditLogActionBotAdd), 10)
if err != nil || logs == nil {
return ""
}
botID := s.State.User.ID
now := time.Now().UTC()
for _, entry := range logs.AuditLogEntries {
if entry == nil || entry.TargetID != botID || entry.ActionType == nil || *entry.ActionType != discordgo.AuditLogActionBotAdd {
continue
}
ts, err := discordgo.SnowflakeTimestamp(entry.ID)
if err != nil {
continue
}
if now.Sub(ts) > 10*time.Minute {
continue
}
if entry.UserID != "" {
return entry.UserID
}
}
return ""
}
func guildOwnerID(s *discordgo.Session, guildID string) string {
if s == nil || guildID == "" {
return ""
}
if s.State != nil {
if g, err := s.State.Guild(guildID); err == nil && g != nil && g.OwnerID != "" {
return g.OwnerID
}
}
if g, err := s.Guild(guildID); err == nil && g != nil {
return g.OwnerID
}
return ""
}
+107
View File
@@ -0,0 +1,107 @@
package events
import (
"context"
"fmt"
"log"
"strconv"
"time"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// StartScheduleReminderLoop runs a background loop that periodically checks for
// upcoming sessions and sends DM reminders to all participants.
func StartScheduleReminderLoop(s *discordgo.Session, svc *services.Services) {
if svc == nil || svc.Schedule == nil || s == nil {
return
}
const (
interval = time.Minute // check every minute
remindBefore = 10 * time.Minute // remind 10 minutes before
initialDelay = 10 * time.Second
)
go func() {
// small delay so the bot can fully start
time.Sleep(initialDelay)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
now := time.Now().UTC()
ctx := context.Background()
// Find all sessions that start in the next `remindBefore` window and haven't been reminded.
schedules, err := svc.Schedule.ListDueForReminder(ctx, now, remindBefore)
if err != nil {
log.Printf("schedule: reminder query failed: %v", err)
continue
}
for _, sch := range schedules {
if sch == nil {
continue
}
utcStr := sch.ScheduledAt.UTC().Format("2006-01-02 15:04")
desc := sch.Description
// Notify requester with local time if available.
if svc.UserSettings != nil {
locReq, zoneReq, _, err := svc.UserSettings.GetTimezone(ctx, sch.RequesterID)
if err != nil {
locReq = sch.ScheduledAt.UTC().Location()
zoneReq = "UTC"
}
localReq := sch.ScheduledAt.In(locReq).Format("2006-01-02 15:04")
base := fmt.Sprintf("Reminder: you have a scheduled session at %s UTC (%s %s) with <@%d>.", utcStr, localReq, zoneReq, sch.InviteeID)
if desc != "" {
base += "\nTopic: " + desc
}
if err := dmUser(s, sch.RequesterID, base); err != nil {
log.Printf("schedule: failed to DM requester reminder: %v", err)
}
}
// Notify invitee with their local time if available.
if svc.UserSettings != nil {
locInv, zoneInv, _, err := svc.UserSettings.GetTimezone(ctx, sch.InviteeID)
if err != nil {
locInv = sch.ScheduledAt.UTC().Location()
zoneInv = "UTC"
}
localInv := sch.ScheduledAt.In(locInv).Format("2006-01-02 15:04")
baseInvitee := fmt.Sprintf("Reminder: you have a scheduled session at %s UTC (%s %s) with <@%d>.", utcStr, localInv, zoneInv, sch.RequesterID)
if desc != "" {
baseInvitee += "\nTopic: " + desc
}
if err := dmUser(s, sch.InviteeID, baseInvitee); err != nil {
log.Printf("schedule: failed to DM invitee reminder: %v", err)
}
}
if err := svc.Schedule.MarkReminded(ctx, sch.ID); err != nil {
log.Printf("schedule: failed to mark reminder sent for id=%d: %v", sch.ID, err)
}
}
}
}()
}
func dmUser(s *discordgo.Session, userID int64, content string) error {
if s == nil || userID == 0 {
return nil
}
uid := strconv.FormatInt(userID, 10)
ch, err := s.UserChannelCreate(uid)
if err != nil {
return err
}
_, err = s.ChannelMessageSend(ch.ID, content)
return err
}
+144
View File
@@ -0,0 +1,144 @@
package events
import (
"context"
"log"
"strconv"
"time"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// StartTwitchLiveLoop periodically checks configured Twitch streamers and
// sends live notifications to the configured channel.
func StartTwitchLiveLoop(s *discordgo.Session, svc *services.Services) {
if svc == nil || svc.Twitch == nil || s == nil {
return
}
const (
interval = 30 * time.Second
initialDelay = 10 * time.Second
)
go func() {
time.Sleep(initialDelay)
log.Printf("twitch: starting live notification loop (interval=%s)", interval)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
ctx := context.Background()
guildIDs, err := svc.Twitch.ListGuilds(ctx)
if err != nil {
log.Printf("twitch: failed to list guilds: %v", err)
continue
}
if len(guildIDs) == 0 {
log.Printf("twitch: no guilds with configured streamers")
}
for _, guildID := range guildIDs {
log.Printf("twitch: processing guild %d", guildID)
enabled, err := svc.Twitch.IsEnabled(ctx, guildID)
if err != nil {
log.Printf("twitch: failed to check enabled state for guild %d: %v", guildID, err)
continue
}
if !enabled {
log.Printf("twitch: notifications disabled for guild %d", guildID)
continue
}
channelID, ok, err := svc.Twitch.GetNotificationChannel(ctx, guildID)
if err != nil {
log.Printf("twitch: failed to get channel for guild %d: %v", guildID, err)
continue
}
if !ok || channelID == 0 {
log.Printf("twitch: no notification channel configured for guild %d", guildID)
continue
}
users, err := svc.Twitch.ListUsersForGuild(ctx, guildID)
if err != nil {
log.Printf("twitch: failed to list users for guild %d: %v", guildID, err)
continue
}
if len(users) == 0 {
log.Printf("twitch: no streamers configured for guild %d", guildID)
continue
}
chIDStr := strconv.FormatInt(channelID, 10)
for _, username := range users {
log.Printf("twitch: checking live status for guild %d, user %s", guildID, username)
isLive, err := svc.Twitch.IsUserStreaming(ctx, username)
if err != nil {
log.Printf("twitch: failed to check stream for %s: %v", username, err)
continue
}
status, ok, err := svc.Twitch.GetStatus(ctx, guildID, username)
if err != nil {
log.Printf("twitch: failed to get status for %s: %v", username, err)
continue
}
if !ok {
status = "not live"
}
if isLive {
if status == "not live" {
log.Printf("twitch: %s went live in guild %d, sending notification to channel %s", username, guildID, chIDStr)
liveURL := "https://www.twitch.tv/" + username
content := "@everyone"
previewURL := "https://static-cdn.jtvnw.net/previews-ttv/live_user_" + username + "-640x360.jpg"
embed := &discordgo.MessageEmbed{
Title: ":red_circle: " + username + " is now LIVE on Twitch!",
Description: "Click the link below to watch the stream.",
URL: liveURL,
Color: 0x9146FF, // Twitch purple
Image: &discordgo.MessageEmbedImage{
URL: previewURL,
},
}
if _, err := s.ChannelMessageSendComplex(chIDStr, &discordgo.MessageSend{
Content: content,
Embed: embed,
}); err != nil {
log.Printf("twitch: failed to send notification for %s: %v", username, err)
continue
}
if err := svc.Twitch.UpdateStatus(ctx, guildID, username, "live"); err != nil {
log.Printf("twitch: failed to update status to live for %s in guild %d: %v", username, guildID, err)
}
}
} else {
if status != "not live" {
log.Printf("twitch: %s is no longer live in guild %d, updating status", username, guildID)
if err := svc.Twitch.UpdateStatus(ctx, guildID, username, "not live"); err != nil {
log.Printf("twitch: failed to update status to not live for %s in guild %d: %v", username, guildID, err)
}
}
}
}
}
}
}()
}
+133
View File
@@ -0,0 +1,133 @@
package events
import (
"context"
"log"
"strconv"
"strings"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
// HandleGuildMemberAdd sends a configurable welcome message in a guild channel
// and an optional configurable DM to the joining user.
func HandleGuildMemberAdd(s *discordgo.Session, m *discordgo.GuildMemberAdd, svc *services.Services) {
if s == nil || m == nil || svc == nil || svc.Welcome == nil {
return
}
if m.User == nil {
return
}
ctx := context.Background()
guildID := mustParseInt64(m.GuildID)
settings, err := svc.Welcome.GetSettings(ctx, guildID)
if err != nil {
log.Printf("welcome: failed to load settings for guild %s: %v", m.GuildID, err)
return
}
hasWelcomeChannel := settings != nil && settings.ChannelID != 0
memberMention := m.User.Mention()
// Resolve guild/server name and user avatar for placeholders / visuals.
guildName := ""
userAvatarURL := ""
if g, err := s.State.Guild(m.GuildID); err == nil && g != nil {
guildName = g.Name
} else if g, err := s.Guild(m.GuildID); err == nil && g != nil {
guildName = g.Name
}
if m.User.Avatar != "" {
userAvatarURL = discordgo.EndpointUserAvatar(m.User.ID, m.User.Avatar)
}
if hasWelcomeChannel {
// Build guild welcome message.
channelID := strconv.FormatInt(settings.ChannelID, 10)
welcomeMsg := strings.TrimSpace(settings.WelcomeMessage)
if welcomeMsg == "" {
// Default message when none configured.
// "<user>! Welcome to <server>! Have fun!"
welcomeMsg = "<user>! Welcome to <server>! Have fun!"
}
welcomeMsg = strings.ReplaceAll(welcomeMsg, "{user}", memberMention)
if guildName != "" {
welcomeMsg = strings.ReplaceAll(welcomeMsg, "{server}", guildName)
welcomeMsg = strings.ReplaceAll(welcomeMsg, "<server>", guildName)
}
welcomeMsg = strings.ReplaceAll(welcomeMsg, "<user>", memberMention)
embed := &discordgo.MessageEmbed{
Title: "👋 Welcome!",
Description: welcomeMsg,
Color: 0xFFA500,
Footer: &discordgo.MessageEmbedFooter{
Text: "ID: " + m.User.ID,
},
}
if userAvatarURL != "" {
embed.Author = &discordgo.MessageEmbedAuthor{
Name: m.User.Username,
IconURL: userAvatarURL,
}
embed.Thumbnail = &discordgo.MessageEmbedThumbnail{
URL: userAvatarURL,
}
}
gif := strings.TrimSpace(settings.WelcomeGIFURL)
if gif == "" {
// Default GIF when none configured.
gif = "https://images-ext-1.discordapp.net/external/uJ6XfdK2WwDnei3RmNWUqSiOVboC4mK9r78TtgVE_9g/https/media.giphy.com/media/XD9o33QG9BoMis7iM4/giphy.gif"
}
embed.Image = &discordgo.MessageEmbedImage{URL: gif}
if _, err := s.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{
Content: memberMention,
Embed: embed,
}); err != nil {
log.Printf("welcome: failed to send channel welcome in guild %s: %v", m.GuildID, err)
}
}
// Optional DM.
dmText := ""
if settings != nil {
dmText = strings.TrimSpace(settings.WelcomeDM)
}
if dmText == "" {
// Default DM when none configured.
// "Welcome to <server>! Have fun!"
dmText = "Welcome to <server>! Have fun!"
}
dmText = strings.ReplaceAll(dmText, "{user}", memberMention)
if guildName != "" {
dmText = strings.ReplaceAll(dmText, "{server}", guildName)
dmText = strings.ReplaceAll(dmText, "<server>", guildName)
}
dmCh, err := s.UserChannelCreate(m.User.ID)
if err != nil {
log.Printf("welcome: failed to create DM channel for user %s: %v", m.User.ID, err)
return
}
if _, err := s.ChannelMessageSend(dmCh.ID, dmText); err != nil {
log.Printf("welcome: failed to send DM welcome to user %s: %v", m.User.ID, err)
}
// Default role assignment.
if svc.DefaultRole != nil {
roleID, err := svc.DefaultRole.GetRole(ctx, guildID)
if err != nil {
log.Printf("defaultrole: failed to get default role for guild %s: %v", m.GuildID, err)
} else if roleID != 0 {
if err := s.GuildMemberRoleAdd(m.GuildID, m.User.ID, strconv.FormatInt(roleID, 10)); err != nil {
log.Printf("defaultrole: failed to assign role %d to user %s in guild %s: %v", roleID, m.User.ID, m.GuildID, err)
}
}
}
}
+30
View File
@@ -0,0 +1,30 @@
package modlog
import (
"context"
"strconv"
"velox-bot/internal/db/services"
"github.com/bwmarrin/discordgo"
)
func Send(s *discordgo.Session, svc *services.Services, guildID string, embed *discordgo.MessageEmbed) error {
if s == nil || svc == nil || svc.LogSettings == nil || embed == nil || guildID == "" {
return nil
}
gid, err := strconv.ParseInt(guildID, 10, 64)
if err != nil {
return nil
}
cfg, err := svc.LogSettings.GetSettings(context.Background(), gid)
if err != nil || cfg == nil || !cfg.IsEnabled || cfg.ChannelID == 0 {
return err
}
_, err = s.ChannelMessageSendEmbed(strconv.FormatInt(cfg.ChannelID, 10), embed)
return err
}
+111
View File
@@ -0,0 +1,111 @@
package music
import (
"strings"
"github.com/bwmarrin/discordgo"
)
func HandleComponent(s *discordgo.Session, i *discordgo.InteractionCreate) {
// DJ role is required for all music controls.
if !memberHasDJRoleForComponents(s, i.GuildID, i.Member) {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You need the **DJ** role to use music commands.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
customID := i.MessageComponentData().CustomID
parts := strings.Split(customID, ":")
if len(parts) < 2 {
return
}
action := parts[1]
guildID := i.GuildID
// Ignore controls from old now-playing messages
currentMsgID := CurrentNowPlayingMessageID(guildID)
if currentMsgID != "" && i.Message != nil && i.Message.ID != currentMsgID {
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "These controls are outdated.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
return
}
// Acknowledge immediately to avoid "This interaction failed".
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredMessageUpdate,
})
var err error
content := ""
switch action {
case "pause":
err = Pause(guildID, true)
content = "Paused."
case "resume":
err = Pause(guildID, false)
content = "Resumed."
case "toggle_pause":
paused, _ := pausedAndVolume(guildID)
err = Pause(guildID, !paused)
if paused {
content = "Resumed."
} else {
content = "Paused."
}
updateNowPlayingButtons(i.ChannelID, i.Message.ID, guildID)
case "skip":
err = Skip(guildID)
content = "Skipped."
case "stop":
err = Stop(guildID)
content = "Stopped."
case "repeat_song":
rs, rq := ToggleRepeatSong(guildID)
_ = rs
_ = rq
updateNowPlayingButtons(i.ChannelID, i.Message.ID, guildID)
if rs {
content = "Repeat song enabled."
} else {
content = "Repeat song disabled."
}
case "repeat_queue":
rs, rq := ToggleRepeatQueue(guildID)
_ = rs
_ = rq
updateNowPlayingButtons(i.ChannelID, i.Message.ID, guildID)
if rq {
content = "Repeat queue enabled."
} else {
content = "Repeat queue disabled."
}
}
if content == "" {
content = "Done."
}
if err != nil {
// err can carry a raw Lavalink/network failure here (Player.Update),
// not just our own "music manager not initialized" - don't echo
// that detail into the ephemeral reply.
content = "That didn't work. Please try again."
}
// send ephemeral confirmation
_, _ = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: content,
Flags: discordgo.MessageFlagsEphemeral,
})
}
+133
View File
@@ -0,0 +1,133 @@
package music
import (
"context"
"encoding/json"
"fmt"
"log"
"strconv"
"velox-bot/internal/db/repos/musicrepo"
"github.com/jackc/pgx/v5"
)
func StartCommandListener(ctx context.Context, connString string, repo *musicrepo.Repo) error {
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return fmt.Errorf("connect: %w", err)
}
defer conn.Close(ctx)
_, err = conn.Exec(ctx, "LISTEN music_commands")
if err != nil {
return fmt.Errorf("exec: %w", err)
}
for {
_, err := conn.WaitForNotification(ctx)
if err != nil {
return fmt.Errorf("waitfornotification: %w", err)
}
processCommands(ctx, repo)
}
}
func processCommands(ctx context.Context, repo *musicrepo.Repo) {
cmds, err := repo.ListUnprocessedCommands(ctx)
if err != nil {
log.Printf("music: failed to list unprocessed commands: %v", err)
return
}
for _, cmd := range cmds {
if err := dispatchCommand(cmd); err != nil {
log.Printf("music: command %d (%s) for guild %d failed: %v", cmd.ID, cmd.CommandType, cmd.GuildID, err)
}
if err := repo.MarkCommandProcessed(ctx, cmd.ID); err != nil {
log.Printf("music: failed to mark command %d processed: %v", cmd.ID, err)
}
}
}
func dispatchCommand(cmd musicrepo.MusicCommand) error {
guildID := strconv.FormatInt(cmd.GuildID, 10)
switch cmd.CommandType {
case "skip":
return Skip(guildID)
case "pause":
return Pause(guildID, true)
case "resume":
return Pause(guildID, false)
case "stop":
return Stop(guildID)
case "set_volume":
var payload struct {
Volume int `json:"volume"`
}
if err := json.Unmarshal(cmd.Payload, &payload); err != nil {
return fmt.Errorf("unmarshal payload: %w", err)
}
return SetVolume(guildID, payload.Volume)
case "remove_track":
var payload struct {
QueueID string `json:"queue_id"`
}
if err := json.Unmarshal(cmd.Payload, &payload); err != nil {
return fmt.Errorf("unmarshal payload: %w", err)
}
return RemoveFromQueue(guildID, payload.QueueID)
case "reorder":
var payload struct {
QueueID string `json:"queue_id"`
Position int `json:"position"`
}
if err := json.Unmarshal(cmd.Payload, &payload); err != nil {
return fmt.Errorf("unmarshal payload: %w", err)
}
return Reorder(guildID, payload.QueueID, payload.Position)
case "repeat_song":
ToggleRepeatSong(guildID)
return nil
case "repeat_queue":
ToggleRepeatQueue(guildID)
return nil
case "add_song":
var payload struct {
Query string `json:"query"`
VoiceChannelID string `json:"voice_channel_id"`
}
if err := json.Unmarshal(cmd.Payload, &payload); err != nil {
return fmt.Errorf("unmarshal payload: %w", err)
}
requesterID := strconv.FormatInt(cmd.RequestedBy, 10)
// A voice channel means "start fresh" (nothing was playing, the
// dashboard had the user pick one), otherwise this just adds to
// whatever's already going.
if payload.VoiceChannelID != "" {
// Voice channels have their own built-in text chat at the same
// channel ID, post the now-playing embed there so starting
// playback from the dashboard still shows up somewhere in
// Discord, same as starting it with /play would.
_, _, err := EnqueueAndPlay(guildID, payload.VoiceChannelID, payload.VoiceChannelID, payload.Query, "Dashboard", requesterID)
return err
}
_, err := AddToQueue(guildID, payload.Query, requesterID)
return err
default:
return fmt.Errorf("unknown command type %q", cmd.CommandType)
}
}
+837
View File
@@ -0,0 +1,837 @@
package music
import (
"context"
"fmt"
"log"
"net/url"
"strconv"
"strings"
"sync"
"time"
"velox-bot/internal/db/repos/musicrepo"
"github.com/bwmarrin/discordgo"
"github.com/disgoorg/disgolink/v3/disgolink"
"github.com/disgoorg/disgolink/v3/lavalink"
"github.com/disgoorg/snowflake/v2"
"github.com/google/uuid"
)
type TrackEntry struct {
Track lavalink.Track
RequestedBy string
RequesterID string
StartedAt time.Time
// QueueID is generated once, when the track is first added to the
// queue, and never changes for the rest of its life there - it's
// what lets syncState upsert this track's row across syncs instead
// of deleting and recreating it (and its DB id) every single time,
// which is what remove/reorder commands need to reliably target a
// specific track.
QueueID string
}
type guildPlayer struct {
Player disgolink.Player
Queue []TrackEntry
RepeatSong bool
RepeatQueue bool
Paused bool
Volume int
IdleSince time.Time
TextChannelID string
NowPlayingMsgID string
}
type Manager struct {
client disgolink.Client
session *discordgo.Session
repo *musicrepo.Repo
mu sync.Mutex
players map[string]*guildPlayer
}
var manager *Manager
func Init(session *discordgo.Session, repo *musicrepo.Repo, appID, lavalinkHost, lavalinkPass string) error {
if lavalinkHost == "" {
return nil
}
userID, err := snowflake.Parse(appID)
if err != nil {
return fmt.Errorf("parse app id for lavalink: %w", err)
}
m := &Manager{
client: disgolink.New(userID, disgolink.WithListenerFunc(onTrackEnd)),
session: session,
repo: repo,
players: make(map[string]*guildPlayer),
}
u, err := url.Parse(lavalinkHost)
if err != nil {
return fmt.Errorf("parse lavalink host: %w", err)
}
secure := u.Scheme == "https" || u.Scheme == "wss"
password := lavalinkPass
if password == "" {
password = "youshallnotpass"
}
// Connecting to the Lavalink node is a blocking network call (and, on
// failure, disgolink retries indefinitely with backoff) — do it in the
// background so bot startup isn't held hostage by it. Music commands
// simply fail with "not initialized" via the manager==nil checks until
// this completes.
go func() {
_, err := m.client.AddNode(context.Background(), disgolink.NodeConfig{
Name: "main",
Address: u.Host,
Password: password,
Secure: secure,
})
if err != nil {
log.Printf("music: failed to connect to lavalink node: %v", err)
return
}
manager = m
go idleDisconnectLoop()
}()
return nil
}
func idleDisconnectLoop() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
if manager == nil || manager.session == nil {
continue
}
now := time.Now()
var toDisconnect []string
manager.mu.Lock()
for guildID, gp := range manager.players {
if gp == nil {
continue
}
// If we're paused or have anything queued/playing, clear idle timer.
if gp.Paused || len(gp.Queue) > 0 {
gp.IdleSince = time.Time{}
continue
}
if gp.IdleSince.IsZero() {
gp.IdleSince = now
continue
}
if now.Sub(gp.IdleSince) >= time.Minute {
toDisconnect = append(toDisconnect, guildID)
gp.IdleSince = time.Time{}
}
}
manager.mu.Unlock()
for _, guildID := range toDisconnect {
// Best-effort: disconnect. Safe even if we're already disconnected.
_ = manager.session.ChannelVoiceJoinManual(guildID, "", false, false)
}
}
}
func OnVoiceStateUpdate(vs *discordgo.VoiceStateUpdate) {
if manager == nil {
return
}
if vs.UserID != manager.session.State.User.ID {
return
}
guildID := snowflake.MustParse(vs.GuildID)
var channelID *snowflake.ID
if vs.ChannelID != "" {
id := snowflake.MustParse(vs.ChannelID)
channelID = &id
}
manager.client.OnVoiceStateUpdate(
context.Background(),
guildID,
channelID,
vs.SessionID,
)
}
func OnVoiceServerUpdate(ev *discordgo.VoiceServerUpdate) {
if manager == nil {
return
}
endpoint := ""
if ev.Endpoint != "" {
endpoint = ev.Endpoint
}
manager.client.OnVoiceServerUpdate(
context.Background(),
snowflake.MustParse(ev.GuildID),
ev.Token,
endpoint,
)
}
func getOrCreateGuildPlayer(guildID string) *guildPlayer {
manager.mu.Lock()
defer manager.mu.Unlock()
if gp, ok := manager.players[guildID]; ok {
return gp
}
player := manager.client.Player(snowflake.MustParse(guildID))
gp := &guildPlayer{
Player: player,
Queue: make([]TrackEntry, 0),
Volume: 100,
}
manager.players[guildID] = gp
return gp
}
func syncState(guidID string) {
if manager == nil || manager.repo == nil {
return
}
manager.mu.Lock()
gp, ok := manager.players[guidID]
if !ok {
manager.mu.Unlock()
return
}
queue := make([]TrackEntry, len(gp.Queue))
copy(queue, gp.Queue)
paused := gp.Paused
volume := gp.Volume
repeatSong := gp.RepeatSong
repeatQueue := gp.RepeatQueue
manager.mu.Unlock()
gID, err := strconv.ParseInt(guidID, 10, 64)
if err != nil {
return
}
if len(queue) == 0 {
err := manager.repo.ClearNowPlaying(context.Background(), gID)
if err != nil {
return
}
err = manager.repo.ReplaceQueue(context.Background(), gID, nil)
if err != nil {
return
}
return
}
current := queue[0]
title := current.Track.Info.Title
var uri string
if current.Track.Info.URI != nil {
uri = *current.Track.Info.URI
}
length := int(current.Track.Info.Length / 1000)
startedAt := current.StartedAt
err = manager.repo.SetNowPlaying(context.Background(), gID, title, uri, length, startedAt, paused, volume, repeatSong, repeatQueue)
if err != nil {
return
}
rest := queue[1:]
var queueEntries []musicrepo.QueueEntry
for _, entry := range rest {
reqID, _ := strconv.ParseInt(entry.RequesterID, 10, 64)
var uri string
if entry.Track.Info.URI != nil {
uri = *entry.Track.Info.URI
}
queueEntries = append(queueEntries, musicrepo.QueueEntry{
Title: entry.Track.Info.Title,
URL: uri,
RequestedBy: reqID,
ClientID: entry.QueueID,
})
}
err = manager.repo.ReplaceQueue(context.Background(), gID, queueEntries)
if err != nil {
return
}
}
// NormalizeQuery turns plain text into a YouTube search and strips
// auto-generated "radio/mix" params off a pasted YouTube URL
// (https://www.youtube.com/watch?v=ID&list=RDID&start_radio=1 becomes
// .../watch?v=ID), while leaving normal playlist URLs and non-YouTube
// links (SoundCloud, etc.) untouched. Every entry point that accepts a
// user-supplied query - /play and the dashboard's "add song" - should
// normalize through this before handing the query to Lavalink.
func NormalizeQuery(query string) string {
if !strings.HasPrefix(query, "http://") && !strings.HasPrefix(query, "https://") && !strings.HasPrefix(query, "ytsearch:") {
return "ytsearch:" + query
}
u, err := url.Parse(query)
if err != nil || u == nil {
return query
}
host := strings.ToLower(u.Host)
if !strings.Contains(host, "youtube.com") || u.Path != "/watch" {
return query
}
q := u.Query()
v := q.Get("v")
if v == "" {
return query
}
list := q.Get("list")
_, hasStartRadio := q["start_radio"]
if !hasStartRadio && !strings.HasPrefix(list, "RD") {
return query
}
u.RawQuery = url.Values{"v": []string{v}}.Encode()
u.Fragment = ""
return u.String()
}
// resolveTracks searches Lavalink for query (already normalized) and
// returns a playable track list - a single track, a search result's
// first hit, or a whole playlist (rotated to respect Lavalink's own
// selectedTrack when present).
func resolveTracks(query string) ([]lavalink.Track, error) {
var loadedTracks []lavalink.Track
manager.client.BestNode().LoadTracksHandler(
context.Background(),
query,
disgolink.NewResultHandler(
func(track lavalink.Track) {
loadedTracks = append(loadedTracks, track)
},
func(playlist lavalink.Playlist) {
if len(playlist.Tracks) == 0 {
return
}
// Respect Lavalink's selectedTrack when present by rotating the playlist.
selected := playlist.Info.SelectedTrack
if selected >= 0 && selected < len(playlist.Tracks) {
loadedTracks = append(loadedTracks, playlist.Tracks[selected:]...)
loadedTracks = append(loadedTracks, playlist.Tracks[:selected]...)
return
}
loadedTracks = append(loadedTracks, playlist.Tracks...)
},
func(tracks []lavalink.Track) {
if len(tracks) > 0 {
loadedTracks = append(loadedTracks, tracks[0])
}
},
func() {
},
func(err error) {
},
),
)
if len(loadedTracks) == 0 {
return nil, fmt.Errorf("no tracks found for query")
}
// Some sources may return unplayable entries; pick the first with an encoded track.
firstPlayableIdx := 0
for idx := range loadedTracks {
if loadedTracks[idx].Encoded != "" {
firstPlayableIdx = idx
break
}
}
if firstPlayableIdx != 0 && firstPlayableIdx < len(loadedTracks) {
loadedTracks = append(loadedTracks[firstPlayableIdx:], loadedTracks[:firstPlayableIdx]...)
}
return loadedTracks, nil
}
func EnqueueAndPlay(guildID, voiceChannelID, textChannelID, query, requester, requesterID string) (*TrackEntry, bool, error) {
if manager == nil {
return nil, false, fmt.Errorf("music manager not initialized")
}
// Join voice channel
if err := manager.session.ChannelVoiceJoinManual(guildID, voiceChannelID, false, false); err != nil {
return nil, false, fmt.Errorf("join voice channel: %w", err)
}
gp := getOrCreateGuildPlayer(guildID)
if textChannelID != "" {
manager.mu.Lock()
gp.TextChannelID = textChannelID
manager.mu.Unlock()
}
loadedTracks, err := resolveTracks(NormalizeQuery(query))
if err != nil {
return nil, false, err
}
entries := make([]TrackEntry, len(loadedTracks))
for idx, t := range loadedTracks {
entries[idx] = TrackEntry{
Track: t,
RequestedBy: requester,
RequesterID: requesterID,
QueueID: uuid.New().String(),
}
}
firstEntry := entries[0]
manager.mu.Lock()
shouldStart := len(gp.Queue) == 0
gp.Queue = append(gp.Queue, entries...)
gp.IdleSince = time.Time{}
manager.mu.Unlock()
if shouldStart {
gp.Queue[0].StartedAt = time.Now()
if err := gp.Player.Update(context.Background(), lavalink.WithTrack(firstEntry.Track)); err != nil {
return nil, false, fmt.Errorf("start track: %w", err)
}
if gp.TextChannelID != "" {
postNowPlaying(guildID, gp.TextChannelID, firstEntry)
}
}
syncState(guildID)
return &firstEntry, shouldStart, nil
}
// AddToQueue adds a track to a guild's existing queue without joining a
// voice channel, unlike EnqueueAndPlay it can't start a brand new
// session (that needs a voice channel to join, which this has no way to
// pick), so it requires one to already be active.
func AddToQueue(guildID, query, requesterID string) (*TrackEntry, error) {
if manager == nil {
return nil, fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
alreadyActive := len(gp.Queue) > 0
manager.mu.Unlock()
if !alreadyActive {
return nil, fmt.Errorf("nothing is currently playing in this server")
}
loadedTracks, err := resolveTracks(NormalizeQuery(query))
if err != nil {
return nil, err
}
entries := make([]TrackEntry, len(loadedTracks))
for idx, t := range loadedTracks {
entries[idx] = TrackEntry{
Track: t,
RequestedBy: "Dashboard",
RequesterID: requesterID,
QueueID: uuid.New().String(),
}
}
manager.mu.Lock()
gp.Queue = append(gp.Queue, entries...)
manager.mu.Unlock()
syncState(guildID)
return &entries[0], nil
}
func onTrackEnd(player disgolink.Player, event lavalink.TrackEndEvent) {
if manager == nil {
return
}
if !event.Reason.MayStartNext() {
return
}
guildID := player.GuildID().String()
manager.mu.Lock()
gp, ok := manager.players[guildID]
if !ok || len(gp.Queue) == 0 {
manager.mu.Unlock()
return
}
// repeat current track
if gp.RepeatSong {
gp.Queue[0].StartedAt = time.Now()
next := gp.Queue[0]
textChannelID := gp.TextChannelID
manager.mu.Unlock()
if err := gp.Player.Update(context.Background(), lavalink.WithTrack(next.Track)); err != nil {
return
}
if textChannelID != "" {
postNowPlaying(guildID, textChannelID, next)
}
syncState(guildID)
return
}
// pop current and optionally cycle it to end
finished := gp.Queue[0]
gp.Queue = gp.Queue[1:]
if gp.RepeatQueue {
gp.Queue = append(gp.Queue, finished)
}
if len(gp.Queue) == 0 {
textChannelID := gp.TextChannelID
nowPlayingMsgID := gp.NowPlayingMsgID
gp.NowPlayingMsgID = ""
gp.IdleSince = time.Now()
manager.mu.Unlock()
if textChannelID != "" && nowPlayingMsgID != "" {
disableNowPlaying(textChannelID, nowPlayingMsgID)
}
_ = gp.Player.Update(context.Background(), lavalink.WithNullTrack())
syncState(guildID)
return
}
gp.Queue[0].StartedAt = time.Now()
next := gp.Queue[0]
textChannelID := gp.TextChannelID
manager.mu.Unlock()
if err := gp.Player.Update(context.Background(), lavalink.WithTrack(next.Track)); err != nil {
return
}
if textChannelID != "" {
postNowPlaying(guildID, textChannelID, next)
}
syncState(guildID)
}
func Pause(guildID string, pause bool) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
gp.Paused = pause
if pause {
gp.IdleSince = time.Time{}
}
manager.mu.Unlock()
syncState(guildID)
return gp.Player.Update(context.Background(), lavalink.WithPaused(pause))
}
func Skip(guildID string) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
if len(gp.Queue) == 0 {
manager.mu.Unlock()
return nil
}
// skip always advances regardless of repeat song
skipped := gp.Queue[0]
gp.Queue = gp.Queue[1:]
if gp.RepeatQueue {
gp.Queue = append(gp.Queue, skipped)
}
if len(gp.Queue) == 0 {
textChannelID := gp.TextChannelID
nowPlayingMsgID := gp.NowPlayingMsgID
gp.NowPlayingMsgID = ""
gp.IdleSince = time.Now()
manager.mu.Unlock()
if textChannelID != "" && nowPlayingMsgID != "" {
disableNowPlaying(textChannelID, nowPlayingMsgID)
}
syncState(guildID)
return gp.Player.Update(context.Background(), lavalink.WithNullTrack())
}
gp.Queue[0].StartedAt = time.Now()
next := gp.Queue[0]
textChannelID := gp.TextChannelID
manager.mu.Unlock()
if err := gp.Player.Update(context.Background(), lavalink.WithTrack(next.Track)); err != nil {
return err
}
if textChannelID != "" {
postNowPlaying(guildID, textChannelID, next)
}
syncState(guildID)
return nil
}
func Stop(guildID string) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
textChannelID := gp.TextChannelID
nowPlayingMsgID := gp.NowPlayingMsgID
gp.Queue = nil
gp.Paused = false
gp.NowPlayingMsgID = ""
gp.IdleSince = time.Now()
manager.mu.Unlock()
if textChannelID != "" && nowPlayingMsgID != "" {
disableNowPlaying(textChannelID, nowPlayingMsgID)
}
syncState(guildID)
return gp.Player.Update(context.Background(), lavalink.WithNullTrack())
}
func GetQueue(guildID string) (*TrackEntry, []TrackEntry) {
if manager == nil {
return nil, nil
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
defer manager.mu.Unlock()
if len(gp.Queue) == 0 {
return nil, nil
}
current := gp.Queue[0]
rest := make([]TrackEntry, len(gp.Queue)-1)
copy(rest, gp.Queue[1:])
return &current, rest
}
func ToggleRepeatSong(guildID string) (bool, bool) {
if manager == nil {
return false, false
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
gp.RepeatSong = !gp.RepeatSong
if gp.RepeatSong {
gp.RepeatQueue = false
}
repeatSong, repeatQueue := gp.RepeatSong, gp.RepeatQueue
manager.mu.Unlock()
syncState(guildID)
return repeatSong, repeatQueue
}
func ToggleRepeatQueue(guildID string) (bool, bool) {
if manager == nil {
return false, false
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
gp.RepeatQueue = !gp.RepeatQueue
if gp.RepeatQueue {
gp.RepeatSong = false
}
repeatSong, repeatQueue := gp.RepeatSong, gp.RepeatQueue
manager.mu.Unlock()
syncState(guildID)
return repeatSong, repeatQueue
}
// RepeatFlags reports whether the current song or the whole queue repeats.
func RepeatFlags(guildID string) (song, queue bool) { return repeatFlags(guildID) }
// SetRepeat sets the repeat mode directly. At most one of the two applies;
// asking for both repeats the song.
func SetRepeat(guildID string, song, queue bool) {
if manager == nil {
return
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
gp.RepeatSong = song
gp.RepeatQueue = queue && !song
manager.mu.Unlock()
syncState(guildID)
}
func repeatFlags(guildID string) (bool, bool) {
if manager == nil {
return false, false
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
defer manager.mu.Unlock()
return gp.RepeatSong, gp.RepeatQueue
}
func pausedAndVolume(guildID string) (bool, int) {
if manager == nil {
return false, 100
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
defer manager.mu.Unlock()
vol := gp.Volume
if vol <= 0 {
vol = 100
}
return gp.Paused, vol
}
func SetVolume(guildID string, volume int) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
if volume < 0 {
volume = 0
}
if volume > 150 {
volume = 150
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
gp.Volume = volume
textChannelID := gp.TextChannelID
nowPlayingMsgID := gp.NowPlayingMsgID
manager.mu.Unlock()
if err := gp.Player.Update(context.Background(), lavalink.WithVolume(volume)); err != nil {
return err
}
// Refresh the embed so the displayed volume matches.
if textChannelID != "" && nowPlayingMsgID != "" {
current, _ := GetQueue(guildID)
if current != nil {
postNowPlaying(guildID, textChannelID, *current)
}
}
syncState(guildID)
return nil
}
func RemoveFromQueue(guildID, queueID string) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
idx := -1
for i, q := range gp.Queue {
if q.QueueID == queueID {
idx = i
break
}
}
if idx == -1 {
manager.mu.Unlock()
return fmt.Errorf("queue not found")
}
if idx == 0 {
manager.mu.Unlock()
return Skip(guildID)
}
gp.Queue = append(gp.Queue[:idx], gp.Queue[idx+1:]...)
manager.mu.Unlock()
syncState(guildID)
return nil
}
func Reorder(guildID, queueID string, newPosition int) error {
if manager == nil {
return fmt.Errorf("music manager not initialized")
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
idx := -1
for i, q := range gp.Queue {
if q.QueueID == queueID {
idx = i
break
}
}
if idx == -1 {
manager.mu.Unlock()
return fmt.Errorf("queue not found")
}
if idx == 0 {
manager.mu.Unlock()
return Skip(guildID)
}
entry := gp.Queue[idx]
gp.Queue = append(gp.Queue[:idx], gp.Queue[idx+1:]...)
pos := max(1, min(newPosition, len(gp.Queue)))
gp.Queue = append(gp.Queue[:pos], append([]TrackEntry{entry}, gp.Queue[pos:]...)...)
manager.mu.Unlock()
syncState(guildID)
return nil
}
func CurrentNowPlayingMessageID(guildID string) string {
if manager == nil {
return ""
}
gp := getOrCreateGuildPlayer(guildID)
manager.mu.Lock()
defer manager.mu.Unlock()
return gp.NowPlayingMsgID
}
+179
View File
@@ -0,0 +1,179 @@
package music
import (
"fmt"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/disgoorg/disgolink/v3/lavalink"
"github.com/disgoorg/snowflake/v2"
)
func nowPlayingComponents(disabled bool, repeatSong bool, repeatQueue bool, paused bool) []discordgo.MessageComponent {
repeatSongStyle := discordgo.SecondaryButton
if repeatSong {
repeatSongStyle = discordgo.SuccessButton
}
repeatQueueStyle := discordgo.SecondaryButton
if repeatQueue {
repeatQueueStyle = discordgo.SuccessButton
}
return []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Style: discordgo.SecondaryButton,
Emoji: &discordgo.ComponentEmoji{Name: map[bool]string{true: "▶️", false: "⏸️"}[paused]},
CustomID: "music:toggle_pause",
Disabled: disabled,
},
discordgo.Button{
Style: discordgo.SecondaryButton,
Emoji: &discordgo.ComponentEmoji{Name: "⏭️"},
CustomID: "music:skip",
Disabled: disabled,
},
discordgo.Button{
Style: repeatSongStyle,
Emoji: &discordgo.ComponentEmoji{Name: "🔂"},
CustomID: "music:repeat_song",
Disabled: disabled,
},
discordgo.Button{
Style: repeatQueueStyle,
Emoji: &discordgo.ComponentEmoji{Name: "🔁"},
CustomID: "music:repeat_queue",
Disabled: disabled,
},
discordgo.Button{
Style: discordgo.DangerButton,
Emoji: &discordgo.ComponentEmoji{Name: "✖️"},
CustomID: "music:stop",
Disabled: disabled,
},
},
},
}
}
func disableNowPlaying(textChannelID, messageID string) {
if manager == nil || textChannelID == "" || messageID == "" {
return
}
disabled := nowPlayingComponents(true, false, false, false)
_, _ = manager.session.ChannelMessageEditComplex(&discordgo.MessageEdit{
Channel: textChannelID,
ID: messageID,
Components: &disabled,
})
}
func postNowPlaying(guildID, textChannelID string, entry TrackEntry) {
if manager == nil || textChannelID == "" {
return
}
manager.mu.Lock()
gp, ok := manager.players[guildID]
var oldMsgID string
if ok {
oldMsgID = gp.NowPlayingMsgID
}
manager.mu.Unlock()
if oldMsgID != "" {
disableNowPlaying(textChannelID, oldMsgID)
}
repeatSong, repeatQueue := repeatFlags(guildID)
paused, volume := pausedAndVolume(guildID)
info := entry.Track.Info
title := info.Title
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{
Name: info.Author,
IconURL: sourceIconURL(info.SourceName),
},
Title: title,
Color: 0x2B2D31, // matches Discord dark-ish embed accent
Fields: []*discordgo.MessageEmbedField{
{Name: "Duration", Value: formatDuration(info.Length, info.IsStream), Inline: true},
{Name: "Volume", Value: fmt.Sprintf("%d%%", volume), Inline: true},
{Name: "Requested by", Value: entry.RequestedBy, Inline: true},
},
}
if info.URI != nil && *info.URI != "" {
embed.URL = *info.URI
}
if art := artworkURL(info); art != "" {
embed.Thumbnail = &discordgo.MessageEmbedThumbnail{URL: art}
}
msg, err := manager.session.ChannelMessageSendComplex(textChannelID, &discordgo.MessageSend{
Embeds: []*discordgo.MessageEmbed{embed},
Components: nowPlayingComponents(false, repeatSong, repeatQueue, paused),
})
if err != nil {
return
}
manager.mu.Lock()
// Avoid calling getOrCreateGuildPlayer while holding manager.mu (it also locks).
gp = manager.players[guildID]
if gp == nil {
gp = &guildPlayer{
Player: manager.client.Player(snowflake.MustParse(guildID)),
Queue: make([]TrackEntry, 0),
}
manager.players[guildID] = gp
}
gp.TextChannelID = textChannelID
gp.NowPlayingMsgID = msg.ID
manager.mu.Unlock()
}
func artworkURL(info lavalink.TrackInfo) string {
if info.ArtworkURL != nil && *info.ArtworkURL != "" {
return *info.ArtworkURL
}
// Lavalink sets Identifier for YouTube videos; use standard thumbnail as fallback.
if strings.EqualFold(info.SourceName, "youtube") && info.Identifier != "" {
return "https://img.youtube.com/vi/" + info.Identifier + "/hqdefault.jpg"
}
return ""
}
func formatDuration(d lavalink.Duration, isStream bool) string {
if isStream {
return "Live"
}
secs := d.Seconds()
if secs < 0 {
secs = 0
}
h := secs / 3600
m := (secs % 3600) / 60
s := secs % 60
if h > 0 {
return fmt.Sprintf("%d:%02d:%02d", h, m, s)
}
return fmt.Sprintf("%d:%02d", m, s)
}
func sourceIconURL(source string) string {
switch strings.ToLower(strings.TrimSpace(source)) {
case "youtube":
// Stable PNG favicon (Discord doesn't render .ico/.svg reliably in embeds)
return "https://www.google.com/s2/favicons?sz=64&domain=youtube.com"
case "soundcloud":
return "https://www.google.com/s2/favicons?sz=64&domain=soundcloud.com"
default:
return ""
}
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more