Compare commits

..
18 Commits
Author SHA1 Message Date
asepharyana 5fe57c63d9 ci: fix Nix GC cleanup job SSH key secret for Booster-role 2026-08-04 14:04:44 +07:00
asepharyana 240fd76fc8 ci: add Nix GC cleanup job on VPS after deploy 2026-08-04 13:57:58 +07:00
aseph 54bda6a539 ci: use free GHA Nix cache (disable FlakeHub cache, not subscribed) 2026-08-03 16:44:24 +07:00
asepharyana 0c1f1a5ae6 ci: enable FlakeHub Cache (bump cache action + use-flakehub) 2026-08-03 16:22:09 +07:00
asepharyana d20c5f392c ci: add test gate before Nix deploy (bun test + typecheck) 2026-08-03 13:37:28 +07:00
asepharyana 630a85963d chore: sync DB to imrnes pgbouncer pool 6432 2026-08-02 16:11:35 +07:00
asepharyana e1b84112b6 fix(nix): restrict flake to x86_64-linux (nixpkgs 26.11 dropped darwin) 2026-08-01 18:03:52 +07:00
asepharyana 5f9a7801d3 ci: publish flake to FlakeHub (rolling) 2026-08-01 17:58:47 +07:00
asepharyana e78dd0d833 ci: migrate deploy to Nix (flake + systemd via GitHub Actions)
Build & Deploy (Nix) / build-and-deploy (push) Canceled after 0s
2026-07-31 13:33:03 +07:00
asepharyana f9a35ee230 Fix booster role metadata updates 2026-07-09 01:29:56 +07:00
asepharyana 0eec0affbe fix(index): adjust comment formatting for clarity 2026-07-08 23:20:04 +07:00
asepharyana ec9f27ee26 fix(ci): use deployment environment secrets 2026-07-08 03:12:54 +07:00
MythEclipseandClaude Opus 4.8 016eddcce7 fix(dockerfile): prevent crash loop when migration fails
Change && to ; so the bot still starts even if db:migrate exits
with a non-zero code. Migration errors are logged but don't block
the main process.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 19:12:29 +07:00
MythEclipseandClaude Opus 4.8 03c5f73891 fix(dockerfile): run db migration before bot startup
Adds auto-migration step to fix missing color2 column.
Also adds drizzle.config.ts and db migration files to image.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 19:01:23 +07:00
MythEclipse 8ff46104f1 feat(boost-greeting): implement randomized greeting messages
Introduce a collection of greeting templates to provide variety when
a user boosts the server. The system now selects a random message
from the available variants and logs the selected variant index.
2026-06-06 03:39:25 +07:00
MythEclipse 97442265ba test(boost-greeting): update greeting message to Indonesian
Update the boost greeting message and its corresponding test assertions
to use Indonesian instead of English.
2026-06-06 03:38:37 +07:00
MythEclipse b2cd402adc ``` 2026-06-06 03:31:36 +07:00
MythEclipse 9c193c3530 feat(boost-greeting): integrate greeting into guild member update and clean up handler 2026-06-06 03:30:16 +07:00
18 changed files with 387 additions and 142 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
DISCORD_TOKEN= DISCORD_TOKEN=
DISCORD_CLIENT_ID= DISCORD_CLIENT_ID=
DISCORD_GUILD_ID= DISCORD_GUILD_ID=
DATABASE_URL=postgresql://booster_role:booster_role@localhost:5432/booster_role DATABASE_URL=postgresql://asephs:***@100.121.180.82:6432/boost
BOOSTER_ROLE_ANCHOR_ROLE_ID= BOOSTER_ROLE_ANCHOR_ROLE_ID=
BOOSTER_ELIGIBILITY_ROLE_ID=1206431347925852162 BOOSTER_ELIGIBILITY_ROLE_ID=1206431347925852162
BOOSTER_GREETING_CHANNEL_ID= BOOSTER_GREETING_CHANNEL_ID=
+83 -83
View File
@@ -1,112 +1,112 @@
name: Deploy name: Build & Deploy (Nix)
on: on:
push: push:
branches: branches: [main]
- main
workflow_dispatch: workflow_dispatch:
concurrency:
group: booster-role-deploy
cancel-in-progress: false
permissions: permissions:
contents: read contents: read
packages: write id-token: write
concurrency:
group: deploy-production
cancel-in-progress: true
env:
IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/booster-role
jobs: jobs:
deploy: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - uses: actions/checkout@v4
uses: actions/checkout@v4
- name: Set up Bun - uses: oven-sh/setup-bun@v2
uses: oven-sh/setup-bun@v2
with: with:
bun-version: latest bun-version: latest
- name: Install dependencies - name: Install deps
run: bun install run: bun install --frozen-lockfile
- name: Type check - name: Typecheck
run: bun run typecheck run: bun run typecheck
- name: Run tests - name: Test
run: bun test run: bun test
- name: Lint build-and-deploy:
run: bun run lint needs: test
runs-on: ubuntu-latest
environment: orangevps
- name: Set lowercase image name steps:
run: echo "IMAGE_NAME=${IMAGE_NAME,,}" >> "$GITHUB_ENV" - uses: actions/checkout@v4
- name: Log in to GHCR - uses: DeterminateSystems/nix-installer-action@v16
uses: docker/login-action@v3
with: with:
registry: ghcr.io determinate: false
username: ${{ github.actor }} extra-conf: |
password: ${{ secrets.GITHUB_TOKEN }} sandbox = false
accept-flake-config = true
- name: Build and push image - uses: DeterminateSystems/magic-nix-cache-action@v14
uses: docker/build-push-action@v6
with: with:
context: . use-flakehub: false
push: true
tags: |
${{ env.IMAGE_NAME }}:latest
${{ env.IMAGE_NAME }}:${{ github.sha }}
- name: Deploy on VPS - name: Build & Deploy
uses: appleboy/ssh-action@v1.2.0
env: env:
IMAGE_NAME: ${{ env.IMAGE_NAME }} VPS_HOST: ${{ secrets.VPS_HOST }}
GHCR_USERNAME: ${{ github.actor }} VPS_USER: ${{ secrets.VPS_USER }}
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }} run: |
DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} set -eu
DISCORD_GUILD_ID: ${{ secrets.DISCORD_GUILD_ID }} STORE_PATH=$(nix build . --impure --option sandbox false --no-link --print-out-paths | tail -1)
DATABASE_URL: ${{ secrets.DATABASE_URL }} echo "Store path: $STORE_PATH"
BOOSTER_ROLE_ANCHOR_ROLE_ID: ${{ secrets.BOOSTER_ROLE_ANCHOR_ROLE_ID }}
BOOSTER_ELIGIBILITY_ROLE_ID: ${{ secrets.BOOSTER_ELIGIBILITY_ROLE_ID }} key_file=$(mktemp /tmp/deploy-key.XXXXXX)
BOOSTER_GREETING_CHANNEL_ID: ${{ secrets.BOOSTER_GREETING_CHANNEL_ID }} printf '%s\n' "$VPS_SSH_KEY" > "$key_file"
LOG_LEVEL: ${{ secrets.LOG_LEVEL }} chmod 600 "$key_file"
with: sed -i 's/\r$//' "$key_file"
host: ${{ secrets.VPS_HOST }} ssh-keygen -y -f "$key_file" >/dev/null 2>&1 || { echo "SSH key invalid"; exit 1; }
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }} export NIX_SSHOPTS="-i $key_file -o StrictHostKeyChecking=no"
envs: IMAGE_NAME,GHCR_USERNAME,GHCR_TOKEN,DISCORD_TOKEN,DISCORD_CLIENT_ID,DISCORD_GUILD_ID,DATABASE_URL,BOOSTER_ROLE_ANCHOR_ROLE_ID,BOOSTER_ELIGIBILITY_ROLE_ID,BOOSTER_GREETING_CHANNEL_ID,LOG_LEVEL nix copy --to "ssh://${VPS_USER}@${VPS_HOST}" "$STORE_PATH" 2>&1
script: |
ssh -i "$key_file" -o StrictHostKeyChecking=no "${VPS_USER}@${VPS_HOST}" "
set -eu set -eu
mkdir -p /opt/booster-role if [ -d /nix/var/nix/profiles/booster-role ] && [ ! -L /nix/var/nix/profiles/booster-role ]; then
cd /opt/booster-role rm -rf /nix/var/nix/profiles/booster-role
fi
nix-env --profile /nix/var/nix/profiles/booster-role --set $STORE_PATH
systemctl daemon-reload
systemctl enable booster-role 2>/dev/null || true
systemctl restart booster-role
for i in \$(seq 1 30); do
systemctl is-active --quiet booster-role && break
sleep 1
done
systemctl is-active booster-role || {
echo \"=== SERVICE FAILED — journal ===\"
journalctl -u booster-role -n 40 --no-pager
exit 1
}
systemctl status booster-role --no-pager 2>&1 | head -8
" 2>&1
cat > .env <<EOF cleanup:
DISCORD_TOKEN=${DISCORD_TOKEN} # Bersihkan sampah Nix di VPS SETELAH deploy: hapus generasi profile lama
DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID} # + nix store gc. Profil yang sedang dipakai tidak disentuh.
DISCORD_GUILD_ID=${DISCORD_GUILD_ID} needs: build-and-deploy
DATABASE_URL=${DATABASE_URL:?DATABASE_URL is required} if: always()
BOOSTER_ROLE_ANCHOR_ROLE_ID=${BOOSTER_ROLE_ANCHOR_ROLE_ID} runs-on: ubuntu-latest
BOOSTER_ELIGIBILITY_ROLE_ID=${BOOSTER_ELIGIBILITY_ROLE_ID:-1206431347925852162} steps:
BOOSTER_GREETING_CHANNEL_ID=${BOOSTER_GREETING_CHANNEL_ID} - name: Nix GC on VPS
LOG_LEVEL=${LOG_LEVEL:-info} env:
EOF VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
cat > docker-compose.yml <<EOF VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
services: run: |
booster-role: key_file=$(mktemp /tmp/gc-key.XXXXXX)
image: ${IMAGE_NAME}:latest printf '%s\n' "$VPS_SSH_KEY" > "$key_file"
container_name: booster-role chmod 600 "$key_file"
restart: unless-stopped sed -i 's/\r$//' "$key_file"
env_file: ssh -i "$key_file" -o StrictHostKeyChecking=no "${VPS_USER}@${VPS_HOST}" "sudo /usr/local/bin/nix-gc-vps.sh" || echo "⚠️ Nix GC gagal (non-fatal)"
- .env rm -f "$key_file"
EOF
echo "$GHCR_TOKEN" | docker login ghcr.io -u "$GHCR_USERNAME" --password-stdin
docker compose pull
docker compose up -d
docker image prune -f
@@ -0,0 +1,20 @@
name: Publish to FlakeHub
on:
push:
branches: [main, master]
workflow_dispatch:
jobs:
flakehub-publish:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v6
- uses: DeterminateSystems/determinate-nix-action@main
- uses: DeterminateSystems/flakehub-push@main
with:
visibility: public
rolling: true
+5 -1
View File
@@ -10,4 +10,8 @@ COPY src ./src
ENV NODE_ENV=production ENV NODE_ENV=production
CMD ["bun", "run", "src/index.ts"] COPY src/db ./src/db
COPY drizzle.config.ts ./
RUN bun add -d drizzle-kit
CMD ["sh", "-c", "bun run db:migrate; bun run src/index.ts"]
+2 -2
View File
@@ -30,7 +30,7 @@ Isi `.env`:
DISCORD_TOKEN=token_bot_discord DISCORD_TOKEN=token_bot_discord
DISCORD_CLIENT_ID=client_id_aplikasi_discord DISCORD_CLIENT_ID=client_id_aplikasi_discord
DISCORD_GUILD_ID=id_server_discord DISCORD_GUILD_ID=id_server_discord
DATABASE_URL=postgresql://booster_role:booster_role@localhost:5432/booster_role DATABASE_URL=postgresql://asephs:***@100.121.180.82:6432/boost
BOOSTER_ROLE_ANCHOR_ROLE_ID=id_role_pembatas_opsional BOOSTER_ROLE_ANCHOR_ROLE_ID=id_role_pembatas_opsional
BOOSTER_ELIGIBILITY_ROLE_ID=1206431347925852162 BOOSTER_ELIGIBILITY_ROLE_ID=1206431347925852162
LOG_LEVEL=info LOG_LEVEL=info
@@ -47,7 +47,7 @@ bun run db:generate
bun run db:migrate bun run db:migrate
``` ```
Pastikan `DATABASE_URL` mengarah ke database PostgreSQL external sebelum menjalankan migration. Pastikan `DATABASE_URL` mengarah ke database PostgreSQL external (pool PgBouncer imrnes `100.121.180.82:6432`) sebelum menjalankan migration.
## Menjalankan bot ## Menjalankan bot
+1 -1
View File
@@ -5,6 +5,6 @@ export default defineConfig({
out: "./src/db/migrations", out: "./src/db/migrations",
dialect: "postgresql", dialect: "postgresql",
dbCredentials: { dbCredentials: {
url: process.env.DATABASE_URL ?? "postgresql://booster_role:booster_role@localhost:5432/booster_role" url: process.env.DATABASE_URL ?? "postgresql://asephs:***@100.121.180.82:6432/boost"
} }
}); });
Generated
+61
View File
@@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1785301185,
"narHash": "sha256-eoS3KQTO0aPWXZvIaRbRAzSSHW3l5wdMFXtT1ISfoKA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9bc02893134c733dd85de46ee4fb2fac696b5529",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+49
View File
@@ -0,0 +1,49 @@
{
description = "Booster Role Discord Bot (Nix build)";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachSystem [ "x86_64-linux" ] (system:
let
pkgs = import nixpkgs { inherit system; };
in
{
packages.default = pkgs.stdenvNoCC.mkDerivation {
pname = "booster-role";
version = "0.1.0";
src = ./.;
nativeBuildInputs = [ pkgs.bun ];
buildPhase = ''
export HOME="$TMPDIR"
bun install --frozen-lockfile
bun run typecheck
bun test
'';
installPhase = ''
mkdir -p $out/bin $out/lib/booster-role
cp -r package.json bun.lock tsconfig.json drizzle.config.ts $out/lib/booster-role/
cp -r src $out/lib/booster-role/src
cp -r node_modules $out/lib/booster-role/node_modules
cat > $out/bin/booster-role << WRAPPER
#!${pkgs.runtimeShell}
cd $out/lib/booster-role
export NODE_ENV=production
${pkgs.bun}/bin/bun run db:migrate
exec ${pkgs.bun}/bin/bun run src/index.ts
WRAPPER
chmod +x $out/bin/booster-role
'';
};
devShells.default = pkgs.mkShell {
buildInputs = [ pkgs.bun ];
};
});
}
+1 -1
View File
@@ -14,7 +14,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
discordToken: requireEnv(env, "DISCORD_TOKEN"), discordToken: requireEnv(env, "DISCORD_TOKEN"),
discordClientId: requireEnv(env, "DISCORD_CLIENT_ID"), discordClientId: requireEnv(env, "DISCORD_CLIENT_ID"),
discordGuildId: requireEnv(env, "DISCORD_GUILD_ID"), discordGuildId: requireEnv(env, "DISCORD_GUILD_ID"),
databaseUrl: env.DATABASE_URL ?? "postgresql://booster_role:booster_role@localhost:5432/booster_role", databaseUrl: env.DATABASE_URL ?? "postgresql://asephs:***@100.121.180.82:6432/boost",
boosterRoleAnchorRoleId: env.BOOSTER_ROLE_ANCHOR_ROLE_ID ?? null, boosterRoleAnchorRoleId: env.BOOSTER_ROLE_ANCHOR_ROLE_ID ?? null,
boosterEligibilityRoleId: env.BOOSTER_ELIGIBILITY_ROLE_ID ?? "1206431347925852162", boosterEligibilityRoleId: env.BOOSTER_ELIGIBILITY_ROLE_ID ?? "1206431347925852162",
boostCleanupIntervalMs: Number(env.BOOST_CLEANUP_INTERVAL_MS) || 5 * 60 * 1000, boostCleanupIntervalMs: Number(env.BOOST_CLEANUP_INTERVAL_MS) || 5 * 60 * 1000,
+18 -1
View File
@@ -1,10 +1,12 @@
import type { Client } from "discord.js"; import type { Client } from "discord.js";
import type { AppConfig } from "../config"; import type { AppConfig } from "../config";
import { createDb } from "../db"; import { createDb } from "../db";
import { logger } from "../logger";
import { BoosterRoleService } from "../services/boosterRoleService"; import { BoosterRoleService } from "../services/boosterRoleService";
import { DrizzleBoosterRoleStore } from "../services/drizzleBoosterRoleStore"; import { DrizzleBoosterRoleStore } from "../services/drizzleBoosterRoleStore";
import { DiscordRoleRepository } from "../services/discordRoleRepository"; import { DiscordRoleRepository } from "../services/discordRoleRepository";
import { handleGuildMemberUpdate } from "./events/guildMemberUpdate"; import { handleGuildMemberUpdate } from "./events/guildMemberUpdate";
import { sendBoostGreeting } from "./events/boostGreeting";
import { handleInteraction } from "./interactionHandler"; import { handleInteraction } from "./interactionHandler";
export function attachBotHandlers(client: Client, config: AppConfig): void { export function attachBotHandlers(client: Client, config: AppConfig): void {
@@ -26,13 +28,28 @@ export function attachBotHandlers(client: Client, config: AppConfig): void {
}); });
client.on("guildMemberUpdate", async (oldMember, newMember) => { client.on("guildMemberUpdate", async (oldMember, newMember) => {
const eligibilityRoleId = config.boosterEligibilityRoleId;
// Detect boost gain: member just acquired the booster eligibility role
const hadBooster = oldMember.roles.cache.has(eligibilityRoleId);
const hasBooster = newMember.roles.cache.has(eligibilityRoleId);
if (!hadBooster && hasBooster && config.boosterGreetingChannelId) {
const channel = newMember.guild.channels.cache.get(config.boosterGreetingChannelId);
if (channel && "send" in channel) {
await sendBoostGreeting(channel as { send(input: { content: string }): Promise<unknown> }, newMember.id, config.boosterGreetingChannelId).catch((err) => {
logger.error("Failed to send boost greeting", { error: String(err), userId: newMember.id });
});
}
}
// Handle boost loss (existing behaviour)
const service = new BoosterRoleService( const service = new BoosterRoleService(
store, store,
new DiscordRoleRepository(newMember.guild), new DiscordRoleRepository(newMember.guild),
{ anchorPosition: resolveAnchorPosition(newMember.guild, config.boosterRoleAnchorRoleId) } { anchorPosition: resolveAnchorPosition(newMember.guild, config.boosterRoleAnchorRoleId) }
); );
await handleGuildMemberUpdate(oldMember, newMember, service, config.boosterEligibilityRoleId); await handleGuildMemberUpdate(oldMember, newMember, service, eligibilityRoleId);
}); });
} }
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, test } from "bun:test";
import { sendBoostGreeting } from "./boostGreeting";
describe("sendBoostGreeting", () => {
test("sends boost greeting to the given channel", async () => {
const sent: string[] = [];
const channel = {
send: async (input: { content: string }): Promise<void> => {
sent.push(input.content);
},
};
await sendBoostGreeting(channel, "user-123", "channel-456");
expect(sent.length).toBe(1);
expect(sent[0]).toContain("<@user-123>");
expect(sent[0]).toContain("/booster-role claim");
expect(sent[0]).toContain("di sini");
});
test("handles different user and channel IDs", async () => {
const sent: string[] = [];
const channel = {
send: async (input: { content: string }): Promise<void> => {
sent.push(input.content);
},
};
await sendBoostGreeting(channel, "other-user", "other-channel");
expect(sent[0]).toContain("<@other-user>");
expect(sent[0]).toContain("di sini");
});
});
+20 -49
View File
@@ -1,60 +1,31 @@
import { logger } from "../../logger"; import { logger } from "../../logger";
type GuildTextChannel = { const greetings = [
send(input: { content: string }): Promise<unknown>; (userId: string) =>
}; `🎉 Makasih udah ngeboost <@${userId}>! Sekarang kamu bisa claim custom role pake \`/booster-role claim\` di sini.`,
(userId: string) =>
type GuildMember = { `🔥 <@${userId}> baru aja ngeboost! Langsung aja claim custom role kamu pake \`/booster-role claim\` di sini.`,
id: string; (userId: string) =>
guild: { `✨ Thank you <@${userId}> for the boost! Claim custom role kamu pake \`/booster-role claim\` di sini ya.`,
id: string; (userId: string) =>
channels: { `👑 <@${userId}> ngeboost server! Yuk langsung claim custom role pake \`/booster-role claim\` di sini.`,
cache: { (userId: string) =>
get(channelId: string): GuildTextChannel | undefined; `🎊 Ada booster baru nih, <@${userId}>! Jangan lupa claim custom role kamu pake \`/booster-role claim\` di sini.`,
}; ];
};
};
user?: { id: string };
};
/** /**
* Sends a welcome message to the configured greeting channel when a member * Sends a random welcome message via the given channel when a member newly
* newly acquires the booster eligibility role (i.e. just boosted the server). * acquires the booster eligibility role (i.e. just boosted the server).
*
* Only fires on a *gain* transition (hadBoosterRole = false → hasBoosterRole = true).
*/
export function handleBoostGreeting(
oldMember: GuildMember,
newMember: GuildMember,
greetingChannelId: string | null,
): void {
if (!greetingChannelId) return;
const hadBoosterRole = oldMember.roles.cache.has(/** @type {any} */ (null) as any);
// Actually detect the gain: we need the actual role ID. The caller should pass it.
}
/**
* Sends a welcome message when a member newly acquires the booster eligibility role.
* Must be called with the booster eligibility role ID to check correctly.
*/ */
export async function sendBoostGreeting( export async function sendBoostGreeting(
member: { id: string; guild: { id: string; channels: { cache: { get(channelId: string): { send(input: { content: string }): Promise<unknown> } | undefined } } } }, channel: { send(input: { content: string }): Promise<unknown> },
userId: string,
greetingChannelId: string, greetingChannelId: string,
): Promise<void> { ): Promise<void> {
const channel = member.guild.channels.cache.get(greetingChannelId); const pick = Math.floor(Math.random() * greetings.length);
if (!channel) { const message = greetings[pick](userId);
logger.warn("Boost greeting channel not found", { channelId: greetingChannelId, guildId: member.guild.id });
return;
}
await channel.send({ await channel.send({ content: message });
content: `🎉 Thank you for boosting <@${member.user?.id ?? member.id}>! You can now claim a custom role using \`/booster-role claim\` in <#${greetingChannelId}>.`
});
logger.info("Boost greeting sent", { logger.info("Boost greeting sent", { userId, channelId: greetingChannelId, variant: pick });
userId: member.user?.id ?? member.id,
guildId: member.guild.id,
channelId: greetingChannelId,
});
} }
+8 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { startBoostCleanup } from "./boostCleanupService"; import { startBoostCleanup } from "./boostCleanupService";
import type { BoosterRoleRecord } from "./drizzleBoosterRoleStore"; import type { BoosterRoleRecord, BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
import type { RoleRepository } from "./discordRoleRepository"; import type { RoleRepository } from "./discordRoleRepository";
class MemoryStore { class MemoryStore {
@@ -18,6 +18,13 @@ class MemoryStore {
this.records.set(`${record.guildId}:${record.userId}`, record); this.records.set(`${record.guildId}:${record.userId}`, record);
} }
async update(guildId: string, userId: string, changes: BoosterRoleUpdate) {
const key = `${guildId}:${userId}`;
const record = this.records.get(key);
if (!record) return;
this.records.set(key, { ...record, ...changes });
}
async delete(guildId: string, userId: string) { async delete(guildId: string, userId: string) {
this.records.delete(`${guildId}:${userId}`); this.records.delete(`${guildId}:${userId}`);
} }
+12 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { BoosterRoleService } from "./boosterRoleService"; import { BoosterRoleService } from "./boosterRoleService";
import type { BoosterRoleRecord } from "./drizzleBoosterRoleStore"; import type { BoosterRoleRecord, BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
import type { RoleRepository } from "./discordRoleRepository"; import type { RoleRepository } from "./discordRoleRepository";
class MemoryRoleStore { class MemoryRoleStore {
@@ -18,6 +18,13 @@ class MemoryRoleStore {
this.records.set(`${record.guildId}:${record.userId}`, record); this.records.set(`${record.guildId}:${record.userId}`, record);
} }
async update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void> {
const key = `${guildId}:${userId}`;
const record = this.records.get(key);
if (!record) return;
this.records.set(key, { ...record, ...changes });
}
async delete(guildId: string, userId: string): Promise<void> { async delete(guildId: string, userId: string): Promise<void> {
this.records.delete(`${guildId}:${userId}`); this.records.delete(`${guildId}:${userId}`);
} }
@@ -115,6 +122,7 @@ describe("BoosterRoleService", () => {
await service.renameRole({ guildId: "guild", userId: "user", name: "Renamed" }); await service.renameRole({ guildId: "guild", userId: "user", name: "Renamed" });
expect(roles.roles.get(claimed.roleId)?.name).toBe("Renamed"); expect(roles.roles.get(claimed.roleId)?.name).toBe("Renamed");
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ name: "Renamed" }));
await expect(service.renameRole({ guildId: "guild", userId: "attacker", name: "Stolen" })).rejects.toThrow("No booster role found"); await expect(service.renameRole({ guildId: "guild", userId: "attacker", name: "Stolen" })).rejects.toThrow("No booster role found");
}); });
@@ -127,6 +135,7 @@ describe("BoosterRoleService", () => {
await service.setRoleIcon({ guildId: "guild", userId: "user", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } }); await service.setRoleIcon({ guildId: "guild", userId: "user", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } });
expect(roles.roles.get(claimed.roleId)?.icon).toBe("data:image/png;base64,abc"); expect(roles.roles.get(claimed.roleId)?.icon).toBe("data:image/png;base64,abc");
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ icon: "data:image/png;base64,abc" }));
await expect(service.setRoleIcon({ guildId: "guild", userId: "attacker", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } })).rejects.toThrow("No booster role found"); await expect(service.setRoleIcon({ guildId: "guild", userId: "attacker", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } })).rejects.toThrow("No booster role found");
}); });
@@ -175,6 +184,7 @@ describe("BoosterRoleService", () => {
const updated = roles.getRole(claimed.roleId); const updated = roles.getRole(claimed.roleId);
expect(updated).not.toBeNull(); expect(updated).not.toBeNull();
expect(updated!.colors).toEqual({ primaryColor: "#FF0000" }); expect(updated!.colors).toEqual({ primaryColor: "#FF0000" });
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ color: "#FF0000", color2: null }));
// Other user cannot recolor // Other user cannot recolor
await expect(service.recolorRole({ guildId: "guild", userId: "attacker", color: "#00FF00" })).rejects.toThrow("No booster role found"); await expect(service.recolorRole({ guildId: "guild", userId: "attacker", color: "#00FF00" })).rejects.toThrow("No booster role found");
@@ -191,6 +201,7 @@ describe("BoosterRoleService", () => {
const updated = roles.getRole(claimed.roleId); const updated = roles.getRole(claimed.roleId);
expect(updated).not.toBeNull(); expect(updated).not.toBeNull();
expect(updated!.colors).toEqual({ primaryColor: "#FF0000", secondaryColor: "#0000FF" }); expect(updated!.colors).toEqual({ primaryColor: "#FF0000", secondaryColor: "#0000FF" });
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ color: "#FF0000", color2: "#0000FF" }));
}); });
test("deletes the stored role owned by the user", async () => { test("deletes the stored role owned by the user", async () => {
+3
View File
@@ -108,6 +108,7 @@ export class BoosterRoleService {
const name = validateRoleName(input.name); const name = validateRoleName(input.name);
assertRoleNameIsAvailable(name, (await this.roles.listRoles()).filter((role) => role.id !== record.roleId)); assertRoleNameIsAvailable(name, (await this.roles.listRoles()).filter((role) => role.id !== record.roleId));
await this.roles.updateRole(record.roleId, { name }); await this.roles.updateRole(record.roleId, { name });
await this.store.update(guildId, userId, { name, updatedAt: this.now() });
} }
async recolorRole(input: { guildId: string; userId: string; color: string; color2?: string | null }): Promise<void> { async recolorRole(input: { guildId: string; userId: string; color: string; color2?: string | null }): Promise<void> {
@@ -118,6 +119,7 @@ export class BoosterRoleService {
const secondaryColor = normalizeOptionalHexColor(color2 ?? null); const secondaryColor = normalizeOptionalHexColor(color2 ?? null);
const colors = resolveGradientColors(primaryColor, secondaryColor); const colors = resolveGradientColors(primaryColor, secondaryColor);
await this.roles.updateRole(record.roleId, { colors }); await this.roles.updateRole(record.roleId, { colors });
await this.store.update(guildId, userId, { color: primaryColor, color2: secondaryColor, updatedAt: this.now() });
} }
async setRoleIcon(input: { guildId: string; userId: string; icon: RoleIcon }): Promise<void> { async setRoleIcon(input: { guildId: string; userId: string; icon: RoleIcon }): Promise<void> {
@@ -126,6 +128,7 @@ export class BoosterRoleService {
assertCanManageStoredRole(this.identity(record), { guildId, userId, roleId: record.roleId }); assertCanManageStoredRole(this.identity(record), { guildId, userId, roleId: record.roleId });
this.validateRoleIcon(icon); this.validateRoleIcon(icon);
await this.roles.updateRole(record.roleId, { icon: icon.dataUri }); await this.roles.updateRole(record.roleId, { icon: icon.dataUri });
await this.store.update(guildId, userId, { icon: icon.dataUri, updatedAt: this.now() });
} }
async deleteRole(input: { guildId: string; userId: string }): Promise<void> { async deleteRole(input: { guildId: string; userId: string }): Promise<void> {
@@ -0,0 +1,53 @@
import { describe, expect, test } from "bun:test";
import { DrizzleBoosterRoleStore, type BoosterRoleRecord, type BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
class FakeDb {
rows: BoosterRoleRecord[] = [];
lastUpdate: { changes: BoosterRoleUpdate; condition: unknown } | null = null;
select() {
return {
from: () => ({
where: () => Object.assign(Promise.resolve(this.rows), {
limit: (count: number) => Promise.resolve(this.rows.slice(0, count))
})
})
};
}
insert() {
return {
values: (record: BoosterRoleRecord) => {
this.rows.push(record);
}
};
}
update() {
return {
set: (changes: BoosterRoleUpdate) => ({
where: (condition: unknown) => {
this.lastUpdate = { changes, condition };
}
})
};
}
delete() {
return {
where: () => {}
};
}
}
describe("DrizzleBoosterRoleStore", () => {
test("persists metadata updates for a stored booster role", async () => {
const db = new FakeDb();
const store = new DrizzleBoosterRoleStore(db);
await store.update("guild", "user", { name: "Renamed", color: "#AABBCC", updatedAt: 123 });
expect(db.lastUpdate?.changes).toEqual({ name: "Renamed", color: "#AABBCC", updatedAt: 123 });
expect(db.lastUpdate?.condition).toBeDefined();
});
});
+15
View File
@@ -13,10 +13,13 @@ export type BoosterRoleRecord = {
updatedAt: number; updatedAt: number;
}; };
export type BoosterRoleUpdate = Partial<Pick<BoosterRoleRecord, "name" | "color" | "color2" | "icon" | "updatedAt">>;
export type BoosterRoleStore = { export type BoosterRoleStore = {
findByUser(guildId: string, userId: string): Promise<BoosterRoleRecord | null>; findByUser(guildId: string, userId: string): Promise<BoosterRoleRecord | null>;
findByGuild(guildId: string): Promise<BoosterRoleRecord[]>; findByGuild(guildId: string): Promise<BoosterRoleRecord[]>;
create(record: BoosterRoleRecord): Promise<void>; create(record: BoosterRoleRecord): Promise<void>;
update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void>;
delete(guildId: string, userId: string): Promise<void>; delete(guildId: string, userId: string): Promise<void>;
}; };
@@ -35,6 +38,11 @@ type DatabaseLike = {
insert(table: typeof boosterRoles): { insert(table: typeof boosterRoles): {
values(record: BoosterRoleRecord): Promise<unknown> | unknown; values(record: BoosterRoleRecord): Promise<unknown> | unknown;
}; };
update(table: typeof boosterRoles): {
set(changes: BoosterRoleUpdate): {
where(condition: unknown): Promise<unknown> | unknown;
};
};
delete(table: typeof boosterRoles): { delete(table: typeof boosterRoles): {
where(condition: unknown): Promise<unknown> | unknown; where(condition: unknown): Promise<unknown> | unknown;
}; };
@@ -64,6 +72,13 @@ export class DrizzleBoosterRoleStore implements BoosterRoleStore {
await this.db.insert(boosterRoles).values(record); await this.db.insert(boosterRoles).values(record);
} }
async update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void> {
await this.db
.update(boosterRoles)
.set(changes)
.where(and(eq(boosterRoles.guildId, guildId), eq(boosterRoles.userId, userId)));
}
async delete(guildId: string, userId: string): Promise<void> { async delete(guildId: string, userId: string): Promise<void> {
await this.db await this.db
.delete(boosterRoles) .delete(boosterRoles)