Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ DB_NAME=your_db_name_here
# wondering where the data went.
DATABASE_URL=

# ─── GitHub Sponsors role (features.sponsor in config.jsonc) ────────────────
#
# Two secrets shared with the shop that checks the sponsorships. Each must be at
# least 32 characters and EXACTLY the same as on the shop's side. Generate one
# with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
#
# SPONSOR_LINK_SECRET signs the personal link a member gets from the verify
# button. SPONSOR_SYNC_SECRET is sent as a bearer token when the bot fetches the
# shop's list of current sponsors. Use two different values.
#
# Leave both empty unless you switch the feature on. If one is missing or too
# short, the feature stays off and says so at startup.
SPONSOR_LINK_SECRET=
SPONSOR_SYNC_SECRET=

# ─── Web dashboard ───────────────────────────────────────────────────────────
#
# Started with `npm run dashboard`, which runs the bot as a CHILD process and
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ DB_NAME=es_extended
| `/send_message` | Sends a custom message to any channel via modal | ✅ Manager / Founder |
| `/send_embed` | Sends a fully customizable embed to any channel | ✅ Manager / Founder |
| `/backup_database` | Creates a MySQL database backup and uploads it to the log channel | ✅ Founder |
| `/sponsor post` | Posts the GitHub Sponsors panel with the verify button | ✅ Manager / Founder |
| `/sponsor sync [force]` | Runs the sponsor role sync now; `force` overrides the removal brake once | ✅ Manager / Founder |
| `/ping` | Shows bot latency and API response time | — |
| `/userinfo` | Shows info and minigame points for a user | — |
| `/clear` | Bulk-deletes up to 100 messages | ✅ Team |
Expand All @@ -200,6 +202,20 @@ DB_NAME=es_extended
- `🎁 Giveaway Notify` — toggles the Giveaway notification role
- `⏰ Garage / Handcuffs / Storage / Vehicle Keys` — toggles script update notification roles

