150 Commits
Author SHA1 Message Date
BlackAngelTV ed14b8260c feat(tickets): open tickets from a panel button in any channel
CI / quality (push) Has been cancelled
Members had to know `/ticket create` and its category list to reach support,
so the entry point is now a panel: `/ticket setup` publishes it in the current
channel, the button opens a menu of the categories the member is allowed to
open, and the choice creates the ticket.

The panel channel and message are stored in `ticket_panels`, so a reinstall
replaces the previous message instead of leaving the server two entry points,
and the panel survives a restart.
2026-10-02 20:29:22 +02:00
BlackAngelTV 1310840215 feat(tickets): guide members in ticket channels and log to the technical salon
CI / quality (push) Has been cancelled
Tickets were opened with three words and members expected an immediate answer,
so the channel now posts a guidance embed: what details to give (context, steps
to reproduce, exact error, OS version) and that a reply can take a while.

The ticket journal moves to CHANNEL_LOGS_ID so the environment keeps one log
salon per purpose: CHANNEL_TICKETS_LOGS_ID held the same entries and nothing
else read it. A wrong CATEGORY_TICKETS_ID now says which case it is, since a
missing category was reported as a mistyped one.
2026-10-02 20:13:31 +02:00
BlackAngelTV a996065861 Merge pull request 'Feat/dashboard rules' (#150) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #150
2026-09-25 19:16:10 +00:00
BlackAngelTV ffb54a8e37 chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 21:14:00 +02:00
BlackAngelTV e6ce594b34 fix(rules): show the rules field with a save button and edit the message
The rules lived in a card of their own that never showed up next to the
settings, so the section read as an empty toggle nobody could fill in. The
markdown now renders as a real field with an "Enregistrer" button, and
saving edits the message already pinned instead of deleting it and
posting a new one: same link, same place, pin kept.
2026-09-25 21:14:00 +02:00
BlackAngelTV 4e0f43eace Merge pull request 'Feat/dashboard rules' (#149) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #149
2026-09-25 18:50:41 +00:00
BlackAngelTV 22e9723700 chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 20:44:36 +02:00
BlackAngelTV 31c0fc861a feat(rules): write the rules from the dashboard and republish them
The rules lived in a channel nobody but a staff member with a shell could
edit, and the welcome message pointed at it. They are now written in
markdown under Settings and published as a single pinned embed, and a new
publication deletes the message the bot posted last time instead of
piling copies up in the channel.
2026-09-25 20:44:29 +02:00
BlackAngelTV 20ffbbacad Merge pull request 'Fix/mute log wording' (#147) from fix/mute-log-wording into main
CI / quality (push) Has been cancelled
Reviewed-on: #147
2026-09-25 18:34:31 +00:00
BlackAngelTV c61a13176e chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 20:29:32 +02:00
BlackAngelTV 44e990d04b docs(agents): update the repository conventions and commit rules
The instructions now speak of a dépôt rather than a repo, point at
CONTRIBUTING.md for the collaboration conventions, require signed commits
and state how a commit asked for by the maintainer must be written.
2026-09-25 20:29:31 +02:00
BlackAngelTV 99e1fd2723 fix(moderation): tell a mute apart from a kick in the logs
A timeout was filed as "Exclusion temporaire" right next to "Expulsion",
so a sanction could not be read back from the log channel, the direct
message or `/mod logs`. Each action now carries its own emoji and wording
behind a single label, used by every surface.
2026-09-25 20:29:19 +02:00
BlackAngelTV 859b229181 Merge pull request 'Feat/add missing commands' (#146) from feat/add-missing-commands into main
CI / quality (push) Has been cancelled
Reviewed-on: #146
2026-09-25 18:13:58 +00:00
BlackAngelTV d720c0a17e chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-25 20:11:05 +02:00
BlackAngelTV 9f8ac0d29e feat(moderation): add the unmute and unban commands
A sanction could be applied but never lifted from Discord, so undoing a
mistake meant leaving the bot for the server settings. Both lifts are
recorded next to the sanctions they lift, which means widening the
moderation history CHECK constraint through a table rebuild.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-25 20:11:00 +02:00
nocode b8be549fda Merge branch 'feat/web-dashboard'
CI / quality (push) Has been cancelled
2026-09-24 20:53:31 +02:00
nocodeandClaude Opus 5 b9bc3b934b chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:36 +02:00
nocodeandClaude Opus 5 566af4db70 docs(web): document my tasks, the search and the status page
Adds the chapter the three tools were missing, and points the monitoring
guide at /api/status rather than /api/health, which answers a narrower
question than an operator usually means.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:35 +02:00
nocodeandClaude Opus 5 a1e1de7734 feat(web): publish a public status page at /status
Checking whether the service is up required an account, so the answer
lived where the people asking could not reach it.

The page is rendered on the server with no script at all and refreshes
through a meta tag: a status page that needs a working browser is
useless at the moment it is read. Two rules follow from it being public.
A repository the forge does not list as public keeps its environment
visible but loses its name, and the banner always states the worst true
thing — a failed deployment forbids the green headline even while the
bot answers. WEB_PUBLIC_STATUS=false removes page and route together.

/api/status gives the same in JSON, which is what a monitor should watch
rather than /api/health — the latter only says the process is alive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:26 +02:00
nocodeandClaude Opus 5 9acb523510 feat(web): search the whole panel from one place
Finding anything meant knowing which tab it lived in — fine once you
have learned the panel, hopeless before. ⌘K now covers cards,
repositories, issues, wiki pages and members at once.

Pages are matched in the browser, so the palette answers before it has
asked the server and stays useful while the forge is down. Each remote
source is queried independently and a source that fails is simply absent
from the results, rather than taking the others with it. Issues come
from one organization-wide request: per repository, the palette could
not afford them on every keystroke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:04 +02:00
nocodeandClaude Opus 5 fcc82d82d6 feat(projects): gather the cards one member carries
A board answers "where does the work stand". Nobody opens a dashboard to
ask that first: they ask what is on them today, and once the work is
spread over several boards no single board can answer it.

The cards assigned to a member are now listed on a page of their own,
grouped by deadline, with a counter on the sidebar entry — a page you
have to open to know whether it needs you is a page you stop opening.
The column travels with each card, so finishing one from the list is a
single move rather than a detour through its board.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:45:03 +02:00
nocodeandClaude Opus 5 d2256e2211 refactor(web): extract the build marker into its own module
The version and the interface build date were computed inside the route
file, where two copies of the same comment had already drifted apart. The
status page needs the same answer, and a second copy would eventually
give a different one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:43:41 +02:00
nocodeandClaude Opus 5 e3ce266225 docs(ops): correct the deployment path for a panel without a shell
Pterodactyl's console is the process stdin, not a terminal, so the previous
instructions could not be followed even with full panel rights. The chapter
now covers both cases: a real shell where one exists, and otherwise the
dashboard's own command deploy, which runs inside the container and needs no
console at all.

It also starts by checking the commands land on the filesystem the bot
reads — a pull in the wrong place reports success and changes nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:11:51 +02:00
nocodeandClaude Opus 5 1643fcb591 docs(ops): document deployment, CI, monitoring and backups
Four independent procedures, each opening with the failure it prevents —
most of them ones this project actually hit: a front-end older than its API
after a partial upload, a broken card move that no test ran before it
shipped, an evening spent asking whether the site was down, and a database
that came back empty after a rebuild.

The CI workflow ships with them. It leaves out `format:check`, which would
fail on CRLF files that predate the Prettier configuration; normalising them
deserves a commit of its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:08:52 +02:00
nocodeandClaude Opus 5 1c21f6ff53 feat(projects): pull Gitea issues onto any board
The import only existed on a repository board and always landed in the first
column. The organization board is exactly where issues from several
repositories belong together, so the button now lives on every board and
asks which repository, which column, and whether closed issues come too.

An issue already on the board is skipped rather than duplicated, so the
button survives being pressed twice — which the tests check against a
stand-in forge, along with the due date and labels carried over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:03:06 +02:00
nocodeandClaude Opus 5 8869c74b7b fix(wiki): render the public pages on the server
The documentation was assembled in the browser, so a client that runs no
script saw an empty shell — including whoever fetches the terms and privacy
links before approving an application, which is exactly what those pages are
for.

The wiki is now delivered as finished HTML, carries no script at all, and
declares itself indexable, unlike the panel. Search works through a plain
query string, an unknown page answers 404 rather than a blank page, and both
legal pages are linked from the footer of every page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:31:27 +02:00
nocodeandClaude Opus 5 3d0e21d7cb feat(wiki): serve the legal pages at /terms-of-service and /privacy-policy
Discord, and most platforms, ask for a terms URL and a privacy URL in a
form field; pasting a `/wiki/...` address there reads like an afterthought.
Both pages now answer at the root, while everything else stays under
`/wiki/`.

The API states each page's address instead of leaving the front to rebuild
it, so there is one place that decides. Existing pages are renamed rather
than recreated, keeping whatever has already been written in them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:25:59 +02:00
nocodeandClaude Opus 5 e1b9a5cc77 feat(projects): add the board interface
Drag and drop between columns, cards carrying an assignee, a due date,
labels and a linked issue whose state shows on the card. An overloaded
column says so in its header rather than blocking the drop.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:09 +02:00
nocodeandClaude Opus 5 901ca56959 feat(projects): add a Kanban board per repository and one for the organization
Boards live in SQLite rather than in Gitea, whose project API is not stable
across versions: a board that stops working whenever the forge hiccups is
worse than no board, and this one has hiccupped already.

A card can still point at an issue — `owner/repo#12` — and its real state is
resolved when the forge answers, one request per repository rather than per
card. Open issues can also be imported in bulk, skipping those already on
the board.

Columns follow the ones the README describes, and carry an optional card
limit which warns rather than refuses: stopping someone mid-gesture to
enforce a convention is not what a limit is for.

Moving a card rebuilds the order explicitly — take the column without it,
insert at the wanted rank, renumber — because fractional positions get the
same-column case wrong, as the tests showed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 b793298cbf test(web): lock the sidebar highlighting behind tests
It has been reported twice and fixed twice by reading the code, which is how
it came back. The decision is now a module of its own — the shell only asks
it which entry is current — and twelve cases pin it down: a detail page, a
query string, every spelling of the home route, and the original regression
where home stayed lit everywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 3f4a5709cf fix(web): stop caching the interface modules
Modules cache independently, so a browser could revalidate one and keep an
older copy of another — leaving a page running one version of itself and a
different version of its helpers. That surfaces as an error inside a
feature, which is nothing like what it is, and no reload short of clearing
the site data reliably fixes it.

A dashboard is a handful of small files read by one person at a time: the
bandwidth caching saves is worth less than the failure it causes. They are
now fetched fresh.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 c031b4d9e2 fix(web): keep the stack when a view fails
Views caught their errors and showed only the message, so nothing said which
module or which line had failed — neither in the console, which never saw
the error, nor on the page.

The stack is now logged and offered on the page behind a disclosure, because
opening the developer console is not always an option on a self-hosted
panel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 92c27aed9f fix(web): read the interface build date instead of freezing it at startup
The marker was captured once at import, while the front-end is served from
disk on every request. Uploading new files therefore left it announcing the
old build until the next restart — the exact confusion it was added to
prevent.

It is now read from disk, cached ten seconds so a health check does not walk
the tree each time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 75d1e53205 fix(web): stop the settings page breaking on an unexpected payload
Every list the page walks was read straight off the response, so a single
missing field took the whole view down with `undefined.map` — which reads as
a broken feature rather than as what it is, a page and an API disagreeing on
the shape of the data.

The page now normalises what it receives: absent lists render empty, an enum
without options falls back to a text field, and settings that arrive without
sections are shown under one heading instead of not at all.

Errors of that family also say so, and point at the reload that fixes them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 95b51ab428 feat(web): open a repository from anywhere on its row
The cards on the repository page already opened as a whole, but the tables
on the organisation and overview pages still only linked the name, so the
same object behaved differently depending on where it was listed.

A table row can now carry a destination. Controls inside it keep their own
behaviour, the row is reachable with the keyboard, and only the empty space
navigates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 539b1506f4 fix(web): give static assets a validator caches can check
The front-end was served with `no-cache` but no `ETag` and no
`Last-Modified`, so a cache had nothing to revalidate against and could keep
handing out modules older than the API they talk to — which surfaces as a
cryptic error in a view rather than as anything resembling a stale cache.

Assets now carry both, and an unchanged file answers 304.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 3bd290cba6 fix(web): say when the dashboard is disabled
`WEB_ENABLED` not being `true` produced no output at all, so a missing site
looked exactly like a broken one and there was nothing in the console to
tell the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 afcd0e55bc fix(web): say out loud when the dashboard cannot listen
A failed `listen` only produced a generic line the bot then carried on past,
so the site was simply absent with nothing explaining why — and inside a
container a bind on an unpublished port succeeds while staying unreachable,
which looks identical to a crash from the browser.

The error now names the address, the port and the actual cause, and a
successful bind on `0.0.0.0` reminds that the port still has to be published
by the host.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 40032ec091 fix(config): warn when a public address is announced but only loopback is bound
`WEB_HOST=127.0.0.1` is the right default behind a reverse proxy on the same
machine, and the wrong one inside a container or on a hosting panel, where
the process has to bind the allocation. The guidance only mentioned the
first case, so a `.env` written from the wizard could leave the dashboard
listening where nothing could reach it — every request timing out with
nothing saying why.

The wizard now flags the contradiction between a loopback bind and a public
URL, and both the help text and `.env.example` name the container case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 5660235f3d docs(web): document the wiki, the settings and the command publishing
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 e5b7303a01 feat(wiki): add the reading site and its editor
The renderer escapes HTML before any transformation and drops
`javascript:` links. Pages are written by the team, but a renderer that
relies on that is one mistake away from being a hole.

The editor previews as you type: legal pages are long, and writing Markdown
blind is how broken tables end up published.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 c76c0b96eb feat(wiki): serve a public documentation written from the panel
Pages live in SQLite and are read without a session: documentation nobody
can reach without an account is not documentation. Drafts answer 404 even
when their address is guessed, and the site never falls back to the
dashboard shell, which would send a visitor to a login screen.

The wiki ships with terms of use and a privacy policy written against the
revised Swiss LPD, describing table by table what this codebase actually
stores. Both are marked protected: they can be rewritten, not deleted, and
a deleted one comes back on the next start — a bot that processes personal
data must always be able to show its notice.

The bracketed details still have to be completed and the whole reviewed;
this is a starting point written from the schema, not legal advice.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 621f3e404b style(web): adopt the official FWS mark and its palette
The placeholder mark was an Arch-blue chevron. The site now carries the FWS
logo — cyan ring on dark navy — and its accent colour follows, so the
dashboard and the brand no longer disagree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 e397abcfcd fix(web): make the whole repository card open the repository
Only the name was a link, so most of a rectangle that reacts to the pointer
led nowhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 262274473a feat(web): publish the slash commands from the panel
Registering the commands was the one routine step that still needed shell
access on the host, which is awkward when the bot runs behind a hosting
panel. Guild commands take effect immediately, so the button says what it
did as soon as it returns.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 b42fb1065a feat(voice): take back the generated channels the database forgot
A voice channel outlives the process that made it. A restored backup, a
wiped `data/` folder or a redeployment shipping a fresh database all leave
real channels behind that nothing manages any more: they are never cleaned
up, and their owner can no longer rename or lock them.

At startup the bot now reclaims the channels sitting in a trigger's own
category and named after its template — a channel created by hand is never
touched. Those still in use go back to whoever is inside; the empty ones are
leftovers and are removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 406b5af3ea feat(settings): make the server settings real, and widen them
The dashboard offered seven switches that nothing read: they promised a
behaviour the bot did not have, which is worse than offering nothing.

Every setting is now declared once, with its type, its bounds and its
explanation, and the services read it: the welcome message and its wording,
the automatic role, departure notices, the private notice sent to a
sanctioned member, the default mute duration, how much history a ban erases,
whether a closed ticket is deleted or archived, and an optional role mention
on the Gitea notifications.

A test walks the sources and fails when a declared key is read nowhere, so
the list cannot drift back into decoration.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 d439b1b3e8 feat(web): make deploying reachable from where it is looked for
The « Déployer » button only existed on the row of an already created
target, so an empty list was a dead end whose only way out sat in the page
header. The empty state now carries the action that fills it.

A release also gains its own deploy button: wanting to ship a given version
is the moment people look for it, and sending them to another page to retype
the tag was needless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:47:47 +02:00
nocodeandClaude Opus 5 a44ff0cb52 fix(web): pin the sidebar highlight to the route, and name the build
The highlight compared hrefs, which a trailing slash or a query string in the
hash was enough to defeat, and it only ran once the view had loaded. Each
link now carries the route it stands for and the highlight is applied as soon
as the sidebar exists.

The footer also states the running version and the date of the newest
interface file. Deployments that ship an archive make it easy to look at a
stale copy and wonder why a fix is missing; the page can now say so.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:47:46 +02:00
nocodeandClaude Opus 5 2083133c7a docs(web): document the live updates
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 5481e79dc4 feat(web): refresh the pages as the events arrive
One `EventSource` for the whole dashboard, held in a single slot: a view that
re-renders itself would otherwise register a second listener each time and
double the work on every event.

A refresh landing under someone's fingers is worse than data a few seconds
old, so it waits while a dialog is open or a field has focus, a burst of
writes collapses into one reload, and a background tab closes its stream.
The Discord page stays off the tick because listing members calls the
Discord API. When the stream cannot be established a timer takes over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 df89cc5893 feat(web): push live updates to the dashboard
Reading a page and wondering whether it is still true is a poor way to watch
a deployment, and polling every page on a timer costs far more than it
returns.

The server keeps one `text/event-stream` per open tab and publishes on it:
a write once it has actually succeeded, tagged with the page it concerns, a
deployment when it starts and when it ends, an incoming Gitea webhook, plus
a tick and a heartbeat that stops proxies closing an idle stream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 9c6297e00e fix(web): always offer the bootstrap token on the sign-in page
The field only appeared when a token was already configured, which hid the
one way back into the configuration exactly when Discord sign-in is broken
or not set up yet. It is now always present, and says how to obtain a token
when none is available.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:16 +02:00
nocodeandClaude Opus 5 ff15dfe92f fix(web): let a deploy target be created without a reachable Gitea
The « Nouvelle cible » button was hidden whenever the repository list came
back empty, and a Gitea answering 403 took the whole page down with it — so
a forge problem removed every way to set up a deployment, including webhook
and shell targets that never talk to Gitea at all.

The list is now a convenience: its failure is reported as a warning and the
repository falls back to a free-text field.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:16 +02:00
nocodeandClaude Opus 5 a0428e0549 fix(web): keep the sidebar in step with the page being shown
Navigating only swapped the main area, so the highlighted entry stayed on
whichever page the shell was built with and nothing on screen said where you
were. The highlight is now refreshed on every navigation, carries
`aria-current` for screen readers and an inset marker that reads at a glance,
and the browser tab takes the page name.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:09 +02:00
nocodeandClaude Opus 5 20ff701430 fix(web): derive the OAuth2 redirect from the address actually used
`WEB_PUBLIC_URL` was the only source of the `redirect_uri`, so a hosting
panel or a proxy publishing the dashboard on another port produced a link
Discord refuses, with nothing on screen pointing at the port mismatch.

The browser's own origin is what Discord compares against, so the redirect
now comes from the request, honouring `X-Forwarded-Host` and
`X-Forwarded-Proto` when a proxy sits in front. `WEB_PUBLIC_URL` stays as
the fallback for links built outside a request, and the sign-in page prints
the exact value to declare in the portal.

The `Secure` cookie flag follows the same rule: announcing HTTPS in the
configuration while serving plain HTTP made the browser drop the session.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:12:44 +02:00
nocodeandClaude Opus 5 e63d6aa18e docs(web): document the dashboard and the configuration wizard
Both READMEs gain the same section and the same variables, as the
organisation requires them to stay in sync.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 bd7fdea275 test(web): cover the router, configuration, auth, deployments and server
The schema test compares the declared variables against `.env.example`, so
the two cannot drift apart. The server tests drive the real handler over a
loopback socket rather than a mock, which is what caught the health probe
missing from bootstrap mode and the deployments recorded under the wrong
guild.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 06a9be0cba feat(web): serve the dashboard and its interface
The front-end is plain JavaScript served as is: no build step to run before
the bot starts, and no second toolchain to keep alive. A simple/advanced
switch hides the technical panels without ever standing in for a permission.

`npm run setup` starts the wizard alone, because the bot refuses to boot
without a token and the `.env` has to be writable from somewhere. When the
webhook and the dashboard share a port, a single HTTP server is started.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 bf92badb05 feat(web): expose the dashboard API
One module per domain, each route declaring the minimum access level the
server enforces before the handler runs. Irreversible actions ask for the
exact name to be typed back, and every write lands in `event_logs` with its
author so the history says who did what.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 611129b23c feat(web): run and record release deployments
Three kinds of target, ordered by how much they trust the caller: a signed
webhook runs nothing locally, a Gitea Action delegates to the forge, and a
shell command executes arbitrary code on the bot host — hence the double
lock of an environment flag plus the Owner level on that last one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 efaaca35dd feat(web): read, validate and write the .env configuration
Every variable is described once, with its explanation and the steps to
obtain it. The form, the validation and the generated file all derive from
that description, so adding a variable to the bot means touching one file.

The previous file is backed up before being replaced, and an empty secret
means "keep the current value" so a token cannot be wiped by accident.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 e03b184d68 feat(web): add the HTTP layer and Discord-backed sessions
Visitors sign in with Discord and inherit the very same access levels as the
slash commands, so there is no second permission model to keep in sync.

Writes require a header a cross-site form cannot forge, on top of the
`SameSite=Lax` cookie, and a bootstrap token opens the configuration wizard
alone for the case where no Discord application exists yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 5abe713279 feat(database): store dashboard sessions, deploy targets and deployments
Sessions and API tokens keep only a hash of the value handed to the client,
so a database dump cannot be replayed. A deployment denormalises its target
name so the history survives the deletion of that target.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 4b0737a512 feat(gitea): add an organization and repository administration client
`gitea-client.js` stays focused on the single repository the slash commands
talk to. The dashboard addresses any repository of the organization, so its
endpoints live apart instead of bloating the command path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:12 +02:00
nocodeandClaude Opus 5 e4534d4d50 feat(config): declare the web dashboard environment variables
The dashboard is off by default and listens on the loopback interface: it
must be an explicit decision to expose it, not a side effect of upgrading.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:12 +02:00
nocodeandClaude Opus 5 92405ac618 fix(notifications): apply the channel overrides set from Discord
`/notify set` stores the types listed in `NOTIFICATION_TYPES` (`releases`,
`commits`, `pull_requests`) while the webhook handler looks them up under the
Gitea event names (`release`, `push`, `pull_request`), so an override chosen
from Discord was never found and the environment default always won.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:07 +02:00
BlackAngelTV 2ccb462e35 Merge pull request 'refactor(all): uniformisation' (#144) from build/project-structure into main
Reviewed-on: #144
2026-09-23 16:31:05 +00:00
BlackAngelTV 50665c8edd refactor(all): uniformisation 2026-09-23 18:25:28 +02:00
BlackAngelTV 865f2eb91b Merge pull request 'Build/project structure' (#142) from build/project-structure into main
Reviewed-on: #142
2026-09-23 12:31:21 +00:00
BlackAngelTV ee538cb943 docs(changelog): list the voice, status and tone work in the changelog
The generated file only knew the history of the previous pass, so the features
merged after it were missing from the notes.
2026-09-15 16:15:01 +02:00
BlackAngelTV 9bbe9cb0b4 docs(readme): translate the documentation and document the contribution workflow
The organisation asks every repository for both languages, for the issue and
pull request templates, and for the commit, branch and release rules; the
README now states them, README.en.md mirrors it, and a test keeps the two in
sync so a change on one side cannot be forgotten on the other.

The readme also documents what shipped since it was last written: several voice
triggers, the guaranteed cleanup of empty channels, the editable bot statuses,
the message tone and the variables they add.
2026-09-15 16:15:00 +02:00
BlackAngelTV 478ae41d86 build(changelog): generate the changelog from the commit history
Releases are expected to ship notes built from the Conventional Commits, and a
hand-written file drifts from the history within a few merges. The generator
reads the log directly, so it adds no dependency, and `npm run changelog:check`
gives CI a way to fail when the file was not regenerated.

A commit that only rewrites the changelog is left out of it, otherwise the
check could never be green once that file is committed.
2026-09-15 16:14:28 +02:00
BlackAngelTV 2df33c205c chore(gitignore): ignore the AI assistant data and the other toolchains
The organisation lists a minimum ignore set for every repository: the data
directory of the development assistants and the artefacts of the languages a
contributor may build next to this one must never reach the repository.
2026-09-15 16:13:52 +02:00
BlackAngelTV c785e9abb7 feat(status): rotate an editable list of bot statuses
The presence line was hard-coded, so advertising a different message meant
editing the source and restarting the bot. Statuses now live in the database
and are managed from Discord with /status — add, list, remove, pause and the
rotation interval, which applies without a restart.

An empty list falls back to a neutral "see the commands with /help" line, and
the first status added shows up right away instead of waiting a full turn.
2026-09-15 16:12:50 +02:00
BlackAngelTV ef8f09da10 refactor(ui): give every message one friendly, ungendered voice
Members read all replies as one voice, so the wording now lives in one place:
the shared titles, the list marker and the "what to do next" hint come from
src/ui/embeds.js, and every module follows them.

An error explains the cause, recalls the rule and offers the way out instead of
blaming; a success says what happens next. Nothing agrees on the gender of a
person ("utilisateur", "cher/chère", "ravie"), which also keeps the sentences
shorter. Two tests lock the shared titles and reject gendered descriptions.
2026-09-15 16:12:19 +02:00
BlackAngelTV 76e2269555 feat(voice): guarantee an empty generated channel disappears
A generated channel could survive with nobody in it: the row was dropped before
the channel was really gone, so a refused delete call left a room nothing could
track anymore, and an event missed while the bot was down was never retried.

The row is now kept until Discord confirms the channel is gone, and a sweep at
startup then every minute deletes whatever the event missed. The grace period
is tunable with VOICE_EMPTY_GRACE_MS, 0 deleting as soon as the room empties.
2026-09-15 16:11:30 +02:00
BlackAngelTV 836abeafd5 feat(voice): support several trigger channels with their own category
A server needs one "create your own room" channel per theme, which a single
trigger id could not express. Triggers are now stored as a list, each with its
own home category, name template and default limit.

Joining a trigger creates the channel at the bottom of that trigger's category,
and a member keeps one channel per trigger instead of one room for the whole
server. Triggers declared by the single-trigger version and
CHANNEL_VOICE_TRIGGER_ID still work as fallbacks, so no server has to be
reconfigured.
2026-09-15 16:09:39 +02:00
BlackAngelTV 66c04c617a docs(agents): add the shared agent instructions for FWS repositories 2026-09-15 15:23:25 +02:00
BlackAngelTV be4981aa75 docs(readme): document the implemented features and the voice manager
The status tables now describe real behaviour, and the required intents and invite permissions include the new voice features so a fresh install works on the first try.
2026-09-15 14:51:22 +02:00
BlackAngelTV aa5343b4b2 test(app): add command and event loading smoke tests
Loading every module catches broken imports and invalid slash command definitions, which unit tests on the services cannot see.
2026-09-15 14:51:18 +02:00
BlackAngelTV 5191942d5a feat(voice): add temporary voice channel manager
Joining the trigger channel must feel instant and never leave orphan channels behind, so the ownership is stored in SQLite, empty channels are deleted after a short grace period and a startup sweep cleans up whatever a restart left behind.
2026-09-15 14:51:17 +02:00
BlackAngelTV ef1bedbc65 feat(polls): implement polls, fun and statistics commands
A poll must end even when nobody is there to close it, so a scheduler reads the stored end dates and finalises the results at startup and while running.
2026-09-15 14:50:54 +02:00
BlackAngelTV f29c09577a feat(members): add welcome, default role and departure reporting
The welcome direct message is best effort: a member with closed private messages must still receive the channel message and the default role.
2026-09-15 14:50:48 +02:00
BlackAngelTV c49c60071d feat(moderation): implement the moderation service and commands
Every action checks the role hierarchy before touching Discord, then records the sanction in SQLite and mirrors it in the moderation log channel, so the history outlives the audit log.
2026-09-15 14:50:48 +02:00
BlackAngelTV e8c95b2ba3 feat(tickets): implement the ticket service, command and channel controls
Each ticket category is visible to a different set of staff roles, and the claim and close actions must also be reachable from the channel itself, so the buttons live in the ticket and share the service checks.
2026-09-15 14:50:47 +02:00
BlackAngelTV a5280ce205 feat(notifications): dispatch Gitea webhooks through the notification service
A guild can reroute a notification type to its own channel from SQLite, with the environment values as fallback, without editing the configuration or restarting the bot.
2026-09-15 14:50:41 +02:00
BlackAngelTV 26d7cce05f feat(fws): implement the version, status and changelog subcommands
Status reports each dependency separately so a Gitea outage never hides a database or webhook problem.
2026-09-15 14:50:41 +02:00
BlackAngelTV 76d0bf9250 feat(gitea): add embeds, modals and the issue and pull request commands
Creating an issue or a pull request needs a title and a description, which do not fit in a slash command option, so the branches chosen as options are kept in memory for a few minutes until the modal is submitted.
2026-09-15 14:50:40 +02:00
BlackAngelTV 66be463ba3 feat(core): add shared constants, interaction components and Gitea client helpers
Moderation, tickets, polls and Gitea events reuse the same labels, colours and buttons; normalising list responses in the client keeps both commands and webhooks free of version quirks.
2026-09-15 14:50:34 +02:00
BlackAngelTV 03a217c775 feat(database): add repositories for tickets, moderation, polls and notifications
Keep every SQL statement out of the command layer so each feature can be built and tested without a Discord dependency.
2026-09-15 14:50:34 +02:00
nocode abf6701bb0 docs(core): document project structure
Refs: #12
2026-09-13 12:25:12 +02:00
nocode fec8007c62 chore(docs): add screenshots directory
Refs: #101
2026-09-13 12:25:11 +02:00
nocode 9f2aa90a28 chore(observability): keep logs directory in repository
Refs: #17
2026-09-13 12:25:11 +02:00
nocode 070612abe4 chore(database): keep data directory in repository
Refs: #16
2026-09-13 12:25:11 +02:00
nocode baef3fa0af test(database): add sqlite storage tests
Refs: #16
2026-09-13 12:25:11 +02:00
nocode 52e24bd4af test(auth): add permission checks tests
Refs: #115
2026-09-13 12:25:11 +02:00
nocode 9a266b70fc feat(database): add database initialization script
Refs: #16
2026-09-13 12:25:11 +02:00
nocode 6b4ac374ed feat(commands): add slash command deployment script
Refs: #24
2026-09-13 12:25:10 +02:00
nocode de97f878e1 feat(core): add bot entry point
Refs: #22
2026-09-13 12:25:10 +02:00
nocode 208d713fe0 feat(fun): add fun command skeleton
Refs: #88
2026-09-13 12:25:10 +02:00
nocode baca3f0993 feat(stats): add stats command skeleton
Refs: #90
2026-09-13 12:25:10 +02:00
nocode 9ccecb3071 feat(polls): add poll command skeleton
Refs: #82
2026-09-13 12:25:10 +02:00
nocode cef9ed0371 feat(roles): add role command skeleton
Refs: #63
2026-09-13 12:25:09 +02:00
nocode 744eaa8398 feat(moderation): add moderation logs command skeleton
Refs: #70
2026-09-13 12:25:09 +02:00
nocode dc4958fa26 feat(moderation): add clear command skeleton
Refs: #69
2026-09-13 12:25:09 +02:00
nocode 002380c03f feat(moderation): add ban command skeleton
Refs: #68
2026-09-13 12:25:09 +02:00
nocode 4cc475edef feat(moderation): add kick command skeleton
Refs: #67
2026-09-13 12:25:09 +02:00
nocode 373c7e6455 feat(moderation): add mute command skeleton
Refs: #66
2026-09-13 12:25:09 +02:00
nocode 1bcc3d382d feat(moderation): add warn command skeleton
Refs: #65
2026-09-13 12:25:08 +02:00
nocode ab08253126 feat(support): add ticket command skeleton
Refs: #52
2026-09-13 12:25:08 +02:00
nocode d9ce9e4aae feat(gitea): add activity and release command skeleton
Refs: #48
2026-09-13 12:25:08 +02:00
nocode 44c9595ae0 feat(gitea): add pull request command skeleton
Refs: #48
2026-09-13 12:25:08 +02:00
nocode bd2475cb73 feat(gitea): add issue command skeleton
Refs: #48
2026-09-13 12:25:08 +02:00
nocode 4cc6964a3c feat(fws): add fws information command
Refs: #35
2026-09-13 12:25:08 +02:00
nocode 3aa17e5707 feat(commands): add help command
Refs: #25
2026-09-13 12:25:07 +02:00
nocode 9cb2a7356d feat(members): add member leave event handler
Refs: #62
2026-09-13 12:25:07 +02:00
nocode aa404dd588 feat(members): add member join event handler
Refs: #62
2026-09-13 12:25:07 +02:00
nocode 017764d5b8 feat(commands): dispatch slash commands with access control
Refs: #30
2026-09-13 12:25:07 +02:00
nocode 8f48efdcdc feat(discord): log shard disconnections
Refs: #23
2026-09-13 12:25:07 +02:00
nocode e9c110a752 feat(discord): log discord client errors
Refs: #27
2026-09-13 12:25:07 +02:00
nocode 0fb20d120a feat(discord): handle client ready event
Refs: #22
2026-09-13 12:25:06 +02:00
nocode fb63cc9a2f feat(webhooks): add http server for gitea webhooks
Refs: #75
2026-09-13 12:25:06 +02:00
nocode 7a7d8e6fcd feat(webhooks): validate and deduplicate gitea webhook events
Refs: #75
2026-09-13 12:25:06 +02:00
nocode 13f8e24e54 feat(notifications): add notification dispatch service
Refs: #74
2026-09-13 12:25:06 +02:00
nocode 6fca3b7ec4 feat(gitea): add gitea api client
Refs: #42
2026-09-13 12:25:06 +02:00
nocode 856e7ba321 feat(ui): add link buttons builder
Refs: #99
2026-09-13 12:25:05 +02:00
nocode 94dab89791 feat(ui): add standard embed builders
Refs: #98
2026-09-13 12:25:05 +02:00
nocode f56e837e58 feat(utils): add cooldown guard against duplicate actions
Refs: #111
2026-09-13 12:25:05 +02:00
nocode 4205ed5d5b feat(utils): add retry helper with exponential backoff
Refs: #108
2026-09-13 12:25:05 +02:00
nocode de64a0eaf2 feat(database): add event log repository
Refs: #93
2026-09-13 12:25:05 +02:00
nocode 910cf3252f feat(database): add guild settings repository
Refs: #33
2026-09-13 12:25:05 +02:00
nocode 5716d248d3 feat(database): initialize sqlite connection and migrations
Refs: #16
2026-09-13 12:25:04 +02:00
nocode a2520fe787 feat(database): add initial sqlite schema
Refs: #16
2026-09-13 12:25:04 +02:00
nocode 34da3eb647 feat(discord): add event loader
Refs: #22
2026-09-13 12:25:04 +02:00
nocode 15e7279fc0 feat(commands): add slash command loader
Refs: #24
2026-09-13 12:25:04 +02:00
nocode baf8db059b feat(discord): create client with required gateway intents
Refs: #21
2026-09-13 12:25:04 +02:00
nocode 2085f570a8 feat(auth): add centralized permission checks
Refs: #29
2026-09-13 12:25:04 +02:00
nocode c03027e819 feat(observability): add json logger with secret masking
Refs: #17
2026-09-13 12:25:03 +02:00
nocode bba2ee7520 feat(core): add typed application errors
Refs: #17
2026-09-13 12:25:03 +02:00
nocode eca9bbed9f feat(config): add colors, access levels and ticket categories
Refs: #28
2026-09-13 12:25:03 +02:00
nocode d1388b6e93 feat(config): load and expose environment settings
Refs: #15
2026-09-13 12:25:03 +02:00
nocode 1cf7b1f6c8 build(config): add environment variables example
Refs: #15
2026-09-13 12:25:03 +02:00
nocode de328aff2e build(quality): configure eslint flat config
Refs: #18
2026-09-13 12:25:03 +02:00
nocode 25cc44d471 build(quality): add prettier ignore rules
Refs: #18
2026-09-13 12:25:02 +02:00
nocode bafda6b1f5 build(quality): configure prettier
Refs: #18
2026-09-13 12:25:02 +02:00
nocode d4d58544c3 build(deps): add npm lockfile 2026-09-13 12:25:02 +02:00
nocode f57a4f231d build(deps): add package manifest with discord.js and npm scripts
Refs: #12
2026-09-13 12:25:02 +02:00
nocode 4693ea09c4 chore(editor): add editorconfig settings
Refs: #18
2026-09-13 12:25:02 +02:00
nocode bfd4c2611f build(security): replace python ignore rules with node.js rules
Refs: #14
2026-09-13 12:25:02 +02:00
194 changed files with 32559 additions and 3332 deletions

No files matched your search

+9 -9
View File
@@ -1,9 +1,9 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
+112 -70
View File
@@ -1,70 +1,112 @@
# =============================================================================
# FWS-Bot — environment configuration example
# Copy this file to `.env` and fill in the values. Never commit `.env`.
# =============================================================================
# --- Runtime -----------------------------------------------------------------
# development | production | test
NODE_ENV=development
# debug | info | warn | error
LOG_LEVEL=info
LOG_DIR=./logs
# Number of days functional/technical logs are kept (M11-T08)
LOG_RETENTION_DAYS=30
# --- Discord application (M2-T01) -------------------------------------------
# Developer Portal > Bot > Token
DISCORD_TOKEN=
# Developer Portal > General Information > Application ID
DISCORD_CLIENT_ID=
# FWS server ID (slash commands are registered on this guild)
DISCORD_GUILD_ID=
# --- FWS roles (M3-T01) — Discord role IDs ----------------------------------
ROLE_OWNER_ID=
ROLE_DEV_ID=
ROLE_STAFF_ID=
# Role given to new members on join (M7-T03)
ROLE_MEMBER_ID=
# --- Discord channels (M0-T04 / M9-T01) — channel IDs -----------------------
CHANNEL_WELCOME_ID=
CHANNEL_RULES_ID=
CHANNEL_ANNOUNCEMENTS_ID=
CHANNEL_LOGS_ID=
CHANNEL_MOD_LOGS_ID=
CHANNEL_TICKETS_LOGS_ID=
CHANNEL_NOTIF_ISSUES_ID=
CHANNEL_NOTIF_PULL_REQUESTS_ID=
CHANNEL_NOTIF_COMMITS_ID=
CHANNEL_NOTIF_RELEASES_ID=
CHANNEL_NOTIF_ERRORS_ID=
# Category under which private ticket channels are created (M6)
CATEGORY_TICKETS_ID=
# --- Gitea (M5-T01) ----------------------------------------------------------
GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it.
GITEA_TOKEN=
GITEA_OWNER=FWS
GITEA_REPO=FWS-Arch
GITEA_TIMEOUT_MS=10000
GITEA_MAX_RETRIES=2
# --- Gitea webhooks (M9-T02) -------------------------------------------------
WEBHOOK_ENABLED=false
WEBHOOK_HOST=0.0.0.0
WEBHOOK_PORT=3000
WEBHOOK_PATH=/webhooks/gitea
# Shared secret configured in Gitea > Settings > Webhooks
GITEA_WEBHOOK_SECRET=
# --- SQLite (M1-T05) ---------------------------------------------------------
DATABASE_PATH=./data/fws-bot.sqlite
BACKUP_DIR=./data/backups
# --- FWS links (M0-T06 / M4-T04) ---------------------------------------------
FWS_WEBSITE_URL=
FWS_DOCS_URL=
FWS_DISCORD_INVITE_URL=
FWS_ARCH_REPO_URL=
# =============================================================================
# FWS-Bot — environment configuration example
# Copy this file to `.env` and fill in the values. Never commit `.env`.
# =============================================================================
# --- Runtime -----------------------------------------------------------------
# development | production | test
NODE_ENV=development
# debug | info | warn | error
LOG_LEVEL=info
LOG_DIR=./logs
# Number of days functional/technical logs are kept (M11-T08)
LOG_RETENTION_DAYS=30
# --- Discord application (M2-T01) -------------------------------------------
# Developer Portal > Bot > Token
DISCORD_TOKEN=
# Developer Portal > General Information > Application ID
DISCORD_CLIENT_ID=
# FWS server ID (slash commands are registered on this guild)
DISCORD_GUILD_ID=
# --- FWS roles (M3-T01) — Discord role IDs ----------------------------------
ROLE_OWNER_ID=
ROLE_DEV_ID=
ROLE_STAFF_ID=
# Role given to new members on join (M7-T03)
ROLE_MEMBER_ID=
# --- Discord channels (M0-T04 / M9-T01) — channel IDs -----------------------
CHANNEL_WELCOME_ID=
CHANNEL_RULES_ID=
CHANNEL_ANNOUNCEMENTS_ID=
CHANNEL_LOGS_ID=
CHANNEL_MOD_LOGS_ID=
CHANNEL_NOTIF_ISSUES_ID=
CHANNEL_NOTIF_PULL_REQUESTS_ID=
CHANNEL_NOTIF_COMMITS_ID=
CHANNEL_NOTIF_RELEASES_ID=
CHANNEL_NOTIF_ERRORS_ID=
# Category under which private ticket channels are created (M6)
CATEGORY_TICKETS_ID=
# --- Salons vocaux temporaires (M14) ----------------------------------------
# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire
CHANNEL_VOICE_TRIGGER_ID=
# Catégorie d'accueil des salons vocaux créés (facultatif)
CATEGORY_VOICE_ID=
# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat)
VOICE_EMPTY_GRACE_MS=5000
# --- Statuts du bot (M15) -----------------------------------------------------
# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval)
BOT_STATUS_INTERVAL_SECONDS=60
# --- Gitea (M5-T01) ----------------------------------------------------------
GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it.
GITEA_TOKEN=
GITEA_OWNER=FWS
GITEA_REPO=FWS-Arch
GITEA_TIMEOUT_MS=10000
GITEA_MAX_RETRIES=2
# --- Gitea webhooks (M9-T02) -------------------------------------------------
WEBHOOK_ENABLED=false
WEBHOOK_HOST=0.0.0.0
WEBHOOK_PORT=3000
WEBHOOK_PATH=/webhooks/gitea
# Shared secret configured in Gitea > Settings > Webhooks
GITEA_WEBHOOK_SECRET=
# --- Tableau de bord web (M16) -----------------------------------------------
# Site d'administration servi par le bot : `npm run setup` pour l'assistant .env,
# puis http://WEB_HOST:WEB_PORT une fois le bot démarré.
WEB_ENABLED=false
# 127.0.0.1 derrière un reverse proxy installé sur la même machine.
# 0.0.0.0 dans un conteneur ou sur un panel d'hébergement (Pterodactyl, Docker) :
# sinon le site n'écoute que sur la boucle locale et reste injoignable.
WEB_HOST=127.0.0.1
WEB_PORT=3080
# URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord.
# Doit correspondre exactement à une redirection déclarée dans le Developer Portal.
WEB_PUBLIC_URL=http://localhost:3080
# Clé de signature des cookies de session (64 caractères hex).
# Générer avec : node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
WEB_SESSION_SECRET=
WEB_SESSION_TTL_HOURS=12
# Developer Portal > OAuth2 > Client Secret. Requis pour la connexion au tableau de bord.
DISCORD_CLIENT_SECRET=
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
# À vider une fois le .env rempli.
WEB_SETUP_TOKEN=
# Publie /status : bot en ligne, derniers déploiements, dernières releases.
# Les dépôts privés n'y apparaissent jamais par leur nom.
WEB_PUBLIC_STATUS=true
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
WEB_ALLOW_COMMAND_DEPLOYS=false
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
WEB_ALLOW_RESTART=false
WEB_DEPLOY_TIMEOUT_MS=900000
WEB_RATE_LIMIT_PER_MINUTE=240
# --- SQLite (M1-T05) ---------------------------------------------------------
DATABASE_PATH=./data/fws-bot.sqlite
BACKUP_DIR=./data/backups
# --- FWS links (M0-T06 / M4-T04) ---------------------------------------------
FWS_WEBSITE_URL=
FWS_DOCS_URL=
FWS_DISCORD_INVITE_URL=
FWS_ARCH_REPO_URL=
+39
View File
@@ -0,0 +1,39 @@
---
name: Bug
about: Signaler un comportement inattendu
title: "[bug] "
labels: bug
---
## Description
<!-- Ce qui ne va pas, en une ou deux phrases. -->
## Étapes de reproduction
1.
2.
3.
## Comportement attendu
<!-- Ce qui devrait se passer. -->
## Comportement observé
<!-- Ce qui se passe vraiment : message affiché, code d'erreur, capture. -->
## Environnement
- OS :
- Node.js (`node -v`) :
- Version du bot (`version` dans `package.json`) :
- Serveur / salon concerné :
## Logs
<!-- Colle les lignes de logs/AAAA-MM-JJ.log (en masquant les identifiants si besoin) ou une capture d'écran. -->
## Contexte
<!-- Optionnel : commande utilisée, carte Kanban, issue ou PR liée, contournement trouvé. -->
+29
View File
@@ -0,0 +1,29 @@
---
name: Demande / amélioration
about: Proposer une fonctionnalité ou une amélioration
title: "[enhancement] "
labels: enhancement
---
## Besoin
<!-- Quel problème cela résout, pour qui (membres, équipe, développeurs). -->
## Proposition
<!-- Le comportement souhaité, vu depuis Discord : quelle commande, quelles options, quelle réponse. -->
## Alternatives envisagées
<!-- Optionnel : autres pistes, solutions de contournement existantes. -->
## Impact
- [ ] Nouvelle commande ou nouvelle option
- [ ] Changement de comportement d'une fonctionnalité existante
- [ ] Base de données (nouvelle migration)
- [ ] Documentation (`README.md` / `README.en.md` / `docs/`)
## Contexte
<!-- Optionnel : carte Kanban, issue liée, maquette, capture. -->
+28
View File
@@ -0,0 +1,28 @@
## Objectif
<!-- Pourquoi cette pull request existe : besoin traité, carte Kanban. -->
Fixes #
## Ce que fait la pull request
<!-- Les changements, du point de vue de qui relit. Pas de liste de fichiers. -->
## Comment tester
<!-- Étapes concrètes : commande à lancer dans Discord, entrée à envoyer au webhook, migration à appliquer. -->
## Vérifications
- [ ] `npm run lint`
- [ ] `npm run format:check`
- [ ] `npm test`
- [ ] `npm run changelog` (si des commits `feat:` ou `fix:` sont ajoutés)
## Checklist
- [ ] Commits en **anglais** au format Conventional Commits (`<type>(<scope>): <description>`)
- [ ] Branche `type/description` créée depuis `main`
- [ ] Tests ajoutés ou mis à jour quand le comportement change
- [ ] `README.md` et `README.en.md` synchronisés quand la documentation change
- [ ] Au moins un reviewer demandé, merge en **squash** (1 PR = 1 commit)
+35
View File
@@ -0,0 +1,35 @@
name: CI
# Lint and tests on every push and every pull request. `format:check` is
# deliberately absent: the repository still holds CRLF files that predate the
# Prettier configuration, so the step would fail on untouched code. Normalise
# the line endings in a commit of their own, then add it here.
on:
push:
branches: [main]
pull_request:
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- name: Installer les dépendances
run: npm ci
- name: Lint
run: npm run lint
- name: Tests
run: npm test
# The changelog is generated from the commit history, so a stale one is
# a real defect rather than a formatting detail.
- name: Changelog à jour
run: npm run changelog:check
+52 -37
View File
@@ -1,37 +1,52 @@
# Dependencies
node_modules/
# Environment and secrets
.env
.env.*
!.env.example
.freebuff
# SQLite databases and backups
data/*
!data/.gitkeep
*.sqlite
*.sqlite3
*.db
*.db-journal
*-wal
*-shm
# Logs
logs/*
!logs/.gitkeep
*.log
npm-debug.log*
# Build and coverage
dist/
build/
coverage/
.cache/
# Editors and OS
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
Thumbs.db
# Dependencies
node_modules/
# Environment and secrets
.env
.env.*
!.env.example
# Development assistant data (never committed)
.freebuff/
.cursor/
# SQLite databases and backups
data/*
!data/.gitkeep
*.sqlite
*.sqlite3
*.db
*.db-journal
*-wal
*-shm
# Logs
logs/*
!logs/.gitkeep
*.log
npm-debug.log*
# Build and coverage
dist/
build/
coverage/
.cache/
# Compiled artefacts of the other toolchains used across FWS projects
target/
__pycache__/
*.pyc
*.pyo
*.o
*.so
*.exe
*.dll
# Editors and OS
# `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions
# shared by the project. Everything else in the folder is personal.
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
Thumbs.db
+5 -5
View File
@@ -1,5 +1,5 @@
node_modules/
data/
logs/
package-lock.json
README.md
node_modules/
data/
logs/
package-lock.json
README.md
+6 -6
View File
@@ -1,6 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 110,
"semi": true
}
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 110,
"semi": true
}
+59
View File
@@ -0,0 +1,59 @@
# AGENTS.md — Instructions pour les agents IA
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un dépôt de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` présente l'organisation et le `CONTRIBUTING.md` détaille les conventions de collaboration.
## Contexte
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack technique (sans restriction de langage).
- Projet principal : **FWS ISO** — une distribution Linux basée sur Arch Linux, pensée pour simplifier l'installation et l'usage au quotidien.
- Conventions détaillées : `CONTRIBUTING.md` (FR) / `CONTRIBUTING.en.md` (EN).
## Règles à respecter
### Commits
- Messages en **anglais**, format **Conventional Commits** : `<type>(<portée>): <description>`.
- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Titre court et impératif ; un corps n'est ajouté que pour expliquer le **pourquoi**, pas le comment.
### Nommage
- Branches : `type/description` (ex. `feat/login`, `fix/typo`).
- Fichiers : **kebab-case** (ex. `my-component.ts`).
- Identifiants (variables, fonctions, classes) : **anglais**.
### Code & commentaires
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite ; documenter le non-évident (choix d'implémentation, compromis, cas limites).
- Respecter la stack technique et les conventions existantes du dépôt avant d'ajouter de nouvelles dépendances.
### Fichiers sensibles (`.gitignore`)
- Ne **jamais** versionner : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
- Un `.gitignore` doit exister à la racine de chaque dépôt.
### Tests
- Fichiers de test : `*.test.*` ; noms de tests `describe` / `it` en anglais.
- Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée.
### Issues & signalement de bugs
- Les bugs et demandes sont suivis via les **issues** et, lorsqu'il existe, le tableau Kanban du projet.
- Une pull request qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
- Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur.
### Commits demandés par l'utilisateur
- Lorsque l'utilisateur demande explicitement de créer un commit, l'IA doit le faire après avoir vérifié les changements et les contrôles disponibles, sans attendre une confirmation supplémentaire.
- Le titre et le corps du commit ne doivent jamais mentionner l'IA, l'assistant, Codebuff ou l'outil utilisé.
- Ne pas ajouter l'IA comme auteur ou co-auteur dans le message du commit.
## Bonnes pratiques pour un agent
- Lire `AGENTS.md`, le `README.md` et le `CONTRIBUTING.md` avant d'éditer du code.
- Les commits doivent être signés.
- Faire les changements les plus petits possibles qui répondent à la demande.
- Ne pas pousser, fusionner ni publier sans demande explicite de l'utilisateur.
- Suivre les cartes du tableau Kanban lorsqu'il existe pour organiser le travail.
- En cas de doute, demander plutôt que de deviner.
+150
View File
@@ -0,0 +1,150 @@
# Changelog
All notable changes to this project are documented in this file. It is **generated from the
Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.
The project follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Features
- **rules:** _(feat)_ write the rules from the dashboard and republish them ([31c0fc8])
- **moderation:** _(feat)_ add the unmute and unban commands ([9f8ac0d])
- **web:** _(feat)_ publish a public status page at /status ([a1e1de7])
- **web:** _(feat)_ search the whole panel from one place ([9acb523])
- **projects:** _(feat)_ gather the cards one member carries ([fcc82d8])
- **projects:** _(feat)_ pull Gitea issues onto any board ([1c21f6f])
- **wiki:** _(feat)_ serve the legal pages at /terms-of-service and /privacy-policy ([3d0e21d])
- **projects:** _(feat)_ add the board interface ([e1b9a5c])
- **projects:** _(feat)_ add a Kanban board per repository and one for the organization ([901ca56])
- **web:** _(feat)_ open a repository from anywhere on its row ([95b51ab])
- **wiki:** _(feat)_ add the reading site and its editor ([e5b7303])
- **wiki:** _(feat)_ serve a public documentation written from the panel ([c76c0b9])
- **web:** _(feat)_ publish the slash commands from the panel ([2622744])
- **voice:** _(feat)_ take back the generated channels the database forgot ([b42fb10])
- **settings:** _(feat)_ make the server settings real, and widen them ([406b5af])
- **web:** _(feat)_ make deploying reachable from where it is looked for ([d439b1b])
- **web:** _(feat)_ refresh the pages as the events arrive ([5481e79])
- **web:** _(feat)_ push live updates to the dashboard ([df89cc5])
- **web:** _(feat)_ serve the dashboard and its interface ([06a9be0])
- **web:** _(feat)_ expose the dashboard API ([bf92bad])
- **web:** _(feat)_ run and record release deployments ([611129b])
- **web:** _(feat)_ read, validate and write the .env configuration ([efaaca3])
- **web:** _(feat)_ add the HTTP layer and Discord-backed sessions ([e03b184])
- **database:** _(feat)_ store dashboard sessions, deploy targets and deployments ([5abe713])
- **gitea:** _(feat)_ add an organization and repository administration client ([4b0737a])
- **config:** _(feat)_ declare the web dashboard environment variables ([e4534d4])
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
- **voice:** _(feat)_ add temporary voice channel manager ([5191942])
- **polls:** _(feat)_ implement polls, fun and statistics commands ([ef1bedb])
- **members:** _(feat)_ add welcome, default role and departure reporting ([f29c095])
- **moderation:** _(feat)_ implement the moderation service and commands ([c49c600])
- **tickets:** _(feat)_ implement the ticket service, command and channel controls ([e8c95b2])
- **notifications:** _(feat)_ dispatch Gitea webhooks through the notification service ([a5280ce])
- **fws:** _(feat)_ implement the version, status and changelog subcommands ([26d7cce])
- **gitea:** _(feat)_ add embeds, modals and the issue and pull request commands ([76d0bf9])
- **core:** _(feat)_ add shared constants, interaction components and Gitea client helpers ([66be463])
- **database:** _(feat)_ add repositories for tickets, moderation, polls and notifications ([03a217c])
- **database:** _(feat)_ add database initialization script ([9a266b7])
- **commands:** _(feat)_ add slash command deployment script ([6b4ac37])
- **core:** _(feat)_ add bot entry point ([de97f87])
- **fun:** _(feat)_ add fun command skeleton ([208d713])
- **stats:** _(feat)_ add stats command skeleton ([baca3f0])
- **polls:** _(feat)_ add poll command skeleton ([9ccecb3])
- **roles:** _(feat)_ add role command skeleton ([cef9ed0])
- **moderation:** _(feat)_ add moderation logs command skeleton ([744eaa8])
- **moderation:** _(feat)_ add clear command skeleton ([dc4958f])
- **moderation:** _(feat)_ add ban command skeleton ([002380c])
- **moderation:** _(feat)_ add kick command skeleton ([4cc475e])
- **moderation:** _(feat)_ add mute command skeleton ([373c7e6])
- **moderation:** _(feat)_ add warn command skeleton ([1bcc3d3])
- **support:** _(feat)_ add ticket command skeleton ([ab08253])
- **gitea:** _(feat)_ add activity and release command skeleton ([d9ce9e4])
- **gitea:** _(feat)_ add pull request command skeleton ([44c9595])
- **gitea:** _(feat)_ add issue command skeleton ([bd2475c])
- **fws:** _(feat)_ add fws information command ([4cc6964])
- **commands:** _(feat)_ add help command ([3aa17e5])
- **members:** _(feat)_ add member leave event handler ([9cb2a73])
- **members:** _(feat)_ add member join event handler ([aa404dd])
- **commands:** _(feat)_ dispatch slash commands with access control ([017764d])
- **discord:** _(feat)_ log shard disconnections ([8f48efd])
- **discord:** _(feat)_ log discord client errors ([e9c110a])
- **discord:** _(feat)_ handle client ready event ([0fb20d1])
- **webhooks:** _(feat)_ add http server for gitea webhooks ([fb63cc9])
- **webhooks:** _(feat)_ validate and deduplicate gitea webhook events ([7a7d8e6])
- **notifications:** _(feat)_ add notification dispatch service ([13f8e24])
- **gitea:** _(feat)_ add gitea api client ([6fca3b7])
- **ui:** _(feat)_ add link buttons builder ([856e7ba])
- **ui:** _(feat)_ add standard embed builders ([94dab89])
- **utils:** _(feat)_ add cooldown guard against duplicate actions ([f56e837])
- **utils:** _(feat)_ add retry helper with exponential backoff ([4205ed5])
- **database:** _(feat)_ add event log repository ([de64a0e])
- **database:** _(feat)_ add guild settings repository ([910cf32])
- **database:** _(feat)_ initialize sqlite connection and migrations ([5716d24])
- **database:** _(feat)_ add initial sqlite schema ([a2520fe])
- **discord:** _(feat)_ add event loader ([34da3eb])
- **commands:** _(feat)_ add slash command loader ([15e7279])
- **discord:** _(feat)_ create client with required gateway intents ([baf8db0])
- **auth:** _(feat)_ add centralized permission checks ([2085f57])
- **observability:** _(feat)_ add json logger with secret masking ([c03027e])
- **core:** _(feat)_ add typed application errors ([bba2ee7])
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
- **config:** _(feat)_ load and expose environment settings ([d1388b6])
### Bug Fixes
- **rules:** _(fix)_ show the rules field with a save button and edit the message ([e6ce594])
- **moderation:** _(fix)_ tell a mute apart from a kick in the logs ([99e1fd2])
- **wiki:** _(fix)_ render the public pages on the server ([8869c74])
- **web:** _(fix)_ stop caching the interface modules ([3f4a570])
- **web:** _(fix)_ keep the stack when a view fails ([c031b4d])
- **web:** _(fix)_ read the interface build date instead of freezing it at startup ([92c27ae])
- **web:** _(fix)_ stop the settings page breaking on an unexpected payload ([75d1e53])
- **web:** _(fix)_ give static assets a validator caches can check ([539b150])
- **web:** _(fix)_ say when the dashboard is disabled ([3bd290c])
- **web:** _(fix)_ say out loud when the dashboard cannot listen ([afcd0e5])
- **config:** _(fix)_ warn when a public address is announced but only loopback is bound ([40032ec])
- **web:** _(fix)_ make the whole repository card open the repository ([e397abc])
- **web:** _(fix)_ pin the sidebar highlight to the route, and name the build ([a44ff0c])
- **web:** _(fix)_ always offer the bootstrap token on the sign-in page ([9c6297e])
- **web:** _(fix)_ let a deploy target be created without a reachable Gitea ([ff15dfe])
- **web:** _(fix)_ keep the sidebar in step with the page being shown ([a0428e0])
- **web:** _(fix)_ derive the OAuth2 redirect from the address actually used ([20ff701])
- **notifications:** _(fix)_ apply the channel overrides set from Discord ([92405ac])
### Other changes
- **agents:** _(docs)_ update the repository conventions and commit rules ([44e990d])
- **web:** _(docs)_ document my tasks, the search and the status page ([566af4d])
- **web:** _(refactor)_ extract the build marker into its own module ([d2256e2])
- **ops:** _(docs)_ correct the deployment path for a panel without a shell ([e3ce266])
- **ops:** _(docs)_ document deployment, CI, monitoring and backups ([1643fcb])
- **web:** _(test)_ lock the sidebar highlighting behind tests ([b793298])
- **web:** _(docs)_ document the wiki, the settings and the command publishing ([5660235])
- **web:** _(style)_ adopt the official FWS mark and its palette ([621f3e4])
- **web:** _(docs)_ document the live updates ([2083133])
- **web:** _(docs)_ document the dashboard and the configuration wizard ([e63d6aa])
- **web:** _(test)_ cover the router, configuration, auth, deployments and server ([bd7fdea])
- **all:** _(refactor)_ uniformisation ([50665c8])
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
- **ui:** _(refactor)_ give every message one friendly, ungendered voice ([ef8f09d])
- **agents:** _(docs)_ add the shared agent instructions for FWS repositories ([66c04c6])
- **readme:** _(docs)_ document the implemented features and the voice manager ([be4981a])
- **app:** _(test)_ add command and event loading smoke tests ([aa5343b])
- **core:** _(docs)_ document project structure ([abf6701])
- **docs:** _(chore)_ add screenshots directory ([fec8007])
- **observability:** _(chore)_ keep logs directory in repository ([9f2aa90])
- **database:** _(chore)_ keep data directory in repository ([070612a])
- **database:** _(test)_ add sqlite storage tests ([baef3fa])
- **auth:** _(test)_ add permission checks tests ([52e24bd])
- **config:** _(build)_ add environment variables example ([1cf7b1f])
- **quality:** _(build)_ configure eslint flat config ([de328af])
- **quality:** _(build)_ add prettier ignore rules ([25cc44d])
- **quality:** _(build)_ configure prettier ([bafda6b])
- **deps:** _(build)_ add npm lockfile ([d4d5854])
- **deps:** _(build)_ add package manifest with discord.js and npm scripts ([f57a4f2])
- **editor:** _(chore)_ add editorconfig settings ([4693ea0])
- **security:** _(build)_ replace python ignore rules with node.js rules ([bfd4c26])
- **BREAKING** **readme:** _(docs)_ Edit of the Readme ([2a91229])
- Initial commit ([5fc5cf8])
+546
View File
@@ -0,0 +1,546 @@
# FWS-Bot
> Discord bot for the open source **FWS** organisation — community support, tickets, moderation, Gitea integration and statistics for **FWS Arch** (an Arch Linux fork with a friendly layer on top).
🌍 [Version française](README.md) · **English**
Status: **working**. The 19 commands are implemented (support, private tickets, moderation, Gitea, polls, statistics, bot statuses, voice channel manager), together with member welcome and the Gitea webhook delivery.
This project follows the [FWS organisation conventions](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md): English commit messages in the Conventional Commits format, `type/description` branches, reviewed pull requests merged with squash, SemVer and a `CHANGELOG.md` generated from the commits.
---
## 1. Tech stack
Deliberate choices: **a single runtime dependency** (discord.js), no native module to compile, and the test runner built into Node.
| Tech | Version | Purpose |
| ------------------ | --------------------- | ------------------------------------------------------------------------- |
| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Required for `node:sqlite`, `process.loadEnvFile`, `--watch` |
| **discord.js** | ^14.21.0 | Discord API: slash commands, embeds, buttons, intents |
| **`node:sqlite`** | native module | SQLite database (WAL, foreign keys) — no `better-sqlite3`, no compilation |
| **native `fetch`** | — | Gitea REST client (with `AbortSignal.timeout`) |
| **`node:http`** | — | Gitea webhook server (no Express) |
| **`node:crypto`** | — | HMAC-SHA256 signature of the webhooks |
| **`node:test`** | — | Built-in unit tests (`node --test`) |
| **ESLint** | ^9.30.0 (flat config) | Linting |
| **Prettier** | ^3.6.2 | Formatting |
## 2. Requirements
- Node.js ≥ 22.13 (`node -v` to check) and npm
- A Discord application (free) with a bot token
- (Optional) a Gitea instance for issues/pull requests and webhooks
## 3. Quick start with a test token
### 3.1 Create the Discord application
1. Open the [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**.
2. **Bot** tab → **Reset Token** → copy the token: that is your `DISCORD_TOKEN` (never share it, never commit it).
3. Still in **Bot** → **Privileged Gateway Intents** → enable **Server Members Intent** (needed to welcome new members; `Message Content` is not required).
4. **General Information** tab → copy the **Application ID**: that is your `DISCORD_CLIENT_ID`.
### 3.2 Invite the bot to a test server
Replace `CLIENT_ID` with your Application ID:
```text
https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294
```
That URL pre-checks every permission the commands use: View Channels, Send Messages, Manage Messages, Embed Links, Read Message History, Kick Members, Ban Members, Manage Roles, Moderate Members (timeout), plus the voice channel ones: Manage Channels, Connect, Speak, Mute Members, Deafen Members, Move Members. You can also use **OAuth2 → URL Generator** with the `bot` + `applications.commands` scopes.
Create (or reuse) a test server you own: that is what grants the bot the **Owner** level.
### 3.3 Collect the Discord IDs
On Discord: **Settings → Advanced → Developer Mode** on, then right-click a server / channel / role → **Copy ID**.
| Variable | Where to find it |
| ----------------------------------------------------------------- | ------------------------------------------- |
| `DISCORD_GUILD_ID` | Right-click the test server |
| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Server settings → Roles (create them first) |
| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Right-click each channel |
> Without configured roles everyone counts as **User** (except the server owner, who is Owner).
### 3.4 Run the bot
```bash
# 1. Dependencies
npm install
# 2. Configuration: copy .env.example to .env and fill it in
# Minimum required: DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID
cp .env.example .env
# 3. Create the SQLite database and apply the migrations
npm run db:init
# 4. Register the slash commands on the server (instant, per guild)
npm run deploy:commands
# 5. Start with automatic reload
npm run dev
```
The logs should show `Connected as <BotName>`. Type `/help` on the server: you should see the commands your role can use.
Without a `.env` the bot refuses to start (`assertRequiredEnv` checks the token, client ID and guild ID).
## 4. Configuration — every variable (`.env`)
Full template: [`.env.example`](.env.example). Default values in brackets.
### Runtime
| Variable | Default | Description |
| ----------------------------- | ------------- | ------------------------------------------------------------------------------- |
| `NODE_ENV` | `development` | `development` \| `production` \| `test` |
| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
| `LOG_DIR` | `./logs` | Directory of the daily JSON logs |
| `LOG_RETENTION_DAYS` | `30` | Retention window (purges `event_logs`) |
| `VOICE_EMPTY_GRACE_MS` | `5000` | Delay before a generated voice channel left empty is deleted (`0` = immediate) |
| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Default rotation speed of the bot statuses (changeable with `/status interval`) |
### Discord application
| Variable | Description |
| ------------------- | ------------------------------------------------------------ |
| `DISCORD_TOKEN` | **Required.** Bot token (Developer Portal → Bot) |
| `DISCORD_CLIENT_ID` | **Required.** Application ID |
| `DISCORD_GUILD_ID` | **Required.** Server where the slash commands are registered |
### FWS roles (Discord role IDs)
| Variable | Matching level |
| ---------------- | ------------------------------------------ |
| `ROLE_OWNER_ID` | Owner — full access |
| `ROLE_DEV_ID` | Dev — FWS Arch configuration, Gitea writes |
| `ROLE_STAFF_ID` | Staff — moderation, support, tickets |
| `ROLE_MEMBER_ID` | Initial role given to new members |
### Discord channels (IDs)
| Variable | Usage |
| -------------------------------- | --------------------------------------------------------------------------- |
| `CHANNEL_WELCOME_ID` | Welcome messages |
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
| | Later saves edit that same message |
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
| `CHANNEL_LOGS_ID` | Functional and technical logs, ticket journal |
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications |
| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications |
| `CHANNEL_NOTIF_RELEASES_ID` | Release notifications |
| `CHANNEL_NOTIF_ERRORS_ID` | Errors and incidents |
| `CATEGORY_TICKETS_ID` | Category where the private ticket channels are created |
| `CHANNEL_VOICE_TRIGGER_ID` | Trigger voice channel (fallback: `/voice setup` manages a list of triggers) |
| `CATEGORY_VOICE_ID` | Home category of the generated voice channels (optional) |
### Gitea
| Variable | Default | Description |
| ------------------- | ------- | ---------------------------------------------------------------------- |
| `GITEA_URL` | — | Instance URL (without a trailing `/`) |
| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged |
| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) |
| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Request timeout |
| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) |
### Gitea webhooks
| Variable | Default | Description |
| ---------------------- | ----------------- | ---------------------------------------------------- |
| `WEBHOOK_ENABLED` | `false` | Starts the receiving HTTP server |
| `WEBHOOK_HOST` | `0.0.0.0` | Listening interface |
| `WEBHOOK_PORT` | `3000` | Listening port |
| `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea |
| `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks |
### Web dashboard
| Variable | Default | Description |
| --- | --- | --- |
| `WEB_ENABLED` | `false` | Serves the admin site from the bot process |
| `WEB_HOST` | `127.0.0.1` | Listening interface. Use `0.0.0.0` only behind an HTTPS reverse proxy |
| `WEB_PORT` | `3080` | Site port. When it equals `WEBHOOK_PORT`, a single HTTP server is started |
| `WEB_PUBLIC_URL` | — | Public URL of the site, base of the OAuth2 `/auth/callback` redirect |
| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret |
| `WEB_SESSION_SECRET` | — | Session signing key (64 hexadecimal characters) |
| `WEB_SESSION_TTL_HOURS` | `12` | Session lifetime before signing in again |
| `WEB_SETUP_TOKEN` | — | Bootstrap token opening the wizard without a Discord account |
| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Allows shell-command deploy targets (Owner only) |
| `WEB_ALLOW_RESTART` | `false` | Shows the bot restart button |
| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Delay after which a deployment is marked failed |
| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | API requests per minute and per IP address |
### SQLite and links
| Variable | Default | Description |
| -------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------- |
| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Database file (excluded from git) |
| `BACKUP_DIR` | `./data/backups` | Backup directory |
| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Official links shown by `/fws info` and `/fws links` (empty buttons are omitted) |
## 5. Slash commands
19 commands are registered. Every command carries an **FWS access level** checked server-side before running, and the moderation commands additionally check the matching **Discord permission** (`DefaultMemberPermissions`).
### Access levels
Resolved from the roles configured in `.env` (highest to lowest):
| Level | Who |
| ----------- | ------------------------------- |
| `OWNER` (3) | Owner role, or the server owner |
| `DEV` (2) | Dev role |
| `STAFF` (1) | Staff role |
| `USER` (0) | Every member |
### General and FWS
| Command | Options | Access | State | Description |
| --------------------------------------- | --------------------------------- | --------------------------- | ----- | -------------------------------------------------------------------------------------- |
| `/help` | — | User | ✅ | Lists the commands your role can use (ephemeral reply) |
| `/fws info` | — | User | ✅ | Presents FWS and FWS Arch (text overridable through `guild_settings`) + official links |
| `/fws links` | — | User | ✅ | Resources: website, docs, repository, Gitea, Discord |
| `/fws version` | — | User | ✅ | Latest Gitea release (tag, date, author) + button to the notes |
| `/fws status` | — | User | ✅ | Service status: Gitea API, webhooks, SQLite, Discord latency, uptime |
| `/fws changelog` | `version` (optional) | User | ✅ | Release notes (latest by default, clear message when the tag does not exist) |
| `/status add` | `text` (128 chars), `type`, `url` | **Staff** + _Manage Server_ | ✅ | Adds a status to the rotation; the first one is shown right away |
| `/status list` | — | **Staff** + _Manage Server_ | ✅ | Stored statuses: number, type, state, rotation speed |
| `/status remove` · `enable` · `disable` | `id` | **Staff** + _Manage Server_ | ✅ | Removes a status, puts it back in rotation or pauses it |
| `/status interval` | `seconds` (5–86 400) | **Staff** + _Manage Server_ | ✅ | Rotation speed, applied without a restart |
| `/status clear` | — | **Staff** + _Manage Server_ | ✅ | Empties the list and returns to the default line |
### Gitea — issues and pull requests
| Command | Options | Access | State | Description |
| ----------------- | ------------------------------------------- | ------------------- | ----- | ------------------------------------------------------ |
| `/issue create` | — (modal: title + description) | User (configurable) | ✅ | Creates a Gitea issue and returns its link |
| `/issue view` | `number` | User | ✅ | Title, author, state, labels, link of an issue |
| `/issue list` | — | User | ✅ | Open issues (last 15) |
| `/pr create` | `head`, `base` + modal (title, description) | **Dev** | ✅ | Creates a Gitea pull request |
| `/pr view` | `number` | User | ✅ | Title, author, state, branches, link of a pull request |
| `/pr list` | — | User | ✅ | Open pull requests (last 15) |
| `/gitea activity` | — | User | ✅ | Latest commits + open issues and pull requests |
| `/gitea release` | — | User | ✅ | FWS Arch releases (last 5) |
> The Gitea client (`src/services/gitea/gitea-client.js`): REST with token, timeout, exponential retry on transient errors. The forms (`/issue create`, `/pr create`) go through a **modal**; the branch options are kept in memory for a few minutes (`pending-actions.js`). Any failure (missing token, 404, 5xx) becomes an explicit ephemeral message, never a raw error.
### Support tickets
Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint).
`/ticket setup` publishes a panel with an **Open a ticket** button in the current channel: the member presses the button, picks a category in a menu, and the private channel opens. The panel channel is stored (`ticket_panels`), so the panel survives a restart and a reinstall replaces the previous message instead of stacking a second one.
| Command | Options | Access | State | Description |
| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ |
| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button |
| `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) |
| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel |
| `/ticket setup` | — | **Staff** | ✅ | Publishes and pins the opening panel in this channel (replaces the previous one) |
| `/ticket setup-remove` | — | **Staff** | ✅ | Removes the panel from this channel |
Available categories and who can use them:
| Category | Visible to |
| ------------------------- | ----------------- |
| Aide et support | Staff, Owner |
| Bug | Staff, Dev, Owner |
| Question de développement | Dev, Owner |
| Signalement | Staff, Owner |
| Demande interne | Owner |
### Temporary voice channels
A server can declare **as many trigger channels as it needs** — one per theme (`Dev`, `SIO`, …) — each with its own home category (`/voice setup`): joining a trigger creates a private voice channel **at the bottom of that trigger's category**, moves the member in and hands over ownership. The channel is then managed from the **control panel** posted in its chat (_Rename_, _Limit_, _Lock_, _Claim_, _Delete_ buttons and the _Permit_, _Reject_, _Transfer_ menus) or with `/voice`. The number of simultaneous channels is **unlimited**, and a member keeps one channel **per trigger**: joining the same trigger again simply moves them back into the channel they already own.
As soon as **nobody** is left in a generated channel, it is deleted: the delay (5 s by default) lets it survive a quick hop to another channel — tunable with `VOICE_EMPTY_GRACE_MS`, `0` deletes it immediately. A periodic sweep (at startup, then every minute) catches the cases where a Discord event was missed or a deletion was refused, so a generated channel cannot stay empty: either it is deleted, or the attempt is retried.
| Command | Options | Access | Description |
| ---------------------------------------- | ------------------------------------------------------------ | --------------------- | ------------------------------------------------------------------------------------------- |
| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Adds (or updates) a trigger channel; without `category`, the trigger's own category is used |
| `/voice config` · `/voice triggers list` | — | User · **Staff** | Declared triggers: category, template, limit, state and live channels |
| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Pauses a trigger (its configuration is kept, joining it creates nothing) · resumes it |
| `/voice triggers remove` | `trigger` | **Staff** | Deletes a trigger declared from Discord |
| `/voice panel` | `trigger` (default: all) | **Staff** | Re-posts the explanation panel in the trigger channels |
| `/voice name` | `name` (100 chars) | Owner | Renames the channel |
| `/voice limit` | `limit` (0–99, 0 = unlimited) | Owner | Number of spots |
| `/voice lock` · `/voice unlock` | — | Owner | Refuses · allows everyone to join |
| `/voice permit` | `user` | Owner | Allows a member to join the channel |
| `/voice reject` | `user` | Owner | Denies access (and kicks them out if they are inside) |
| `/voice kick` | `user` | Owner | Kicks a member out of the channel |
| `/voice transfer` | `user` | Owner | Transfers ownership (the new owner must already be inside) |
| `/voice claim` | — | Member of the channel | Claims a channel whose owner left |
| `/voice delete` | `channel` (staff) | Owner, Staff | Deletes the channel immediately |
| `/voice info` | `channel` (staff) | User | Owner, state, limit, members, age |
> Name template: `{user}` is replaced by the member's display name (default `🔊 Salon de {user}`). Staff can always act on any temporary channel. The owner receives `Manage Channel` + `Move Members` on their own channel only.
>
> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` remain a **fallback**: a server whose `.env` declares a trigger works without `/voice setup`, but a trigger coming from the environment can only be paused (`/voice triggers disable`), not deleted from Discord. Changing a trigger's category does not move the channels already created.
### Moderation
Every command checks the FWS level **and** the matching Discord permission. The bot refuses to act on a member whose highest role is equal or higher than the caller's (`canActOn`), and never acts on the server owner.
| Command | Options | Discord permission | State | Description |
| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ |
| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action |
| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification |
| `/unmute` | `user`, `reason` | Moderate Members | ✅ | Lifts the timeout early (clear message when nobody is muted) |
| `/unban` | `user`, `reason` | Ban Members | ✅ | Lifts the ban, even if the member already left, and DMs them |
| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action |
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge |
| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) |
| `/mod logs` | `user` (filter) | Moderate Members | ✅ | History read from `moderation_actions` (last 15, ephemeral) |
| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Manage Roles | ✅ | Adds or removes a role (both hierarchies checked) |
| `/notify set` | `type`, `channel` | Manage Server | ✅ | Notification channel specific to this server (SQLite) |
| `/notify remove` | `type` | Manage Server | ✅ | Returns to the default channel (environment variables) |
| `/notify list` | — | Manage Server | ✅ | Current configuration of every type |
> Every successful action is recorded in `moderation_actions` **and** posted in `CHANNEL_MOD_LOGS_ID` (member, moderator, reason, duration).
### Community and statistics
| Command | Options | Access | State | Description |
| ---------------- | --------------------------------------------------------------------- | --------- | ----- | ---------------------------------------------------------------- |
| `/poll create` | `question`, `choices` (separated by « ; », 2–10), `minutes` (1–10080) | **Staff** | ✅ | Poll voted with buttons, live results |
| `/poll close` | `id` | **Staff** | ✅ | Closes it, shows the winning choice and freezes the message |
| `/stats discord` | — | User | ✅ | Members, channels, roles, boosts, server age, latency |
| `/stats gitea` | — | User | ✅ | Recent commits, open issues and pull requests, latest release |
| `/stats fws` | — | User | ✅ | Local indicators (tickets, polls, moderation) + FWS Arch version |
| `/fun coinflip` | — | User | ✅ | Heads or tails |
| `/fun dice` | `sides` (2–1000, 6 by default) | User | ✅ | Dice roll |
| `/fun 8ball` | `question` | User | ✅ | Magic eight ball (12 answers) |
| `/fun choose` | `options` (separated by « ; », 2–10) | User | ✅ | Random pick |
Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message.
## 6. Web dashboard
The bot serves its own admin site: Gitea organization, repositories, releases, deployments, Discord server, logs and configuration. Full details: [`docs/web-dashboard.md`](docs/web-dashboard.md).
No added dependency: `node:http` for the server, `node:sqlite` for the sessions, and a plain JavaScript front-end served as is.
The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed.
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, rules, tickets, voice, notifications.
### 6.1 Getting started
Without a `.env` the bot refuses to start, so the configuration wizard runs on its own, without connecting to Discord.
```bash
npm run setup
```
The console prints the site URL and a temporary bootstrap token. Once the file is written, set `WEB_ENABLED=true` and start the bot as usual: the site then listens on `WEB_HOST:WEB_PORT`.
So that members can sign in with Discord: copy the **Client Secret** from the portal into `DISCORD_CLIENT_SECRET`, add `<WEB_PUBLIC_URL>/auth/callback` under **OAuth2 → Redirects** exactly as is, and generate `WEB_SESSION_SECRET`.
### 6.2 Access and display modes
The site reuses the access levels of the slash commands, derived from the Discord roles. Signing in requires at least the **Staff** level; **Dev** unlocks writes on repositories and deployments; **Owner** unlocks repository deletion, API tokens, backups and configuration.
A **Simple / Advanced** switch hides or reveals the technical panels. It changes no permission: every call is checked again on the server.
The pages update on their own: the server pushes every change over a `text/event-stream`, and an indicator at the bottom of the sidebar says where the connection stands. Nothing reloads while a dialog is open or a field has focus, and a periodic refresh takes over when the stream cannot get through.
### 6.3 Configuration wizard
Every `.env` variable is described once, in `src/web/services/env-schema.js`: the form, the explanations, the validation and the generated file all derive from it.
The wizard tells you where to find each value, validates as you type, flags questionable combinations, generates the secrets, tests the Discord token and the Gitea token **before** writing anything, shows a preview of the file, backs the previous one up as `.env.bak-<timestamp>` then writes the new one with `600` permissions. An empty secret keeps the value already in place.
### 6.4 Releases and deployments
Publishing a release from the site builds its notes from the Conventional Commits, announces it in the releases channel and triggers the targets marked for automatic deployment.
Three kinds of target: an HMAC-SHA256 signed **webhook** (recommended, nothing runs on the bot host), a **Gitea Actions workflow**, and a **shell command** — the latter stays blocked until `WEB_ALLOW_COMMAND_DEPLOYS` is enabled, and requires the Owner level. Every attempt leaves its full log in the history, successful or not.
## 7. Automations
- **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed).
- **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age.
- **Notifications** (`src/services/notifications/notification-service.js`): routing per type — per-guild override in SQLite (`notification_channels`, configured with `/notify set`), otherwise the matching environment variable. A type without a channel is simply ignored (`debug` log).
- **Gitea webhooks**: native HTTP server (`WEBHOOK_ENABLED=true`). Verifies the **HMAC-SHA256** signature (`x-gitea-signature`) in constant time, rejects bodies over 1 MB and invalid JSON, deduplicates redeliveries through `webhook_deliveries`, then posts the embeds through the notification service: `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → refs, `release` → releases.
- **Polls** (`src/services/polls/poll-service.js`): one vote per member and per poll (changeable, one click moves the vote), the message is refreshed on every vote, and a scheduler closes expired polls automatically (checked every 30 s) even after a restart.
- **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status.
- **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call.
## 8. Architecture
Full details: [`docs/architecture.md`](docs/architecture.md).
```text
src/
├── index.js # Entry point: env, DB, client, loaders, webhooks, clean shutdown
├── config/ # env.js (.env reading/validation) · constants.js (colors, levels, categories)
├── core/ # client.js · command-loader.js · event-loader.js
│ # permissions.js (levels + hierarchy) · logger.js · errors.js
├── commands/<category>/ # fws, gitea, tickets, moderation, community, general
├── events/ # interaction-create (commands, buttons, modals), ready, member add/remove,
│ # voice state (voice channels), errors, shard
├── services/
│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js
│ ├── members/ # member-service.js (welcome, initial role, departures)
│ ├── moderation/ # moderation-service.js (hierarchy, sanctions, journal)
│ ├── notifications/ # notification-service.js (routing) · gitea-notifications.js (webhook mapping)
│ ├── polls/ # poll-service.js (creation, votes, closing, scheduler)
│ ├── status/ # bot-status-service.js (bot statuses, validation, rotation)
│ ├── tickets/ # ticket-service.js (private channels, lifecycle)
│ └── voice/ # voice-service.js (several triggers, temporary channels, panel)
├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/
├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch)
├── web/ # Dashboard: server.js · router.js · http.js
│ # auth/ (Discord OAuth2, sessions, access control) · api/ (one module per domain)
│ # services/ (.env schema, deployments) · public/ (front-end, no build)
├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls)
└── utils/ # retry.js (exponential backoff) · cooldown.js
```
Automatic loading: any command under `src/commands/**` and any event under `src/events/*` is picked up at startup.
**Command contract** (`access` checked in `interaction-create.js`, a `UserFacingError` is shown as-is, any other error is logged and replaced by a generic message):
```js
export const access = ACCESS_LEVELS.STAFF; // minimum level
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optional, per subcommand
export const data = new SlashCommandBuilder(); /* ... */
export async function execute(interaction) {}
```
**Intents used**: `Guilds`, `GuildMembers` _(privileged — enable it in the portal)_, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` is deliberately not requested.
### Message tone and vocabulary
Every text shown in Discord follows the same rules, listed at the top of `src/ui/embeds.js` (single source of truth):
- **Informal “tu”**, short sentences, active voice; never a reproach, irony or shouting capitals.
- The **title** states the outcome, the **description** says what to do next; one emoji per title, never decorative inside the body.
- **No gendered agreement** on a person: “tu es propriétaire”, “cette personne”, “l'équipe”, “ce membre” — no “il / elle”, no “cher / chère”, no inclusive dots.
- An **error** explains the cause, recalls the rule and offers the way out; a success thanks and gives the next step (`/ban` points at `/mod logs`, `/ticket create` recalls that the owner can close).
- Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`.
- Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**.
## 9. Database (SQLite)
- Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled.
- Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`).
- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `ticket_panels` (channel and message of the `/ticket setup` panel), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run).
- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — SQL queries never leave that layer.
- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) `005-bot-statuses.sql` (bot statuses edited from a command) and `006-web-dashboard.sql` (sessions, API tokens, deploy targets and history) complete the initial schema.
- The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`).
## 10. Logs
- **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console.
- Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr.
- **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line.
- Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`).
## 11. npm scripts
| Script | Purpose |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm start` | Starts the bot (`node src/index.js`) |
| `npm run dev` | Starts with automatic reload (`node --watch`) |
| `npm run deploy:commands` | Registers the slash commands on `DISCORD_GUILD_ID` (run it again after adding or changing a command) |
| `npm run db:init` | Creates the SQLite database and applies the migrations |
| `npm run lint` / `npm run lint:fix` | ESLint (check / fix) |
| `npm run format` / `npm run format:check` | Prettier (format / check) |
| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §13) |
| `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date |
| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` |
When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels.
## 12. Security
- Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted.
- No action is possible on a role or member positioned above the caller.
- Secrets are never committed (`.env` is ignored) nor logged in plain text (automatic masking).
- Gitea webhooks: mandatory HMAC-SHA256 signature, constant-time comparison, 1 MB body limit, duplicate protection on the delivery ID.
- Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only).
- User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option).
## 13. Versioning and releases
- **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states).
- **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date.
- Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`.
- Generating it is part of the definition of done: the file is never edited by hand.
## 14. Contributing
The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here:
### Commits
- Messages in **English**, **Conventional Commits** format: `<type>(<scope>): <description>`.
- Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Short imperative title; a **body** is added only to explain the _why_ (context, decision, trade-off).
### Branches and pull requests
1. Create a `type/description` branch **from `main`** (e.g. `feat/ticket-service`, `fix/voice-cleanup`).
2. Commit following the conventions above.
3. Open a **pull request** with a clear title and description, referencing the issue (`Fixes #123`).
4. **At least one reviewer** approves; the tests must pass.
5. Merge with **squash**: 1 PR = 1 clean commit on `main`.
### Work organisation
- Project **Kanban** board: _Backlog / To do_, _In progress_, _In review_, _Done_. One card = one unit of work = one branch + one pull request; a card only moves to _Done_ once its pull request is merged.
- Every bug or request goes through an **issue** (clear title + precise description) with a recommended label: `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Templates are provided in [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) and [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md).
- A bug report includes the **reproduction steps**, the **expected** vs **observed** behaviour, the **environment** and useful **logs**.
### Code and documentation
- Files in **kebab-case**, identifiers **in English**, comments **in English** explaining the _why_ (the non-obvious: trade-offs, edge cases, references).
- Check the stack and the dependencies already present before adding a new one (a single runtime dependency here: `discord.js`).
- Before proposing: `npm run lint`, `npm run format:check`, `npm test` and `npm run changelog` must pass.
- **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it.
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions.
## 15. Production checklist
- [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention)
- [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_)
- [ ] Fill in the bot statuses (`/status add`, `/status interval`) — the rotation is stored in the database
- [ ] Register the slash commands on the FWS server (`npm run deploy:commands`)
- [ ] Create and configure the Owner, Dev, Staff and User roles (IDs in `.env`)
- [ ] Set the channels: welcome, tickets, notifications, logs
- [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion
- [ ] Enable the **Server Members** intent in the developer portal
- [ ] Configure Gitea: least privilege token + webhook with a secret
- [ ] Configure the dashboard: `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` and the OAuth2 redirect declared in the portal
- [ ] Put an HTTPS reverse proxy in front of the site, then clear `WEB_SETUP_TOKEN`
- [ ] Declare the deploy targets and run a test deployment
- [ ] Protect and back up the SQLite database
- [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook
- [ ] Test the API limits and the error paths
- [ ] Check the embeds on desktop and mobile
- [ ] Fill in the official links and the screenshots (`assets/screenshots/`)
- [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`)
## 16. Resources
- FWS organisation: `[link to add]`
- FWS Discord server: `[link to add]`
- FWS Arch repository: `[link to add]`
- Gitea instance: `[link to add]`
- FWS documentation: `[link to add]`
- Technical documentation: [`docs/architecture.md`](docs/architecture.md)
- Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md)
- Operations (deployment, continuous integration, monitoring, backups): [`docs/exploitation.md`](docs/exploitation.md)
- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md)
- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md)
- French version of this document: [`README.md`](README.md)
+550 -221
View File
@@ -1,221 +1,550 @@
# Documentation fonctionnelle — FWS-Bot
> Documentation de référence du bot Discord de l'organisation open source FWS.
## 1. Contexte de l'organisation
**FWS** est une organisation open source multi-projets. Chaque projet peut choisir librement sa stack technique, sans restriction de langage.
Le projet principal est **FWS Arch**, un fork d'Arch Linux avec une surcouche conviviale qui simplifie l'installation et l'utilisation quotidienne.
FWS-Bot est le bot Discord du serveur communautaire FWS. Il s'adresse aux utilisateurs de FWS Arch, aux développeurs et au staff.
## 2. Objectifs du bot
FWS-Bot a pour objectifs de :
- centraliser les informations relatives à FWS et FWS Arch ;
- faciliter l'assistance aux utilisateurs ;
- permettre la création d'issues et de pull requests Gitea depuis Discord ;
- diffuser l'activité du projet ;
- organiser les tickets privés ;
- fournir des outils de modération ;
- présenter des statistiques Discord, Gitea et FWS ;
- conserver des logs utiles au suivi et à la sécurité.
Les commandes utilisent le préfixe slash `/` et privilégient les embeds Discord modernes, accompagnés de boutons, menus, liens et captures lorsque cela est pertinent.
## 3. Utilisateurs et permissions
### Owner
Accès complet : configuration, rôles, intégrations, commandes de développement, modération, tickets, notifications, statistiques et logs.
### Dev
Accès aux commandes permettant de configurer les informations et les fonctions qui touchent directement à FWS Arch et à son développement. Les Dev peuvent également utiliser les fonctions Gitea autorisées.
### Staff
Accès aux fonctions de modération, de support et de gestion des tickets, selon les permissions Discord configurées.
### User / Membre
Accès aux commandes d'information, aux ressources publiques, aux statistiques publiques et aux commandes fun. Un membre peut également ouvrir un ticket lorsque le serveur l'autorise.
## 4. Commandes fonctionnelles
Les noms suivants constituent une organisation fonctionnelle recommandée. Ils peuvent être adaptés aux noms réellement enregistrés dans Discord.
### Informations FWS
| Commande | Accès | Résultat |
| --- | --- | --- |
| `/fws info` | Tous | Présente FWS, FWS Arch, les objectifs et les liens officiels. |
| `/fws version` | Tous | Affiche la version actuelle de FWS Arch. |
| `/fws status` | Tous | Présente l'état connu des services et projets. |
| `/fws links` | Tous | Affiche les ressources Discord, Gitea, dépôt et documentation. |
| `/fws changelog` | Tous | Présente les changements d'une version ou de la dernière release. |
| `/help` | Tous | Affiche les commandes accessibles selon le rôle de l'utilisateur. |
### Issues et pull requests
| Commande | Accès | Résultat |
| --- | --- | --- |
| `/issue create` | Selon configuration | Crée une issue Gitea depuis un formulaire Discord. |
| `/issue view` | Tous | Affiche le titre, l'auteur, le statut, les détails et le lien d'une issue. |
| `/issue list` | Tous | Liste les issues ouvertes, récentes ou filtrées. |
| `/pr create` | Dev, Owner | Crée une pull request Gitea depuis Discord. |
| `/pr view` | Tous | Affiche les informations et le lien d'une pull request. |
| `/pr list` | Tous | Liste les pull requests ouvertes ou récentes. |
| `/gitea activity` | Tous | Affiche les commits, issues, PR et événements récents. |
| `/gitea release` | Tous | Affiche les releases disponibles de FWS Arch. |
Les créations peuvent être effectuées depuis Discord et doivent produire un lien vers l'élément Gitea créé. Les permissions sont vérifiées avant toute écriture.
### Tickets et support
| Commande | Accès | Résultat |
| --- | --- | --- |
| `/ticket create` | Membre | Crée un espace privé selon la catégorie choisie. |
| `/ticket close` | Auteur, Staff, Owner | Ferme le ticket et journalise sa clôture. |
| `/ticket claim` | Staff, Owner | Indique quel membre du staff prend le ticket en charge. |
| `/ticket add` | Staff, Owner | Ajoute une personne autorisée au périmètre du ticket. |
Les tickets sont privés par défaut. Leur scope dépend de leur catégorie : support utilisateur, bug, question de développement, signalement ou demande interne.
### Modération
| Commande | Accès | Résultat |
| --- | --- | --- |
| `/warn` | Staff, Owner | Avertit un membre et enregistre l'action. |
| `/mute` | Staff, Owner | Restreint temporairement les interactions d'un membre. |
| `/kick` | Staff, Owner | Retire un membre du serveur. |
| `/ban` | Staff autorisé, Owner | Bannit un membre selon les règles de modération. |
| `/clear` | Staff, Owner | Supprime un nombre contrôlé de messages. |
| `/mod logs` | Staff, Owner | Consulte les actions de modération disponibles. |
| `/role set` | Dev autorisé, Staff autorisé, Owner | Attribue ou retire un rôle selon la configuration. |
Le bot doit empêcher les actions sur des rôles supérieurs et effectuer les contrôles de permissions côté serveur.
### Communauté et statistiques
| Commande | Accès | Résultat |
| --- | --- | --- |
| `/poll create` | Staff, Dev, Owner | Crée un sondage avec choix et durée. |
| `/poll close` | Créateur autorisé, Staff, Owner | Ferme un sondage et affiche les résultats. |
| `/stats discord` | Tous | Affiche les statistiques publiques du serveur Discord. |
| `/stats gitea` | Tous | Affiche l'activité et les indicateurs Gitea. |
| `/stats fws` | Tous | Affiche les indicateurs disponibles de FWS/FWS Arch. |
| `/fun` | Membres | Affiche les commandes de divertissement. |
## 5. Automatisations
### Bienvenue et rôles
À l'arrivée d'un membre, FWS-Bot peut envoyer un message de bienvenue, présenter FWS Arch, fournir les règles et liens utiles, attribuer un rôle initial et enregistrer l'événement.
Les changements de rôles doivent respecter la hiérarchie Discord et être journalisés lorsqu'ils sont sensibles.
### Notifications
Les notifications couvrent notamment :
- nouvelles issues et changements de statut ;
- nouvelles pull requests et changements de statut ;
- commits ;
- releases ;
- annonces FWS ;
- erreurs et incidents techniques ;
- événements communautaires configurés.
Chaque catégorie de notification doit pouvoir être associée à un canal dédié et à un niveau de détail adapté.
### Sondages
Les sondages utilisent les composants Discord disponibles. Le bot contrôle les votes, respecte la durée définie et publie les résultats à la clôture.
### Statistiques
Les statistiques peuvent provenir de trois domaines :
- **Discord** : membres, activité et évolution de la communauté ;
- **Gitea** : issues, PR, commits, contributeurs et releases ;
- **FWS Arch** : versions, activité ou indicateurs fournis par les services du projet.
## 6. Intégrations et stockage
### Gitea
Gitea est utilisé pour consulter et créer les issues et pull requests, suivre les commits et releases, et transmettre les notifications de développement vers Discord.
Les embeds peuvent afficher le titre, l'auteur, le statut, la date, un résumé et un lien direct. Les tokens d'accès ne doivent jamais apparaître dans Discord ni dans les logs.
### SQLite
SQLite stocke les données locales nécessaires au bot, par exemple les paramètres des serveurs, les catégories de tickets, les associations de canaux, les sondages et les événements journalisés.
La base doit être protégée, sauvegardée et exclue du dépôt si elle contient des données réelles.
## 7. Embeds, liens et captures
Les réponses doivent utiliser une identité visuelle cohérente :
- titres courts ;
- champs structurés ;
- couleurs par catégorie ;
- boutons vers Gitea et la documentation ;
- footer FWS-Bot ;
- messages d'erreur compréhensibles.
Les captures doivent être placées dans un dossier dédié, par exemple `assets/screenshots/`, puis référencées ainsi :
```md
![Présentation de FWS-Bot](../assets/screenshots/fws-info.png)
```
## 8. Sécurité, limites et erreurs
FWS-Bot doit respecter les limites et délais des API Discord et Gitea. Une erreur API ou un timeout doit :
1. informer l'utilisateur sans exposer de détail sensible ;
2. être enregistré dans les logs techniques ;
3. éviter les répétitions immédiates et les doublons ;
4. utiliser une nouvelle tentative contrôlée uniquement si elle est prévue.
Les entrées utilisateur doivent être validées. Les permissions doivent être vérifiées côté serveur. Les secrets, fichiers `.env*`, bases de données réelles et artefacts générés ne doivent jamais être commités.
## 9. Conventions de contribution FWS
- Messages de commit en anglais au format Conventional Commits : `<type>(<scope>): <description>`.
- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Branches au format `type/description`.
- Fichiers en kebab-case.
- Identifiants de code en anglais.
- Commentaires en anglais et uniquement lorsqu'ils expliquent un choix non évident.
- Tests nommés avec des descriptions `describe` et `it` en anglais.
- Bugs et demandes suivis via les issues et le tableau Kanban.
- Une PR de correction doit référencer l'issue concernée, par exemple `Fixes #123`.
- Ne pas fermer ou modifier une issue sans demande explicite.
Les instructions complètes destinées aux agents sont disponibles dans `AGENTS.md`.
## 10. Ressources
- Organisation FWS : `[lien à ajouter]`
- Serveur Discord FWS : `[lien à ajouter]`
- Dépôt FWS Arch : `[lien à ajouter]`
- Instance Gitea : `[lien à ajouter]`
- Documentation FWS : `[lien à ajouter]`
## 11. Checklist
- [ ] Enregistrer les commandes slash sur le serveur FWS.
- [ ] Configurer les rôles Owner, Dev, Staff et User.
- [ ] Définir les canaux de bienvenue, tickets, notifications et logs.
- [ ] Configurer Gitea avec les permissions minimales.
- [ ] Protéger et sauvegarder SQLite.
- [ ] Tester les limites API et les erreurs.
- [ ] Vérifier les embeds sur ordinateur et mobile.
- [ ] Ajouter les liens et captures définitifs.
- [ ] Vérifier les tests, le typecheck et le lint lorsqu'ils existent.
# FWS-Bot
> Bot Discord de l'organisation open source **FWS** — assistance communautaire, tickets, modération, intégration Gitea et statistiques pour **FWS Arch** (fork d'Arch Linux avec surcouche conviviale).
🌍 **Français** · [English version](README.en.md)
Statut : **fonctionnel**. Les 19 commandes sont implémentées (assistance, tickets privés, modération, Gitea, sondages, statistiques, statuts du bot, gestionnaire de salons vocaux), tout comme l'accueil des membres et la diffusion des webhooks Gitea.
Projet conforme aux [conventions de l'organisation FWS](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) : commits en anglais au format Conventional Commits, branche `type/description`, PR relue puis mergée en squash, SemVer et `CHANGELOG.md` généré depuis les commits.
---
## 1. Stack technique
Choix assumés : **une seule dépendance runtime** (discord.js), aucun module natif à compiler, outil de test intégré à Node.
| Techno | Version | Rôle |
| --- | --- | --- |
| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Requis pour `node:sqlite`, `process.loadEnvFile`, `--watch` |
| **discord.js** | ^14.21.0 | API Discord : commandes slash, embeds, boutons, intents |
| **`node:sqlite`** | module natif | Base SQLite (WAL, foreign keys) — pas de `better-sqlite3` ni compilation |
| **`fetch` natif** | — | Client REST Gitea (avec `AbortSignal.timeout`) |
| **`node:http`** | — | Serveur de webhooks Gitea (sans Express) |
| **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks |
| **`node:test`** | — | Tests unitaires intégrés (`node --test`) |
| **ESLint** | ^9.30.0 (flat config) | Lint |
| **Front du tableau de bord** | — | JavaScript natif servi tel quel, aucune étape de build |
| **Prettier** | ^3.6.2 | Format |
## 2. Prérequis
- Node.js ≥ 22.13 (`node -v` pour vérifier) et npm
- Une application Discord (gratuite) avec un token de bot
- (Optionnel) une instance Gitea pour les issues/PR et les webhooks
## 3. Démarrage rapide avec un token de test
### 3.1 Créer l'application Discord
1. Ouvre le [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**.
2. Onglet **Bot** → **Reset Token** → copie le token : c'est ton `DISCORD_TOKEN` (ne le partage jamais, ne le committe jamais).
3. Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent** (requis pour l'accueil des nouveaux membres ; `Message Content` n'est pas nécessaire).
4. Onglet **General Information** → copie l'**Application ID** : c'est ton `DISCORD_CLIENT_ID`.
### 3.2 Inviter le bot sur un serveur de test
Remplace `CLIENT_ID` par ton Application ID :
```text
https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294
```
Cette URL pré-coche les permissions utilisées par les commandes : Voir les salons, Envoyer des messages, Gérer les messages, Intégrer des liens, Lire l'historique, Expulser, Bannir, Gérer les rôles, Modérer les membres (timeout), ainsi que celles des salons vocaux : Gérer les salons, Se connecter, Parler, Rendre muet, Rendre sourd, Déplacer les membres. Tu peux aussi passer par **OAuth2 → URL Generator** avec les scopes `bot` + `applications.commands`.
Crée (ou utilise) un serveur de test dont tu es propriétaire : c'est lui qui donne le niveau **Owner** au bot.
### 3.3 Récupérer les IDs Discord
Sur Discord : **Paramètres → Avancés → Mode développeur** activé, puis clic droit sur un serveur / salon / rôle → **Copier l'identifiant**.
| Variable | Où le trouver |
| --- | --- |
| `DISCORD_GUILD_ID` | Clic droit sur le serveur de test |
| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Paramètres du serveur → Rôles (crée-les d'abord) |
| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Clic droit sur chaque salon |
> Si les rôles ne sont pas configurés, tout le monde est considéré **User** (sauf le propriétaire du serveur = Owner).
### 3.4 Lancer le bot
```bash
# 1. Dépendances
npm install
# 2. Configuration : copie .env.example vers .env puis remplis-le
# Minimum requis : DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID
cp .env.example .env
# 3. Créer la base SQLite et appliquer les migrations
npm run db:init
# 4. Enregistrer les commandes slash sur le serveur (instantané, par guild)
npm run deploy:commands
# 5. Démarrer avec rechargement automatique
npm run dev
```
Dans les logs tu dois voir `Connected as <NomDuBot>`. Tape `/help` sur le serveur : tu dois voir la liste des commandes accessibles selon ton rôle.
Sans `.env`, le bot refuse de démarrer (`assertRequiredEnv` vérifie token, client ID et guild ID).
## 4. Configuration — toutes les variables (`.env`)
Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre parenthèses.
### Runtime
| Variable | Défaut | Description |
| --- | --- | --- |
| `NODE_ENV` | `development` | `development` \| `production` \| `test` |
| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
| `LOG_DIR` | `./logs` | Dossier des logs JSON journaliers |
| `LOG_RETENTION_DAYS` | `30` | Durée de conservation (purge des `event_logs`) |
| `VOICE_EMPTY_GRACE_MS` | `5000` | Délai avant qu'un salon vocal généré devenu vide soit supprimé (`0` = immédiat) |
| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Rythme par défaut de la rotation des statuts du bot (modifiable par `/status interval`) |
### Application Discord
| Variable | Description |
| --- | --- |
| `DISCORD_TOKEN` | **Requis.** Token du bot (Developer Portal → Bot) |
| `DISCORD_CLIENT_ID` | **Requis.** Application ID |
| `DISCORD_GUILD_ID` | **Requis.** Serveur d'enregistrement des commandes slash |
### Rôles FWS (IDs de rôles Discord)
| Variable | Niveau correspondant |
| --- | --- |
| `ROLE_OWNER_ID` | Owner — accès complet |
| `ROLE_DEV_ID` | Dev — configuration FWS Arch, écritures Gitea |
| `ROLE_STAFF_ID` | Staff — modération, support, tickets |
| `ROLE_MEMBER_ID` | Rôle initial attribué aux nouveaux membres |
### Salons Discord (IDs)
| Variable | Usage |
| --- | --- |
| `CHANNEL_WELCOME_ID` | Messages de bienvenue |
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
| `CHANNEL_LOGS_ID` | Logs fonctionnels et techniques, journal des tickets |
| `CHANNEL_MOD_LOGS_ID` | Logs de modération |
| `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests |
| `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits |
| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases |
| `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents |
| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés |
| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) |
| `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) |
### Gitea
| Variable | Défaut | Description |
| --- | --- | --- |
| `GITEA_URL` | — | URL de l'instance (sans `/` final) |
| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé |
| `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) |
| `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes |
| `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) |
### Webhooks Gitea
| Variable | Défaut | Description |
| --- | --- | --- |
| `WEBHOOK_ENABLED` | `false` | Démarre le serveur HTTP de réception |
| `WEBHOOK_HOST` | `0.0.0.0` | Interface d'écoute |
| `WEBHOOK_PORT` | `3000` | Port d'écoute |
| `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea |
| `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks |
### Tableau de bord web
| Variable | Défaut | Description |
| --- | --- | --- |
| `WEB_ENABLED` | `false` | Sert le site d'administration depuis le processus du bot |
| `WEB_HOST` | `127.0.0.1` | Interface d'écoute. `0.0.0.0` uniquement derrière un reverse proxy HTTPS |
| `WEB_PORT` | `3080` | Port du site. S'il vaut `WEBHOOK_PORT`, un seul serveur HTTP est démarré |
| `WEB_PUBLIC_URL` | — | URL publique du site, base de la redirection OAuth2 `/auth/callback` |
| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret |
| `WEB_SESSION_SECRET` | — | Clé de signature des sessions (64 caractères hexadécimaux) |
| `WEB_SESSION_TTL_HOURS` | `12` | Durée d'une session avant reconnexion |
| `WEB_SETUP_TOKEN` | — | Jeton d'amorçage ouvrant l'assistant sans compte Discord |
| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Autorise les cibles de déploiement de type commande shell (Owner) |
| `WEB_ALLOW_RESTART` | `false` | Affiche le bouton de redémarrage du bot |
| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Délai au-delà duquel un déploiement est en échec |
| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | Requêtes API par minute et par adresse IP |
### SQLite et liens
| Variable | Défaut | Description |
| --- | --- | --- |
| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Fichier de base (exclu de git) |
| `BACKUP_DIR` | `./data/backups` | Dossier de sauvegarde |
| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Liens officiels affichés par `/fws info` et `/fws links` (les boutons vides sont omis) |
## 5. Commandes slash
19 commandes sont enregistrées. Chaque commande a un **niveau d'accès FWS** vérifié côté serveur avant exécution, et les commandes de modération vérifient en plus les **permissions Discord** (`DefaultMemberPermissions`).
### Niveaux d'accès
Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) :
| Niveau | Qui |
| --- | --- |
| `OWNER` (3) | Rôle Owner, ou propriétaire du serveur |
| `DEV` (2) | Rôle Dev |
| `STAFF` (1) | Rôle Staff |
| `USER` (0) | Tous les membres |
### Générales et FWS
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/help` | — | User | ✅ | Liste les commandes accessibles selon ton rôle (réponse éphémère) |
| `/fws info` | — | User | ✅ | Présente FWS et FWS Arch (texte surchargeable via `guild_settings`) + liens officiels |
| `/fws links` | — | User | ✅ | Ressources : site, docs, dépôt, Gitea, Discord |
| `/fws version` | — | User | ✅ | Dernière release Gitea (tag, date, auteur) + bouton vers les notes |
| `/fws status` | — | User | ✅ | État des services : API Gitea, webhooks, SQLite, latence Discord, uptime |
| `/fws changelog` | `version` (optionnel) | User | ✅ | Notes de version (dernière par défaut, message clair si le tag n'existe pas) |
| `/status add` | `text` (128 car.), `type`, `url` | **Staff** + *Gérer le serveur* | ✅ | Ajoute un statut à la rotation ; le premier ajouté s'affiche tout de suite |
| `/status list` | — | **Staff** + *Gérer le serveur* | ✅ | Statuts enregistrés : numéro, type, état, rythme de rotation |
| `/status remove` · `enable` · `disable` | `id` | **Staff** + *Gérer le serveur* | ✅ | Retire un statut, le remet en rotation ou le met en pause |
| `/status interval` | `seconds` (5–86 400) | **Staff** + *Gérer le serveur* | ✅ | Rythme de la rotation, appliqué sans redémarrage |
| `/status clear` | — | **Staff** + *Gérer le serveur* | ✅ | Vide la liste et revient à la ligne par défaut |
### Gitea — issues et pull requests
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/issue create` | — (modale : titre + description) | User (configurable) | ✅ | Crée une issue Gitea et renvoie son lien |
| `/issue view` | `number` | User | ✅ | Titre, auteur, état, labels, lien d'une issue |
| `/issue list` | — | User | ✅ | Issues ouvertes (15 dernières) |
| `/pr create` | `head`, `base` + modale (titre, description) | **Dev** | ✅ | Crée une pull request Gitea |
| `/pr view` | `number` | User | ✅ | Titre, auteur, état, branches, lien d'une PR |
| `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) |
| `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes |
| `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) |
> Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute.
### Tickets de support
Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL).
`/ticket setup` publie dans le salon courant un panneau avec un bouton **Ouvrir un ticket** : le membre presse le bouton, choisit sa catégorie dans un menu, et le salon privé s'ouvre. Le salon du panneau est retenu en base (`ticket_panels`), donc le panneau survit au redémarrage et une réinstallation remplace l'ancien message au lieu de l'empiler.
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** |
| `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) |
| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé |
| `/ticket setup` | — | **Staff** | ✅ | Publie et épingle le panneau d'ouverture dans ce salon (remplace le précédent) |
| `/ticket setup-remove` | — | **Staff** | ✅ | Retire le panneau de ce salon |
Catégories disponibles et qui y a accès :
| Catégorie | Visible par |
| --- | --- |
| Aide et support | Staff, Owner |
| Bug | Staff, Dev, Owner |
| Question de développement | Dev, Owner |
| Signalement | Staff, Owner |
| Demande interne | Owner |
### Salons vocaux temporaires
Un serveur peut déclarer **autant de salons déclencheurs que nécessaire** — un par thème (`Dev`, `SIO`, …) — chacun avec sa propre catégorie d'accueil (`/voice setup`) : rejoindre un déclencheur crée un salon vocal privé **en bas de la catégorie de ce déclencheur**, y déplace le membre et lui en donne la propriété. Le salon se gère ensuite depuis le **panneau de contrôle** publié dans son chat (boutons *Renommer*, *Limiter*, *Verrouiller*, *Réclamer*, *Supprimer* et menus *Autoriser*, *Exclure*, *Transférer*) ou avec `/voice`. Le nombre de salons simultanés est **illimité**, et un membre conserve un salon **par déclencheur** : rejoindre à nouveau le même déclencheur le renvoie simplement dans le salon qu'il possède déjà.
Dès que **plus personne** ne reste dans un salon généré, il est supprimé : le délai (5 s par défaut) le laisse survivre à un passage rapide dans un autre salon — réglable par `VOICE_EMPTY_GRACE_MS`, `0` le supprime immédiatement. Un balayage automatique (au démarrage puis toutes les minutes) rattrape les cas où l'événement Discord a été manqué ou la suppression refusée, si bien qu'un salon généré ne peut pas rester vide : soit il est supprimé, soit la tentative est réessayée.
| Commande | Options | Accès | Description |
| --- | --- | --- | --- |
| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Ajoute (ou met à jour) un salon déclencheur ; sans `category`, celle du salon déclencheur est utilisée |
| `/voice config` · `/voice triggers list` | — | User · **Staff** | Déclencheurs déclarés : catégorie, modèle, limite, état et salons actifs |
| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Désactive un déclencheur (sans perdre sa configuration, y entrer ne crée plus de salon) · le réactive |
| `/voice triggers remove` | `trigger` | **Staff** | Supprime un déclencheur déclaré dans Discord |
| `/voice panel` | `trigger` (défaut : tous) | **Staff** | Republie le panneau d'explication dans les salons déclencheurs |
| `/voice name` | `name` (100 car.) | Propriétaire | Renomme le salon |
| `/voice limit` | `limit` (0–99, 0 = illimité) | Propriétaire | Nombre de places |
| `/voice lock` · `/voice unlock` | — | Propriétaire | Refuse · autorise l'accès de tout le monde |
| `/voice permit` | `user` | Propriétaire | Autorise un membre à rejoindre le salon |
| `/voice reject` | `user` | Propriétaire | Interdit l'accès (et l'éjecte s'il y est déjà) |
| `/voice kick` | `user` | Propriétaire | Éjecte un membre du salon |
| `/voice transfer` | `user` | Propriétaire | Transfère la propriété (le nouveau doit être dans le salon) |
| `/voice claim` | — | Membre du salon | Récupère un salon dont le propriétaire est parti |
| `/voice delete` | `channel` (staff) | Propriétaire, Staff | Supprime immédiatement le salon |
| `/voice info` | `channel` (staff) | User | Propriétaire, état, limite, membres, ancienneté |
> Modèle de nom : `{user}` est remplacé par le pseudo du membre (défaut `🔊 Salon de {user}`). Le staff peut toujours agir sur n'importe quel salon temporaire. Le propriétaire reçoit `Gérer le salon` + `Déplacer des membres` sur son seul salon.
>
> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` restent un **repli** : un serveur dont le `.env` déclare un déclencheur fonctionne sans `/voice setup`, mais ce déclencheur venu de l'environnement ne peut qu'être désactivé (`/voice triggers disable`), pas supprimé depuis Discord. Changer la catégorie d'un déclencheur ne déplace pas les salons déjà créés.
### Modération
Chaque commande vérifie le niveau FWS **et** la permission Discord correspondante. Le bot refuse d'agir sur un membre dont le plus haut rôle est égal ou supérieur à celui de l'auteur (`canActOn`), et n'agit jamais sur le propriétaire du serveur.
| Commande | Options | Permission Discord | État | Description |
| --- | --- | --- | --- | --- |
| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action |
| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP |
| `/unmute` | `user`, `reason` | Modérer les membres | ✅ | Lève le timeout avant l’échéance (message clair si la personne n’est pas en exclusion) |
| `/unban` | `user`, `reason` | Bannir | ✅ | Lève le bannissement, même si la personne a déjà quitté, et la prévient en MP |
| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action |
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages |
| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) |
| `/mod logs` | `user` (filtre) | Modérer les membres | ✅ | Historique lu depuis `moderation_actions` (15 dernières, éphémère) |
| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Gérer les rôles | ✅ | Attribue ou retire un rôle (double hiérarchie vérifiée) |
| `/notify set` | `type`, `channel` | Gérer le serveur | ✅ | Salon de notification propre à ce serveur (SQLite) |
| `/notify remove` | `type` | Gérer le serveur | ✅ | Revenir au salon par défaut (variables d'environnement) |
| `/notify list` | — | Gérer le serveur | ✅ | Configuration actuelle de chaque type |
> Chaque action réussie est enregistrée dans `moderation_actions` **et** publiée dans `CHANNEL_MOD_LOGS_ID` (cible, modérateur, raison, durée).
### Communauté et statistiques
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/poll create` | `question`, `choices` (« ; » séparés, 2–10), `minutes` (1–10080) | **Staff** | ✅ | Sondage voté par boutons, résultats en direct |
| `/poll close` | `id` | **Staff** | ✅ | Clôture, affiche le résultat gagnant et fige le message |
| `/stats discord` | — | User | ✅ | Membres, salons, rôles, boosts, âge du serveur, latence |
| `/stats gitea` | — | User | ✅ | Commits récents, issues et PR ouvertes, dernière release |
| `/stats fws` | — | User | ✅ | Indicateurs locaux (tickets, sondages, modération) + version FWS Arch |
| `/fun coinflip` | — | User | ✅ | Pile ou face |
| `/fun dice` | `sides` (2–1000, 6 par défaut) | User | ✅ | Lancer de dé |
| `/fun 8ball` | `question` | User | ✅ | Boule magique (12 réponses) |
| `/fun choose` | `options` (« ; » séparés, 2–10) | User | ✅ | Choix aléatoire argumenté |
Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique.
## 6. Tableau de bord web
Le bot sert son propre site d'administration : organisation Gitea, dépôts, releases, déploiements, serveur Discord, journaux et configuration. Détail complet : [`docs/web-dashboard.md`](docs/web-dashboard.md).
Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour les sessions, et un front en JavaScript natif servi tel quel.
Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire.
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, règlement, tickets, vocaux, notifications.
### 6.1 Démarrer
Sans `.env`, le bot refuse de démarrer : l'assistant de configuration se lance donc seul, sans connexion à Discord.
```bash
npm run setup
```
La console affiche l'URL du site et un jeton d'amorçage temporaire. Une fois le fichier écrit, mets `WEB_ENABLED=true` et démarre le bot normalement : le site écoute alors sur `WEB_HOST:WEB_PORT`.
Pour que les membres puissent se connecter avec Discord : copie le **Client Secret** du portail dans `DISCORD_CLIENT_SECRET`, ajoute `<WEB_PUBLIC_URL>/auth/callback` dans **OAuth2 → Redirects** à l'identique, et génère `WEB_SESSION_SECRET`.
### 6.2 Accès et modes d'affichage
Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff** ; **Dev** ouvre l'écriture sur les dépôts et les déploiements ; **Owner** ouvre la suppression de dépôt, les jetons d'API, les sauvegardes et la configuration.
Un commutateur **Simple / Avancé** masque ou révèle les panneaux techniques. Il ne change aucun droit : chaque appel est revérifié côté serveur.
Les pages se mettent à jour toutes seules : le serveur pousse chaque changement sur un flux `text/event-stream`, et un indicateur en bas de la barre latérale dit où en est la connexion. Rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus, et un rafraîchissement périodique prend le relais si le flux ne passe pas.
### 6.3 Assistant de configuration
Chaque variable du `.env` est décrite une seule fois, dans `src/web/services/env-schema.js` : le formulaire, les explications, la validation et le fichier généré en découlent tous.
L'assistant indique où trouver chaque valeur, valide au fil de la frappe, signale les combinaisons douteuses, génère les secrets, teste le token Discord et le jeton Gitea **avant** d'écrire, montre un aperçu du fichier, sauvegarde l'ancien en `.env.bak-<horodatage>` puis écrit le nouveau avec les permissions `600`. Un secret laissé vide conserve la valeur déjà en place.
### 6.4 Releases et déploiements
Publier une release depuis le site génère ses notes à partir des commits Conventional Commits, l'annonce dans le salon des releases et déclenche les cibles marquées en déploiement automatique.
Trois types de cible : **webhook** signé en HMAC-SHA256 (recommandé, rien ne s'exécute sur la machine du bot), **workflow Gitea Actions**, et **commande shell** — cette dernière reste bloquée tant que `WEB_ALLOW_COMMAND_DEPLOYS` n'est pas activé, et demande le niveau Owner. Chaque tentative laisse son journal complet dans l'historique, réussie comme échouée.
## 7. Automatisations
- **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés).
- **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte.
- **Notifications** (`src/services/notifications/notification-service.js`) : routage par type — override par serveur en SQLite (`notification_channels`, configuré via `/notify set`), sinon la variable d'environnement correspondante. Un type sans salon est simplement ignoré (log en `debug`).
- **Webhooks Gitea** : serveur HTTP natif (`WEBHOOK_ENABLED=true`). Vérifie la signature **HMAC-SHA256** (`x-gitea-signature`) en temps constant, rejette les corps > 1 Mo et les JSON invalides, déduplique les redeliveries via `webhook_deliveries`, puis publie les embeds via le service de notifications : `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → références, `release` → releases.
- **Sondages** (`src/services/polls/poll-service.js`) : un vote par membre et par sondage (modifiable, un clic change le vote), message rafraîchi à chaque vote, et un ordonnanceur ferme automatiquement les sondages arrivés à échéance (vérification toutes les 30 s) même après un redémarrage.
- **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé.
- **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API.
## 8. Architecture
Détails complets : [`docs/architecture.md`](docs/architecture.md).
```text
src/
├── index.js # Point d'entrée : env, DB, client, loaders, webhooks, shutdown propre
├── config/ # env.js (lecture/validation .env) · constants.js (couleurs, niveaux, catégories)
├── core/ # client.js · command-loader.js · event-loader.js
│ # permissions.js (niveaux + hiérarchie) · logger.js · errors.js
├── commands/<catégorie>/ # fws, gitea, tickets, moderation, community, general
├── events/ # interaction-create (commandes, boutons, modales), ready, member add/remove,
│ # voice state (salons vocaux), errors, shard
├── services/
│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js
│ ├── members/ # member-service.js (accueil, rôle initial, départs)
│ ├── moderation/ # moderation-service.js (hiérarchie, sanctions, journal)
│ ├── notifications/ # notification-service.js (routage) · gitea-notifications.js (mapping webhooks)
│ ├── polls/ # poll-service.js (création, votes, clôture, ordonnanceur)
│ ├── status/ # bot-status-service.js (statuts du bot, validation, rotation)
│ ├── tickets/ # ticket-service.js (salons privés, cycle de vie)
│ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau)
├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/
├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch)
├── web/ # Tableau de bord : server.js · router.js · http.js
│ # auth/ (OAuth2 Discord, sessions, contrôle d'accès) · api/ (un module par domaine)
│ # services/ (schéma du .env, déploiements) · public/ (front, sans build)
├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages)
└── utils/ # retry.js (backoff exponentiel) · cooldown.js
```
Chargement automatique : toute commande dans `src/commands/**` et tout événement dans `src/events/*` sont pris en compte au démarrage.
**Contrat d'une commande** (`access` vérifié dans `interaction-create.js`, une `UserFacingError` est affichée telle quelle, toute autre erreur est loggée et remplacée par un message générique) :
```js
export const access = ACCESS_LEVELS.STAFF; // niveau minimum
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel, par sous-commande
export const data = new SlashCommandBuilder() /* ... */;
export async function execute(interaction) {}
```
**Intents utilisés** : `Guilds`, `GuildMembers` *(privilégié — à activer dans le portail)*, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` n'est volontairement pas demandé.
### Ton et vocabulaire des messages
Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en tête de `src/ui/embeds.js` (source unique de vérité) :
- **Tutoiement**, phrases courtes, voix active ; jamais de reproche, d'ironie ni de majuscules hurlantes.
- Le **titre** annonce le résultat, la **description** dit quoi faire ensuite ; un seul emoji par titre, jamais décoratif dans le corps.
- **Aucun accord genré** sur une personne : « tu es propriétaire », « cette personne », « l'équipe », « ce membre » — pas de « il / elle », de « cher / chère », ni d'écriture inclusive à points.
- Une **erreur** explique la cause, rappelle la règle et propose la sortie de secours ; un succès remercie et précise la suite (`/ban` renvoie vers `/mod logs`, `/ticket create` rappelle que la personne propriétaire peut fermer).
- Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`.
- Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal.
## 9. Base de données (SQLite)
- Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées.
- Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`).
- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `ticket_panels` (salon et message du panneau `/ticket setup`), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`, `web_sessions` (sessions du tableau de bord, empreinte du cookie seulement), `web_api_tokens`, `deploy_targets` (cibles de déploiement), `deployments` (historique et journal de chaque exécution).
- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — les requêtes SQL ne sortent jamais de cette couche.
- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) `005-bot-statuses.sql` (statuts du bot édités en commande) et `006-web-dashboard.sql` (sessions, jetons d'API, cibles et historique de déploiement) complètent le schéma initial.
- La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`).
## 10. Logs
- Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console.
- Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr.
- **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée.
- Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`).
## 11. Scripts npm
| Script | Rôle |
| --- | --- |
| `npm start` | Démarre le bot (`node src/index.js`) |
| `npm run dev` | Démarre avec rechargement automatique (`node --watch`) |
| `npm run setup` | Lance l'assistant de configuration du `.env`, sans connexion Discord |
| `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) |
| `npm run db:init` | Crée la base SQLite et applique les migrations |
| `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) |
| `npm run format` / `npm run format:check` | Prettier (formater / vérifier) |
| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §13) |
| `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) |
| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` |
En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles.
## 12. Sécurité
- Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client.
- Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur.
- Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique).
- Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery.
- Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement).
- Tableau de bord : connexion Discord obligatoire (niveau Staff minimum), session en cookie `HttpOnly` dont seule l'empreinte est stockée, en-tête `X-Requested-With` exigé sur chaque écriture, vérification de l'origine, CSP restreinte à `self`, limitation de débit par adresse IP.
- Le site écoute sur `127.0.0.1` par défaut : place un reverse proxy HTTPS devant lui avant toute exposition. Les déploiements par commande shell et le redémarrage restent désactivés tant qu'on ne les active pas explicitement.
- Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options).
## 13. Versionnage et releases
- **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer).
- **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour.
- Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`.
- La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main.
## 14. Contribution
Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici :
### Commits
- Messages en **anglais**, format **Conventional Commits** : `<type>(<scope>): <description>`.
- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Titre court et impératif ; un **corps** est ajouté seulement pour expliquer le *pourquoi* (contexte, décision, compromis).
### Branches et pull requests
1. Créer une branche `type/description` **depuis `main`** (ex. `feat/ticket-service`, `fix/voice-cleanup`).
2. Commiter selon les conventions ci-dessus.
3. Ouvrir une **pull request** avec un titre et une description clairs, en référençant l'issue (`Fixes #123`).
4. **Au moins un reviewer** valide ; les tests doivent passer.
5. Merger en **squash** : 1 PR = 1 commit propre sur `main`.
### Organisation du travail
- Tableau **Kanban** du projet : *Backlog / À faire*, *En cours*, *En revue*, *Terminé*. Une carte = une unité de travail = une branche + une PR ; une carte ne passe en *Terminé* qu'une fois la PR mergée.
- Toute anomalie ou demande passe par une **issue** (titre clair + description précise) avec un label recommandé : `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Les modèles sont fournis dans [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) et [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md).
- Un bug se décrit avec les **étapes de reproduction**, le **comportement attendu** vs **observé**, l'**environnement** et les **logs** utiles.
### Code et documentation
- Fichiers en **kebab-case**, identifiants **en anglais**, commentaires **en anglais** expliquant le *pourquoi* (le non-évident : compromis, cas limites, références).
- Vérifier la stack et les dépendances déjà présentes avant d'en ajouter une nouvelle (une seule dépendance runtime ici : `discord.js`).
- Avant de proposer : `npm run lint`, `npm run format:check`, `npm test` et `npm run changelog` doivent passer.
- Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie.
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions.
## 15. Checklist de mise en production
- [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation)
- [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*)
- [ ] Renseigner les statuts du bot (`/status add`, `/status interval`) — la rotation est enregistrée en base
- [ ] Enregistrer les commandes slash sur le serveur FWS (`npm run deploy:commands`)
- [ ] Créer et configurer les rôles Owner, Dev, Staff, User (IDs dans `.env`)
- [ ] Définir les salons : bienvenue, tickets, notifications, logs
- [ ] Configurer chaque salon vocal déclencheur (`/voice setup`) et vérifier création/suppression automatique
- [ ] Activer l'intent **Server Members** dans le portail développeur
- [ ] Configurer Gitea : token à moindre privilège + webhook avec secret
- [ ] Configurer le tableau de bord : `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` et la redirection OAuth2 déclarée dans le portail
- [ ] Placer un reverse proxy HTTPS devant le site, puis vider `WEB_SETUP_TOKEN`
- [ ] Déclarer les cibles de déploiement et lancer un déploiement de test
- [ ] Protéger et sauvegarder la base SQLite
- [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea
- [ ] Tester les limites API et les chemins d'erreur
- [ ] Vérifier les embeds sur ordinateur et mobile
- [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`)
- [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`)
## 16. Ressources
- Organisation FWS : `[lien à ajouter]`
- Serveur Discord FWS : `[lien à ajouter]`
- Dépôt FWS Arch : `[lien à ajouter]`
- Instance Gitea : `[lien à ajouter]`
- Documentation FWS : `[lien à ajouter]`
- Documentation technique : [`docs/architecture.md`](docs/architecture.md)
- Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md)
- Exploitation (déploiement, intégration continue, surveillance, sauvegardes) : [`docs/exploitation.md`](docs/exploitation.md)
- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md)
- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)*
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md)
- Version anglaise de ce document : [`README.en.md`](README.en.md)
+112 -88
View File
@@ -1,88 +1,112 @@
# Architecture — FWS-Bot
Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler).
## Arborescence
```text
fws-discordbot/
├── .env.example # Modèle de configuration (sans secret)
├── assets/screenshots/ # Captures référencées dans la documentation
├── data/ # Base SQLite et sauvegardes (ignoré par git)
├── docs/ # Documentation technique
├── logs/ # Logs techniques journaliers (ignoré par git)
├── scripts/
│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur
│ └── init-database.js # Crée la base et applique les migrations
├── src/
│ ├── index.js # Point d'entrée
│ ├── config/
│ │ ├── env.js # Lecture et validation des variables d'environnement
│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets
│ ├── core/
│ │ ├── client.js # Client Discord et intents
│ │ ├── command-loader.js # Chargement automatique de src/commands/**
│ │ ├── event-loader.js # Chargement automatique de src/events/*
│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie
│ │ ├── logger.js # Logs JSON avec masquage des secrets
│ │ └── errors.js # Erreurs typées (utilisateur, permission, API)
│ ├── commands/<catégorie>/<commande>.js
│ ├── events/ # Un fichier par événement Discord
│ ├── services/ # Logique métier et intégrations (Gitea, notifications…)
│ ├── database/
│ │ ├── index.js # Connexion et migrations
│ │ ├── migrations/ # Fichiers SQL numérotés
│ │ └── repositories/ # Accès aux tables
│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea
│ ├── ui/ # Embeds et boutons standardisés
│ └── utils/ # Retry, cooldown…
└── tests/ # Tests node:test
```
## Contrat d'une commande
```js
export const access = ACCESS_LEVELS.STAFF; // niveau minimum
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel
export const data = new SlashCommandBuilder()...;
export async function execute(interaction) {}
```
Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique.
## Contrat d'un événement
```js
export const name = Events.GuildMemberAdd;
export const once = false; // optionnel
export async function execute(client, ...args) {}
```
## Intents Discord
| Intent | Usage | Privilégié |
| ----------------- | -------------------------------- | ----------------------------------- |
| `Guilds` | Commandes, salons, rôles | Non |
| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) |
| `GuildModeration` | Événements de ban | Non |
| `GuildMessages` | `/clear`, salons de tickets | Non |
`MessageContent` n'est pas demandé.
## Lancement local
```bash
npm install
cp .env.example .env # puis remplir les valeurs
npm run db:init
npm run deploy:commands
npm run dev
```
## Qualité
| Commande | Rôle |
| ---------------------- | ----------------- |
| `npm run lint` | ESLint |
| `npm run format:check` | Prettier |
| `npm test` | Tests `node:test` |
# Architecture — FWS-Bot
Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler).
## Arborescence
```text
fws-discordbot/
├── .env.example # Modèle de configuration (sans secret)
├── assets/screenshots/ # Captures référencées dans la documentation
├── data/ # Base SQLite et sauvegardes (ignoré par git)
├── docs/ # Documentation technique
├── logs/ # Logs techniques journaliers (ignoré par git)
├── scripts/
│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur
│ ├── init-database.js # Crée la base et applique les migrations
│ └── setup-server.js # Assistant de configuration du .env, sans Discord
├── src/
│ ├── index.js # Point d'entrée
│ ├── config/
│ │ ├── env.js # Lecture et validation des variables d'environnement
│ │ ├── guild-settings.js # Réglages modifiables depuis le panel, et leur schéma
│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets
│ ├── core/
│ │ ├── client.js # Client Discord et intents
│ │ ├── command-loader.js # Chargement automatique de src/commands/**
│ │ ├── event-loader.js # Chargement automatique de src/events/*
│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie
│ │ ├── logger.js # Logs JSON avec masquage des secrets
│ │ └── errors.js # Erreurs typées (utilisateur, permission, API)
│ ├── commands/<catégorie>/<commande>.js
│ ├── events/ # Un fichier par événement Discord
│ ├── services/ # Logique métier et intégrations (Gitea, notifications…)
│ ├── database/
│ │ ├── index.js # Connexion et migrations
│ │ ├── migrations/ # Fichiers SQL numérotés
│ │ └── repositories/ # Accès aux tables
│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea
│ ├── web/ # Tableau de bord : serveur, API, front (voir web-dashboard.md)
│ │ ├── server.js # Serveur HTTP, répartition et erreurs
│ │ ├── router.js # Routeur minimal `/api/x/:param`
│ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès
│ │ ├── api/ # Un module par domaine exposé
│ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements
│ │ ├── public/ # Front JavaScript natif, servi tel quel
│ │ └── public/wiki.* # Site de documentation public, servi sans session
│ ├── ui/ # Embeds et boutons standardisés
│ └── utils/ # Retry, cooldown…
└── tests/ # Tests node:test
```
## Contrat d'une commande
```js
export const access = ACCESS_LEVELS.STAFF; // niveau minimum
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel
export const data = new SlashCommandBuilder()...;
export async function execute(interaction) {}
```
Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique.
## Contrat d'un événement
```js
export const name = Events.GuildMemberAdd;
export const once = false; // optionnel
export async function execute(client, ...args) {}
```
## Tableau de bord web
Le bot sert un site d'administration (organisation, dépôts, releases, déploiements, configuration). Il réutilise les niveaux d'accès des commandes, déduits des rôles Discord, et ne démarre que si `WEB_ENABLED=true`.
Aucune dépendance ajoutée : `node:http`, `node:sqlite`, `node:crypto`, et un front sans étape de build. Quand `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP sert le site et la route des webhooks.
Une route se déclare avec son niveau minimum, appliqué par le serveur avant l'appel :
```js
router.get('/api/repositories/:owner/:repo', handler, { access: ACCESS_LEVELS.STAFF });
```
Détail complet : [`web-dashboard.md`](web-dashboard.md).
## Intents Discord
| Intent | Usage | Privilégié |
| ----------------- | -------------------------------- | ----------------------------------- |
| `Guilds` | Commandes, salons, rôles | Non |
| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) |
| `GuildModeration` | Événements de ban | Non |
| `GuildMessages` | `/clear`, salons de tickets | Non |
`MessageContent` n'est pas demandé.
## Lancement local
```bash
npm install
npm run setup # assistant de configuration du .env, ou copier .env.example à la main
npm run db:init
npm run deploy:commands
npm run dev
```
## Qualité
| Commande | Rôle |
| ---------------------- | ----------------- |
| `npm run lint` | ESLint |
| `npm run format:check` | Prettier |
| `npm test` | Tests `node:test` |
+305
View File
@@ -0,0 +1,305 @@
# Exploitation
Comment déployer, vérifier, surveiller et sauvegarder FWS-Bot en production. Écrit pour un hébergement de type panel (Pterodactyl), qui est le cas actuel.
Les quatre chapitres sont indépendants et classés par valeur décroissante.
---
## 1. Déployer sans archive
**Le problème qu'on résout.** Téléverser un zip laisse régulièrement une copie partielle : le front plus ancien que l'API, un module oublié, une page qui plante sans raison apparente. Trois symptômes pour une seule cause, et aucun moyen simple de savoir laquelle.
Un déploiement reproductible supprime toute la famille.
> **L'onglet « Console » de Pterodactyl n'est pas un terminal** : c'est l'entrée/sortie du processus en cours. On n'y lance pas de commande shell, même avec tous les droits du panel. Si tu disposes d'un vrai shell ailleurs, suis le point 1.0 ; sinon, tout se fait depuis le tableau de bord, à partir du point 1.1.
### 1.0 Si tu as un accès shell
Assure-toi d'abord d'être **sur le bon système de fichiers** — celui que le bot lit. Un `git pull` au mauvais endroit ne produit aucune erreur et ne change rien, ce qui est le plus trompeur des résultats :
```bash
cd /home/container
ls package.json src/index.js .env && echo "bon endroit"
```
Si cette commande échoue, ton shell ne voit pas le conteneur du bot : passe au point 1.1.
Sinon, l'amorçage se fait directement :
```bash
cp .env .env.sauvegarde && tar czf data-sauvegarde.tgz data/
git init
git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git
git fetch origin main
git reset --hard origin/main
npm ci --omit=dev
```
Puis saute au point 1.3 pour déclarer la cible de production, qui te permettra de déployer d'un clic depuis le tableau de bord plutôt que de revenir ici à chaque fois.
> ⚠️ Ne lance **jamais** `git clean -fd` dans ce dossier : il effacerait `.env` et la base.
### 1.1 Autoriser l'exécution de commandes
**Tableau de bord → Configuration .env → Tableau de bord web** (niveau Owner) :
| Variable | Valeur |
| --------------------------- | ------ |
| `WEB_ALLOW_COMMAND_DEPLOYS` | `true` |
| `WEB_ALLOW_RESTART` | `true` |
Enregistre, puis redémarre le bot depuis le panel. Ces deux valeurs ne sont lues qu'au démarrage.
> Elles permettent d'exécuter une commande sur la machine du bot depuis un navigateur — une exécution de code arbitraire. Réservées au niveau Owner, désactivées par défaut. N'ouvre l'accès Owner qu'à des personnes de confiance.
### 1.2 Amorcer le clone sans shell
Si le point 1.0 ne s'applique pas : le dossier du conteneur contient aujourd'hui une archive décompressée, pas un dépôt. On le convertit avec une cible jetable, exécutée par le bot lui-même.
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| --------------------- | -------------------------------- |
| Nom | `amorçage` |
| Dépôt | `FWS/fws-discordbot` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | voir ci-dessous |
```bash
git init && git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git && git fetch origin main && git reset --hard origin/main
```
Clique **Déployer**, puis lis le journal dans l'historique. Deux cas d'échec :
- **`git: not found`** — l'image du conteneur n'a pas git. Utilise la variante sans git du point 1.5.
- **authentification refusée** — le dépôt est privé. Remplace l'URL par `https://<utilisateur>:<jeton>@gitea.nocode-var.tech/FWS/fws-discordbot.git`. Le jeton est alors stocké dans la configuration de la cible, en base : utilise un jeton dédié, en lecture seule.
`git reset --hard` écrase les fichiers **suivis**. Ton `.env` et ton dossier `data/` sont ignorés par git, donc intacts.
> ⚠️ N'ajoute **jamais** `git clean -fd` à cette commande : elle effacerait `.env` et la base.
Supprime ensuite la cible `amorçage` : elle ne sert qu'une fois.
### 1.3 Déclarer la cible de production
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| ----------------------- | ---------------------------------------------------------------------------- |
| Nom | `production` |
| Dépôt | `FWS/fws-discordbot` |
| Environnement | `production` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | `git fetch origin main && git reset --hard origin/main && npm ci --omit=dev` |
| Déploiement automatique | à activer si tu veux qu'une release publiée déploie seule |
### 1.4 Le cycle courant
1. **Déploiements → Déployer** sur `production`. Le journal complet est conservé, réussite comme échec.
2. **Paramètres → Redémarrer le bot** — le code n'est relu qu'au démarrage.
Contrôle, depuis n'importe où :
```bash
curl -s http://node01.zi-host.ch:25571/api/health
```
`buildAt` doit refléter ton dernier commit. C'est le seul indicateur fiable de ce qui tourne réellement.
### 1.5 Si le conteneur n'a pas git
Gitea sert une archive de n'importe quelle branche. La commande devient :
```bash
curl -sL -H "Authorization: token TON_JETON" https://gitea.nocode-var.tech/api/v1/repos/FWS/fws-discordbot/archive/main.tar.gz | tar xz --strip-components=1 && npm ci --omit=dev
```
Moins bien que git — pas d'historique, pas de moyen de savoir ce qui a changé — mais reproductible, et suffisant pour supprimer le téléversement à la main.
### Ce qu'il faut savoir
- `npm ci --omit=dev` n'installe ni ESLint, ni Prettier, ni de quoi lancer les tests. C'est voulu : ils tournent en intégration continue (chapitre 2), pas en production.
- Si ton egg Pterodactyl réinstalle les fichiers au démarrage, il écrasera le clone. Vérifie l'option _Auto-update / Reinstall on boot_ et désactive-la.
- Les migrations de base s'appliquent toutes seules au démarrage : rien à lancer.
- Tout ce chapitre reste faisable en **SFTP** si tu préfères : le panel en donne les identifiants, et un client comme FileZilla remplace le téléversement par zip. Mais tu restes exposé à la copie partielle, que le déploiement par commande supprime.
---
## 2. Faire tourner les tests avant de déployer
**Le problème qu'on résout.** 301 tests et un lint existent, et ne tournent jamais avant une mise en production. Un déplacement de cartes cassé est passé inaperçu jusqu'à ce qu'un test l'attrape — après coup.
Le fichier de workflow est déjà dans le dépôt : [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml). Il reste à donner un exécuteur à Gitea.
### 2.1 Activer Actions sur l'instance
Côté administration Gitea, dans `app.ini` :
```ini
[actions]
ENABLED = true
```
Puis redémarrer Gitea. Si l'instance ne t'appartient pas, c'est à demander à son administration.
### 2.2 Enregistrer un exécuteur
**Dépôt → Settings → Actions → Runners → Create new runner** te donne un jeton d'enregistrement.
Sur une machine qui a Docker et qui joint ton Gitea — ton poste, un VPS, ou le nœud lui-même :
```bash
curl -sL -o act_runner \
https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64
chmod +x act_runner
./act_runner register --no-interactive \
--instance https://gitea.nocode-var.tech \
--token <JETON_DENREGISTREMENT> \
--name fws-runner \
--labels ubuntu-latest:docker://node:22-bookworm
./act_runner daemon
```
Sans Docker, remplace l'étiquette par `ubuntu-latest:host` — les tâches s'exécutent alors directement sur la machine, qui doit avoir Node 22.
Pour qu'il survive à un redémarrage, place-le en service systemd ou en conteneur `--restart=always`.
### 2.3 Vérifier
Pousse une branche : l'onglet **Actions** du dépôt montre le résultat, et la pull request affiche son état.
### Pourquoi `format:check` n'est pas dans le workflow
Le dépôt contient encore des fichiers en CRLF antérieurs à la configuration Prettier. L'étape échouerait sur du code que personne n'a touché.
Pour l'ajouter : normalise les fins de ligne dans un commit dédié (`refactor(all): normalise les fins de ligne`), puis ajoute l'étape. Tant que ce n'est pas fait, l'absence est volontaire.
---
## 3. Savoir que le bot est tombé
**Le problème qu'on résout.** Une soirée passée à chercher pourquoi le site ne répondait plus, alors qu'une sonde aurait répondu en trente secondes.
Le bot expose déjà tout ce qu'il faut :
```json
GET /api/health
{ "status": "ok", "version": "0.1.0", "buildAt": "…", "uptimeMs": 106470 }
```
### 3.1 Surveiller depuis l'extérieur
Un bot ne peut pas signaler sa propre mort : il faut une sonde **externe**. [Uptime Kuma](https://github.com/louislam/uptime-kuma) est léger et sait écrire sur Discord.
```bash
docker run -d --restart=always -p 3001:3001 \
-v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
```
Puis, dans son interface :
| Réglage | Valeur |
| ------------ | ------------------------------------------- |
| Type | HTTP(s) - Keyword |
| URL | `http://node01.zi-host.ch:25571/api/health` |
| Mot-clé | `"status":"ok"` |
| Intervalle | 60 s |
| Notification | Webhook Discord vers ton salon de logs |
> **Surveille l'origine, pas le domaine public.** Cloudflare renvoie un challenge à toute requête non-navigateur : une sonde sur `https://fws-bot.laxacube.ch` signalerait une panne permanente qui n'existe pas.
Le mot-clé compte : une page qui répond `200` mais sans `"status":"ok"` n'est pas un bot en bonne santé.
### 3.2 Une page que les autres peuvent lire
`/status` répond sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue côté serveur, sans JavaScript, et se rafraîchit toute seule.
C’est l’adresse à donner à la communauté quand quelqu’un demande « c’est en panne ou c’est moi ? ».
`/api/status` en donne la version JSON. Elle vaut mieux que `/api/health` pour une sonde qui affiche un tableau de bord :
```json
GET /api/status
{ "bot": { "online": true, "pingMs": 42, "version": "0.1.0" },
"environments": [ { "environment": "production", "status": "success", "tone": "ok" } ],
"releases": [ … ] }
```
`WEB_PUBLIC_STATUS=false` désactive les deux. Un dépôt privé n’apparaît jamais par son nom sur la page publique.
### 3.3 Ce que le bot surveille déjà lui-même
- Chaque déploiement, réussi ou non, est annoncé sur Discord et consigné avec son journal.
- Les erreurs d'appel Gitea partent dans le salon `errors`.
- **Paramètres → Tester la connexion** vérifie Discord et Gitea à la demande.
Ça couvre les pannes partielles. Ça ne couvre pas un processus mort — d'où le point 3.1.
---
## 4. Sauvegarder hors du conteneur
**Le problème qu'on résout.** Le bouton _Sauvegarder la base_ écrit dans `data/backups`, **à l'intérieur du conteneur**. Une reconstruction efface les deux. C'est déjà arrivé : les salons vocaux orphelins venaient d'une base repartie de zéro.
### 4.1 Sauvegardes du panel (le plus simple)
Pterodactyl sait archiver le serveur entier, hors conteneur.
**Panel → Schedules → Create schedule**
| Réglage | Valeur |
| ------- | ----------------------- |
| Nom | Sauvegarde hebdomadaire |
| Cron | `0 4 * * 1` (lundi 4 h) |
| Tâche | _Create backup_ |
Les archives apparaissent dans l'onglet **Backups**, avec téléchargement. Vérifie la limite d'archives de ton offre.
### 4.2 Instantané cohérent de la base
Une archive de fichiers peut attraper la base en cours d'écriture. Le bot, lui, produit une copie cohérente (`VACUUM INTO`), même journal WAL actif.
Crée un jeton dans **Paramètres → Jetons d'API** (niveau Owner), puis, depuis une machine qui tourne en permanence :
```bash
# Chaque nuit à 3 h
0 3 * * * curl -sS -X POST -H "Authorization: Bearer fws_…" \
http://node01.zi-host.ch:25571/api/settings/backup
```
Le fichier atterrit dans `BACKUP_DIR`, que la sauvegarde du panel emporte ensuite.
### 4.3 Vraiment hors site
Une sauvegarde chez le même hébergeur ne protège pas d'un incident chez lui. Depuis une machine qui a l'accès SFTP du panel :
```bash
rclone sync sftp-panel:/home/container/data backblaze:fws-bot-backups \
--backup-dir backblaze:fws-bot-backups/anciens/$(date +%F)
```
### 4.4 Tester la restauration
Une sauvegarde jamais restaurée n'est pas une sauvegarde. Une fois :
```bash
cp fws-bot-2026-09-24.sqlite /tmp/test.sqlite
DATABASE_PATH=/tmp/test.sqlite npm run db:init
```
La commande doit se terminer sans erreur et appliquer les migrations.
---
## Dans quel ordre
1. **Chapitre 1** — supprime une famille entière de pannes, ne demande que de la configuration.
2. **Chapitre 2** — évite de découvrir un bug en production.
3. **Chapitre 4** — protège ce qui n'est pas remplaçable.
4. **Chapitre 3** — utile, mais vient après ce qui empêche les pannes plutôt que ce qui les signale.
+301
View File
@@ -0,0 +1,301 @@
# Tableau de bord web
Le bot sert lui-même un site d'administration : pilotage de l'organisation Gitea et de ses dépôts, gestion du serveur Discord, pipeline de releases et de déploiements, et un assistant qui écrit le fichier `.env` pas à pas.
Aucune dépendance supplémentaire : `node:http` pour le serveur, `node:sqlite` pour les sessions, `node:crypto` pour les signatures, et un front en JavaScript natif servi tel quel (pas d'étape de build).
## 1. Démarrer
### Première installation, sans `.env`
Le bot refuse de démarrer sans `DISCORD_TOKEN`. L'assistant de configuration se lance donc seul :
```bash
npm install
npm run setup
```
La console affiche l'URL et un jeton d'amorçage à usage unique. Ouvre l'URL, colle le jeton, déroule l'assistant, enregistre. Puis :
```bash
npm run db:init
npm run deploy:commands
npm run dev
```
### Site complet, bot configuré
Mets `WEB_ENABLED=true` dans le `.env`, puis `npm start`. Le site écoute sur `WEB_HOST:WEB_PORT` (par défaut `127.0.0.1:3080`).
Pour que les membres puissent se connecter avec Discord :
1. Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.
2. Toujours dans **OAuth2 → Redirects**, ajoute `<WEB_PUBLIC_URL>/auth/callback`, à l'identique.
3. Génère `WEB_SESSION_SECRET` (l'assistant a un bouton pour ça).
## 2. Qui a accès à quoi
Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff**.
| Niveau | Peut |
| --------- | --------------------------------------------------------------------------------------------------------- |
| **Staff** | Tout consulter, créer des issues, commenter, modérer, clôturer des tickets, publier une annonce |
| **Dev** | En plus : modifier les dépôts, merger, gérer branches et releases, lancer un déploiement, gérer les rôles |
| **Owner** | En plus : supprimer un dépôt, gérer collaborateurs et webhooks, jetons d'API, sauvegardes, `.env` |
Un membre sans rôle Staff, Dev ou Owner ne peut pas ouvrir le site. Le propriétaire du serveur Discord est toujours Owner.
### Modes Simple et Avancé
Le commutateur en bas de la barre latérale masque ou révèle les panneaux techniques (identifiants bruts, journaux, réglages fins, colonnes secondaires). Le mode est retenu par navigateur, et n'a aucun effet sur les droits réels : le serveur vérifie chaque appel de son côté.
## 3. Les pages
| Page | Contenu |
| ---------------------- | ----------------------------------------------------------------------------------------------- |
| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements |
| **Mes tâches** | Les cartes qui te sont assignées, tous tableaux confondus, la plus urgente en premier |
| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt |
| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages |
| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés |
| **Déploiements** | Cibles de déploiement et historique complet, avec le journal de chaque exécution |
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
| **Paramètres** | Comportement du bot, règlement, connexions, sessions, jetons d'API, maintenance |
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
## 4. Assistant de configuration
Le fichier `src/web/services/env-schema.js` décrit **chaque** variable : libellé, explication, type, valeur par défaut, marche à suivre pour l'obtenir. L'assistant, la validation et le `.env` généré en découlent tous. Ajouter une variable au bot, c'est l'ajouter là et nulle part ailleurs.
L'assistant :
- explique chaque étape (où cliquer dans le Developer Portal, quelles portées cocher dans Gitea) ;
- valide au fil de la frappe et signale les combinaisons douteuses (webhooks sans secret, site exposé sans HTTPS) ;
- génère les secrets aléatoires sur demande ;
- teste le token Discord et le jeton Gitea **avant** d'écrire quoi que ce soit ;
- montre un aperçu du fichier et la liste des changements en attente ;
- sauvegarde l'ancien `.env` en `.env.bak-<horodatage>` puis écrit le nouveau en `chmod 600` ;
- conserve les variables qu'il ne connaît pas plutôt que de les perdre.
Un secret laissé vide signifie « garde la valeur actuelle » : impossible d'effacer un token par inadvertance. Les secrets ne repartent jamais vers le navigateur — seul leur statut (renseigné ou non) est envoyé.
Les valeurs du `.env` ne sont lues qu'au démarrage : l'assistant indique quelles modifications demandent un redémarrage.
## 5. Releases et déploiements
### Publier
Depuis la page **Releases** : choisis le dépôt, le tag et la branche cible. Le bouton **Générer les notes** lit les commits depuis la release précédente et les regroupe comme `scripts/generate-changelog.js` : nouveautés, corrections, performance, autres changements, avec un bloc « changements incompatibles » pour les commits marqués `!` ou `BREAKING CHANGE`.
Publier une release non brouillon annonce la version dans le salon `releases` et déclenche les cibles marquées « déploiement automatique ».
### Cibles de déploiement
| Type | Ce qui se passe | Risque |
| ----------------- | ----------------------------------------------------------------------- | ---------------------------------------- |
| **Webhook** | POST JSON signé HMAC-SHA256 vers ton serveur, en-tête `X-FWS-Signature` | Faible — rien ne s'exécute chez le bot |
| **Gitea Actions** | Déclenche un workflow `workflow_dispatch` | Faible |
| **Commande** | Exécute une commande shell sur la machine du bot | **Élevé** — exécution de code arbitraire |
Les cibles « commande » sont doublement verrouillées : `WEB_ALLOW_COMMAND_DEPLOYS=true` **et** niveau Owner. Elles restent désactivées par défaut.
Corps envoyé à un webhook :
```json
{
"deploymentId": 12,
"repository": "FWS/FWS-Arch",
"environment": "production",
"target": "production-web",
"ref": "main",
"releaseTag": "v1.2.0",
"triggeredBy": "123456789012345678",
"source": "web"
}
```
Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en hexadécimal, comparé en temps constant.
Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec).
## 6. Mise à jour automatique
Les pages suivent le bot en direct : aucun rafraîchissement manuel n'est nécessaire.
Le serveur tient un flux `text/event-stream` sur `GET /api/events`, un par onglet ouvert. Il y publie :
- **chaque écriture réussie** de l'API, étiquetée selon la page concernée (`deployments`, `gitea`, `discord`, `community`, `settings`) — une écriture rejetée ne déclenche rien ;
- **l'avancement des déploiements**, au démarrage puis à l'arrivée du résultat ;
- **les webhooks Gitea** reçus, dès qu'ils sont validés ;
- un **tick** toutes les 15 secondes, et un battement de cœur toutes les 25 secondes qui empêche les proxys de fermer un flux inactif.
Côté navigateur, un seul `EventSource` sert tout le tableau de bord, et chaque page ne réagit qu'aux sujets qui la concernent. L'indicateur en bas de la barre latérale dit où en est la connexion.
Trois garde-fous, parce qu'un rafraîchissement qui tombe au mauvais moment est pire qu'une donnée un peu vieille :
- rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus — le rafraîchissement est rejoué ensuite ;
- une rafale d'écritures ne produit qu'un seul rechargement ;
- l'onglet en arrière-plan ferme son flux et le rouvre au retour.
Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — un rafraîchissement périodique prend le relais automatiquement, et l'indicateur passe en orange. La page Serveur Discord est volontairement hors du tick : lister les membres appelle l'API Discord, elle ne se rafraîchit que sur un vrai changement.
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
## 7. Trouver et suivre son travail
### Mes tâches
**Tableau de bord → Mes tâches** rassemble les cartes qui te sont assignées sur **tous** les tableaux, groupées par échéance : en retard, pour aujourd’hui, cette semaine, plus tard, sans date. Les cartes terminées sont repliées en bas.
- Le bouton rond à gauche d’une carte la déplace dans la colonne « terminé » de son tableau, sans quitter la page.
- Le compteur de la barre latérale indique le nombre de cartes ouvertes, en rouge dès qu’une est en retard.
- Le sélecteur en haut à droite permet de regarder la charge d’un autre membre, quand plusieurs personnes portent des cartes.
Une carte n’apparaît ici que si elle a un **assigné**. C’est le seul champ qui compte pour cette page.
### Recherche globale
**⌘K** (ou **Ctrl+K**, ou la barre « Rechercher ») ouvre une recherche unique sur :
| Source | Où elle mène | D’où elle vient |
| ----------- | -------------------------------------- | ------------------------- |
| Pages | L’onglet correspondant | Le navigateur, sans appel |
| Cartes | Le tableau qui la porte | La base locale |
| Dépôts | La fiche du dépôt | Gitea, en cache 60 s |
| Issues / PR | Gitea, dans un onglet | Gitea |
| Wiki | La page publique | La base locale |
| Membres | L’onglet Discord, recherche préremplie | Le cache du bot |
Les pages sont filtrées dans le navigateur : la palette répond avant même d’avoir interrogé le serveur, et reste utile si Gitea ne répond pas. Une source qui échoue est simplement absente des résultats.
Les flèches naviguent, **Entrée** ouvre, **Échap** ferme. Une page à laquelle tu n’as pas accès n’apparaît jamais dans les résultats.
### Page de statut publique
**`/status`** est lisible sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue **côté serveur, sans une seule ligne de JavaScript**, et s’actualise par une balise `meta refresh` — une page de statut qui a besoin d’un navigateur moderne pour dire qu’il y a une panne est une page inutile au moment où elle sert.
Deux garde-fous, parce que la page est publique :
- Un dépôt que Gitea ne liste pas comme public apparaît **sans son nom** : l’environnement reste visible, le dépôt non.
- La bannière annonce toujours le pire état vrai. Un déploiement en échec empêche l’en-tête vert, même si le bot répond.
`WEB_PUBLIC_STATUS=false` la désactive entièrement ; `/status` renvoie alors 404, comme `/api/status`.
`/api/status` donne la même chose en JSON, sans session : c’est ce qu’une sonde de supervision doit interroger, plutôt que `/api/health` qui ne dit que « le processus vit ».
## 8. Wiki public
Le bot sert une documentation publique sur **`/wiki`**, lisible sans compte, écrite depuis **Tableau de bord → Wiki**.
- Les pages sont rédigées en Markdown, avec un aperçu en direct dans l'éditeur.
- Une page reste en **brouillon** tant qu'elle n'est pas publiée ; un brouillon renvoie 404 même si on devine son adresse.
- Les pages sont regroupées par **catégorie** et ordonnées par **position**.
- La recherche porte sur les titres, les résumés et le contenu des pages publiées.
Le rendu Markdown échappe le HTML **avant** toute transformation et refuse les liens `javascript:`. Les pages sont écrites par l'équipe, mais un moteur qui compte là-dessus est à une erreur près d'être une faille.
### Pages légales
Au premier démarrage, trois pages sont créées : un accueil et deux pages **protégées** — **Conditions d'utilisation** et **Politique de confidentialité**. Elles sont modifiables mais pas supprimables : un bot qui traite des données personnelles doit pouvoir montrer ses conditions.
La politique de confidentialité est rédigée selon la **LPD suisse révisée** (RS 235.1, en vigueur depuis le 1ᵉʳ septembre 2023) et décrit ce que ce code stocke réellement, table par table. Les mentions entre crochets — responsable du traitement, adresse, hébergeur — doivent être complétées, et l'ensemble relu par une personne compétente avant publication.
Une page supprimée par erreur est recréée au démarrage suivant ; une page réécrite ne l'est jamais.
## 9. Réglages du serveur
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, règlement, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
### Rédiger et publier le règlement
La section **Règlement** de la page Paramètres écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et **Enregistrer** les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. L'identifiant du message est retenu en base (`rules_messages`) : les enregistrements suivants **modifient ce message**, même lien, même place dans le salon et épingle conservée, au lieu d'empiler les versions. Un message supprimé à la main, un salon devenu inaccessible ou un bot qui ne peut plus éditer font repartir sur un nouveau message ; un épinglage refusé est signalé sans bloquer la publication. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
## 10. Publier les commandes slash
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
## 11. Jetons d'API
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
```bash
curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview
```
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
## 12. Sécurité
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
- **Écritures.** Toute requête autre qu'une lecture exige l'en-tête `X-Requested-With: fws-dashboard`, que le navigateur ne peut pas forger depuis un autre site, plus une vérification de l'origine.
- **En-têtes.** CSP restreinte à `self`, `X-Frame-Options: DENY`, `nosniff`, aucune ressource tierce.
- **Limitation de débit.** `WEB_RATE_LIMIT_PER_MINUTE` requêtes par adresse IP et par minute.
- **Secrets.** Jamais renvoyés au navigateur, jamais écrits dans les logs (`maskSecrets`).
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
## 13. Fonctionnement interne
```text
src/web/
├── server.js # Serveur HTTP, répartition, gestion des erreurs, limitation de débit
├── router.js # Routeur : motifs `/api/x/:param`, 404 et 405
├── http.js # Réponses JSON, corps, cookies, fichiers statiques, en-têtes de sécurité
├── setup-state.js # Jeton d'amorçage de l'assistant
├── auth/
│ ├── discord-oauth.js # Flux OAuth2 et calcul du niveau d'accès
│ ├── session.js # Sessions signées, jetons d'API, protection anti-CSRF
│ ├── guard.js # Contrôle d'accès par route
│ └── routes.js # /auth/login, /auth/callback, /api/me
├── api/ # Un module par domaine fonctionnel
├── services/
│ ├── env-schema.js # Description documentée de chaque variable
│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env
│ ├── deploy-service.js # Exécution des déploiements et notifications
│ ├── build-info.js # Version et date de l’interface réellement servie
│ ├── wiki-seed.js # Pages créées au premier démarrage, adresses publiques
│ ├── wiki-render.js # Wiki rendu côté serveur
│ ├── status-service.js # Instantané public : bot, déploiements, releases
│ └── status-render.js # Page /status rendue côté serveur, sans script
└── public/ # Front servi tel quel (aucun build)
├── index.html
├── styles.css
├── app.js # Shell, navigation, routage par fragment
├── core/ # dom.js, api.js, ui.js, live.js, nav.js, palette.js
└── views/ # Une vue par page
```
Une route se déclare ainsi :
```js
router.get(
'/api/repositories/:owner/:repo',
async ({ params, query, body, actor, context }) => {
return { fullName: `${params.owner}/${params.repo}` };
},
{ access: ACCESS_LEVELS.STAFF },
);
```
Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le corps JSON, puis sérialise la valeur retournée. Une `HttpError` fixe le code ; une `UserFacingError` devient un 400 ; toute autre erreur est journalisée et remplacée par un message générique.
### Partage de port avec les webhooks
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
## 14. Dépannage
| Symptôme | Cause probable |
| ---------------------------------------------- | ------------------------------------------------------------------------------- |
| `state-mismatch` à la connexion | Cookies bloqués, ou plus de 10 minutes entre le clic et le retour |
| `exchange-failed` | L'URL de redirection du portail ne correspond pas exactement à `WEB_PUBLIC_URL` |
| `insufficient-level` | Le compte n'a ni rôle Staff, ni Dev, ni Owner sur le serveur |
| Déconnexion à chaque redémarrage | `WEB_SESSION_SECRET` n'est pas défini |
| « Gitea n'est pas configuré » | `GITEA_URL` ou `GITEA_TOKEN` manquant — teste le jeton depuis les paramètres |
| Onglet Actions vide | Gitea Actions désactivé sur le dépôt, ou Gitea antérieur à 1.20 |
| Les modifications du `.env` restent sans effet | Le fichier n'est lu qu'au démarrage : redémarre le bot |
+26 -21
View File
@@ -1,21 +1,26 @@
import js from '@eslint/js';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
export default [
{ ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] },
js.configs.recommended,
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: globals.node,
},
rules: {
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'prefer-const': 'error',
eqeqeq: ['error', 'always'],
},
},
prettier,
];
import js from '@eslint/js';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
export default [
{ ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] },
js.configs.recommended,
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: globals.node,
},
rules: {
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'prefer-const': 'error',
eqeqeq: ['error', 'always'],
},
},
{
// The dashboard front-end runs in the browser, not in Node (M16-T11).
files: ['src/web/public/**/*.js'],
languageOptions: { globals: globals.browser },
},
prettier,
];
+1443 -1443
View File
File diff suppressed because it is too large. Load diff
+35 -32
View File
@@ -1,32 +1,35 @@
{
"name": "fws-discordbot",
"version": "0.1.0",
"description": "FWS-Bot — Discord bot for the FWS open source organization",
"private": true,
"type": "module",
"main": "src/index.js",
"engines": {
"node": ">=22.13.0"
},
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"deploy:commands": "node scripts/deploy-commands.js",
"db:init": "node scripts/init-database.js",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "node --test tests/"
},
"dependencies": {
"discord.js": "^14.21.0"
},
"devDependencies": {
"@eslint/js": "^9.30.0",
"eslint": "^9.30.0",
"eslint-config-prettier": "^10.1.5",
"globals": "^16.3.0",
"prettier": "^3.6.2"
}
}
{
"name": "fws-discordbot",
"version": "0.1.0",
"description": "FWS-Bot — Discord bot for the FWS open source organization",
"private": true,
"type": "module",
"main": "src/index.js",
"engines": {
"node": ">=22.13.0"
},
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"setup": "node scripts/setup-server.js",
"deploy:commands": "node scripts/deploy-commands.js",
"db:init": "node scripts/init-database.js",
"changelog": "node scripts/generate-changelog.js",
"changelog:check": "node scripts/generate-changelog.js --check",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "node --test tests/"
},
"dependencies": {
"discord.js": "^14.21.0"
},
"devDependencies": {
"@eslint/js": "^9.30.0",
"eslint": "^9.30.0",
"eslint-config-prettier": "^10.1.5",
"globals": "^16.3.0",
"prettier": "^3.6.2"
}
}
+13 -13
View File
@@ -1,13 +1,13 @@
import { REST, Routes } from 'discord.js';
import { assertRequiredEnv, env } from '../src/config/env.js';
import { loadCommands } from '../src/core/command-loader.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
const body = (await loadCommands()).map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token);
// Guild commands update instantly, which suits a single-server bot (M2-T05).
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body });
console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`);
import { REST, Routes } from 'discord.js';
import { assertRequiredEnv, env } from '../src/config/env.js';
import { loadCommands } from '../src/core/command-loader.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
const body = (await loadCommands()).map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token);
// Guild commands update instantly, which suits a single-server bot (M2-T05).
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body });
console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`);
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions
* require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are
* grouped under "Other changes". The file is generated, so run this script instead of editing it.
*
* Usage: node scripts/generate-changelog.js [--check]
* --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests)
*/
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const changelogPath = path.join(rootDir, 'CHANGELOG.md');
const checkOnly = process.argv.includes('--check');
/** Section order and titles; anything else falls into "Other changes". */
const SECTIONS = [
{ title: 'Features', test: (type) => type === 'feat' },
{ title: 'Bug Fixes', test: (type) => type === 'fix' },
{ title: 'Performance', test: (type) => type === 'perf' },
{
title: 'Other changes',
test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf',
},
];
const OTHER_LABELS = {
build: 'build',
chore: 'chore',
ci: 'ci',
docs: 'docs',
refactor: 'refactor',
revert: 'revert',
style: 'style',
test: 'test',
};
const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' });
function readCommits() {
// One record per commit, fields separated by unit separators so bodies stay readable.
const raw = git([
'log',
'--no-merges',
'--date=short',
'--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e',
// A commit that only rewrites the changelog must not appear in it, otherwise `--check`
// could never be green once that file is committed.
'--',
'.',
':(exclude)CHANGELOG.md',
]);
return raw
.split('\x1e')
.map((record) => record.trim())
.filter(Boolean)
.map((record) => {
const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f');
const match = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/.exec(
subject.trim(),
);
const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body);
return {
hash,
date,
subject: subject.trim(),
type: match?.groups.type ?? 'other',
scope: match?.groups.scope ?? null,
description: match?.groups.description ?? subject.trim(),
breaking,
tags: decoration
.split(',')
.map((ref) => ref.trim().replace(/^tag: /, ''))
.filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)),
};
});
}
function entryLine(commit) {
const scope = commit.scope ? `**${commit.scope}:** ` : '';
const breaking = commit.breaking ? '**BREAKING** ' : '';
const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `;
const detail = commit.type === 'other' ? commit.subject : commit.description;
return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`;
}
/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */
function groupByRelease(commits) {
const releases = [];
let current = { title: 'Unreleased', date: null, commits: [] };
for (const commit of commits) {
current.commits.push(commit);
for (const tag of commit.tags) {
releases.push({ title: tag, date: commit.date, commits: current.commits });
current = { title: 'Unreleased', date: null, commits: [] };
}
}
if (current.commits.length > 0) releases.push(current);
return releases;
}
function renderRelease(release) {
const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`;
const lines = [heading];
for (const section of SECTIONS) {
const entries = release.commits.filter((commit) => section.test(commit.type));
if (entries.length === 0) continue;
lines.push('', `### ${section.title}`, ...entries.map(entryLine));
}
if (release.commits.length === 0) lines.push('', '_Nothing yet._');
return lines.join('\n');
}
/** SemVer hint from the commits since the last release: breaking > feature > fix. */
function suggestVersion(commits) {
const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version;
const [major, minor, patch] = version.split('.').map(Number);
const breaking = commits.some((commit) => commit.breaking);
const feature = commits.some((commit) => commit.type === 'feat');
// SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor.
if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`;
if (breaking) return `${major + 1}.0.0`;
if (feature) return `${major}.${minor + 1}.0`;
return `${major}.${minor}.${patch + 1}`;
}
function buildChangelog(commits) {
const releases = groupByRelease(commits);
return [
'# Changelog',
'',
'All notable changes to this project are documented in this file. It is **generated from the',
'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.',
'The project follows [Semantic Versioning](https://semver.org/).',
'',
releases.map(renderRelease).join('\n\n'),
'',
].join('\n');
}
const commits = readCommits();
const content = buildChangelog(commits);
const unreleased = commits.filter((commit) => !commit.tags.length);
const previous = (() => {
try {
return readFileSync(changelogPath, 'utf8');
} catch {
return null;
}
})();
if (checkOnly) {
if (previous !== content) {
console.error('CHANGELOG.md is out of date: run `npm run changelog`.');
process.exit(1);
}
console.log('CHANGELOG.md is up to date.');
process.exit(0);
}
writeFileSync(changelogPath, content);
console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`);
console.log(`Suggested next version: ${suggestVersion(unreleased)}`);
+7 -7
View File
@@ -1,7 +1,7 @@
import { env } from '../src/config/env.js';
import { closeDatabase, initDatabase } from '../src/database/index.js';
initDatabase();
closeDatabase();
console.log(`Database ready at ${env.database.path}`);
import { env } from '../src/config/env.js';
import { closeDatabase, initDatabase } from '../src/database/index.js';
initDatabase();
closeDatabase();
console.log(`Database ready at ${env.database.path}`);
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
import { env } from '../src/config/env.js';
import { logger } from '../src/core/logger.js';
import { initDatabase } from '../src/database/index.js';
import { startWebServer } from '../src/web/server.js';
import { generateRuntimeSetupToken, hasSetupToken } from '../src/web/setup-state.js';
/**
* Starts the configuration wizard alone, without connecting to Discord (M16-T09).
*
* This is the entry point for a fresh clone: the bot itself refuses to start
* without `DISCORD_TOKEN`, so the `.env` has to be writable from somewhere else.
*
* Usage: npm run setup
*/
// The wizard stores its session in SQLite, so the database must exist.
initDatabase();
const token = env.web.setupToken || generateRuntimeSetupToken();
const url =
env.web.publicUrl || `http://${env.web.host === '0.0.0.0' ? 'localhost' : env.web.host}:${env.web.port}`;
const server = startWebServer({ client: null, setupOnly: true });
logger.info('Configuration wizard started');
console.log(`
┌──────────────────────────────────────────────────────────────────────┐
│ Assistant de configuration FWS-Bot │
└──────────────────────────────────────────────────────────────────────┘
Ouvre ${url}/#/setup
Jeton ${token}
${env.web.setupToken ? 'Ce jeton vient de WEB_SETUP_TOKEN.' : 'Ce jeton est temporaire : il change à chaque lancement.'}
Une fois le .env enregistré : Ctrl+C, puis npm run db:init,
npm run deploy:commands et npm run dev.
`);
if (!hasSetupToken()) logger.warn('No setup token available, the wizard cannot be opened');
const shutdown = () => {
server.close();
process.exit(0);
};
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
+107 -12
View File
@@ -1,12 +1,107 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder().setName('fun').setDescription('Commandes de divertissement');
// TODO(M10-T07): add fun subcommands.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/fun')] });
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
const EIGHT_BALL_ANSWERS = Object.freeze([
'Oui, sans aucun doute.',
'Compte là-dessus et bois de l’eau.',
'Les signes disent que oui.',
'Impossible de le prédire pour le moment.',
'Concentre-toi et redemande.',
'Ma réponse est non.',
'Très probablement.',
'Mes sources disent non.',
'La réponse est floue, réessaie.',
'Absolument !',
'Pas dans un avenir proche.',
'Oui, mais fais attention à toi.',
]);
const pick = (list) => list[Math.floor(Math.random() * list.length)];
export const data = new SlashCommandBuilder()
.setName('fun')
.setDescription('Commandes de divertissement')
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
.addSubcommand((sub) =>
sub
.setName('dice')
.setDescription('Lancer un dé')
.addIntegerOption((option) =>
option
.setName('sides')
.setDescription('Nombre de faces (6 par défaut)')
.setMinValue(2)
.setMaxValue(1000),
),
)
.addSubcommand((sub) =>
sub
.setName('8ball')
.setDescription('Poser une question à la boule magique')
.addStringOption((option) =>
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
),
)
.addSubcommand((sub) =>
sub
.setName('choose')
.setDescription('Choisir au hasard parmi plusieurs options')
.addStringOption((option) =>
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
),
);
/** Lightweight, stateless fun commands (M10-T07). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']);
await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)],
});
return;
}
if (subcommand === 'dice') {
const sides = interaction.options.getInteger('sides') ?? 6;
const roll = 1 + Math.floor(Math.random() * sides);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle(`🎲 Lancer de dé (d${sides})`)
.setDescription(`Tu obtiens **${roll}** !`),
],
});
return;
}
if (subcommand === '8ball') {
const question = interaction.options.getString('question', true);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎱 Boule magique')
.addFields(
{ name: 'Question', value: question },
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
),
],
});
return;
}
const options = parseChoices(interaction.options.getString('options', true));
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎯 Choix aléatoire')
.addFields({ name: 'Options', value: bullets(options) })
.setDescription(`Je choisis : **${pick(options)}**`),
],
});
}
+62 -34
View File
@@ -1,34 +1,62 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('poll')
.setDescription('Sondages')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Créer un sondage')
.addStringOption((option) =>
option.setName('question').setDescription('Question').setRequired(true).setMaxLength(200),
)
.addStringOption((option) =>
option.setName('choices').setDescription('Choix séparés par ";" (2 à 10)').setRequired(true),
)
.addIntegerOption((option) =>
option.setName('minutes').setDescription('Durée en minutes').setMinValue(1).setMaxValue(10_080),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer un sondage')
.addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)),
);
// TODO(M10-T01..T06): implement with polls / poll_votes tables.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/poll ${interaction.options.getSubcommand()}`)] });
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('poll')
.setDescription('Sondages')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Créer un sondage')
.addStringOption((option) =>
option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200),
)
.addStringOption((option) =>
option
.setName('choices')
.setDescription('Propositions séparées par des « ; » (2 à 10)')
.setRequired(true),
)
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée avant fermeture automatique, en minutes')
.setMinValue(1)
.setMaxValue(10_080),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer un sondage')
.addIntegerOption((option) =>
option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true),
),
);
/** Polls are published in the current channel and voted with buttons (M10). */
export async function execute(interaction) {
if (interaction.options.getSubcommand() === 'close') {
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
await interaction.reply({ embeds: [buildPollEmbed(poll)] });
return;
}
const question = interaction.options.getString('question', true);
const choicesInput = interaction.options.getString('choices', true);
const minutes = interaction.options.getInteger('minutes');
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const pollId = await createPoll(interaction, { question, choicesInput, minutes });
await interaction.editReply({
embeds: [
successEmbed(
`Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`,
),
],
});
}
+116 -17
View File
@@ -1,17 +1,116 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('stats')
.setDescription('Statistiques publiques')
.addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord'))
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
// TODO(M11-T02..T04): implement per data source.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/stats ${interaction.options.getSubcommand()}`)] });
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { createLogger } from '../../core/logger.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
const log = createLogger('stats');
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('stats')
.setDescription('Statistiques publiques')
.addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord'))
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
const discordStatsEmbed = (interaction) => {
const guild = interaction.guild;
return baseEmbed()
.setTitle(`📊 Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 }))
.addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true },
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true },
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
);
};
async function giteaStatsEmbed() {
const [issues, pulls, commits, releases] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
gitea.listReleases(1),
]);
const latestCommits = asList(commits)
.slice(0, 5)
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
.join('\n');
const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité Gitea')
.setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
if (release)
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
return embed;
}
/** Community activity stored locally, independent from Gitea availability (M11). */
function fwsStatsEmbed(interaction) {
const actions = countByAction(interaction.guildId);
const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea)
.setTitle('📈 Indicateurs FWS')
.addFields(
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
{ name: 'Actions de modération', value: String(total), inline: true },
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
)
.setFooter({ text: 'Statistiques locales · FWS-Bot' });
}
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
await interaction.deferReply();
if (subcommand === 'discord') {
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
return;
}
if (subcommand === 'fws') {
try {
const releases = asList(await gitea.listReleases(1));
const embed = fwsStatsEmbed(interaction);
if (releases[0])
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
log.warn('Gitea unavailable while building /stats fws', error);
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
}
return;
}
try {
await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
} catch (error) {
log.error('Could not read Gitea stats', error);
await interaction.editReply({
embeds: [
errorEmbed(
'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.',
),
],
});
}
}
+238 -57
View File
@@ -1,57 +1,238 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('fws')
.setDescription('Informations sur FWS et FWS Arch')
.addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch'))
.addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch'))
.addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets'))
.addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles'))
.addSubcommand((sub) =>
sub
.setName('changelog')
.setDescription("Changements d'une version")
.addStringOption((option) => option.setName('version').setDescription('Version (dernière par défaut)')),
);
const officialLinks = () => [
{ label: 'Site', url: env.links.website },
{ label: 'Documentation', url: env.links.docs },
{ label: 'Dépôt FWS Arch', url: env.links.archRepo },
{ label: 'Gitea', url: env.gitea.url },
{ label: 'Discord', url: env.links.discordInvite },
];
const handlers = {
// TODO(M4-T01): content should come from guild_settings (M4-T07).
info: (interaction) =>
interaction.reply({
embeds: [
baseEmbed()
.setTitle('FWS & FWS Arch')
.setDescription(
'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.",
),
],
components: linkButtons(officialLinks()),
}),
links: (interaction) =>
interaction.reply({
embeds: [baseEmbed().setTitle('Liens officiels FWS')],
components: linkButtons(officialLinks()),
}),
version: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws version')] }),
status: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws status')] }),
changelog: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws changelog')] }),
};
export async function execute(interaction) {
await handlers[interaction.options.getSubcommand()](interaction);
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws');
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('fws')
.setDescription('Informations sur FWS et FWS Arch')
.addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch'))
.addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch'))
.addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets'))
.addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles'))
.addSubcommand((sub) =>
sub
.setName('changelog')
.setDescription('Nouveautés d’une version')
.addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'),
),
);
const officialLinks = () => [
{ label: 'Site', url: env.links.website },
{ label: 'Documentation', url: env.links.docs },
{ label: 'Dépôt FWS Arch', url: env.links.archRepo },
{ label: 'Gitea', url: env.gitea.url },
{ label: 'Discord', url: env.links.discordInvite },
];
/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
function readSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch (error) {
log.debug(`Could not read setting ${key}`, error);
return fallback;
}
}
const DEFAULT_PRESENTATION =
'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
async function latestRelease() {
try {
return await gitea.getLatestRelease();
} catch {
return asList(await gitea.listReleases(1))[0] ?? null;
}
}
async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: errorEmbed(
'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
async function showStatus(interaction) {
await interaction.deferReply();
const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured
? await gitea
.listReleases(1)
.then(() => true)
.catch(() => false)
: false;
let openTickets = null;
try {
openTickets = countOpenTickets(interaction.guildId);
} catch (error) {
log.warn('Database unavailable while building /fws status', error);
}
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('🩺 État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Pas encore configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable pour le moment',
inline: false,
},
{
name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false,
},
{
name: 'Base SQLite',
value:
openTickets === null
? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false,
},
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
}
async function showChangelog(interaction) {
const version = interaction.options.getString('version');
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
});
} catch (error) {
if (version) {
log.warn(`Release ${version} not found`, error);
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
),
],
});
return;
}
await replyGiteaFailure(interaction, error);
}
}
/** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'info':
await showInfo(interaction);
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
case 'version':
await showVersion(interaction);
return;
case 'status':
await showStatus(interaction);
return;
case 'changelog':
await showChangelog(interaction);
return;
default:
return;
}
}
+25 -21
View File
@@ -1,21 +1,25 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('help')
.setDescription('Affiche les commandes accessibles selon ton rôle');
export async function execute(interaction) {
const level = getAccessLevel(interaction.member);
const lines = interaction.client.commands
.filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level)
.map((command) => `\`/${command.data.name}\` — ${command.data.description}`)
.sort();
const embed = baseEmbed().setTitle('Commandes FWS-Bot').setDescription(lines.join('\n'));
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('help')
.setDescription('Affiche les commandes accessibles selon ton rôle');
export async function execute(interaction) {
const level = getAccessLevel(interaction.member);
const lines = interaction.client.commands
.filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level)
.map((command) => `\`/${command.data.name}\` — ${command.data.description}`)
.sort();
const embed = baseEmbed()
.setTitle('🤖 Tes commandes')
.setDescription(
`Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`,
);
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+153
View File
@@ -0,0 +1,153 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
addBotStatus,
applyBotStatus,
applyStatusIfAlone,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
removeBotStatus,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
saveRotationSeconds,
STATUS_TYPE_CHOICES,
statusAddedEmbed,
statusListEmbed,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder()
.setName('status')
.setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un statut à la rotation')
.addStringOption((option) =>
option
.setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true)
.setMaxLength(128),
)
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES),
)
.addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub
.setName('interval')
.setDescription('Rythme de la rotation')
.addIntegerOption((option) =>
option
.setName('seconds')
.setDescription('Secondes entre deux changements')
.setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS),
),
)
.addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
);
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return;
}
if (subcommand === 'add') {
const status = addBotStatus({
text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'),
createdBy: interaction.user.id,
});
// A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied }));
return;
}
if (subcommand === 'interval') {
const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true),
interaction.guildId,
interaction.user.id,
);
await reply(
interaction,
successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
),
);
return;
}
if (subcommand === 'clear') {
const removed = clearBotStatusList();
applyBotStatus(interaction.client);
await reply(
interaction,
successEmbed(
removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
),
);
return;
}
const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') {
const status = removeBotStatus(id);
await reply(
interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
);
return;
}
const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client);
await reply(
interaction,
successEmbed(
enabled
? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
),
);
}
+74 -16
View File
@@ -1,16 +1,74 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('gitea')
.setDescription('Activité Gitea de FWS Arch')
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
// TODO(M5-T06 / M5-T07): implement with services/gitea/gitea-client.js.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/gitea ${interaction.options.getSubcommand()}`)] });
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('gitea')
.setDescription('Activité Gitea de FWS Arch')
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
const commitLines = (commits) =>
bullets(
asList(commits)
.slice(0, 5)
.map((commit) => {
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`;
}),
);
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
if (interaction.options.getSubcommand() === 'release') {
const releases = asList(await gitea.listReleases(5));
if (releases.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('📦 Releases FWS Arch')
.setURL(repositoryUrl())
.setDescription(
releases
.map((release) => {
const date = release.published_at
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
: 'date inconnue';
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
})
.join('\n'),
);
await interaction.editReply({ embeds: [embed] });
return;
}
const [issues, pulls, commits] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
]);
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité récente')
.setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+80 -27
View File
@@ -1,27 +1,80 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// TODO(M5-T03): make the required level for `create` configurable per guild.
export const subcommandAccess = { create: ACCESS_LEVELS.USER };
export const data = new SlashCommandBuilder()
.setName('issue')
.setDescription('Issues Gitea')
.addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea'))
.addSubcommand((sub) =>
sub
.setName('view')
.setDescription('Afficher une issue')
.addIntegerOption((option) =>
option.setName('number').setDescription("Numéro de l'issue").setRequired(true).setMinValue(1),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
// TODO(M5-T02 / M5-T03): implement with services/gitea/gitea-client.js.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/issue ${interaction.options.getSubcommand()}`)] });
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openIssueModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// TODO(M5-T03): make the required level for `create` configurable per guild.
export const subcommandAccess = { create: ACCESS_LEVELS.USER };
export const data = new SlashCommandBuilder()
.setName('issue')
.setDescription('Issues Gitea')
.addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea'))
.addSubcommand((sub) =>
sub
.setName('view')
.setDescription('Afficher une issue')
.addIntegerOption((option) =>
option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openIssueModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
if (!issue?.number) {
throw new UserFacingError(
'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.',
);
}
await interaction.editReply({ embeds: [issueEmbed(issue)] });
return;
}
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
if (issues.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`)
.setDescription(
bullets(
issues.map(
(issue) =>
`**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`,
),
),
)
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+95 -31
View File
@@ -1,31 +1,95 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
export const data = new SlashCommandBuilder()
.setName('pr')
.setDescription('Pull requests Gitea')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Créer une pull request')
.addStringOption((option) => option.setName('head').setDescription('Branche source').setRequired(true))
.addStringOption((option) => option.setName('base').setDescription('Branche cible').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('view')
.setDescription('Afficher une pull request')
.addIntegerOption((option) =>
option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
// TODO(M5-T04 / M5-T05): implement with services/gitea/gitea-client.js.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/pr ${interaction.options.getSubcommand()}`)] });
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openPullRequestModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
export const data = new SlashCommandBuilder()
.setName('pr')
.setDescription('Pull requests Gitea')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Créer une pull request')
.addStringOption((option) =>
option
.setName('head')
.setDescription('Branche source, celle qui apporte les changements')
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('base')
.setDescription('Branche cible, celle qui reçoit les changements')
.setRequired(true),
),
)
.addSubcommand((sub) =>
sub
.setName('view')
.setDescription('Afficher une pull request')
.addIntegerOption((option) =>
option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
/** The title and description are collected through a modal (M5-T04 / M5-T05). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openPullRequestModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
if (!pull?.number) {
throw new UserFacingError(
'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.',
);
}
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
return;
}
const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
if (pulls.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`)
.setDescription(
bullets(
pulls.map(
(pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`,
),
),
)
.setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+59 -24
View File
@@ -1,24 +1,59 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('ban')
.setDescription('Bannir un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500))
.addIntegerOption((option) =>
option
.setName('delete_days')
.setDescription('Supprimer les messages des N derniers jours')
.setMinValue(0)
.setMaxValue(7),
);
// TODO(M8-T04): ban after canActOn() check and log the sensitive action (M8-T09).
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/ban')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js';
import {
assertModerationTarget,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('ban')
.setDescription('Bannir un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500))
.addIntegerOption((option) =>
option
.setName('delete_days')
.setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)')
.setMinValue(0)
.setMaxValue(7),
);
/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
// Falls back to what the server configured rather than to a blunt zero.
const deleteDays =
interaction.options.getInteger('delete_days') ??
Math.round(readSetting('moderation.banDeleteMessageHours', interaction.guildId) / 24);
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) {
assertModerationTarget(interaction, member);
await notifyTarget(member, {
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
});
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.create(user.id, {
reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400,
});
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+49 -23
View File
@@ -1,23 +1,49 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('clear')
.setDescription('Supprimer des messages')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
.addIntegerOption((option) =>
option
.setName('amount')
.setDescription('Nombre de messages')
.setRequired(true)
.setMinValue(1)
.setMaxValue(100),
);
// TODO(M8-T05): channel.bulkDelete(amount, true) and log the action.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/clear')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('clear')
.setDescription('Supprimer des messages')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
.addIntegerOption((option) =>
option
.setName('amount')
.setDescription('Nombre de messages à supprimer (1 à 100)')
.setRequired(true)
.setMinValue(1)
.setMaxValue(100),
);
/** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) {
const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError(
'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const deleted = await interaction.channel.bulkDelete(amount, true);
await logModerationAction(interaction, {
action: 'clear',
targetId: null,
reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount
? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._'
: ''),
),
],
});
}
+43 -17
View File
@@ -1,17 +1,43 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('kick')
.setDescription('Expulser un membre du serveur')
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T03): kick after canActOn() check and log the action.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/kick')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('kick')
.setDescription('Expulser un membre du serveur')
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await notifyTarget(target, {
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
});
await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`,
),
],
});
}
+54 -21
View File
@@ -1,21 +1,54 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('mod')
.setDescription('Outils de modération')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addSubcommand((sub) =>
sub
.setName('logs')
.setDescription('Consulter les actions de modération')
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
);
// TODO(M8-T06): read from moderation_actions.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/mod logs')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration, moderationLabel } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const HISTORY_LIMIT = 15;
export const data = new SlashCommandBuilder()
.setName('mod')
.setDescription('Outils de modération')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addSubcommand((sub) =>
sub
.setName('logs')
.setDescription('Consulter les actions de modération')
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
);
function formatEntry(row) {
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
return (
`\`${row.created_at}\` **${moderationLabel(row.action)}** — ${target}${duration}\n` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
);
}
/** Reads the moderation history from SQLite (M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user');
const actions = listActions({
guildId: interaction.guildId,
targetId: user?.id ?? null,
limit: HISTORY_LIMIT,
});
const embed =
actions.length === 0
? infoEmbed(
'📜 Historique de modération',
user
? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.`
: 'Aucune action de modération enregistrée sur ce serveur, tout est calme.',
)
: baseEmbed(COLORS.moderation)
.setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération')
.setDescription(actions.map(formatEntry).join('\n\n'))
.setFooter({ text: `${actions.length} action(s) affichée(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+62 -25
View File
@@ -1,25 +1,62 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('mute')
.setDescription('Restreindre temporairement un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée en minutes')
.setRequired(true)
.setMinValue(1)
.setMaxValue(40_320),
)
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T02 / M8-T07): use member.timeout() after canActOn() check.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/mute')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js';
import {
assertModerationTarget,
fetchTargetMember,
formatDuration,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('mute')
.setDescription('Restreindre temporairement un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée de la sanction, en minutes')
.setMinValue(1)
.setMaxValue(40_320),
)
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const minutes =
interaction.options.getInteger('minutes') ??
readSetting('moderation.defaultMuteMinutes', interaction.guildId);
const reason = interaction.options.getString('reason');
const durationMs = minutes * 60_000;
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(durationMs, reason ?? `Mise en sourdine de ${minutes} minutes`);
await logModerationAction(interaction, {
action: 'mute',
targetId: target.id,
reason,
durationMs,
});
await notifyTarget(target, {
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** est en sourdine pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
),
],
});
}
+105
View File
@@ -0,0 +1,105 @@
import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
listNotificationChannels,
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type }));
export const data = new SlashCommandBuilder()
.setName('notify')
.setDescription('Configuration des salons de notification')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Associer un salon à un type de notification')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
)
.addChannelOption((option) =>
option
.setName('channel')
.setDescription('Salon de destination')
.setRequired(true)
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement),
),
)
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Revenir au salon par défaut de la configuration')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle'));
/** Per-guild notification routing stored in SQLite (M9-T01). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'set') {
const type = interaction.options.getString('type', true);
const channel = interaction.options.getChannel('channel', true);
setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id });
await interaction.reply({
embeds: [
successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
if (subcommand === 'remove') {
const type = interaction.options.getString('type', true);
const removed = removeNotificationChannel(interaction.guildId, type);
if (!removed) {
throw new UserFacingError(
`Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`,
);
}
await interaction.reply({
embeds: [
successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const overrides = new Map(
listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]),
);
const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type);
return channelId
? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('🔔 Salons de notification')
.setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`)
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
});
}
+91 -29
View File
@@ -1,29 +1,91 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('role')
.setDescription('Gestion des rôles')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Attribuer ou retirer un rôle')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true))
.addStringOption((option) =>
option
.setName('action')
.setDescription('Action')
.setRequired(true)
.addChoices({ name: 'Ajouter', value: 'add' }, { name: 'Retirer', value: 'remove' }),
),
);
// TODO(M7-T05 / M7-T06): enforce role hierarchy (M3-T05) and log the change.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/role set')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('role')
.setDescription('Gestion des rôles')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Attribuer ou retirer un rôle')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true))
.addStringOption((option) =>
option
.setName('action')
.setDescription('Ajouter ou retirer le rôle')
.setRequired(true)
.addChoices(
{ name: 'Ajouter le rôle', value: 'add' },
{ name: 'Retirer le rôle', value: 'remove' },
),
),
);
/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true);
const action = interaction.options.getString('action', true);
const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError(
'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.',
);
}
if (role.managed) {
throw new UserFacingError(
'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.',
);
}
const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) {
throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`);
}
if (!adding && !hasRole) {
throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`);
}
const isGuildOwner = interaction.guild.ownerId === interaction.user.id;
if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (adding) {
await target.roles.add(role, `Ajouté par ${interaction.user.tag}`);
} else {
await target.roles.remove(role, `Retiré par ${interaction.user.tag}`);
}
await logModerationAction(interaction, {
action: 'role',
targetId: target.id,
reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`,
),
],
});
}
+62
View File
@@ -0,0 +1,62 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
assertModerationTarget,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('unban')
.setDescription('Lever le bannissement d’un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Counterpart of `/ban`, usable whether or not the member already left. */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
// Fetching the ban first turns “not banned” into a clear message instead of
// the missing-ban error Discord returns from the removal itself.
const ban = await interaction.guild.bans.fetch(user.id).catch(() => null);
if (!ban) {
throw new UserFacingError(`${user.tag} n’est pas banni de ce serveur : il n’y a rien à lever.`);
}
// A banned member has usually already left, so the hierarchy is only checked
// while they are still on the server (a ban applied too quickly, typically).
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) assertModerationTarget(interaction, member);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.remove(
user.id,
reason ?? `Débannissement demandé par ${interaction.user.tag}`,
);
await logModerationAction(interaction, { action: 'unban', targetId: user.id, reason });
// A direct message is the only way to tell someone they may come back.
const recipient = member ?? (await interaction.client.users.fetch(user.id).catch(() => null));
if (recipient) {
await notifyTarget(
recipient,
{ embeds: [targetNoticeEmbed({ action: 'unban', guildName: interaction.guild.name, reason })] },
interaction.guildId,
);
}
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${user.tag}** peut de nouveau rejoindre le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+52
View File
@@ -0,0 +1,52 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('unmute')
.setDescription('Lever l’exclusion temporaire d’un membre avant la fin')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Counterpart of `/mute`: clears the timeout early and keeps the trail. */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
// Discord answers a timeout removal on a member who is not muted with an
// opaque error, so the check turns it into an explicit message.
if (!target.isCommunicationDisabled()) {
throw new UserFacingError(
`${target.user.tag} n’est pas en exclusion temporaire : cette personne peut déjà écrire.`,
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(null, reason ?? `Levée d’exclusion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'unmute', targetId: target.id, reason });
await notifyTarget(target, {
embeds: [targetNoticeEmbed({ action: 'unmute', guildName: interaction.guild.name, reason })],
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** peut de nouveau écrire sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+52 -19
View File
@@ -1,19 +1,52 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('warn')
.setDescription('Avertir un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) =>
option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500),
);
// TODO(M8-T01): record in moderation_actions and log (M8-T06).
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/warn')] });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { countActions } from '../../database/repositories/moderation-repository.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('warn')
.setDescription('Avertir un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) =>
option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500),
);
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason', true);
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await notifyTarget(target, {
embeds: [
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
name: 'Avertissements',
value: String(total),
}),
],
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`,
),
],
});
}
+89 -43
View File
@@ -1,43 +1,89 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service.
export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF };
export const data = new SlashCommandBuilder()
.setName('ticket')
.setDescription('Tickets de support privés')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Ouvrir un ticket')
.addStringOption((option) =>
option
.setName('category')
.setDescription('Catégorie du ticket')
.setRequired(true)
.addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500)),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un participant')
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
);
// TODO(M6-T03..T09): implement with a ticket service backed by the tickets table.
export async function execute(interaction) {
await interaction.reply({
embeds: [notImplementedEmbed(`/ticket ${interaction.options.getSubcommand()}`)],
});
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import {
addParticipant,
claimTicket,
closeTicket,
createTicket,
removePanel,
setupPanel,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service.
export const subcommandAccess = {
claim: ACCESS_LEVELS.STAFF,
add: ACCESS_LEVELS.STAFF,
setup: ACCESS_LEVELS.STAFF,
'setup-remove': ACCESS_LEVELS.STAFF,
};
export const data = new SlashCommandBuilder()
.setName('ticket')
.setDescription('Tickets de support privés')
.addSubcommand((sub) =>
sub
.setName('create')
.setDescription('Ouvrir un ticket')
.addStringOption((option) =>
option
.setName('category')
.setDescription('Catégorie du ticket')
.setRequired(true)
.addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)),
)
.addSubcommand((sub) =>
sub.setName('setup').setDescription('Publier le panneau d’ouverture de ticket dans ce salon'),
)
.addSubcommand((sub) => sub.setName('setup-remove').setDescription('Retirer le panneau de ce salon'))
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un participant')
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
);
/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'create': {
const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [
successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
),
],
});
return;
}
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'setup':
await setupPanel(interaction);
return;
case 'setup-remove':
await removePanel(interaction);
return;
case 'claim':
await claimTicket(interaction);
return;
case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id);
return;
default:
return;
}
}
+373
View File
@@ -0,0 +1,373 @@
import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
activeChannelCount,
claimOwnership,
findTrigger,
kickUser,
listTriggerSummaries,
NAME_MAX,
permitUser,
postSetupPanel,
rejectUser,
removeChannel,
removeVoiceTriggerConfig,
renameChannel,
saveVoiceTrigger,
setChannelLimit,
setTriggerEnabled,
showInfo,
toggleLock,
transferOwnership,
} from '../../services/voice/voice-service.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = {
setup: ACCESS_LEVELS.STAFF,
panel: ACCESS_LEVELS.STAFF,
list: ACCESS_LEVELS.STAFF,
remove: ACCESS_LEVELS.STAFF,
enable: ACCESS_LEVELS.STAFF,
disable: ACCESS_LEVELS.STAFF,
};
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
/** Longest embed listing worth sending before it gets unreadable. */
const MAX_LISTED_TRIGGERS = 20;
export const data = new SlashCommandBuilder()
.setName('voice')
.setDescription('Gestion des salons vocaux temporaires')
.addSubcommand((sub) =>
sub
.setName('setup')
.setDescription('Ajouter ou modifier un salon déclencheur')
.addChannelOption((option) =>
voiceChannelOption(
option
.setName('trigger')
.setDescription('Salon vocal à rejoindre pour créer un salon')
.setRequired(true),
),
)
.addStringOption((option) =>
option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40),
)
.addChannelOption((option) =>
option
.setName('category')
.setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)')
.addChannelTypes(ChannelType.GuildCategory),
)
.addStringOption((option) =>
option
.setName('template')
.setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)')
.setMaxLength(NAME_MAX),
)
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Places par défaut (0 = illimité)')
.setMinValue(0)
.setMaxValue(99),
)
.addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'),
),
)
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés'))
.addSubcommand((sub) =>
sub
.setName('panel')
.setDescription('Republier le panneau d’explication dans les salons déclencheurs')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')),
),
)
.addSubcommandGroup((group) =>
group
.setName('triggers')
.setDescription('Gérer les salons déclencheurs')
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs'))
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Supprimer un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('disable')
.setDescription('Désactiver un déclencheur sans le supprimer')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('enable')
.setDescription('Réactiver un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
),
)
.addSubcommand((sub) =>
sub
.setName('name')
.setDescription('Renommer ton salon')
.addStringOption((option) =>
option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX),
),
)
.addSubcommand((sub) =>
sub
.setName('limit')
.setDescription('Limiter le nombre de places (0 = illimité)')
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Nombre de places')
.setRequired(true)
.setMinValue(0)
.setMaxValue(99),
),
)
.addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon'))
.addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon'))
.addSubcommand((sub) =>
sub
.setName('permit')
.setDescription('Autoriser un membre à rejoindre ton salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('reject')
.setDescription('Interdire l’accès à un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('kick')
.setDescription('Exclure un membre du salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('transfer')
.setDescription('Transférer la propriété du salon')
.addUserOption((option) =>
option.setName('user').setDescription('Nouveau propriétaire').setRequired(true),
),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné'))
.addSubcommand((sub) =>
sub
.setName('delete')
.setDescription('Supprimer un salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
)
.addSubcommand((sub) =>
sub
.setName('info')
.setDescription('Détails du salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
);
const ORIGIN_LABELS = {
env: 'variables d’environnement',
settings: 'anciens réglages du bot',
};
/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */
function describeTrigger(trigger, index = null) {
const lines = [
`**Salon :** <#${trigger.triggerId}>`,
`**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`,
`**Modèle :** \`${trigger.template}\``,
`**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`,
`**Salons en cours :** ${trigger.activeChannels ?? 0}`,
];
const origin = ORIGIN_LABELS[trigger.source];
if (origin) lines.push(`**Origine :** ${origin}`);
return {
name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${
trigger.enabled ? '✅ Actif' : '⛔ Désactivé'
}`,
value: lines.join('\n'),
};
}
function configEmbed(guildId) {
const triggers = listTriggerSummaries(guildId);
const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires');
if (triggers.length === 0) {
return embed.setDescription(
'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).',
);
}
embed.setDescription(
`**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` +
'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.',
);
embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i)));
if (triggers.length > MAX_LISTED_TRIGGERS) {
embed.addFields({
name: 'Autres déclencheurs',
value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`,
});
}
return embed;
}
async function runSetup(interaction) {
const channel = interaction.options.getChannel('trigger', true);
if (channel.type !== ChannelType.GuildVoice) {
throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.');
}
const category = interaction.options.getChannel('category');
if (category && category.type !== ChannelType.GuildCategory) {
throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.');
}
const existing = findTrigger(interaction.guildId, channel.id);
const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit');
const label = interaction.options.getString('label');
const trigger = saveVoiceTrigger(
interaction.guildId,
{
triggerId: channel.id,
...(label !== null && { label }),
// A trigger with no explicit category hosts its channels in its own category.
categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null,
...(template !== null && { template }),
...(limit !== null && { userLimit: limit }),
},
interaction.user.id,
);
if (!trigger) {
throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.');
}
const embed = baseEmbed(COLORS.success)
.setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté')
.addFields(describeTrigger(trigger))
.setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {});
}
/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */
async function runTriggerGroup(interaction, subcommand) {
const guildId = interaction.guildId;
if (subcommand === 'list') {
await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral });
return;
}
const target = interaction.options.getChannel('trigger', true);
if (subcommand === 'remove') {
removeVoiceTriggerConfig(guildId, target.id);
await interaction.reply({
embeds: [
successEmbed(
`C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`,
),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable');
await interaction.reply({
embeds: [
successEmbed(
trigger.enabled
? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.`
: `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel');
if (interaction.options.getSubcommandGroup(false) === 'triggers') {
await runTriggerGroup(interaction, subcommand);
return;
}
switch (subcommand) {
case 'setup':
await runSetup(interaction);
return;
case 'panel':
await postSetupPanel(interaction, {
triggerId: interaction.options.getChannel('trigger')?.id ?? null,
});
return;
case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
return;
case 'name':
await renameChannel(interaction, interaction.options.getString('name', true));
return;
case 'limit':
await setChannelLimit(interaction, interaction.options.getInteger('limit', true));
return;
case 'lock':
case 'unlock':
await toggleLock(interaction, { locked: subcommand === 'lock' });
return;
case 'permit':
await permitUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'reject':
await rejectUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'kick':
await kickUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'transfer':
await transferOwnership(interaction, interaction.options.getUser('user', true).id);
return;
case 'claim':
await claimOwnership(interaction);
return;
case 'delete':
await removeChannel(interaction, { channelId: channel?.id ?? null });
return;
case 'info':
await showInfo(interaction, { channelId: channel?.id ?? null });
return;
default:
return;
}
}
+105 -40
View File
@@ -1,40 +1,105 @@
export const BOT_NAME = 'FWS-Bot';
/** Embed colors by category (M12-T01). */
export const COLORS = Object.freeze({
primary: 0x1793d1,
success: 0x2ecc71,
warning: 0xf1c40f,
error: 0xe74c3c,
info: 0x3498db,
gitea: 0x609926,
moderation: 0xe67e22,
ticket: 0x9b59b6,
});
/** Ordered from least to most privileged (M3-T01). */
export const ACCESS_LEVELS = Object.freeze({
USER: 0,
STAFF: 1,
DEV: 2,
OWNER: 3,
});
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Support utilisateur', scope: ['staff', 'owner'] },
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] },
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] },
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] },
{ id: 'internal', label: 'Demande interne', scope: ['owner'] },
]);
export const NOTIFICATION_TYPES = Object.freeze([
'issues',
'pull_requests',
'commits',
'releases',
'announcements',
'errors',
'community',
]);
export const BOT_NAME = 'FWS-Bot';
/** Embed colors by category (M12-T01). */
export const COLORS = Object.freeze({
primary: 0x1793d1,
success: 0x2ecc71,
warning: 0xf1c40f,
error: 0xe74c3c,
info: 0x3498db,
gitea: 0x609926,
moderation: 0xe67e22,
ticket: 0x9b59b6,
});
/** Ordered from least to most privileged (M3-T01). */
export const ACCESS_LEVELS = Object.freeze({
USER: 0,
STAFF: 1,
DEV: 2,
OWNER: 3,
});
/** Same names for the same levels in every message (M12-T02). */
export const ACCESS_LABELS = Object.freeze({
[ACCESS_LEVELS.USER]: 'Membre',
[ACCESS_LEVELS.STAFF]: 'Staff',
[ACCESS_LEVELS.DEV]: 'Dev',
[ACCESS_LEVELS.OWNER]: 'Owner',
});
/**
* Moderation actions: Discord label, embed color and stored duration (M8).
* The emoji belongs to the entry so every surface (log channel, direct message,
* `/mod logs`, dashboard) tells a mute from a kick at a glance: the wording
* alone read like a temporary kick.
*/
export const MODERATION_ACTIONS = Object.freeze({
warn: { label: 'Avertissement', emoji: '⚠️', color: COLORS.warning, duration: false },
mute: { label: 'Mise en sourdine', emoji: '🔇', color: COLORS.moderation, duration: true },
unmute: {
label: 'Levée de la mise en sourdine',
emoji: '🔊',
color: COLORS.success,
duration: false,
},
kick: { label: 'Expulsion', emoji: '👢', color: COLORS.moderation, duration: false },
ban: { label: 'Bannissement', emoji: '🔨', color: COLORS.error, duration: false },
unban: { label: 'Débannissement', emoji: '🔓', color: COLORS.success, duration: false },
clear: { label: 'Supclusion de messages', emoji: '🧹', color: COLORS.warning, duration: false },
role: { label: 'Modification de rôle', emoji: '🏷️', color: COLORS.primary, duration: false },
});
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([
{
id: 'support',
label: 'Aide et support',
description: 'Une question, besoin d’un coup de main',
scope: ['staff', 'owner'],
},
{
id: 'bug',
label: 'Bug',
description: 'Quelque chose ne marche pas comme prévu',
scope: ['staff', 'dev', 'owner'],
},
{
id: 'dev-question',
label: 'Question de développement',
description: 'Conseil, architecture, code',
scope: ['dev', 'owner'],
},
{
id: 'report',
label: 'Signalement',
description: 'Un membre ou un message pose problème',
scope: ['staff', 'owner'],
},
{
id: 'internal',
label: 'Demande interne',
description: 'Réservé à l’équipe',
scope: ['owner'],
},
]);
/** Gitea webhook event -> notification type (M9-T03). */
export const GITEA_EVENT_TYPES = Object.freeze({
issues: 'issues',
pull_request: 'pull_request',
push: 'push',
create: 'push',
delete: 'push',
release: 'release',
});
export const NOTIFICATION_TYPES = Object.freeze([
'issues',
'pull_requests',
'commits',
'releases',
'announcements',
'errors',
'community',
]);
+129 -86
View File
@@ -1,86 +1,129 @@
import { existsSync } from 'node:fs';
if (existsSync('.env')) {
process.loadEnvFile('.env');
}
const read = (key, fallback = '') => process.env[key]?.trim() || fallback;
const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback;
const readBool = (key, fallback = false) => {
const value = read(key);
return value === '' ? fallback : value === 'true';
};
export const env = Object.freeze({
nodeEnv: read('NODE_ENV', 'development'),
logLevel: read('LOG_LEVEL', 'info'),
logDir: read('LOG_DIR', './logs'),
logRetentionDays: readInt('LOG_RETENTION_DAYS', 30),
discord: {
token: read('DISCORD_TOKEN'),
clientId: read('DISCORD_CLIENT_ID'),
guildId: read('DISCORD_GUILD_ID'),
},
roles: {
owner: read('ROLE_OWNER_ID'),
dev: read('ROLE_DEV_ID'),
staff: read('ROLE_STAFF_ID'),
member: read('ROLE_MEMBER_ID'),
},
channels: {
welcome: read('CHANNEL_WELCOME_ID'),
rules: read('CHANNEL_RULES_ID'),
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
logs: read('CHANNEL_LOGS_ID'),
modLogs: read('CHANNEL_MOD_LOGS_ID'),
ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'),
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
ticketCategory: read('CATEGORY_TICKETS_ID'),
},
gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'),
owner: read('GITEA_OWNER'),
repo: read('GITEA_REPO'),
timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000),
maxRetries: readInt('GITEA_MAX_RETRIES', 2),
},
webhook: {
enabled: readBool('WEBHOOK_ENABLED'),
host: read('WEBHOOK_HOST', '0.0.0.0'),
port: readInt('WEBHOOK_PORT', 3000),
path: read('WEBHOOK_PATH', '/webhooks/gitea'),
secret: read('GITEA_WEBHOOK_SECRET'),
},
database: {
path: read('DATABASE_PATH', './data/fws-bot.sqlite'),
backupDir: read('BACKUP_DIR', './data/backups'),
},
links: {
website: read('FWS_WEBSITE_URL'),
docs: read('FWS_DOCS_URL'),
discordInvite: read('FWS_DISCORD_INVITE_URL'),
archRepo: read('FWS_ARCH_REPO_URL'),
},
});
/** Values that must never appear in Discord messages or logs. */
export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean);
export function assertRequiredEnv(keys) {
const missing = keys.filter((key) => !read(key));
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
import { existsSync } from 'node:fs';
if (existsSync('.env')) {
process.loadEnvFile('.env');
}
const read = (key, fallback = '') => process.env[key]?.trim() || fallback;
const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback;
const readBool = (key, fallback = false) => {
const value = read(key);
return value === '' ? fallback : value === 'true';
};
/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */
const readDuration = (key, fallback) => {
const value = read(key);
if (value === '') return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
};
export const env = Object.freeze({
nodeEnv: read('NODE_ENV', 'development'),
logLevel: read('LOG_LEVEL', 'info'),
logDir: read('LOG_DIR', './logs'),
logRetentionDays: readInt('LOG_RETENTION_DAYS', 30),
discord: {
token: read('DISCORD_TOKEN'),
clientId: read('DISCORD_CLIENT_ID'),
guildId: read('DISCORD_GUILD_ID'),
},
roles: {
owner: read('ROLE_OWNER_ID'),
dev: read('ROLE_DEV_ID'),
staff: read('ROLE_STAFF_ID'),
member: read('ROLE_MEMBER_ID'),
},
channels: {
welcome: read('CHANNEL_WELCOME_ID'),
rules: read('CHANNEL_RULES_ID'),
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
logs: read('CHANNEL_LOGS_ID'),
modLogs: read('CHANNEL_MOD_LOGS_ID'),
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
ticketCategory: read('CATEGORY_TICKETS_ID'),
voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'),
voiceCategory: read('CATEGORY_VOICE_ID'),
},
voice: {
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
},
bot: {
statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60),
},
gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'),
owner: read('GITEA_OWNER'),
repo: read('GITEA_REPO'),
timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000),
maxRetries: readInt('GITEA_MAX_RETRIES', 2),
},
webhook: {
enabled: readBool('WEBHOOK_ENABLED'),
host: read('WEBHOOK_HOST', '0.0.0.0'),
port: readInt('WEBHOOK_PORT', 3000),
path: read('WEBHOOK_PATH', '/webhooks/gitea'),
secret: read('GITEA_WEBHOOK_SECRET'),
},
web: {
enabled: readBool('WEB_ENABLED'),
host: read('WEB_HOST', '127.0.0.1'),
port: readInt('WEB_PORT', 3080),
publicUrl: read('WEB_PUBLIC_URL', '').replace(/\/+$/, ''),
sessionSecret: read('WEB_SESSION_SECRET'),
sessionTtlHours: readInt('WEB_SESSION_TTL_HOURS', 12),
oauthClientSecret: read('DISCORD_CLIENT_SECRET'),
setupToken: read('WEB_SETUP_TOKEN'),
// Running shell commands from a browser is the most dangerous capability of the
// dashboard, so it stays off until it is explicitly enabled (M16-T06).
allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
allowRestart: readBool('WEB_ALLOW_RESTART'),
// The public status page is opt-out rather than opt-in: a bot people rely on
// owes them a place to check before asking.
publicStatus: readBool('WEB_PUBLIC_STATUS', true),
deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
},
database: {
path: read('DATABASE_PATH', './data/fws-bot.sqlite'),
backupDir: read('BACKUP_DIR', './data/backups'),
},
links: {
website: read('FWS_WEBSITE_URL'),
docs: read('FWS_DOCS_URL'),
discordInvite: read('FWS_DISCORD_INVITE_URL'),
archRepo: read('FWS_ARCH_REPO_URL'),
},
});
/** Values that must never appear in Discord messages or logs. */
export const secrets = [
env.discord.token,
env.gitea.token,
env.webhook.secret,
env.web.sessionSecret,
env.web.oauthClientSecret,
env.web.setupToken,
].filter(Boolean);
export function assertRequiredEnv(keys) {
const missing = keys.filter((key) => !read(key));
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
+266
View File
@@ -0,0 +1,266 @@
import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js';
import { env } from './env.js';
/**
* Settings a server can change without touching the `.env` (M16-T13).
*
* Single source of truth: the form, the validation and the values the services
* read all come from here. A setting that is not read by anything has no
* business being in this list — a switch that does nothing is worse than no
* switch at all.
*/
export const SETTING_SECTIONS = Object.freeze([
{
id: 'welcome',
title: 'Arrivées et départs',
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
},
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
{
id: 'rules',
title: 'Règlement',
summary: 'Message affiché et épinglé dans le salon des règles.',
},
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{
id: 'voice',
title: 'Salons vocaux',
summary: 'Salons temporaires créés par les déclencheurs.',
},
{ id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' },
{ id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' },
]);
export const GUILD_SETTINGS = Object.freeze([
// --- Arrivées et départs ---------------------------------------------------
{
key: 'welcome.enabled',
section: 'welcome',
label: 'Message de bienvenue',
help: 'Publier un message dans le salon d’accueil à chaque arrivée.',
type: 'bool',
default: true,
},
{
key: 'welcome.message',
section: 'welcome',
label: 'Texte de bienvenue',
help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.',
type: 'text',
default: 'Bienvenue sur le serveur **{server}** !',
maxLength: 500,
},
{
key: 'welcome.showRules',
section: 'welcome',
label: 'Rappeler le règlement',
help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.',
type: 'bool',
default: true,
},
{
key: 'welcome.directMessage',
section: 'welcome',
label: 'Message privé de bienvenue',
help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.',
type: 'bool',
default: false,
},
{
key: 'members.autoRole',
section: 'welcome',
label: 'Attribuer le rôle d’arrivée',
help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.',
type: 'bool',
default: true,
},
{
key: 'departure.announce',
section: 'welcome',
label: 'Annoncer les départs',
help: 'Publie une ligne dans les logs quand un membre quitte le serveur.',
type: 'bool',
default: true,
},
// --- Modération ------------------------------------------------------------
{
key: 'moderation.dmTarget',
section: 'moderation',
label: 'Prévenir le membre sanctionné',
help: 'Envoie un message privé expliquant la sanction et son motif.',
type: 'bool',
default: true,
},
{
key: 'moderation.defaultMuteMinutes',
section: 'moderation',
label: 'Durée de mise en sourdine par défaut (min)',
help: 'Proposée quand `/mute` est lancé sans durée.',
type: 'int',
default: 60,
min: 1,
max: 40_320,
},
{
key: 'moderation.banDeleteMessageHours',
section: 'moderation',
label: 'Messages supprimés au bannissement (h)',
help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.',
type: 'int',
default: 0,
min: 0,
max: 168,
advanced: true,
},
// --- Règlement ---------------------------------------------------------------
{
key: 'rules.markdown',
section: 'rules',
label: 'Règlement (markdown)',
help: 'Enregistré et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Enregistrer modifie le message déjà publié.',
type: 'markdown',
default: '',
maxLength: 4000,
},
// --- Tickets ---------------------------------------------------------------
{
key: 'tickets.deleteChannelOnClose',
section: 'tickets',
label: 'Supprimer le salon à la clôture',
help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.',
type: 'bool',
default: true,
},
// --- Salons vocaux ---------------------------------------------------------
{
key: 'voice.adoptOrphans',
section: 'voice',
label: 'Récupérer les salons orphelins',
help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.',
type: 'bool',
default: true,
},
// --- Notifications ---------------------------------------------------------
{
key: 'notifications.mentionRoleId',
section: 'notifications',
label: 'Rôle à mentionner',
help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.',
type: 'snowflake',
default: '',
advanced: true,
},
// --- Tableau de bord -------------------------------------------------------
{
key: 'deploy.requireConfirmation',
section: 'interface',
label: 'Confirmation avant déploiement',
help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.',
type: 'bool',
default: true,
},
{
key: 'web.defaultMode',
section: 'interface',
label: 'Mode d’affichage par défaut',
help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.',
type: 'enum',
options: ['simple', 'advanced'],
default: 'simple',
},
]);
export const SETTING_BY_KEY = Object.freeze(
Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])),
);
/** Coerces a stored value to the declared type, falling back on the default. */
function coerce(setting, value) {
if (value === null || value === undefined) return setting.default;
switch (setting.type) {
case 'bool':
return Boolean(value);
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return setting.default;
if (setting.min !== undefined && parsed < setting.min) return setting.min;
if (setting.max !== undefined && parsed > setting.max) return setting.max;
return parsed;
}
case 'enum':
return setting.options.includes(value) ? value : setting.default;
default:
return String(value);
}
}
/**
* Reads a setting. Never throws: called from event handlers that must keep
* working even when the database is momentarily unavailable.
*/
export function readSetting(key, guildId = env.discord.guildId) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
return coerce(setting, resolveSetting(guildId, key, setting.default));
}
/** Validates then stores a setting. Returns the stored value. */
export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
const message = validateSetting(key, value);
if (message) throw new Error(message);
const stored = coerce(setting, value);
setSetting(guildId, key, stored, updatedBy);
return stored;
}
/** Returns null when the value is acceptable, a French message otherwise. */
export function validateSetting(key, value) {
const setting = SETTING_BY_KEY[key];
if (!setting) return `Réglage inconnu : ${key}`;
switch (setting.type) {
case 'bool':
return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.';
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.';
if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`;
if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`;
return null;
}
case 'enum':
return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`;
case 'snowflake': {
const text = String(value ?? '').trim();
return text === '' || /^\d{17,20}$/.test(text)
? null
: 'Un identifiant Discord est composé de 17 à 20 chiffres.';
}
default: {
const text = String(value ?? '');
if (setting.maxLength && text.length > setting.maxLength) {
return `${setting.maxLength} caractères maximum.`;
}
return null;
}
}
}
/** Every setting with its current value, for the settings page. */
export function allSettings(guildId = env.discord.guildId) {
return Object.fromEntries(
GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]),
);
}
+26 -24
View File
@@ -1,24 +1,26 @@
import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js';
/**
* Only the intents required by the bot (M2-T02):
* - Guilds: slash commands, channels, roles
* - GuildMembers (privileged): welcome, departures, role assignment
* - GuildModeration: ban/kick audit events
* - GuildMessages: /clear and ticket channels
* MessageContent is intentionally not requested.
*/
export function createClient() {
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages,
],
partials: [Partials.GuildMember],
});
client.commands = new Collection();
return client;
}
import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js';
/**
* Only the intents required by the bot (M2-T02):
* - Guilds: slash commands, channels, roles
* - GuildMembers (privileged): welcome, departures, role assignment
* - GuildModeration: ban/kick audit events
* - GuildMessages: /clear and ticket channels
* - GuildVoiceStates: temporary voice channels (M14)
* MessageContent is intentionally not requested.
*/
export function createClient() {
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates,
],
partials: [Partials.GuildMember],
});
client.commands = new Collection();
return client;
}
+28 -28
View File
@@ -1,28 +1,28 @@
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands');
/**
* Loads every command module from src/commands/<category>/<name>.js.
* A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`.
*/
export async function loadCommands() {
const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true });
const commands = [];
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith('.js')) continue;
const filePath = path.join(entry.parentPath, entry.name);
const command = await import(pathToFileURL(filePath).href);
if (!command.data || typeof command.execute !== 'function') {
throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`);
}
commands.push(command);
}
return commands;
}
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands');
/**
* Loads every command module from src/commands/<category>/<name>.js.
* A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`.
*/
export async function loadCommands() {
const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true });
const commands = [];
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith('.js')) continue;
const filePath = path.join(entry.parentPath, entry.name);
const command = await import(pathToFileURL(filePath).href);
if (!command.data || typeof command.execute !== 'function') {
throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`);
}
commands.push(command);
}
return commands;
}
+24 -22
View File
@@ -1,22 +1,24 @@
/** Error whose message is safe to show to Discord users. */
export class UserFacingError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'UserFacingError';
}
}
export class PermissionDeniedError extends UserFacingError {
constructor(message = "Tu n'as pas la permission d'utiliser cette commande.") {
super(message);
this.name = 'PermissionDeniedError';
}
}
export class ExternalApiError extends Error {
constructor(service, message, options) {
super(`[${service}] ${message}`, options);
this.name = 'ExternalApiError';
this.service = service;
}
}
/** Error whose message is safe to show to Discord users. */
export class UserFacingError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'UserFacingError';
}
}
export class PermissionDeniedError extends UserFacingError {
constructor(
message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.',
) {
super(message);
this.name = 'PermissionDeniedError';
}
}
export class ExternalApiError extends Error {
constructor(service, message, options) {
super(`[${service}] ${message}`, options);
this.name = 'ExternalApiError';
this.service = service;
}
}
+29 -29
View File
@@ -1,29 +1,29 @@
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createLogger } from './logger.js';
const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events');
const log = createLogger('events');
/**
* Registers every event module from src/events.
* An event module exports: `name`, optional `once` and `execute(client, ...args)`.
*/
export async function registerEvents(client) {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
for (const file of files) {
const event = await import(pathToFileURL(path.join(eventsDir, file)).href);
const handler = async (...args) => {
try {
await event.execute(client, ...args);
} catch (error) {
log.error(`Event handler failed: ${event.name}`, error);
}
};
client[event.once ? 'once' : 'on'](event.name, handler);
log.debug(`Registered event ${event.name}`);
}
}
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createLogger } from './logger.js';
const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events');
const log = createLogger('events');
/**
* Registers every event module from src/events.
* An event module exports: `name`, optional `once` and `execute(client, ...args)`.
*/
export async function registerEvents(client) {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
for (const file of files) {
const event = await import(pathToFileURL(path.join(eventsDir, file)).href);
const handler = async (...args) => {
try {
await event.execute(client, ...args);
} catch (error) {
log.error(`Event handler failed: ${event.name}`, error);
}
};
client[event.once ? 'once' : 'on'](event.name, handler);
log.debug(`Registered event ${event.name}`);
}
}
+50 -50
View File
@@ -1,50 +1,50 @@
import { appendFileSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { env, secrets } from '../config/env.js';
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
const threshold = LEVELS[env.logLevel] ?? LEVELS.info;
mkdirSync(env.logDir, { recursive: true });
export function maskSecrets(text) {
return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text));
}
function serialize(meta) {
if (meta instanceof Error) {
return { name: meta.name, message: meta.message, stack: meta.stack };
}
return meta;
}
function write(level, scope, message, meta) {
if (LEVELS[level] < threshold) return;
const entry = {
time: new Date().toISOString(),
level,
scope,
message,
...(meta !== undefined && { meta: serialize(meta) }),
};
const line = maskSecrets(JSON.stringify(entry));
const output = level === 'error' || level === 'warn' ? console.error : console.log;
output(line);
// Technical logs are split per day to simplify retention (M11-T08).
const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`);
appendFileSync(file, `${line}\n`);
}
export function createLogger(scope) {
return {
debug: (message, meta) => write('debug', scope, message, meta),
info: (message, meta) => write('info', scope, message, meta),
warn: (message, meta) => write('warn', scope, message, meta),
error: (message, meta) => write('error', scope, message, meta),
};
}
export const logger = createLogger('app');
import { appendFileSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { env, secrets } from '../config/env.js';
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
const threshold = LEVELS[env.logLevel] ?? LEVELS.info;
mkdirSync(env.logDir, { recursive: true });
export function maskSecrets(text) {
return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text));
}
function serialize(meta) {
if (meta instanceof Error) {
return { name: meta.name, message: meta.message, stack: meta.stack };
}
return meta;
}
function write(level, scope, message, meta) {
if (LEVELS[level] < threshold) return;
const entry = {
time: new Date().toISOString(),
level,
scope,
message,
...(meta !== undefined && { meta: serialize(meta) }),
};
const line = maskSecrets(JSON.stringify(entry));
const output = level === 'error' || level === 'warn' ? console.error : console.log;
output(line);
// Technical logs are split per day to simplify retention (M11-T08).
const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`);
appendFileSync(file, `${line}\n`);
}
export function createLogger(scope) {
return {
debug: (message, meta) => write('debug', scope, message, meta),
info: (message, meta) => write('info', scope, message, meta),
warn: (message, meta) => write('warn', scope, message, meta),
error: (message, meta) => write('error', scope, message, meta),
};
}
export const logger = createLogger('app');
+33 -33
View File
@@ -1,33 +1,33 @@
import { ACCESS_LEVELS } from '../config/constants.js';
import { env } from '../config/env.js';
/**
* Resolves the highest FWS access level of a guild member (M3-T02).
* @param {import('discord.js').GuildMember} member
*/
export function getAccessLevel(member, roles = env.roles) {
if (!member) return ACCESS_LEVELS.USER;
if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER;
const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId);
if (has(roles.owner)) return ACCESS_LEVELS.OWNER;
if (has(roles.dev)) return ACCESS_LEVELS.DEV;
if (has(roles.staff)) return ACCESS_LEVELS.STAFF;
return ACCESS_LEVELS.USER;
}
export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) {
return getAccessLevel(member, roles) >= requiredLevel;
}
/**
* Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08).
* @param {import('discord.js').GuildMember} actor
* @param {import('discord.js').GuildMember} target
*/
export function canActOn(actor, target) {
if (!actor || !target || actor.id === target.id) return false;
if (target.guild.ownerId === target.id) return false;
if (actor.guild.ownerId === actor.id) return true;
return actor.roles.highest.comparePositionTo(target.roles.highest) > 0;
}
import { ACCESS_LEVELS } from '../config/constants.js';
import { env } from '../config/env.js';
/**
* Resolves the highest FWS access level of a guild member (M3-T02).
* @param {import('discord.js').GuildMember} member
*/
export function getAccessLevel(member, roles = env.roles) {
if (!member) return ACCESS_LEVELS.USER;
if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER;
const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId);
if (has(roles.owner)) return ACCESS_LEVELS.OWNER;
if (has(roles.dev)) return ACCESS_LEVELS.DEV;
if (has(roles.staff)) return ACCESS_LEVELS.STAFF;
return ACCESS_LEVELS.USER;
}
export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) {
return getAccessLevel(member, roles) >= requiredLevel;
}
/**
* Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08).
* @param {import('discord.js').GuildMember} actor
* @param {import('discord.js').GuildMember} target
*/
export function canActOn(actor, target) {
if (!actor || !target || actor.id === target.id) return false;
if (target.guild.ownerId === target.id) return false;
if (actor.guild.ownerId === actor.id) return true;
return actor.roles.highest.comparePositionTo(target.roles.highest) > 0;
}
+63 -63
View File
@@ -1,63 +1,63 @@
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath } from 'node:url';
import { env } from '../config/env.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('database');
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
let db;
function runMigrations(database) {
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);
const applied = new Set(
database
.prepare('SELECT name FROM schema_migrations')
.all()
.map((row) => row.name),
);
const pending = readdirSync(migrationsDir)
.filter((file) => file.endsWith('.sql') && !applied.has(file))
.sort();
for (const file of pending) {
database.exec('BEGIN');
try {
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
database.exec('COMMIT');
log.info(`Applied migration ${file}`);
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
}
}
export function initDatabase(filePath = env.database.path) {
if (db) return db;
if (filePath !== ':memory:') {
mkdirSync(path.dirname(filePath), { recursive: true });
}
db = new DatabaseSync(filePath);
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
runMigrations(db);
return db;
}
export function getDatabase() {
if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
return db;
}
export function closeDatabase() {
db?.close();
db = undefined;
}
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath } from 'node:url';
import { env } from '../config/env.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('database');
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
let db;
function runMigrations(database) {
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);
const applied = new Set(
database
.prepare('SELECT name FROM schema_migrations')
.all()
.map((row) => row.name),
);
const pending = readdirSync(migrationsDir)
.filter((file) => file.endsWith('.sql') && !applied.has(file))
.sort();
for (const file of pending) {
database.exec('BEGIN');
try {
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
database.exec('COMMIT');
log.info(`Applied migration ${file}`);
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
}
}
export function initDatabase(filePath = env.database.path) {
if (db) return db;
if (filePath !== ':memory:') {
mkdirSync(path.dirname(filePath), { recursive: true });
}
db = new DatabaseSync(filePath);
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
runMigrations(db);
return db;
}
export function getDatabase() {
if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
return db;
}
export function closeDatabase() {
db?.close();
db = undefined;
}
+97 -97
View File
@@ -1,97 +1,97 @@
-- Server settings, isolated per guild (M3-T06)
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT,
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (guild_id, key)
);
-- Notification type -> channel mapping (M9-T01)
CREATE TABLE IF NOT EXISTS notification_channels (
guild_id TEXT NOT NULL,
type TEXT NOT NULL,
channel_id TEXT NOT NULL,
detail_level TEXT NOT NULL DEFAULT 'normal',
PRIMARY KEY (guild_id, type)
);
-- Ticket categories (M6-T01) and tickets (M6)
CREATE TABLE IF NOT EXISTS ticket_categories (
guild_id TEXT NOT NULL,
id TEXT NOT NULL,
label TEXT NOT NULL,
description TEXT,
scope TEXT NOT NULL,
PRIMARY KEY (guild_id, id)
);
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
channel_id TEXT UNIQUE,
category_id TEXT NOT NULL,
author_id TEXT NOT NULL,
claimed_by TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
closed_at TEXT,
closed_by TEXT
);
-- Prevents duplicate open tickets per author and category (M6-T08)
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
-- Moderation actions (M8)
CREATE TABLE IF NOT EXISTS moderation_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
target_id TEXT,
moderator_id TEXT NOT NULL,
reason TEXT,
duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
-- Polls (M10)
CREATE TABLE IF NOT EXISTS polls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
message_id TEXT UNIQUE,
creator_id TEXT NOT NULL,
question TEXT NOT NULL,
choices TEXT NOT NULL,
ends_at TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS poll_votes (
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
user_id TEXT NOT NULL,
choice_index INTEGER NOT NULL,
voted_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (poll_id, user_id)
);
-- Functional event log (M11-T05)
CREATE TABLE IF NOT EXISTS event_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT,
type TEXT NOT NULL,
actor_id TEXT,
payload TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
CREATE TABLE IF NOT EXISTS webhook_deliveries (
delivery_id TEXT PRIMARY KEY,
event TEXT NOT NULL,
received_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- Server settings, isolated per guild (M3-T06)
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT,
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (guild_id, key)
);
-- Notification type -> channel mapping (M9-T01)
CREATE TABLE IF NOT EXISTS notification_channels (
guild_id TEXT NOT NULL,
type TEXT NOT NULL,
channel_id TEXT NOT NULL,
detail_level TEXT NOT NULL DEFAULT 'normal',
PRIMARY KEY (guild_id, type)
);
-- Ticket categories (M6-T01) and tickets (M6)
CREATE TABLE IF NOT EXISTS ticket_categories (
guild_id TEXT NOT NULL,
id TEXT NOT NULL,
label TEXT NOT NULL,
description TEXT,
scope TEXT NOT NULL,
PRIMARY KEY (guild_id, id)
);
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
channel_id TEXT UNIQUE,
category_id TEXT NOT NULL,
author_id TEXT NOT NULL,
claimed_by TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
closed_at TEXT,
closed_by TEXT
);
-- Prevents duplicate open tickets per author and category (M6-T08)
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
-- Moderation actions (M8)
CREATE TABLE IF NOT EXISTS moderation_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
target_id TEXT,
moderator_id TEXT NOT NULL,
reason TEXT,
duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
-- Polls (M10)
CREATE TABLE IF NOT EXISTS polls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
message_id TEXT UNIQUE,
creator_id TEXT NOT NULL,
question TEXT NOT NULL,
choices TEXT NOT NULL,
ends_at TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS poll_votes (
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
user_id TEXT NOT NULL,
choice_index INTEGER NOT NULL,
voted_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (poll_id, user_id)
);
-- Functional event log (M11-T05)
CREATE TABLE IF NOT EXISTS event_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT,
type TEXT NOT NULL,
actor_id TEXT,
payload TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
CREATE TABLE IF NOT EXISTS webhook_deliveries (
delivery_id TEXT PRIMARY KEY,
event TEXT NOT NULL,
received_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@@ -0,0 +1,7 @@
-- Claim and close details of a ticket (M6-T05 / M6-T06)
ALTER TABLE tickets ADD COLUMN claimed_at TEXT;
ALTER TABLE tickets ADD COLUMN close_reason TEXT;
-- Faster lookups for the poll scheduler and the result rendering (M10)
CREATE INDEX IF NOT EXISTS idx_polls_due ON polls (status, ends_at);
CREATE INDEX IF NOT EXISTS idx_poll_votes_choice ON poll_votes (poll_id, choice_index);
@@ -0,0 +1,14 @@
-- Temporary voice channels created by joining the trigger channel (M14)
CREATE TABLE IF NOT EXISTS voice_channels (
channel_id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
owner_id TEXT NOT NULL,
trigger_id TEXT,
name TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
user_limit INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_voice_channels_guild ON voice_channels (guild_id);
CREATE INDEX IF NOT EXISTS idx_voice_channels_owner ON voice_channels (guild_id, owner_id);
@@ -0,0 +1,14 @@
-- Several "join to create" triggers per guild, each with its own home category (M14)
CREATE TABLE IF NOT EXISTS voice_triggers (
trigger_id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
label TEXT,
category_id TEXT,
template TEXT,
user_limit INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id);
@@ -0,0 +1,14 @@
-- Rotating presence of the bot, editable from Discord (M15)
-- The presence is global to the bot, so these rows are not tied to a guild.
CREATE TABLE IF NOT EXISTS bot_statuses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'watching',
url TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_bot_statuses_text ON bot_statuses (text);
CREATE INDEX IF NOT EXISTS idx_bot_statuses_enabled ON bot_statuses (enabled, id);
@@ -0,0 +1,80 @@
-- Web dashboard: sessions, machine tokens, deploy targets and deployments (M16)
-- Browser sessions created by the Discord OAuth2 login (M16-T02).
-- Only the hash of the cookie value is stored, so a database dump cannot be replayed.
CREATE TABLE IF NOT EXISTS web_sessions (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
user_id TEXT,
username TEXT,
display_name TEXT,
avatar TEXT,
access_level INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'discord' CHECK (source IN ('discord', 'setup', 'token')),
ip TEXT,
user_agent TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_seen_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at);
CREATE INDEX IF NOT EXISTS idx_web_sessions_user ON web_sessions (user_id);
-- Long lived tokens for scripts and CI calling the dashboard API (M16-T03).
CREATE TABLE IF NOT EXISTS web_api_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
prefix TEXT NOT NULL,
access_level INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_used_at TEXT,
expires_at TEXT,
revoked_at TEXT
);
-- Where a release can be deployed: a signed webhook, a local command or a Gitea Action (M16-T06).
CREATE TABLE IF NOT EXISTS deploy_targets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
name TEXT NOT NULL,
repository TEXT NOT NULL,
environment TEXT NOT NULL DEFAULT 'production',
kind TEXT NOT NULL CHECK (kind IN ('webhook', 'command', 'gitea-action')),
config TEXT NOT NULL DEFAULT '{}',
auto_deploy INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_deploy_targets_name ON deploy_targets (guild_id, name);
CREATE INDEX IF NOT EXISTS idx_deploy_targets_repo ON deploy_targets (guild_id, repository);
-- One row per deployment attempt. `target_name` is denormalised so the history
-- survives the deletion of its target (M16-T07).
CREATE TABLE IF NOT EXISTS deployments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
target_id INTEGER REFERENCES deploy_targets (id) ON DELETE SET NULL,
target_name TEXT NOT NULL,
repository TEXT NOT NULL,
environment TEXT NOT NULL,
ref TEXT,
release_tag TEXT,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'running', 'success', 'failed', 'cancelled')),
source TEXT NOT NULL DEFAULT 'web',
triggered_by TEXT,
log TEXT,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
started_at TEXT,
finished_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_deployments_target ON deployments (guild_id, target_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments (status, id DESC);
+21
View File
@@ -0,0 +1,21 @@
-- Public wiki pages, written from the dashboard and served without a session (M17)
CREATE TABLE IF NOT EXISTS wiki_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
summary TEXT,
content TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'Général',
position INTEGER NOT NULL DEFAULT 0,
published INTEGER NOT NULL DEFAULT 0,
-- A legal page is protected from deletion: the bot must always be able to
-- point at its terms and its privacy notice.
protected INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_wiki_published ON wiki_pages (published, category, position);
+57
View File
@@ -0,0 +1,57 @@
-- Kanban boards: one per repository, plus one for the organization (M18)
CREATE TABLE IF NOT EXISTS project_boards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
-- 'org' has no repository; 'repo' carries `owner/name`.
scope TEXT NOT NULL CHECK (scope IN ('org', 'repo')),
repository TEXT,
name TEXT NOT NULL,
description TEXT,
archived INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- One board per repository, and a single organization board per guild.
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_repository
ON project_boards (guild_id, repository) WHERE repository IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_org
ON project_boards (guild_id) WHERE scope = 'org';
CREATE TABLE IF NOT EXISTS project_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
name TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
-- 0 means no limit; above it the column is flagged as overloaded.
wip_limit INTEGER NOT NULL DEFAULT 0,
-- Cards dropped here are considered finished, which drives the board counters.
is_done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_columns_board ON project_columns (board_id, position);
CREATE TABLE IF NOT EXISTS project_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
column_id INTEGER NOT NULL REFERENCES project_columns (id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT,
position INTEGER NOT NULL DEFAULT 0,
-- Discord id of whoever carries the card.
assignee_id TEXT,
-- `owner/repo#12`, resolved against Gitea when the forge answers.
issue_ref TEXT,
labels TEXT NOT NULL DEFAULT '[]',
due_at TEXT,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_cards_column ON project_cards (column_id, position);
CREATE INDEX IF NOT EXISTS idx_cards_board ON project_cards (board_id);
CREATE INDEX IF NOT EXISTS idx_cards_assignee ON project_cards (board_id, assignee_id);
@@ -0,0 +1,9 @@
-- The legal pages move to the addresses platforms expect (M17)
--
-- Discord, and most app stores, ask for a terms URL and a privacy URL. Serving
-- them under `/wiki/` works but reads badly in a form field, so they move to
-- the root. Renaming rather than recreating keeps whatever the organization
-- has already written in them.
UPDATE wiki_pages SET slug = 'terms-of-service' WHERE slug = 'conditions-utilisation';
UPDATE wiki_pages SET slug = 'privacy-policy' WHERE slug = 'politique-confidentialite';
@@ -0,0 +1,23 @@
-- Lifted sanctions join the sanctions in the moderation history
--
-- `/unmute` and `/unban` are recorded like `/mute` and `/ban`, but SQLite cannot
-- alter a CHECK constraint: the table is rebuilt and the rows copied over so the
-- history already stored survives the migration.
CREATE TABLE moderation_actions_lifted (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'unmute', 'kick', 'ban', 'unban', 'clear', 'role')),
target_id TEXT,
moderator_id TEXT NOT NULL,
reason TEXT,
duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
INSERT INTO moderation_actions_lifted (id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at)
SELECT id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at FROM moderation_actions;
DROP TABLE moderation_actions;
ALTER TABLE moderation_actions_lifted RENAME TO moderation_actions;
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
@@ -0,0 +1,13 @@
-- The rules message published from the dashboard (M19)
--
-- The bot republishes the rules by deleting the previous message and sending
-- the new one, so it has to remember which message it owns. Without this the
-- channel would slowly fill with outdated copies.
CREATE TABLE IF NOT EXISTS rules_messages (
guild_id TEXT PRIMARY KEY,
channel_id TEXT NOT NULL,
message_id TEXT NOT NULL,
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@@ -0,0 +1,13 @@
-- The ticket panel published by `/ticket setup`
--
-- The panel is a button that opens a ticket, and it has to survive a restart:
-- the channel alone is not enough, because reinstalling must replace the previous
-- message instead of leaving an outdated copy in the salon.
CREATE TABLE IF NOT EXISTS ticket_panels (
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
message_id TEXT NOT NULL,
created_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (guild_id, channel_id)
);
@@ -0,0 +1,42 @@
import { getDatabase } from '../index.js';
/** Adds a status and returns the stored row, so the command can show its id. */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
const result = getDatabase()
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
.run(text, type, url, createdBy);
return getBotStatus(Number(result.lastInsertRowid));
}
export function getBotStatus(id) {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
}
/** Every status, disabled ones included, in the order they were added. */
export function listBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
}
/** The statuses the rotation is allowed to show. */
export function listEnabledBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
}
export function setBotStatusEnabled(id, enabled) {
return getDatabase()
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
.run(enabled ? 1 : 0, id).changes;
}
export function removeBotStatus(id) {
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
}
export function clearBotStatuses() {
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
}
export function countBotStatuses() {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
return row.count;
}
@@ -0,0 +1,176 @@
import { getDatabase } from '../index.js';
/** Deploy targets and deployment history of the release pipeline (M16-T06 / M16-T07). */
const parseTarget = (row) =>
row
? {
...row,
config: JSON.parse(row.config),
auto_deploy: Boolean(row.auto_deploy),
enabled: Boolean(row.enabled),
}
: null;
export function createTarget({
guildId,
name,
repository,
environment = 'production',
kind,
config = {},
autoDeploy = false,
enabled = true,
createdBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO deploy_targets
(guild_id, name, repository, environment, kind, config, auto_deploy, enabled, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
guildId,
name,
repository,
environment,
kind,
JSON.stringify(config),
autoDeploy ? 1 : 0,
enabled ? 1 : 0,
createdBy,
);
return getTarget(Number(lastInsertRowid));
}
export function getTarget(id) {
return parseTarget(getDatabase().prepare('SELECT * FROM deploy_targets WHERE id = ?').get(id) ?? null);
}
export function listTargets({ guildId, repository = null } = {}) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (repository) {
clauses.push('repository = ?');
params.push(repository);
}
return getDatabase()
.prepare(`SELECT * FROM deploy_targets WHERE ${clauses.join(' AND ')} ORDER BY environment, name`)
.all(...params)
.map(parseTarget);
}
/** Targets eligible for an automatic deployment when a release is published (M16-T08). */
export function listAutoTargets({ guildId, repository }) {
return getDatabase()
.prepare(
`SELECT * FROM deploy_targets
WHERE guild_id = ? AND repository = ? AND auto_deploy = 1 AND enabled = 1
ORDER BY environment, name`,
)
.all(guildId, repository)
.map(parseTarget);
}
const UPDATABLE = Object.freeze({
name: (value) => value,
repository: (value) => value,
environment: (value) => value,
kind: (value) => value,
config: (value) => JSON.stringify(value),
auto_deploy: (value) => (value ? 1 : 0),
enabled: (value) => (value ? 1 : 0),
});
export function updateTarget(id, patch) {
const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE);
if (entries.length === 0) return getTarget(id);
const assignments = entries.map(([key]) => `${key} = ?`).join(', ');
const values = entries.map(([key, value]) => UPDATABLE[key](value));
getDatabase()
.prepare(`UPDATE deploy_targets SET ${assignments}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getTarget(id);
}
export function removeTarget(id) {
return getDatabase().prepare('DELETE FROM deploy_targets WHERE id = ?').run(id).changes;
}
export function createDeployment({
guildId,
targetId = null,
targetName,
repository,
environment,
ref = null,
releaseTag = null,
source = 'web',
triggeredBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO deployments
(guild_id, target_id, target_name, repository, environment, ref, release_tag, source, triggered_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(guildId, targetId, targetName, repository, environment, ref, releaseTag, source, triggeredBy);
return getDeployment(Number(lastInsertRowid));
}
export function getDeployment(id) {
return getDatabase().prepare('SELECT * FROM deployments WHERE id = ?').get(id) ?? null;
}
export function listDeployments({ guildId, targetId = null, repository = null, status = null, limit = 30 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (targetId) {
clauses.push('target_id = ?');
params.push(targetId);
}
if (repository) {
clauses.push('repository = ?');
params.push(repository);
}
if (status) {
clauses.push('status = ?');
params.push(status);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM deployments WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function markRunning(id) {
return getDatabase()
.prepare("UPDATE deployments SET status = 'running', started_at = datetime('now') WHERE id = ?")
.run(id).changes;
}
export function finishDeployment(id, { status, log = null, error = null }) {
return getDatabase()
.prepare(
`UPDATE deployments SET status = ?, log = ?, error = ?, finished_at = datetime('now') WHERE id = ?`,
)
.run(status, log, error, id).changes;
}
/** Counts per status, used by the dashboard tiles. */
export function countByStatus(guildId) {
return getDatabase()
.prepare('SELECT status, COUNT(*) AS count FROM deployments WHERE guild_id = ? GROUP BY status')
.all(guildId);
}
export function lastDeploymentPerEnvironment(guildId) {
return getDatabase()
.prepare(
`SELECT environment, repository, status, release_tag, finished_at, MAX(id) AS id
FROM deployments WHERE guild_id = ? GROUP BY environment, repository ORDER BY environment`,
)
.all(guildId);
}
@@ -1,13 +1,13 @@
import { getDatabase } from '../index.js';
export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
getDatabase()
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
}
export function purgeEventsOlderThan(days) {
return getDatabase()
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
.run(`-${days} days`).changes;
}
import { getDatabase } from '../index.js';
export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
getDatabase()
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
}
export function purgeEventsOlderThan(days) {
return getDatabase()
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
.run(`-${days} days`).changes;
}
@@ -0,0 +1,50 @@
import { getDatabase } from '../index.js';
export function recordAction({
guildId,
action,
moderatorId,
targetId = null,
reason = null,
durationMs = null,
}) {
getDatabase()
.prepare(
`INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, action, targetId, moderatorId, reason, durationMs);
}
export function listActions({ guildId, targetId = null, action = null, limit = 20 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (targetId) {
clauses.push('target_id = ?');
params.push(targetId);
}
if (action) {
clauses.push('action = ?');
params.push(action);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function countActions({ guildId, targetId, action }) {
const row = getDatabase()
.prepare(
'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?',
)
.get(guildId, targetId, action);
return row.count;
}
export function countByAction(guildId) {
return getDatabase()
.prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action')
.all(guildId);
}
@@ -0,0 +1,34 @@
import { getDatabase } from '../index.js';
/** Per-guild override of a notification channel (M9-T01). */
export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) {
getDatabase()
.prepare(
`INSERT INTO notification_channels (guild_id, type, channel_id, detail_level)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, type) DO UPDATE SET
channel_id = excluded.channel_id,
detail_level = excluded.detail_level`,
)
.run(guildId, type, channelId, detailLevel);
}
export function getNotificationChannel(guildId, type) {
return (
getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?')
.get(guildId, type) ?? null
);
}
export function listNotificationChannels(guildId) {
return getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type')
.all(guildId);
}
export function removeNotificationChannel(guildId, type) {
return getDatabase()
.prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?')
.run(guildId, type).changes;
}
@@ -0,0 +1,97 @@
import { getDatabase } from '../index.js';
export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt);
return Number(lastInsertRowid);
}
export function attachPollMessage(id, messageId) {
getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id);
}
export function getPoll(id) {
return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null;
}
export function getPollByMessage(messageId) {
return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null;
}
export function listPolls({ guildId, status = null, limit = 10 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (status) {
clauses.push('status = ?');
params.push(status);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
/** Polls whose end date is reached and that are still open (M10-T05). */
export function listDuePolls(limit = 10) {
return getDatabase()
.prepare(
`SELECT * FROM polls
WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now')
ORDER BY ends_at ASC LIMIT ?`,
)
.all(limit);
}
export function listOpenPolls(limit = 25) {
return getDatabase()
.prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?")
.all(limit);
}
export function listVotes(pollId) {
return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId);
}
/** Counts votes per choice index: `[{ choice_index, count }]`. */
export function countVotes(pollId) {
return getDatabase()
.prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index')
.all(pollId);
}
/**
* Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04).
*/
export function castVote(pollId, userId, choiceIndex) {
const database = getDatabase();
const previous = database
.prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?')
.get(pollId, userId);
if (previous && previous.choice_index === choiceIndex) return 'unchanged';
database
.prepare(
`INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?)
ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index,
voted_at = datetime('now')`,
)
.run(pollId, userId, choiceIndex);
return previous ? 'changed' : 'created';
}
export function closePoll(id) {
return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id)
.changes;
}
export function countPolls(guildId) {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId);
return row.count;
}
@@ -0,0 +1,352 @@
import { getDatabase } from '../index.js';
/** Kanban boards, their columns and their cards (M18). */
/** Same wording as the board described in the FWS README. */
export const DEFAULT_COLUMNS = Object.freeze([
{ name: 'À faire', wipLimit: 0, isDone: false },
{ name: 'En cours', wipLimit: 3, isDone: false },
{ name: 'En revue', wipLimit: 0, isDone: false },
{ name: 'Terminé', wipLimit: 0, isDone: true },
]);
const parseBoard = (row) => (row ? { ...row, archived: Boolean(row.archived) } : null);
const parseColumn = (row) => (row ? { ...row, is_done: Boolean(row.is_done) } : null);
const parseCard = (row) => (row ? { ...row, labels: JSON.parse(row.labels || '[]') } : null);
// --- Boards ------------------------------------------------------------------
export function createBoard({
guildId,
scope,
repository = null,
name,
description = null,
createdBy = null,
}) {
const database = getDatabase();
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_boards (guild_id, scope, repository, name, description, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, scope, repository, name, description, createdBy);
const id = Number(lastInsertRowid);
// A board with no column cannot receive a card, so it is never created empty.
for (const [index, column] of DEFAULT_COLUMNS.entries()) {
addColumn({
boardId: id,
name: column.name,
position: index,
wipLimit: column.wipLimit,
isDone: column.isDone,
});
}
return getBoard(id);
}
export function getBoard(id) {
return parseBoard(getDatabase().prepare('SELECT * FROM project_boards WHERE id = ?').get(id) ?? null);
}
export function getBoardByRepository(guildId, repository) {
return parseBoard(
getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? AND repository = ?')
.get(guildId, repository) ?? null,
);
}
export function getOrgBoard(guildId) {
return parseBoard(
getDatabase().prepare("SELECT * FROM project_boards WHERE guild_id = ? AND scope = 'org'").get(guildId) ??
null,
);
}
export function listBoards(guildId) {
return getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? ORDER BY scope DESC, name')
.all(guildId)
.map(parseBoard);
}
export function updateBoard(id, { name, description, archived }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (description !== undefined) (fields.push('description = ?'), values.push(description));
if (archived !== undefined) (fields.push('archived = ?'), values.push(archived ? 1 : 0));
if (fields.length === 0) return getBoard(id);
getDatabase()
.prepare(`UPDATE project_boards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getBoard(id);
}
export function removeBoard(id) {
return getDatabase().prepare('DELETE FROM project_boards WHERE id = ?').run(id).changes;
}
// --- Columns -----------------------------------------------------------------
export function addColumn({ boardId, name, position = null, wipLimit = 0, isDone = false }) {
const database = getDatabase();
const nextPosition =
position ??
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_columns WHERE board_id = ?')
.get(boardId).next ??
0;
const { lastInsertRowid } = database
.prepare(
'INSERT INTO project_columns (board_id, name, position, wip_limit, is_done) VALUES (?, ?, ?, ?, ?)',
)
.run(boardId, name, nextPosition, wipLimit, isDone ? 1 : 0);
return getColumn(Number(lastInsertRowid));
}
export function getColumn(id) {
return parseColumn(getDatabase().prepare('SELECT * FROM project_columns WHERE id = ?').get(id) ?? null);
}
export function listColumns(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_columns WHERE board_id = ? ORDER BY position, id')
.all(boardId)
.map(parseColumn);
}
export function updateColumn(id, { name, wipLimit, isDone, position }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (wipLimit !== undefined) (fields.push('wip_limit = ?'), values.push(Number(wipLimit) || 0));
if (isDone !== undefined) (fields.push('is_done = ?'), values.push(isDone ? 1 : 0));
if (position !== undefined) (fields.push('position = ?'), values.push(Number(position) || 0));
if (fields.length === 0) return getColumn(id);
getDatabase()
.prepare(`UPDATE project_columns SET ${fields.join(', ')} WHERE id = ?`)
.run(...values, id);
return getColumn(id);
}
export function removeColumn(id) {
return getDatabase().prepare('DELETE FROM project_columns WHERE id = ?').run(id).changes;
}
export function countColumns(boardId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_columns WHERE board_id = ?')
.get(boardId).count;
}
// --- Cards -------------------------------------------------------------------
export function addCard({
boardId,
columnId,
title,
body = null,
assigneeId = null,
issueRef = null,
labels = [],
dueAt = null,
createdBy = null,
}) {
const database = getDatabase();
const next =
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_cards WHERE column_id = ?')
.get(columnId).next ?? 0;
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_cards
(board_id, column_id, title, body, position, assignee_id, issue_ref, labels, due_at, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
boardId,
columnId,
title,
body,
next,
assigneeId,
issueRef,
JSON.stringify(labels),
dueAt,
createdBy,
);
return getCard(Number(lastInsertRowid));
}
export function getCard(id) {
return parseCard(getDatabase().prepare('SELECT * FROM project_cards WHERE id = ?').get(id) ?? null);
}
export function listCards(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_cards WHERE board_id = ? ORDER BY column_id, position, id')
.all(boardId)
.map(parseCard);
}
export function countCardsInColumn(columnId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_cards WHERE column_id = ?')
.get(columnId).count;
}
export function updateCard(id, { title, body, assigneeId, issueRef, labels, dueAt }) {
const fields = [];
const values = [];
if (title !== undefined) (fields.push('title = ?'), values.push(title));
if (body !== undefined) (fields.push('body = ?'), values.push(body));
if (assigneeId !== undefined) (fields.push('assignee_id = ?'), values.push(assigneeId || null));
if (issueRef !== undefined) (fields.push('issue_ref = ?'), values.push(issueRef || null));
if (labels !== undefined) (fields.push('labels = ?'), values.push(JSON.stringify(labels)));
if (dueAt !== undefined) (fields.push('due_at = ?'), values.push(dueAt || null));
if (fields.length === 0) return getCard(id);
getDatabase()
.prepare(`UPDATE project_cards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getCard(id);
}
/**
* Moves a card to a rank in a column.
*
* The order is rebuilt explicitly — take the column without the card, insert it
* at the wanted index, renumber — rather than nudged with fractional positions.
* Within one column the card has to be removed before being counted back in, a
* subtlety fractional ranks get wrong every time.
*/
export function moveCard(id, { columnId, position = 0 }) {
const database = getDatabase();
const card = getCard(id);
if (!card) return null;
const order = (target) =>
database
.prepare('SELECT id FROM project_cards WHERE column_id = ? ORDER BY position, id')
.all(target)
.map((row) => row.id)
.filter((cardId) => cardId !== id);
const write = (ids, target) => {
for (const [index, cardId] of ids.entries()) {
database
.prepare(
"UPDATE project_cards SET column_id = ?, position = ?, updated_at = datetime('now') WHERE id = ?",
)
.run(target, index, cardId);
}
};
const destination = order(columnId);
const rank = Math.max(0, Math.min(Number(position) || 0, destination.length));
destination.splice(rank, 0, id);
database.exec('BEGIN');
try {
// The column it leaves closes its gap, the one it joins makes room.
if (card.column_id !== columnId) write(order(card.column_id), card.column_id);
write(destination, columnId);
database.exec('COMMIT');
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
return getCard(id);
}
export function removeCard(id) {
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
}
const parseAssignedCard = (row) => ({
...parseCard(row),
column_is_done: Boolean(row.column_is_done),
});
/**
* Cards carried by one member, across every board of the guild (M19).
*
* The column travels with the card: « what am I on today » cannot be answered
* without knowing whether a card is still open, and asking per card turns the
* page into a staircase of queries. `done_column_id` comes along for the same
* reason — finishing a card from here is then a single move.
*/
export function listCardsForAssignee(guildId, assigneeId) {
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done,
(SELECT d.id FROM project_columns d
WHERE d.board_id = b.id AND d.is_done = 1
ORDER BY d.position, d.id LIMIT 1) AS done_column_id
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id = ?
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
)
.all(guildId, assigneeId)
.map(parseAssignedCard);
}
/**
* Who carries cards, and how many are still open.
*
* Lets the page offer a picker without asking Discord for the member list,
* which is unavailable whenever the bot is offline — precisely when someone is
* most likely to be looking at the dashboard.
*/
export function listAssignees(guildId) {
return getDatabase()
.prepare(
`SELECT c.assignee_id AS assigneeId,
COUNT(*) AS total,
SUM(CASE WHEN col.is_done = 1 THEN 0 ELSE 1 END) AS open
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id IS NOT NULL AND c.assignee_id <> ''
GROUP BY c.assignee_id
ORDER BY open DESC, total DESC`,
)
.all(guildId);
}
/** Cards whose title, body, labels or issue matches, for the command palette (M19). */
export function searchCards(guildId, term, limit = 8) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ?
AND (c.title LIKE ? OR c.body LIKE ? OR c.labels LIKE ? OR c.issue_ref LIKE ?)
ORDER BY col.is_done, c.due_at IS NULL, c.due_at, c.id DESC
LIMIT ?`,
)
.all(guildId, needle, needle, needle, needle, limit)
.map(parseAssignedCard);
}
@@ -0,0 +1,24 @@
import { getDatabase } from '../index.js';
/** The rules message the bot published, so the next version can replace it. */
export function setRulesMessage({ guildId, channelId, messageId, updatedBy = null }) {
getDatabase()
.prepare(
`INSERT INTO rules_messages (guild_id, channel_id, message_id, updated_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id) DO UPDATE SET
channel_id = excluded.channel_id,
message_id = excluded.message_id,
updated_by = excluded.updated_by,
updated_at = datetime('now')`,
)
.run(guildId, channelId, messageId, updatedBy);
}
export function getRulesMessage(guildId) {
return getDatabase().prepare('SELECT * FROM rules_messages WHERE guild_id = ?').get(guildId) ?? null;
}
export function clearRulesMessage(guildId) {
return getDatabase().prepare('DELETE FROM rules_messages WHERE guild_id = ?').run(guildId).changes;
}
@@ -1,21 +1,33 @@
import { getDatabase } from '../index.js';
export function getSetting(guildId, key, fallback = null) {
const row = getDatabase()
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
.get(guildId, key);
return row ? JSON.parse(row.value) : fallback;
}
export function setSetting(guildId, key, value, updatedBy = null) {
getDatabase()
.prepare(
`INSERT INTO guild_settings (guild_id, key, value, updated_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, key) DO UPDATE SET
value = excluded.value,
updated_by = excluded.updated_by,
updated_at = datetime('now')`,
)
.run(guildId, key, JSON.stringify(value), updatedBy);
}
import { getDatabase } from '../index.js';
export function getSetting(guildId, key, fallback = null) {
const row = getDatabase()
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
.get(guildId, key);
return row ? JSON.parse(row.value) : fallback;
}
/**
* Reads a setting without throwing when the database is not ready (tests, early startup).
* Never use it when a missing database should be an error.
*/
export function resolveSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch {
return fallback;
}
}
export function setSetting(guildId, key, value, updatedBy = null) {
getDatabase()
.prepare(
`INSERT INTO guild_settings (guild_id, key, value, updated_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, key) DO UPDATE SET
value = excluded.value,
updated_by = excluded.updated_by,
updated_at = datetime('now')`,
)
.run(guildId, key, JSON.stringify(value), updatedBy);
}
@@ -0,0 +1,106 @@
import { getDatabase } from '../index.js';
export function createTicket({ guildId, channelId, categoryId, authorId }) {
const { lastInsertRowid } = getDatabase()
.prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)')
.run(guildId, channelId, categoryId, authorId);
return Number(lastInsertRowid);
}
export function getTicket(id) {
return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null;
}
export function getTicketByChannel(channelId) {
return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null;
}
/** Returns the open ticket of an author for a category, if any (M6-T08). */
export function getOpenTicket({ guildId, authorId, categoryId }) {
return (
getDatabase()
.prepare(
`SELECT * FROM tickets
WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`,
)
.get(guildId, authorId, categoryId) ?? null
);
}
export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (status) {
clauses.push('status = ?');
params.push(status);
}
if (authorId) {
clauses.push('author_id = ?');
params.push(authorId);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function claimTicket(id, userId) {
return getDatabase()
.prepare(
"UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'",
)
.run(userId, id).changes;
}
export function closeTicket(id, { closedBy, reason = null }) {
return getDatabase()
.prepare(
`UPDATE tickets
SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ?
WHERE id = ? AND status = 'open'`,
)
.run(closedBy, reason, id).changes;
}
export function countOpenTickets(guildId) {
const row = getDatabase()
.prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'")
.get(guildId);
return row.count;
}
// --- Ticket panels (`/ticket setup`) ----------------------------------------
export function setTicketPanel({ guildId, channelId, messageId, createdBy = null }) {
getDatabase()
.prepare(
`INSERT INTO ticket_panels (guild_id, channel_id, message_id, created_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, channel_id) DO UPDATE SET
message_id = excluded.message_id,
created_by = excluded.created_by,
updated_at = datetime('now')`,
)
.run(guildId, channelId, messageId, createdBy);
}
export function getTicketPanel({ guildId, channelId }) {
return (
getDatabase()
.prepare('SELECT * FROM ticket_panels WHERE guild_id = ? AND channel_id = ?')
.get(guildId, channelId) ?? null
);
}
export function listTicketPanels({ guildId }) {
return getDatabase()
.prepare('SELECT * FROM ticket_panels WHERE guild_id = ? ORDER BY updated_at DESC')
.all(guildId);
}
export function deleteTicketPanel({ guildId, channelId }) {
return getDatabase()
.prepare('DELETE FROM ticket_panels WHERE guild_id = ? AND channel_id = ?')
.run(guildId, channelId).changes;
}
@@ -0,0 +1,72 @@
import { getDatabase } from '../index.js';
export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) {
getDatabase()
.prepare(
`INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (channel_id) DO UPDATE SET
owner_id = excluded.owner_id,
name = excluded.name`,
)
.run(channelId, guildId, ownerId, triggerId, name, userLimit);
}
export function getVoiceChannel(channelId) {
return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null;
}
export function listVoiceChannels(guildId) {
return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC')
.all(guildId);
}
/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */
export function listOwnedVoiceChannels(guildId, ownerId) {
return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC')
.all(guildId, ownerId);
}
export function setVoiceOwner(channelId, ownerId) {
return getDatabase()
.prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?')
.run(ownerId, channelId).changes;
}
export function setVoiceName(channelId, name) {
return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId)
.changes;
}
export function setVoiceLocked(channelId, locked) {
return getDatabase()
.prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?')
.run(locked ? 1 : 0, channelId).changes;
}
export function setVoiceLimit(channelId, userLimit) {
return getDatabase()
.prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?')
.run(userLimit, channelId).changes;
}
export function removeVoiceChannel(channelId) {
return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes;
}
export function countVoiceChannels(guildId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?')
.get(guildId);
return row.count;
}
/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */
export function countVoiceChannelsByTrigger(triggerId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?')
.get(triggerId);
return row.count;
}
@@ -0,0 +1,52 @@
import { getDatabase } from '../index.js';
/**
* Declares (or updates) a trigger channel. Every value is explicit: the service merges the
* previous row before writing, so an omitted option keeps its stored value (M14-T01).
*/
export function upsertVoiceTrigger({
triggerId,
guildId,
label = null,
categoryId = null,
template = null,
userLimit = 0,
enabled = true,
}) {
getDatabase()
.prepare(
`INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (trigger_id) DO UPDATE SET
guild_id = excluded.guild_id,
label = excluded.label,
category_id = excluded.category_id,
template = excluded.template,
user_limit = excluded.user_limit,
enabled = excluded.enabled,
updated_at = datetime('now')`,
)
.run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0);
}
export function getVoiceTrigger(triggerId) {
return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null;
}
/** All the triggers of a guild, disabled ones included, in creation order. */
export function listVoiceTriggers(guildId) {
return getDatabase()
.prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC')
.all(guildId);
}
export function removeVoiceTrigger(triggerId) {
return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes;
}
export function countVoiceTriggers(guildId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?')
.get(guildId);
return row.count;
}
@@ -0,0 +1,107 @@
import { getDatabase } from '../index.js';
/** Browser sessions and machine tokens of the web dashboard (M16-T02 / M16-T03). */
export function createSession({
id,
tokenHash,
userId = null,
username = null,
displayName = null,
avatar = null,
accessLevel = 0,
source = 'discord',
ip = null,
userAgent = null,
expiresAt,
}) {
getDatabase()
.prepare(
`INSERT INTO web_sessions
(id, token_hash, user_id, username, display_name, avatar, access_level, source, ip, user_agent, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(id, tokenHash, userId, username, displayName, avatar, accessLevel, source, ip, userAgent, expiresAt);
return getSession(id);
}
export function getSession(id) {
return getDatabase().prepare('SELECT * FROM web_sessions WHERE id = ?').get(id) ?? null;
}
/** Only returns sessions that have not expired, so callers never have to check. */
export function getLiveSessionByHash(tokenHash) {
return (
getDatabase()
.prepare("SELECT * FROM web_sessions WHERE token_hash = ? AND expires_at > datetime('now')")
.get(tokenHash) ?? null
);
}
export function touchSession(id) {
return getDatabase().prepare("UPDATE web_sessions SET last_seen_at = datetime('now') WHERE id = ?").run(id)
.changes;
}
export function deleteSession(id) {
return getDatabase().prepare('DELETE FROM web_sessions WHERE id = ?').run(id).changes;
}
export function deleteSessionsOfUser(userId) {
return getDatabase().prepare('DELETE FROM web_sessions WHERE user_id = ?').run(userId).changes;
}
export function listSessions(limit = 50) {
return getDatabase()
.prepare(
`SELECT id, user_id, username, display_name, avatar, access_level, source, ip, user_agent,
created_at, last_seen_at, expires_at
FROM web_sessions WHERE expires_at > datetime('now') ORDER BY last_seen_at DESC LIMIT ?`,
)
.all(limit);
}
export function purgeExpiredSessions() {
return getDatabase().prepare("DELETE FROM web_sessions WHERE expires_at <= datetime('now')").run().changes;
}
export function createApiToken({ name, tokenHash, prefix, accessLevel, createdBy = null, expiresAt = null }) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO web_api_tokens (name, token_hash, prefix, access_level, created_by, expires_at)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(name, tokenHash, prefix, accessLevel, createdBy, expiresAt);
return Number(lastInsertRowid);
}
export function getLiveApiTokenByHash(tokenHash) {
return (
getDatabase()
.prepare(
`SELECT * FROM web_api_tokens
WHERE token_hash = ? AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > datetime('now'))`,
)
.get(tokenHash) ?? null
);
}
export function touchApiToken(id) {
getDatabase().prepare("UPDATE web_api_tokens SET last_used_at = datetime('now') WHERE id = ?").run(id);
}
export function listApiTokens() {
return getDatabase()
.prepare(
`SELECT id, name, prefix, access_level, created_by, created_at, last_used_at, expires_at, revoked_at
FROM web_api_tokens ORDER BY id DESC`,
)
.all();
}
export function revokeApiToken(id) {
return getDatabase()
.prepare("UPDATE web_api_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL")
.run(id).changes;
}
@@ -0,0 +1,106 @@
import { getDatabase } from '../index.js';
/** Public wiki pages (M17). */
const parse = (row) =>
row ? { ...row, published: Boolean(row.published), protected: Boolean(row.protected) } : null;
export function createPage({
slug,
title,
summary = null,
content = '',
category = 'Général',
position = 0,
published = false,
isProtected = false,
createdBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO wiki_pages
(slug, title, summary, content, category, position, published, protected, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
slug,
title,
summary,
content,
category,
position,
published ? 1 : 0,
isProtected ? 1 : 0,
createdBy,
createdBy,
);
return getPage(Number(lastInsertRowid));
}
export function getPage(id) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE id = ?').get(id) ?? null);
}
export function getPageBySlug(slug) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE slug = ?').get(slug) ?? null);
}
/** Published pages only, in reading order — what the public site shows. */
export function listPublished() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages WHERE published = 1 ORDER BY category, position, title')
.all()
.map(parse);
}
export function listAllPages() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages ORDER BY category, position, title')
.all()
.map(parse);
}
const UPDATABLE = Object.freeze({
slug: (value) => value,
title: (value) => value,
summary: (value) => value,
content: (value) => value,
category: (value) => value,
position: (value) => Number.parseInt(value, 10) || 0,
published: (value) => (value ? 1 : 0),
});
export function updatePage(id, patch, updatedBy = null) {
const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE);
if (entries.length === 0) return getPage(id);
const assignments = entries.map(([key]) => `${key} = ?`).join(', ');
const values = entries.map(([key, value]) => UPDATABLE[key](value));
getDatabase()
.prepare(
`UPDATE wiki_pages SET ${assignments}, updated_by = ?, updated_at = datetime('now') WHERE id = ?`,
)
.run(...values, updatedBy, id);
return getPage(id);
}
export function removePage(id) {
return getDatabase().prepare('DELETE FROM wiki_pages WHERE id = ? AND protected = 0').run(id).changes;
}
export function countPages() {
return getDatabase().prepare('SELECT COUNT(*) AS count FROM wiki_pages').get().count;
}
/** Full-text-ish search over the published pages, good enough for a small wiki. */
export function searchPublished(term) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT * FROM wiki_pages
WHERE published = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)
ORDER BY category, position, title LIMIT 25`,
)
.all(needle, needle, needle)
.map(parse);
}
+10 -10
View File
@@ -1,10 +1,10 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('discord');
export const name = Events.Error;
export async function execute(_client, error) {
log.error('Discord client error', error);
}
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('discord');
export const name = Events.Error;
export async function execute(_client, error) {
log.error('Discord client error', error);
}
+30 -15
View File
@@ -1,15 +1,30 @@
import { ActivityType, Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('discord');
export const name = Events.ClientReady;
export const once = true;
export async function execute(client) {
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
});
}
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import {
adoptOrphanVoiceChannels,
startVoiceJanitor,
sweepVoiceChannels,
} from '../services/voice/voice-service.js';
const log = createLogger('discord');
export const name = Events.ClientReady;
export const once = true;
export async function execute(client) {
startPollScheduler(client);
// Channels outlive the process: take back the ones the database forgot before
// the sweep decides they are not ours.
await adoptOrphanVoiceChannels(client).catch((error) =>
log.warn('Could not recover the orphan voice channels', error),
);
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
});
}
+21 -11
View File
@@ -1,11 +1,21 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('members');
export const name = Events.GuildMemberAdd;
// TODO(M7-T01..T04): welcome message, rules and resources, initial role.
export async function execute(_client, member) {
log.info('Member joined', { userId: member.id, guildId: member.guild.id });
}
import { Events } from 'discord.js';
import { readSetting } from '../config/guild-settings.js';
import { createLogger } from '../core/logger.js';
import {
assignMemberRole,
sendWelcome,
sendWelcomeDirectMessage,
} from '../services/members/member-service.js';
const log = createLogger('members');
export const name = Events.GuildMemberAdd;
/** Welcome message, resources and default role (M7-T01..T04). */
export async function execute(client, member) {
log.info('Member joined', { userId: member.id, guildId: member.guild.id });
await assignMemberRole(member);
await sendWelcome(client, member);
if (readSetting('welcome.directMessage', member.guild.id)) await sendWelcomeDirectMessage(member);
}
+13 -11
View File
@@ -1,11 +1,13 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('members');
export const name = Events.GuildMemberRemove;
// TODO(M7-T04): log departures in the configured channel.
export async function execute(_client, member) {
log.info('Member left', { userId: member.id, guildId: member.guild.id });
}
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { announceDeparture } from '../services/members/member-service.js';
const log = createLogger('members');
export const name = Events.GuildMemberRemove;
/** Announces and records departures (M7-T04). */
export async function execute(client, member) {
log.info('Member left', { userId: member.id, guildId: member.guild.id });
await announceDeparture(client, member);
}
+88 -47
View File
@@ -1,47 +1,88 @@
import { Events, MessageFlags } from 'discord.js';
import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js';
import { errorEmbed } from '../ui/embeds.js';
const log = createLogger('interactions');
export const name = Events.InteractionCreate;
async function replyError(interaction, message) {
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload);
} else {
await interaction.reply(payload);
}
}
export async function execute(client, interaction) {
if (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
if (interaction.isAutocomplete()) {
await command.autocomplete?.(interaction);
return;
}
try {
const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError();
}
await command.execute(interaction);
} catch (error) {
if (error instanceof UserFacingError) {
await replyError(interaction, error.message);
return;
}
log.error(`Command failed: /${interaction.commandName}`, error);
await replyError(interaction, 'Une erreur inattendue est survenue. Réessaie plus tard.').catch(() => {});
}
}
import { Events, MessageFlags } from 'discord.js';
import { ACCESS_LABELS } from '../config/constants.js';
import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js';
import { handleGiteaModal } from '../services/gitea/gitea-modals.js';
import { handlePollComponent } from '../services/polls/poll-service.js';
import { handleTicketComponent } from '../services/tickets/ticket-service.js';
import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js';
import { errorEmbed } from '../ui/embeds.js';
const log = createLogger('interactions');
export const name = Events.InteractionCreate;
/** Custom id prefix -> handlers for the message components and the modals. */
const routes = [
{ prefix: 'ticket:', component: handleTicketComponent },
{ prefix: 'poll:', component: handlePollComponent },
{ prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal },
{ prefix: 'issue:', modal: handleGiteaModal },
{ prefix: 'pr:', modal: handleGiteaModal },
];
async function replyError(interaction, message) {
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload);
} else {
await interaction.reply(payload);
}
}
async function runChatInputCommand(interaction) {
const command = interaction.client.commands.get(interaction.commandName);
if (!command) return;
const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError(
`Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`,
);
}
await command.execute(interaction);
}
async function runRoute(interaction, kind) {
const route = routes.find(
({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix),
);
if (!route) {
log.debug(`Ignored ${kind} ${interaction.customId}`);
return;
}
await route[kind](interaction);
}
export async function execute(_client, interaction) {
try {
if (interaction.isAutocomplete()) {
await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction);
return;
}
if (interaction.isButton() || interaction.isAnySelectMenu()) {
await runRoute(interaction, 'component');
return;
}
if (interaction.isModalSubmit()) {
await runRoute(interaction, 'modal');
return;
}
if (!interaction.isChatInputCommand()) return;
await runChatInputCommand(interaction);
} catch (error) {
if (error instanceof UserFacingError) {
await replyError(interaction, error.message);
return;
}
log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error);
await replyError(
interaction,
'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.',
).catch(() => {});
}
}
+11 -11
View File
@@ -1,11 +1,11 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('discord');
// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08).
export const name = Events.ShardDisconnect;
export async function execute(_client, closeEvent, shardId) {
log.warn('Shard disconnected', { shardId, code: closeEvent?.code });
}
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
const log = createLogger('discord');
// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08).
export const name = Events.ShardDisconnect;
export async function execute(_client, closeEvent, shardId) {
log.warn('Shard disconnected', { shardId, code: closeEvent?.code });
}
+32
View File
@@ -0,0 +1,32 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } from '../services/voice/voice-service.js';
const log = createLogger('voice');
export const name = Events.VoiceStateUpdate;
/**
* Joining any of the trigger channels creates a private channel in that trigger's category and
* moves the member in; leaving a temporary channel deletes it once the last member is gone
* (M14-T02 / M14-T04).
*/
export async function execute(_client, oldState, newState) {
const member = newState.member ?? oldState.member;
if (!member || member.user.bot) return;
try {
const joinedId =
newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null;
if (joinedId) {
const trigger = getVoiceTrigger(newState.guild.id, joinedId);
if (trigger) await createFromTrigger(member, trigger);
}
if (oldState.channelId && oldState.channelId !== newState.channelId) {
await cleanupVoiceChannel(oldState.guild, oldState.channelId);
}
} catch (error) {
log.error('Voice state handling failed', error);
}
}
+53 -35
View File
@@ -1,35 +1,53 @@
import { assertRequiredEnv, env } from './config/env.js';
import { createClient } from './core/client.js';
import { loadCommands } from './core/command-loader.js';
import { registerEvents } from './core/event-loader.js';
import { logger } from './core/logger.js';
import { closeDatabase, initDatabase } from './database/index.js';
import { startWebhookServer } from './webhooks/server.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
initDatabase();
const client = createClient();
for (const command of await loadCommands()) {
client.commands.set(command.data.name, command);
}
await registerEvents(client);
const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null;
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`);
webhookServer?.close();
await client.destroy();
closeDatabase();
process.exit(0);
}
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
await client.login(env.discord.token);
import { assertRequiredEnv, env } from './config/env.js';
import { createClient } from './core/client.js';
import { loadCommands } from './core/command-loader.js';
import { registerEvents } from './core/event-loader.js';
import { logger } from './core/logger.js';
import { closeDatabase, initDatabase } from './database/index.js';
import { startWebServer, webhookSharesWebPort } from './web/server.js';
import { startWebhookServer } from './webhooks/server.js';
try {
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
} catch (error) {
logger.error(`${error.message}. Lance \`npm run setup\` pour remplir le .env pas à pas.`);
throw error;
}
initDatabase();
const client = createClient();
for (const command of await loadCommands()) {
client.commands.set(command.data.name, command);
}
await registerEvents(client);
// When both listen on the same port, the dashboard serves the webhook route too.
const webServer = env.web.enabled ? startWebServer({ client }) : null;
const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null;
// Saying nothing when the dashboard is off is how an afternoon gets lost
// looking for a site that was never asked to start.
if (!env.web.enabled) {
logger.warn(
'Le tableau de bord est désactivé : `WEB_ENABLED` ne vaut pas `true`. ' +
'Aucun site ne sera servi. Mets `WEB_ENABLED=true` dans le .env puis redémarre.',
);
}
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`);
webhookServer?.close();
webServer?.close();
await client.destroy();
closeDatabase();
process.exit(0);
}
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
await client.login(env.discord.token);
+153
View File
@@ -0,0 +1,153 @@
import { env } from '../../config/env.js';
import { asList, giteaRequest } from './gitea-client.js';
/**
* Administration endpoints used by the web dashboard (M16-T04).
*
* `gitea-client.js` stays focused on the single repository the Discord commands
* talk to; this module addresses any repository of the organization, which is
* what the dashboard needs.
*/
const query = (params = {}) => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null && value !== '') search.set(key, String(value));
}
const rendered = search.toString();
return rendered ? `?${rendered}` : '';
};
const path = (owner, repo) => `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
/** Organization the dashboard manages by default. */
export const defaultOwner = () => env.gitea.owner;
export const org = {
get: (owner = defaultOwner()) => giteaRequest(`/orgs/${encodeURIComponent(owner)}`),
update: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}`, { method: 'PATCH', body: payload }),
listRepos: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos${query({ page, limit })}`).then(asList),
listMembers: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/members${query({ page, limit })}`).then(asList),
listTeams: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/teams${query({ page, limit })}`).then(asList),
listTeamMembers: (teamId) => giteaRequest(`/teams/${teamId}/members`).then(asList),
listLabels: ({ owner = defaultOwner(), limit = 100 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/labels${query({ limit })}`).then(asList),
listHooks: ({ owner = defaultOwner() } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
createRepo: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
/**
* Issues and pull requests of the whole organization, in one request.
*
* The per-repository endpoint would mean one call per repository, which the
* command palette cannot afford on every keystroke. Absent before Gitea 1.15,
* so callers tolerate a rejection.
*/
searchIssues: ({ owner = defaultOwner(), q, state = 'open', type, limit = 10 } = {}) =>
giteaRequest(`/repos/issues/search${query({ q, owner, state, type, limit })}`).then(asList),
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
whoami: () => giteaRequest('/user'),
};
export const repos = {
get: (owner, repo) => giteaRequest(path(owner, repo)),
update: (owner, repo, payload) => giteaRequest(path(owner, repo), { method: 'PATCH', body: payload }),
remove: (owner, repo) => giteaRequest(path(owner, repo), { method: 'DELETE' }),
listBranches: (owner, repo, { page = 1, limit = 50 } = {}) =>
giteaRequest(`${path(owner, repo)}/branches${query({ page, limit })}`).then(asList),
createBranch: (owner, repo, { newBranchName, oldBranchName }) =>
giteaRequest(`${path(owner, repo)}/branches`, {
method: 'POST',
body: { new_branch_name: newBranchName, old_branch_name: oldBranchName },
}),
removeBranch: (owner, repo, branch) =>
giteaRequest(`${path(owner, repo)}/branches/${encodeURIComponent(branch)}`, { method: 'DELETE' }),
listTags: (owner, repo, { limit = 50 } = {}) =>
giteaRequest(`${path(owner, repo)}/tags${query({ limit })}`).then(asList),
listCommits: (owner, repo, { sha, page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/commits${query({ sha, page, limit })}`).then(asList),
languages: (owner, repo) => giteaRequest(`${path(owner, repo)}/languages`),
listTopics: (owner, repo) => giteaRequest(`${path(owner, repo)}/topics`),
replaceTopics: (owner, repo, topics) =>
giteaRequest(`${path(owner, repo)}/topics`, { method: 'PUT', body: { topics } }),
listIssues: (owner, repo, { state = 'open', type = 'issues', page = 1, limit = 20, q } = {}) =>
giteaRequest(`${path(owner, repo)}/issues${query({ state, type, page, limit, q })}`).then(asList),
createIssue: (owner, repo, { title, body, labels, assignees }) =>
giteaRequest(`${path(owner, repo)}/issues`, { method: 'POST', body: { title, body, labels, assignees } }),
updateIssue: (owner, repo, number, payload) =>
giteaRequest(`${path(owner, repo)}/issues/${number}`, { method: 'PATCH', body: payload }),
commentIssue: (owner, repo, number, body) =>
giteaRequest(`${path(owner, repo)}/issues/${number}/comments`, { method: 'POST', body: { body } }),
listLabels: (owner, repo, { limit = 100 } = {}) =>
giteaRequest(`${path(owner, repo)}/labels${query({ limit })}`).then(asList),
listPulls: (owner, repo, { state = 'open', page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/pulls${query({ state, page, limit })}`).then(asList),
createPull: (owner, repo, { title, body, head, base }) =>
giteaRequest(`${path(owner, repo)}/pulls`, { method: 'POST', body: { title, body, head, base } }),
mergePull: (owner, repo, number, { style = 'squash', title, message, deleteBranch = false } = {}) =>
giteaRequest(`${path(owner, repo)}/pulls/${number}/merge`, {
method: 'POST',
body: {
Do: style,
MergeTitleField: title,
MergeMessageField: message,
delete_branch_after_merge: deleteBranch,
},
}),
listReleases: (owner, repo, { page = 1, limit = 20, draft, preRelease } = {}) =>
giteaRequest(
`${path(owner, repo)}/releases${query({ page, limit, draft, 'pre-release': preRelease })}`,
).then(asList),
getRelease: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/releases/${id}`),
latestRelease: (owner, repo) => giteaRequest(`${path(owner, repo)}/releases/latest`),
createRelease: (owner, repo, { tagName, target, name, body, draft = false, prerelease = false }) =>
giteaRequest(`${path(owner, repo)}/releases`, {
method: 'POST',
body: { tag_name: tagName, target_commitish: target, name, body, draft, prerelease },
}),
updateRelease: (owner, repo, id, payload) =>
giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'PATCH', body: payload }),
removeRelease: (owner, repo, id) =>
giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'DELETE' }),
listCollaborators: (owner, repo) => giteaRequest(`${path(owner, repo)}/collaborators`).then(asList),
addCollaborator: (owner, repo, username, permission = 'write') =>
giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, {
method: 'PUT',
body: { permission },
}),
removeCollaborator: (owner, repo, username) =>
giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { method: 'DELETE' }),
listHooks: (owner, repo) => giteaRequest(`${path(owner, repo)}/hooks`).then(asList),
createHook: (owner, repo, { url, secret, events, type = 'gitea' }) =>
giteaRequest(`${path(owner, repo)}/hooks`, {
method: 'POST',
body: { type, active: true, events, config: { url, content_type: 'json', secret } },
}),
removeHook: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/hooks/${id}`, { method: 'DELETE' }),
/** Gitea Actions. Absent before Gitea 1.20, so callers must tolerate a 404. */
listActionTasks: (owner, repo, { page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/actions/tasks${query({ page, limit })}`),
dispatchWorkflow: (owner, repo, workflow, { ref, inputs = {} }) =>
giteaRequest(`${path(owner, repo)}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, {
method: 'POST',
body: { ref, inputs },
}),
};
/** Splits `FWS/FWS-Arch` into its two parts, rejecting anything else. */
export function splitRepository(fullName) {
const [owner, repo, ...rest] = String(fullName ?? '').split('/');
if (!owner || !repo || rest.length > 0) return null;
return { owner, repo };
}
+69 -51
View File
@@ -1,51 +1,69 @@
import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) {
throw new ExternalApiError('gitea', 'Gitea is not configured');
}
return withRetry(
async () => {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method,
headers: {
Authorization: `token ${env.gitea.token}`,
Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(env.gitea.timeoutMs),
});
if (!response.ok) {
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
error.status = response.status;
throw error;
}
return response.status === 204 ? null : response.json();
},
{ retries: env.gitea.maxRetries, shouldRetry: isTransient },
);
}
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = {
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
createIssue: ({ title, body }) =>
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
createPullRequest: ({ title, body, head, base }) =>
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
};
import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) {
throw new ExternalApiError('gitea', 'Gitea is not configured');
}
return withRetry(
async () => {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method,
headers: {
Authorization: `token ${env.gitea.token}`,
Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(env.gitea.timeoutMs),
});
if (!response.ok) {
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
error.status = response.status;
throw error;
}
return response.status === 204 ? null : response.json();
},
{ retries: env.gitea.maxRetries, shouldRetry: isTransient },
);
}
/** True when both the Gitea URL and token are configured (M5-T01). */
export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token);
}
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) {
if (Array.isArray(payload)) return payload;
return Array.isArray(payload?.data) ? payload.data : [];
}
/** Human readable URL of the configured repository, used in embeds. */
export function repositoryUrl() {
return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : '';
}
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = {
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
createIssue: ({ title, body }) =>
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
createPullRequest: ({ title, body, head, base }) =>
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
};
+97
View File
@@ -0,0 +1,97 @@
import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim();
if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
/** Falls back to a neutral word: the value always sits next to a person, never a role. */
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Ouverte par', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
);
if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') });
return embed;
}
/** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Proposée par', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
if (pull.html_url) embed.setURL(pull.html_url);
return embed;
}
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`)
.addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
);
if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
}
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed;
}
/** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits
.slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.')
.addFields(
{ name: 'Poussé par', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true },
);
if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
/** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
+152
View File
@@ -0,0 +1,152 @@
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() {
if (!isGiteaConfigured()) {
throw new UserFacingError(
'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.',
);
}
}
function modal(id, title, fields) {
return new ModalBuilder()
.setCustomId(id)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true),
),
),
);
}
/** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) {
assertGiteaConfigured();
await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]),
);
}
/** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) {
assertGiteaConfigured();
const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]),
);
}
/** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error);
const detail =
error instanceof ExternalApiError && /not configured/.test(error.message)
? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.'
: 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {});
} else {
await interaction.reply(payload).catch(() => {});
}
}
export async function submitIssueModal(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.issue.created',
actorId: interaction.user.id,
payload: { number: issue.number },
});
await interaction.editReply({
embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
export async function submitPullRequestModal(interaction) {
assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`);
if (!context) {
throw new UserFacingError(
'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.',
);
}
await interaction.deferReply();
try {
const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head,
base: context.base,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.pull_request.created',
actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base },
});
await interaction.editReply({
embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) {
switch (interaction.customId) {
case 'issue:create':
await submitIssueModal(interaction);
return;
case 'pr:create':
await submitPullRequestModal(interaction);
return;
default:
log.debug(`Ignored unknown modal ${interaction.customId}`);
}
}
+32
View File
@@ -0,0 +1,32 @@
/**
* In-memory store for the short-lived context of a modal flow, e.g. the branches
* of `/pr create` which are typed as options but sent with the modal (M5-T04).
* Entries expire on their own and disappear on restart.
*/
const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs });
return value;
}
/** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key);
if (!entry) return null;
entries.delete(key);
return entry.expiresAt > now ? entry.value : null;
}
export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
return entries.size;
}
export function pendingCount() {
return entries.size;
}
+128
View File
@@ -0,0 +1,128 @@
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('members');
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
async function sendTo(channel) {
return channel?.isSendable() ? channel : null;
}
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) {
if (!readSetting('welcome.enabled', member.guild.id)) {
log.debug('Welcome message disabled for this guild');
return;
}
if (!env.channels.welcome) {
log.debug('No welcome channel configured');
return;
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null));
if (!channel) {
log.warn('Welcome channel unavailable', { channelId: env.channels.welcome });
return;
}
const greeting =
readSetting('welcome.message', member.guild.id).replaceAll('{server}', member.guild.name) ||
DEFAULT_WELCOME;
const embed = baseEmbed(COLORS.primary)
.setTitle('🎉 Nouveau membre')
.setDescription(`${member} vient d’arriver. ${greeting}`)
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (env.channels.rules && readSetting('welcome.showRules', member.guild.id)) {
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
}
await channel.send({ content: `${member}`, embeds: [embed] });
logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } });
}
/** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) {
if (!readSetting('members.autoRole', member.guild.id)) return;
const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return;
const role = await member.guild.roles.fetch(roleId).catch(() => null);
if (!role) {
log.warn('Default member role not found', { roleId });
return;
}
if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) {
log.warn('Member role is above the bot role, skipping', { roleId });
return;
}
await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error);
});
}
/** Welcomes the member in a direct message with the server resources (M7-T02). */
export async function sendWelcomeDirectMessage(member) {
const links = [
env.links.website && `[Site officiel](${env.links.website})`,
env.links.docs && `[Documentation](${env.links.docs})`,
env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
].filter(Boolean);
const embed = baseEmbed(COLORS.primary)
.setTitle(`Bienvenue sur ${member.guild.name} !`)
.setDescription(
'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' +
'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.',
);
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
await member.send({ embeds: [embed] }).catch(() => {
log.debug('Welcome DM could not be delivered', { userId: member.id });
});
}
/** Logs a departure in the log channel (M7-T04). */
export async function announceDeparture(client, member) {
if (!readSetting('departure.announce', member.guild.id)) return;
const channelId = env.channels.logs || env.channels.modLogs;
if (!channelId) return;
const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
if (!channel) return;
const joinedAt = member.joinedTimestamp;
const embed = baseEmbed(COLORS.warning)
.setTitle('👋 Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
{ name: 'Membres', value: String(member.guild.memberCount), inline: true },
{
name: 'Compte créé',
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
inline: true,
},
)
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (joinedAt) {
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true });
}
await channel.send({ embeds: [embed] });
logEvent({
guildId: member.guild.id,
type: 'member.left',
payload: { userId: member.id, joinedAt: joinedAt ?? null },
});
}
@@ -0,0 +1,159 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Label shown for an action everywhere it is rendered (log channel, direct
* message, `/mod logs`, dashboard). Falls back to the raw action name, so a
* row written by another version still reads as something.
* @param {string} action
*/
export function moderationLabel(action) {
const meta = MODERATION_ACTIONS[action];
return meta ? `${meta.emoji} ${meta.label}` : action;
}
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction
* @param {import('discord.js').GuildMember} target
*/
export function assertModerationTarget(interaction, target) {
if (!target) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.');
}
if (!canActOn(interaction.member, target)) {
throw new UserFacingError(
'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
throw new UserFacingError(
`Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`,
);
}
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
* Call it only once the Discord action has succeeded.
*/
export async function logModerationAction(
interaction,
{ action, targetId, reason = null, durationMs = null },
) {
recordAction({
guildId: interaction.guildId,
action,
moderatorId: interaction.user.id,
targetId,
reason,
durationMs,
});
logEvent({
guildId: interaction.guildId,
type: `moderation.${action}`,
actorId: interaction.user.id,
payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, {
action,
color: meta?.color ?? COLORS.moderation,
targetId,
moderatorId: interaction.user.id,
reason,
durationMs,
});
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog(
client,
guild,
{ action, targetId, moderatorId, reason, durationMs },
) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`🛡️ Modération — ${moderationLabel(action)}`)
.addFields(
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
}
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
}
/**
* Sends the private notice to the sanctioned member, when the server wants one
* (M8-T07). Never throws: plenty of accounts refuse direct messages, and that
* must not turn a successful sanction into an error.
* @param guildId Server the sanction belongs to. A lifted ban targets someone
* who has left the server, so a plain `User` is accepted with an explicit id.
*/
export async function notifyTarget(member, payload, guildId = member.guild?.id) {
if (!readSetting('moderation.dmTarget', guildId)) return false;
return member
.send(payload)
.then(() => true)
.catch(() => false);
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`)
.setDescription(
`Action : **${moderationLabel(action)}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
)
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) {
const minutes = Math.round(durationMs / 60_000);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
return member;
}
@@ -0,0 +1,31 @@
import { GITEA_EVENT_TYPES } from '../../config/constants.js';
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
/**
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
* should not be published (M9-T03).
*/
export function buildGiteaNotification(event, payload) {
const type = GITEA_EVENT_TYPES[event];
if (!type) return null;
switch (event) {
case 'issues':
return { type, embed: issueEmbed(payload.issue ?? payload) };
case 'pull_request':
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
case 'push':
if (!payload.commits?.length) return null;
return { type, embed: pushEmbed(payload) };
case 'create':
case 'delete':
return {
type,
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
};
case 'release':
return { type, embed: releaseEmbed(payload.release ?? payload) };
default:
return null;
}
}
@@ -1,33 +1,86 @@
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
const log = createLogger('notifications');
const defaultChannels = {
issues: env.channels.notifIssues,
pull_request: env.channels.notifPullRequests,
push: env.channels.notifCommits,
release: env.channels.notifReleases,
errors: env.channels.notifErrors,
};
// TODO(M9-T01): resolve channels from notification_channels in SQLite first.
export function resolveChannelId(type) {
return defaultChannels[type] ?? null;
}
/** Sends a notification payload to the channel configured for its type (M9). */
export async function notify(client, type, payload) {
const channelId = resolveChannelId(type);
if (!channelId) {
log.debug(`No channel configured for notification type ${type}`);
return;
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
log.warn(`Notification channel unavailable for ${type}`, { channelId });
return;
}
await channel.send(payload);
}
import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { createLogger } from '../../core/logger.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js';
const log = createLogger('notifications');
/** Fallback routing from the environment when the guild has no override (M9-T01). */
const defaultChannels = {
issues: env.channels.notifIssues,
pull_request: env.channels.notifPullRequests,
push: env.channels.notifCommits,
release: env.channels.notifReleases,
errors: env.channels.notifErrors,
announcements: env.channels.announcements,
community: env.channels.logs,
};
/**
* `/notify` and the dashboard name the types after `NOTIFICATION_TYPES`, while the
* webhook handler names them after the Gitea event. Both spellings must resolve to
* the same channel, otherwise an override set from Discord is never applied (M9-T01).
*/
const TYPE_ALIASES = Object.freeze({
pull_request: 'pull_requests',
pull_requests: 'pull_request',
push: 'commits',
commits: 'push',
release: 'releases',
releases: 'release',
});
/** SQLite override first, then the environment default (M9-T01). */
export function resolveChannelId(type, guildId = env.discord.guildId) {
try {
if (guildId) {
for (const candidate of [type, TYPE_ALIASES[type]].filter(Boolean)) {
const override = getNotificationChannel(guildId, candidate);
if (override?.channel_id) return override.channel_id;
}
}
} catch {
// The database is unavailable (tests, early startup): use the environment.
}
return defaultChannels[type] ?? defaultChannels[TYPE_ALIASES[type]] ?? null;
}
/** Sends a notification payload to the channel configured for its type (M9). */
export async function notify(client, type, payload) {
const channelId = resolveChannelId(type);
if (!channelId) {
log.debug(`No channel configured for notification type ${type}`);
return null;
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
log.warn(`Notification channel unavailable for ${type}`, { channelId });
return null;
}
// An optional ping, prepended rather than replacing whatever content the
// caller already prepared.
const mention = readSetting('notifications.mentionRoleId');
const message = mention
? { ...payload, content: payload.content ? `<@&${mention}> ${payload.content}` : `<@&${mention}>` }
: payload;
return channel.send(message);
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') {
log.error(`Notification error (${context})`, error);
return notify(client, 'errors', {
embeds: [
errorEmbed(
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`,
).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
],
});
}
+219
View File
@@ -0,0 +1,219 @@
import { MessageFlags } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
attachPollMessage,
castVote,
closePoll,
countVotes,
createPoll as createPollRow,
getPoll,
listDuePolls,
} from '../../database/repositories/poll-repository.js';
import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('polls');
const CHOICES_MIN = 2;
const BAR_LENGTH = 12;
const SCHEDULER_INTERVAL_MS = 30_000;
/** Splits the `choices` option on `;` and validates the count (M10-T01). */
export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) {
const choices = String(input)
.split(';')
.map((choice) => choice.trim())
.filter(Boolean);
if (choices.length < min || choices.length > max) {
throw new UserFacingError(
`Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`,
);
}
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError(
'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.',
);
}
return choices;
}
/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */
export function toSqliteDate(date) {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
function renderBar(ratio) {
const filled = Math.round(ratio * BAR_LENGTH);
return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`;
}
/** Results embed, shared by creation, voting and closing (M10-T06). */
export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
const choices = JSON.parse(poll.choices);
const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0;
const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0);
const lines = choices.map((choice, index) => {
const count = countFor(index);
const percent = total === 0 ? 0 : Math.round((count / total) * 100);
return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`;
});
const embed = baseEmbed(COLORS.info)
.setTitle(`📊 Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n'))
.addFields(
{ name: 'Votes', value: String(total), inline: true },
{ name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true },
{ name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
);
if (poll.ends_at) {
const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000);
embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true });
}
if (poll.status === 'closed') {
embed.setColor(COLORS.success);
const best = choices.reduce(
(winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner),
0,
);
const top = countFor(best);
embed.addFields({
name: 'Résultat',
value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`,
});
}
return embed;
}
export function buildPollComponents(poll) {
return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : [];
}
/** Creates the poll message and records it (M10-T01 / M10-T02). */
export async function createPoll(interaction, { question, choicesInput, minutes = null }) {
const choices = parseChoices(choicesInput);
const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null;
const pollId = createPollRow({
guildId: interaction.guildId,
channelId: interaction.channelId,
creatorId: interaction.user.id,
question,
choices,
endsAt,
});
const poll = getPoll(pollId);
const message = await interaction.channel.send({
embeds: [buildPollEmbed(poll, [])],
components: buildPollComponents(poll),
});
attachPollMessage(pollId, message.id);
logEvent({
guildId: interaction.guildId,
type: 'poll.created',
actorId: interaction.user.id,
payload: { pollId, choices: choices.length },
});
return pollId;
}
async function fetchPollMessage(interaction, poll) {
if (!poll.message_id) return null;
return interaction.channel.messages.fetch(poll.message_id).catch(() => null);
}
/** Closes a poll and freezes its results (M10-T05). */
export async function closePollById(client, pollId) {
const poll = getPoll(pollId);
if (!poll) {
throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`);
}
if (poll.status === 'closed') {
throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`);
}
closePoll(pollId);
const closed = { ...poll, status: 'closed' };
const channel = await client.channels.fetch(poll.channel_id).catch(() => null);
const message = channel?.isSendable()
? await channel.messages.fetch(poll.message_id).catch(() => null)
: null;
await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] });
logEvent({
guildId: poll.guild_id,
type: 'poll.closed',
payload: { pollId },
});
return closed;
}
/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */
export async function handlePollComponent(interaction) {
const [, rawId, rawIndex] = interaction.customId.split(':');
const poll = getPoll(Number(rawId));
if (!poll || poll.status !== 'open') {
throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.');
}
const choices = JSON.parse(poll.choices);
const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Cette proposition n’existe plus dans le sondage.');
}
const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') {
await interaction.reply({
content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`,
flags: MessageFlags.Ephemeral,
});
return;
}
const message = await fetchPollMessage(interaction, poll);
await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) });
await interaction.reply({
content:
result === 'changed'
? `C’est noté : ton vote va maintenant à **${choices[index]}**.`
: `Merci ! Ton vote est sur **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
}
/** Polls expire on their own even without activity (M10-T05). */
export function startPollScheduler(client) {
const timer = setInterval(async () => {
let due = [];
try {
due = listDuePolls();
} catch (error) {
log.warn('Could not read the polls to close', error);
return;
}
for (const poll of due) {
try {
await closePollById(client, poll.id);
log.info(`Closed poll #${poll.id} at its end date`);
} catch (error) {
log.error(`Could not close poll #${poll.id}`, error);
}
}
}, SCHEDULER_INTERVAL_MS);
timer.unref();
return timer;
}
+133
View File
@@ -0,0 +1,133 @@
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { getRulesMessage, setRulesMessage } from '../../database/repositories/rules-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Rules of the server, written from the dashboard and kept in a single pinned
* message in `CHANNEL_RULES_ID` (M19).
*
* Saving edits the message already published, so the channel keeps one set of
* rules — same link, same position, and the pin survives. A new message is
* only sent when the bot has none yet, or when the previous one was deleted by
* hand.
*/
const log = createLogger('rules');
/** Discord refuses an embed description longer than that. */
export const RULES_MAX_LENGTH = 4000;
const TITLE = '📜 Règlement';
const rulesEmbed = (content) =>
baseEmbed(COLORS.primary)
.setTitle(TITLE)
.setDescription(content)
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
.setTimestamp(new Date());
/**
* Publishes the rules, editing the message already there when there is one.
* @param {import('discord.js').Client} client
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
*/
export async function publishRules(
client,
{ guildId, markdown, actorId = null, channelId = env.channels.rules },
) {
if (!channelId) {
throw new Error('Aucun salon des règles configuré : renseigne CHANNEL_RULES_ID dans le .env.');
}
const content = String(markdown ?? '').trim();
if (content === '') throw new Error('Le règlement est vide.');
if (content.length > RULES_MAX_LENGTH) {
throw new Error(`${RULES_MAX_LENGTH} caractères maximum pour un règlement.`);
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
}
const edited = await editPublishedRules(client, guildId, content);
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
// Only a brand new message has to be pinned: an edited one keeps its pin.
const pinned = edited
? true
: await message
.pin()
.then(() => true)
.catch((error) => {
// A bot without “Gérer les messages” still publishes the rules.
log.warn('Could not pin the rules message', error);
return false;
});
setRulesMessage({
guildId,
channelId,
messageId: message.id,
updatedBy: actorId,
});
logEvent({
guildId,
type: 'web.rules.published',
actorId,
payload: { channelId, messageId: message.id, pinned, edited: Boolean(edited) },
});
log.info('Rules saved from the dashboard', {
channelId,
messageId: message.id,
edited: Boolean(edited),
actor: actorId,
});
return {
messageId: message.id,
url: message.url ?? null,
channelId,
pinned,
edited: Boolean(edited),
};
}
/**
* Rewrites the message the bot published last time.
* @returns the edited message, or null when there is none to edit
*/
async function editPublishedRules(client, guildId, content) {
const stored = getRulesMessage(guildId);
if (!stored) return null;
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
if (!message?.editable) return null;
return message
.edit({ embeds: [rulesEmbed(content)] })
.then((edited) => edited ?? message)
.catch((error) => {
// A message deleted by hand, or one the bot may no longer edit, must not
// stop the publication: a fresh one takes its place.
log.warn('Could not edit the previous rules message', error);
return null;
});
}
/** What the dashboard needs to show the current state of the rules. */
export function rulesStatus(guildId, channelId = env.channels.rules) {
const stored = getRulesMessage(guildId);
return {
channelId: channelId || null,
configured: Boolean(channelId),
messageId: stored?.message_id ?? null,
publishedAt: stored?.updated_at ?? null,
publishedBy: stored?.updated_by ?? null,
};
}
+314
View File
@@ -0,0 +1,314 @@
import { ActivityType } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
addBotStatus as addBotStatusRow,
clearBotStatuses,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus as removeBotStatusRow,
setBotStatusEnabled,
} from '../../database/repositories/bot-status-repository.js';
import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
const log = createLogger('status');
/** Discord caps an activity name at 128 characters. */
export const STATUS_TEXT_MAX = 128;
/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */
export const STATUS_MAX = 25;
export const ROTATION_MIN_SECONDS = 5;
export const ROTATION_MAX_SECONDS = 86_400;
/** Key of the rotation delay, stored per guild like the other settings (M15). */
export const ROTATION_KEY = 'bot.status.interval';
/** Shown while the list is empty, so the bot never displays nothing useful. */
export const FALLBACK_STATUS = Object.freeze({
id: null,
text: 'les commandes avec /help',
type: 'watching',
});
/**
* Accepted activity types. Discord writes the verb itself, so only the label used in the
* embeds lives here; `streaming` is the one type that requires a link.
*/
export const STATUS_TYPES = Object.freeze({
playing: { label: 'joue à', activity: ActivityType.Playing },
streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true },
listening: { label: 'écoute', activity: ActivityType.Listening },
watching: { label: 'regarde', activity: ActivityType.Watching },
competing: { label: 'participe à', activity: ActivityType.Competing },
});
/** Choice list for the slash command. */
export const STATUS_TYPE_CHOICES = Object.freeze(
Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })),
);
/** Strips control characters without a control-character regex, then collapses the spaces. */
const clean = (value) =>
[...String(value ?? '')]
.map((char) => {
const code = char.codePointAt(0);
return code <= 31 || code === 127 ? ' ' : char;
})
.join('')
.replace(/\s+/g, ' ')
.trim();
export function sanitizeStatusText(value) {
const text = clean(value);
if (!text) {
throw new UserFacingError(
'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».',
);
}
if (text.length > STATUS_TEXT_MAX) {
throw new UserFacingError(
`Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`,
);
}
return text;
}
export function normalizeStatusType(value) {
const key = String(value ?? 'watching')
.toLowerCase()
.trim();
if (!STATUS_TYPES[key]) {
throw new UserFacingError(
`Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`,
);
}
return key;
}
/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */
export function validateStatusUrl(value, typeKey) {
const url = String(value ?? '').trim();
if (STATUS_TYPES[typeKey]?.needsUrl && !url) {
throw new UserFacingError(
'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.',
);
}
if (!url) return null;
if (!/^https?:\/\/\S+$/i.test(url)) {
throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.');
}
return url;
}
/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */
export function formatSeconds(seconds) {
const value = Math.max(0, Math.round(Number(seconds) || 0));
if (value < 60) return `${value} s`;
const minutes = Math.round(value / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
}
/** Delay used when neither the database nor the environment gives a usable value. */
const FALLBACK_ROTATION_SECONDS = 60;
/** The environment default, ignored when it is out of range rather than applied blindly. */
const envRotationSeconds = () => {
const value = Number(env.bot.statusIntervalSeconds);
return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS
? value
: FALLBACK_ROTATION_SECONDS;
};
export function clampRotation(value, { strict = false } = {}) {
const seconds = Number(value);
if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) {
if (strict) {
throw new UserFacingError(
`Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`,
);
}
return envRotationSeconds();
}
return seconds;
}
/** Rotation delay, overridable from Discord; the environment provides the default (M15). */
export function getRotationSeconds(guildId = env.discord.guildId) {
return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds));
}
export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) {
const value = clampRotation(seconds, { strict: true });
setSetting(guildId, ROTATION_KEY, value, updatedBy);
return value;
}
/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) {
const statusText = sanitizeStatusText(text);
const typeKey = normalizeStatusType(type);
const statusUrl = validateStatusUrl(url, typeKey);
if (countBotStatuses() >= STATUS_MAX) {
throw new UserFacingError(
`La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`,
);
}
let status;
try {
status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy });
} catch (error) {
if (!/UNIQUE constraint/i.test(String(error?.message))) throw error;
log.debug('Duplicate status refused', error);
throw new UserFacingError(
`« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`,
);
}
logEvent({
guildId: env.discord.guildId,
type: 'bot.status.added',
actorId: createdBy,
payload: { id: status.id },
});
return status;
}
export function removeBotStatus(id) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
removeBotStatusRow(id);
logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } });
return status;
}
export function toggleBotStatus(id, enabled) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
if (Boolean(status.enabled) === enabled) {
throw new UserFacingError(
enabled
? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.`
: `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`,
);
}
setBotStatusEnabled(id, enabled);
return { ...status, enabled: enabled ? 1 : 0 };
}
/** Empties the list; the fallback status takes over immediately. */
export function clearBotStatusList() {
const removed = clearBotStatuses();
logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } });
return removed;
}
/**
* Next status of the rotation: the enabled ones in insertion order, one after the other.
* Returns `null` when nothing is enabled, so the caller falls back to a default line.
*/
export function selectNextStatus(statuses, lastId = null) {
if (statuses.length === 0) return null;
const index = statuses.findIndex((status) => status.id === lastId);
return statuses[(index + 1) % statuses.length];
}
/** Shows one status in Discord. */
export function applyBotStatus(client, status = FALLBACK_STATUS) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const activity = { name: status.text, type: type.activity };
if (type.needsUrl && status.url) activity.url = status.url;
client.user.setPresence({ status: 'online', activities: [activity] });
return activity;
}
/** Applies the only enabled status right away, so an addition shows up immediately. */
export function applyStatusIfAlone(client) {
const statuses = listEnabledBotStatuses();
if (statuses.length !== 1) return null;
applyBotStatus(client, statuses[0]);
return statuses[0];
}
/** Shows the next status and returns it; used by the rotation and by the tests. */
export function rotateBotStatus(client, lastId = null) {
const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS;
applyBotStatus(client, status);
return status;
}
/**
* Rotates the statuses forever. The delay is read again on every turn, so `/status interval`
* takes effect without restarting the bot (M15).
*/
export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) {
let lastId = null;
let timer = null;
const tick = () => {
try {
lastId = rotateBotStatus(client, lastId)?.id ?? null;
} catch (error) {
log.warn('Could not rotate the bot status', error);
}
timer = setTimeout(tick, getRotationSeconds(guildId) * 1000);
timer.unref?.();
};
tick();
return { stop: () => clearTimeout(timer) };
}
function describeStatus(status) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const link = type.needsUrl && status.url ? ` · ${status.url}` : '';
return `« ${status.text} » — ${type.label}${link}`;
}
/** The list shown by `/status list` (M15). */
export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) {
const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot');
if (statuses.length === 0) {
return embed.setDescription(
`Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`,
);
}
const active = statuses.filter((status) => status.enabled).length;
embed.setDescription(
`${bullets([
`**${statuses.length}** statut(s), dont **${active}** en rotation`,
`changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`,
'la rotation suit l’ordre d’ajout et saute les statuts en pause',
])}`,
);
embed.addFields(
statuses.map((status) => ({
name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`,
value: describeStatus(status),
})),
);
return embed;
}
/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */
export function statusAddedEmbed(status, { applied = false } = {}) {
const next = applied
? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.'
: 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.';
return successEmbed(
`C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`,
).setTitle('✅ Statut ajouté');
}
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more