Release: open source, and a command for every setting #31

Merged
FernandoJVideira merged 8 commits from dev into master 2026-10-23 01:13:43 +00:00
10 changed files with 503 additions and 30 deletions
Showing only changes of commit 1fbc38ca56 - Show all commits

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# 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). Tables are shared with the dashboard, so a change has to be compatible with an older bot 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.
- **Escape user text and set `AllowedMentions`** so a message can't ping people.
- **Validate everything that comes from users or from the dashboard**: 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.
+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).
+15 -1
View File
@@ -16,6 +16,7 @@ This README is the front page. The rest of the documentation lives in [`docs/`](
| Page | What is in it | | Page | What is in it |
| --- | --- | | --- | --- |
| [Getting started](docs/getting-started.md) | Requirements, creating the Discord application, configuration, database, running locally | | [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 | | [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, the link to the dashboard | | [Architecture](docs/architecture.md) | How the code is laid out, how an interaction flows through it, background loops, the link to the dashboard |
| [Features](docs/features.md) | What each module does and how it behaves | | [Features](docs/features.md) | What each module does and how it behaves |
@@ -71,6 +72,19 @@ internal/modlog, rankcard small shared helpers
schema.sql mirror of the tables the bot reads and writes 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 ## Contributing
Start with the [Development guide](docs/development.md). In short: keep a command's definition and its handler in one package, keep SQL in a repo and rules in a service, and run `go build ./... && go vet ./... && go test ./...` before opening a pull request. 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 is released under the [Apache License 2.0](LICENSE). Copyright 2026 Fernando Videira. See [NOTICE](NOTICE). The libraries it uses are under their own permissive licenses (see `go.mod`).
+1
View File
@@ -20,6 +20,7 @@ This page takes you from nothing to a bot running on your machine.
| --- | --- | | --- | --- |
| View Channels, Send Messages, Embed Links, Attach Files | everything that posts, ticket transcripts | | View Channels, Send Messages, Embed Links, Attach Files | everything that posts, ticket transcripts |
| Read Message History, Manage Messages | moderation purge, spam heat | | 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 Roles | default role, level rewards, quarantine |
| Manage Channels | lockdown, slowmode, meeting rooms, snapshot restore | | Manage Channels | lockdown, slowmode, meeting rooms, snapshot restore |
| Manage Server | pausing invites during a raid | | Manage Server | pausing invites during a raid |
+175
View File
@@ -0,0 +1,175 @@
# 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 web dashboard lives in two other repositories (`velox-dashboard-api` and `velox-dashboard-web`) and is optional. See [What you get without the dashboard](#what-you-get-without-the-dashboard).
## 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.
## What you get without the dashboard
The bot works on its own and every command in the [Command reference](commands.md) does. What needs the dashboard (the `velox-dashboard-api` and `velox-dashboard-web` repositories, which share this database):
- Security thresholds, Join Gate filters and heat settings. Without the dashboard the bot uses the defaults from the schema.
- Beta access: choosing the beta server and role, and servers opting in. Without the dashboard there is no way to set a role, so beta features stay off.
- The web view of the music queue and ticket panel, and the changelog.
If you do run the dashboard, it and the bot must use the **same PostgreSQL database**, and the API runs the migrations. Its own README explains its setup. When both are deployed, [deploy the API first](deployment.md#running-next-to-the-dashboard).
## 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.
+1 -1
View File
@@ -8,7 +8,7 @@ import (
) )
const ( const (
betaGuild = "1170934850157547600" betaGuild = "700000000000000001"
otherGuild = "999000000000000001" otherGuild = "999000000000000001"
testerRol = "555000000000000001" testerRol = "555000000000000001"
testerID = "777000000000000001" testerID = "777000000000000001"
+20 -1
View File
@@ -20,7 +20,7 @@ import (
const ( const (
appID = "100" appID = "100"
betaServer = "1170934850157547600" betaServer = "700000000000000001"
optedIn = "222" optedIn = "222"
leftServer = "333" leftServer = "333"
) )
@@ -219,3 +219,22 @@ func TestBetaCleanupIsRetriedAndGivesUpWhenTheBotIsGone(t *testing.T) {
t.Error("a server the bot can't reach any more is forgotten") 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)
}
}
+19 -24
View File
@@ -21,20 +21,19 @@ import (
) )
type Bot struct { type Bot struct {
Session *discordgo.Session Session *discordgo.Session
AppID string AppID string
GuildID string GuildID string
Commands []*discordgo.ApplicationCommand Commands []*discordgo.ApplicationCommand
registeredCommands []*discordgo.ApplicationCommand Services *services.Services
Services *services.Services MusicRepo *musicrepo.Repo
MusicRepo *musicrepo.Repo DBHost string
DBHost string LavalinkHost string
LavalinkHost string LavalinkPass string
LavalinkPass string betaRegistered map[string]bool // servers where this run registered the beta commands
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
betaKnown map[string]bool // servers where they were registered, now or in an earlier run betaLoaded bool
betaLoaded bool betaRoles sync.Map // "guild:user" -> cachedRoles
betaRoles sync.Map // "guild:user" -> cachedRoles
} }
func NewBot(token, appID, guildID, lavalinkHost, lavalinkPass string, cmds []*discordgo.ApplicationCommand, services *services.Services, musicRepo *musicrepo.Repo, dbHost string) (*Bot, error) { func NewBot(token, appID, guildID, lavalinkHost, lavalinkPass string, cmds []*discordgo.ApplicationCommand, services *services.Services, musicRepo *musicrepo.Repo, dbHost string) (*Bot, error) {
@@ -114,14 +113,12 @@ func (b *Bot) Start() error {
}() }()
} }
b.registeredCommands = make([]*discordgo.ApplicationCommand, len(b.Commands)) // 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 { for _, cmd := range b.Commands {
created, err := b.Session.ApplicationCommandCreate(b.AppID, b.GuildID, cmd) if _, err := b.Session.ApplicationCommandCreate(b.AppID, b.GuildID, cmd); err != nil {
if err != nil {
log.Printf("Cannot create '%v' command: %v", cmd.Name, err) log.Printf("Cannot create '%v' command: %v", cmd.Name, err)
continue
} }
b.registeredCommands = append(b.registeredCommands, created)
} }
b.Session.AddHandler(commands.HandleInteraction) b.Session.AddHandler(commands.HandleInteraction)
@@ -428,11 +425,9 @@ func (b *Bot) removeBetaCommands(guildID string) bool {
return clean 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 { 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() return b.Session.Close()
} }
@@ -153,7 +153,7 @@ func TestGetBetaSettings(t *testing.T) {
t.Fatalf("role = %q, want empty", role) t.Fatalf("role = %q, want empty", role)
} }
_, err = db.ExecContext(ctx, `INSERT INTO beta_settings (id, guild_id) VALUES (TRUE, 1170934850157547600)`) _, err = db.ExecContext(ctx, `INSERT INTO beta_settings (id, guild_id) VALUES (TRUE, 700000000000000001)`)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -161,8 +161,8 @@ func TestGetBetaSettings(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if g != "1170934850157547600" { if g != "700000000000000001" {
t.Fatalf("g = %q, want %q", g, "1170934850157547600") t.Fatalf("g = %q, want %q", g, "700000000000000001")
} }
if role != "" { if role != "" {
t.Fatalf("role = %q, want empty", role) t.Fatalf("role = %q, want empty", role)