**GitHub Sponsors role** (off by default, `features.sponsor` in `config/config.jsonc`):
a shop links a member's GitHub account, checks the sponsorship and grants the
role. The panel's `Verify` button gives the member a personal link into the
shop, signed with `SPONSOR_LINK_SECRET` and valid for 15 minutes. Once a minute
after startup and then daily at `syncHour` (server time), the bot fetches the
shop's sponsor list with `SPONSOR_SYNC_SECRET` and adds or removes the role to
match. If the list cannot be fetched or read, no role is changed. If it would
take the role from more than half of the current holders and at least three
members, the removals are held back (additions still happen) until somebody runs
`/sponsor sync force:true`. Settings:
`enabled`, `role` (default `sponsor` from the `roles` block), `shopBaseUrl`
(https), `sponsorsUrl` (the panel's link button), `syncHour`. Both secrets go in
`.env`, at least 32 characters each and identical to the shop's.

### Events Bot

**Guild logging** — All events are posted as colored embeds to the configured log channel:
Expand Down Expand Up @@ -308,6 +324,7 @@ discord_multibot/
├── core/
│ ├── config.js ← Environment config
│ ├── utils.js ← Shared helpers (makeEmbed, readJson, …)
│ ├── sponsor.js ← GitHub Sponsors: link token, sponsor list, daily role sync
│ └── pointsManager.js ← Points read/write + reward notifications
├── data/
│ ├── points.json ← Persistent user points (auto-created)
Expand All @@ -319,6 +336,7 @@ discord_multibot/
│ └── commands/
│ ├── community.js ← /information, /rules, /roles
│ ├── admin.js ← /backup_database, /send_message, /send_embed
│ ├── sponsor.js ← /sponsor post, /sponsor sync
│ ├── support.js ← /script_guides
│ ├── orders.js ← /donation, /order_terms, /order_price
│ ├── utility.js ← /ping, /userinfo, /clear
Expand Down
19 changes: 19 additions & 0 deletions README_DE.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ DB_NAME=es_extended
| `/send_message` | Sendet eine benutzerdefinierte Nachricht per Modal | ✅ Manager / Founder |
| `/send_embed` | Sendet ein vollständig anpassbares Embed per Modal | ✅ Manager / Founder |
| `/backup_database` | Erstellt ein MySQL-Datenbank-Backup und lädt es in den Log-Channel hoch | ✅ Founder |
| `/sponsor post` | Sendet das GitHub-Sponsors-Panel mit dem Verifizieren-Button | ✅ Manager / Founder |
| `/sponsor sync [force]` | Gleicht die Sponsor-Rolle sofort ab; `force` setzt die Bremse für diesen Lauf außer Kraft | ✅ Manager / Founder |
| `/ping` | Zeigt Bot-Latenz und API-Antwortzeit | — |
| `/userinfo` | Zeigt Infos und Minigame-Punkte eines Benutzers | — |
| `/clear` | Löscht bis zu 100 Nachrichten auf einmal | ✅ Team |
Expand All @@ -201,6 +203,21 @@ DB_NAME=es_extended
- `🎁 Giveaway Notify` — schaltet die Giveaway-Benachrichtigungsrolle um
- `⏰ Garage / Handcuffs / Storage / Vehicle Keys` — schaltet Script-Update-Rollen um

**GitHub-Sponsors-Rolle** (standardmäßig aus, `features.sponsor` in `config/config.jsonc`):
Ein Shop verknüpft den GitHub-Account eines Mitglieds, prüft das Sponsoring und
vergibt die Rolle. Der Button `Verifizieren` im Panel gibt dem Mitglied einen
persönlichen Link in den Shop, signiert mit `SPONSOR_LINK_SECRET` und 15 Minuten
gültig. Eine Minute nach dem Start und danach täglich zur Stunde `syncHour`
(Serverzeit) holt der Bot mit `SPONSOR_SYNC_SECRET` die Sponsorenliste des Shops
und vergibt oder entzieht die Rolle passend dazu. Lässt sich die Liste nicht
abrufen oder lesen, wird keine Rolle geändert. Würde sie mehr als der Hälfte
der aktuellen Inhaber und mindestens drei Mitgliedern die Rolle entziehen, hält
der Bot das Entfernen zurück (Hinzufügen läuft weiter), bis jemand
`/sponsor sync force:true` ausführt. Einstellungen: `enabled`, `role`
(Standard `sponsor` aus dem Block `roles`), `shopBaseUrl` (https), `sponsorsUrl`
(der Link-Button im Panel), `syncHour`. Beide Secrets stehen in der `.env`, je
mindestens 32 Zeichen lang und gleich wie im Shop.

### Events Bot

**Guild-Logging** — Alle Events werden als farbige Embeds in den konfigurierten Log-Channel gepostet:
Expand Down Expand Up @@ -311,6 +328,7 @@ discord_multibot/
├── core/
│ ├── config.js ← Umgebungskonfiguration
│ ├── utils.js ← Gemeinsame Helfer (makeEmbed, readJson, …)
│ ├── sponsor.js ← GitHub Sponsors: Link-Token, Sponsorenliste, täglicher Rollenabgleich
│ └── pointsManager.js ← Punkte lesen/schreiben + Reward-Benachrichtigungen
├── data/
│ ├── points.json ← Persistente Benutzerpunkte (wird automatisch erstellt)
Expand All @@ -322,6 +340,7 @@ discord_multibot/
│ └── commands/
│ ├── community.js ← /information, /rules, /roles
│ ├── admin.js ← /backup_database, /send_message, /send_embed
│ ├── sponsor.js ← /sponsor post, /sponsor sync
│ ├── support.js ← /script_guides
│ ├── orders.js ← /donation, /order_terms, /order_price
│ ├── utility.js ← /ping, /userinfo, /clear
Expand Down
37 changes: 37 additions & 0 deletions bots/commands/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const { join } = require('path');
const { enabled } = require('../../core/commandKit');
const { t } = require('../../core/i18n');
const config = require('../../core/config');
const sponsor = require('../../core/sponsor');

const intents = [
GatewayIntentBits.Guilds,
Expand Down Expand Up @@ -45,6 +46,9 @@ function attach(client, registry) {
client.once(Events.ClientReady, () => {
console.log(`[Commands Bot] Ready as ${client.user.tag} - ${commands.size} commands loaded`
+ (skipped.length ? `, ${skipped.length} off (${skipped.join(', ')})` : '') + '.');
// The daily GitHub Sponsors role sync. Does nothing while the feature is
// off, and warns once when it is on but not configured.
sponsor.startSponsorSync(client);
});

client.on(Events.InteractionCreate, async interaction => {
Expand Down Expand Up @@ -109,6 +113,9 @@ async function handlePersistentButton(interaction) {
// and never takes it away.
if (customId === 'rules_verification') return handleVerification(interaction);

// The GitHub Sponsors panel: a personal, signed link into the shop.
if (customId === sponsor.VERIFY_BUTTON_ID) return handleSponsorVerify(interaction);

const id = buttonIdFromCustomId(customId);
if (!id) return;

Expand Down Expand Up @@ -139,6 +146,36 @@ async function handleVerification(interaction) {
setTimeout(() => interaction.deleteReply().catch(() => {}), 5000);
}

/**
* The sponsor panel's button. Answers with a link that only works for the
* member who clicked, for 15 minutes; the shop does the rest. The link is
* built per click and never posted publicly, which is why it is ephemeral.
*/
async function handleSponsorVerify(interaction) {
// A panel posted while the feature was on keeps its button after it is
// switched off. Say so rather than answer with a link that cannot work.
if (!config.featureEnabled('sponsor')) {
return interaction.reply({ content: t('common.featureDisabled'), flags: MessageFlags.Ephemeral });
}

const url = sponsor.linkFor(interaction.user.id, interaction.guild.id);
if (!url) {
console.error(`[Sponsor] cannot build a link: ${sponsor.settings().missing.join(', ') || 'unknown reason'}`);
return interaction.reply({ content: t('sponsor.verify.unavailable'), flags: MessageFlags.Ephemeral });
}

const row = new ActionRowBuilder().addComponents(new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL(url)
.setLabel(t('sponsor.verify.linkButton')));

await interaction.reply({
content: t('sponsor.verify.text', { minutes: Math.round(sponsor.LINK_TTL_SECONDS / 60) }),
components: [row],
flags: MessageFlags.Ephemeral,
});
}

async function toggleRole(interaction, roleId) {
const { member, guild } = interaction;
const role = guild.roles.cache.get(String(roleId));
Expand Down
96 changes: 96 additions & 0 deletions bots/commands/commands/sponsor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const {
SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, MessageFlags,
} = require('discord.js');
const { makeEmbed } = require('../../../core/utils');
const { applyMeta, optionText, guard } = require('../../../core/commandKit');
const { t } = require('../../../core/i18n');
const config = require('../../../core/config');
const sponsor = require('../../../core/sponsor');

/**
* /sponsor post posts the GitHub Sponsors panel into the current channel.
* /sponsor sync runs the daily role sync now.
*
* ONE COMMAND WITH TWO SUBCOMMANDS rather than two commands: both belong to the
* same feature and the same people, so one entry in the command table and one
* role gate cover both. The panel's button is `sponsor_verify` and is answered
* in bots/commands/bot.js, like every other persistent button.
*/

function panel(interaction) {
const s = sponsor.settings();
const embed = makeEmbed({
title: t('sponsor.panel.title'),
description: t('sponsor.panel.description', {
brand: config.brandName() || interaction.guild.name,
minutes: Math.round(sponsor.LINK_TTL_SECONDS / 60),
}),
guildName: interaction.guild.name,
});

const row = new ActionRowBuilder();
// Left out without a URL: a link button needs one, and a panel that refuses
// to post over an optional button is worse than a panel without it.
if (s.sponsorsUrl) {
row.addComponents(new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL(s.sponsorsUrl)
.setLabel(t('sponsor.panel.sponsorButton')));
}
row.addComponents(new ButtonBuilder()
.setCustomId(sponsor.VERIFY_BUTTON_ID)
.setStyle(ButtonStyle.Success)
.setLabel(t('sponsor.panel.verifyButton')));

return { embeds: [embed], components: [row] };
}

async function post(interaction) {
const s = sponsor.settings();
if (!s.ready) {
console.warn(`[Sponsor] /sponsor post refused, not configured: ${s.missing.join(', ')}`);
return interaction.reply({ content: t('sponsor.notConfigured'), flags: MessageFlags.Ephemeral });
}
await interaction.channel.send(panel(interaction));
await interaction.reply({ content: t('sponsor.posted'), flags: MessageFlags.Ephemeral });
}

async function sync(interaction) {
const s = sponsor.settings();
if (!s.ready) {
console.warn(`[Sponsor] /sponsor sync refused, not configured: ${s.missing.join(', ')}`);
return interaction.reply({ content: t('sponsor.notConfigured'), flags: MessageFlags.Ephemeral });
}

await interaction.deferReply({ flags: MessageFlags.Ephemeral });
console.log(`[Sponsor] manual sync requested by ${interaction.user.id}.`);
// force bypasses the removal brake for this one run only. The daily run
// never sets it: a mass removal always needs a human to look first.
const force = interaction.options.getBoolean('force') === true;
const result = await sponsor.runSync(interaction.client, { force });

let content;
if (result.ok) {
content = t('sponsor.sync.done', { added: result.added, removed: result.removed, failed: result.failed, listed: result.listed });
if (result.braked) content += '\n' + t('sponsor.sync.braked', { count: result.heldBack });
}
else if (result.reason === 'busy') content = t('sponsor.sync.busy');
else content = t('sponsor.sync.failed');
await interaction.editReply({ content });
}

module.exports = {
key: 'sponsor',
feature: 'sponsor',
data: applyMeta(new SlashCommandBuilder(), 'sponsor')
.addSubcommand(sub => sub.setName('post').setDescription(optionText('sponsor', 'post')))
.addSubcommand(sub => sub.setName('sync').setDescription(optionText('sponsor', 'sync'))
.addBooleanOption(o => o.setName('force').setDescription(optionText('sponsor', 'force')).setRequired(false))),

async execute(interaction) {
if (!await guard(interaction, 'sponsor')) return;
const sub = interaction.options.getSubcommand(false);
if (sub === 'sync') return sync(interaction);
return post(interaction);
},
};
23 changes: 22 additions & 1 deletion config/config.example.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@
"manager": "",
"developer": "",
"team": "",
"giveawayNotify": ""
"giveawayNotify": "",
"sponsor": "" // kept in line with the shop's sponsor list, see features.sponsor
},

// ─── Channels ──────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -429,6 +430,25 @@
"deleteLocalFile": true
},

// ── GitHub Sponsors role (/sponsor) ─────────────────────────────────────
//
// A shop links a member's GitHub account, checks the sponsorship and hands
// out the role. The bot posts the panel (/sponsor post), gives each member
// a signed, 15-minute link into the shop (the panel's button) and once a
// day adds and removes the role to match the shop's list (/sponsor sync
// runs it by hand).
//
// Needs SPONSOR_LINK_SECRET and SPONSOR_SYNC_SECRET in .env, each at least
// 32 characters and identical to the shop's. Without them the sync stays
// off. If the shop's list cannot be fetched or read, no role is changed.
"sponsor": {
"enabled": false,
"role": "sponsor", // a key from "roles" above, or a raw role id
"shopBaseUrl": "", // e.g. https://shop.example.com, https only
"sponsorsUrl": "", // e.g. https://github.com/sponsors/<org>, the panel's link button
"syncHour": 4 // 0-23, the server's local time
},

// ── Message context menus ───────────────────────────────────────────────
//
// Right-click a message → Apps. `name` is what Discord shows; renaming one
Expand Down Expand Up @@ -467,6 +487,7 @@
"backup_database": { "enabled": true, "name": "backup_database", "description": "", "roles": ["founder"] },
"send_message": { "enabled": true, "name": "send_message", "description": "", "roles": ["founder", "manager"] },
"send_embed": { "enabled": true, "name": "send_embed", "description": "", "roles": ["founder", "manager"] },
"sponsor": { "enabled": true, "name": "sponsor", "description": "", "roles": ["founder", "manager"] },

"random": { "enabled": true, "name": "random", "description": "", "roles": ["team"] },
"rg": { "enabled": true, "name": "rg", "description": "", "roles": [] },
Expand Down
24 changes: 23 additions & 1 deletion core/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ const database = {
NAME: _env('DB_NAME', 'es_extended'),
};

/**
* The two secrets shared with the shop for the GitHub Sponsors role. Read on
* every call rather than once, so the harness can take one away.
*/
const sponsorSecrets = () => ({
link: _env('SPONSOR_LINK_SECRET'),
sync: _env('SPONSOR_SYNC_SECRET'),
});

// ─── ids ─────────────────────────────────────────────────────────────────────

const SNOWFLAKE = /^\d{17,20}$/;
Expand Down Expand Up @@ -279,6 +288,19 @@ function report() {

if (featureEnabled('backupDatabase') && !database.USER) missing.push('DB_USER (.env)');

// Without these the sync stays off and the verify button answers with an
// apology. Checked here too so it shows up in the one list read at boot.
if (featureEnabled('sponsor')) {
if (!roleId(get('features.sponsor.role', ''))) missing.push('features.sponsor.role');
// https only, plain http just for a shop on this machine: the sync sends a
// bearer secret there. core/sponsor.js applies the same rule.
const shop = String(get('features.sponsor.shopBaseUrl', '') ?? '').trim();
if (!/^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1|\[::1\])([:/]|$))/i.test(shop)) missing.push('features.sponsor.shopBaseUrl');
const secrets = sponsorSecrets();
if (secrets.link.length < 32) missing.push('SPONSOR_LINK_SECRET (.env, at least 32 characters)');
if (secrets.sync.length < 32) missing.push('SPONSOR_SYNC_SECRET (.env, at least 32 characters)');
}

// A bonus role that does not resolve matches nobody, so the multiplier is
// simply never applied and the player sees the ordinary payout. There is
// nothing to notice, which is why it has to be said out loud. Shipped empty,
Expand Down Expand Up @@ -324,7 +346,7 @@ module.exports = {

get, raw: () => merged, reload, load, hasUserConfig,

tokens, database,
tokens, database, sponsorSecrets,
guildId, roleId, roleIds, channelId,
brandName, thumbnailUrl, embedColor, brandLinks, parseColor,
command, commandKeys, contextMenu,
Expand Down
Loading
Loading