Skip to content

feat: add configurable user requirements for community creation#841

Open
Luquitasjeffrey wants to merge 6 commits into
mainfrom
feat/community-creation-requirements
Open

feat: add configurable user requirements for community creation#841
Luquitasjeffrey wants to merge 6 commits into
mainfrom
feat/community-creation-requirements

Conversation

@Luquitasjeffrey

@Luquitasjeffrey Luquitasjeffrey commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Closes #838
Continues #840

Add environment-based minimum requirements to the /community command so only users who meet configurable thresholds can create a community
If any requirement is not met, the bot replies with a short error message and exits — no scene is entered
If an env var is not set, that restriction is simply not applied

Summary by CodeRabbit

  • New Features

    • Added community-creation eligibility checks when community creation is enabled, using configurable minimum thresholds for orders, trading volume, days using the bot, and reputation, with detailed “requirements not met” feedback.
  • Documentation

    • Updated the configuration template (.env-sample) with documented, optional community-creation minimum requirement settings.
  • Localization

    • Added a new eligibility feedback message to English, German, Spanish, Persian, French, Italian, Korean, Portuguese, Russian, and Ukrainian.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 949be379-281b-4acc-8d64-56064152b0de

📥 Commits

Reviewing files that changed from the base of the PR and between 79660d5 and c7d5b1a.

📒 Files selected for processing (12)
  • .env-sample
  • bot/modules/community/index.ts
  • locales/de.yaml
  • locales/en.yaml
  • locales/es.yaml
  • locales/fa.yaml
  • locales/fr.yaml
  • locales/it.yaml
  • locales/ko.yaml
  • locales/pt.yaml
  • locales/ru.yaml
  • locales/uk.yaml
✅ Files skipped from review due to trivial changes (4)
  • locales/ru.yaml
  • locales/it.yaml
  • locales/uk.yaml
  • .env-sample
🚧 Files skipped from review as they are similar to previous changes (6)
  • locales/fr.yaml
  • locales/de.yaml
  • locales/ko.yaml
  • locales/en.yaml
  • locales/es.yaml
  • bot/modules/community/index.ts

Walkthrough

Adds optional minimum-threshold gating for community creation. Four new COMMUNITY_CREATION_MIN_* env vars (orders, volume, days using bot, reputation) are documented in .env-sample. The community command handler parses and validates these thresholds, checks the requesting user's metrics, and replies with a new community_creation_requirements_not_met i18n key—added to all 11 supported locale files.

Changes

Community Creation Minimum Requirements Gating

Layer / File(s) Summary
Env config and eligibility enforcement
.env-sample, bot/modules/community/index.ts
Adds commented COMMUNITY_CREATION_MIN_* env-var placeholders; imports logger; parses each threshold into an optional { value, isValid } structure; aggregates invalid keys and returns a generic error; computes daysUsing from user.created_at; evaluates order/volume/days/reputation eligibility; logs and replies with community_creation_requirements_not_met when the user fails.
Locale strings
locales/en.yaml, locales/es.yaml, locales/de.yaml, locales/fr.yaml, locales/it.yaml, locales/pt.yaml, locales/ru.yaml, locales/uk.yaml, locales/ko.yaml, locales/fa.yaml
Adds the community_creation_requirements_not_met translation key to all 11 supported locale files with placeholders for current vs required metrics.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • lnp2pBot/bot#811: Modifies the same bot/modules/community/index.ts file within the COMMUNITY_CREATION_ENABLED-gated /community command flow, re-registering the command handler that this PR extends with threshold validation.

Suggested reviewers

  • ermeme
  • mostronatorcoder
  • grunch

Poem

🐇 Hippity-hop, not just anyone may pass,
A community gate now checks your class!
Min orders, rep, and days in the den —
Only the worthy may build their warren.
The bot checks metrics with a flick of its ear,
"Requirements not met!" — the message is clear. 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature: adding configurable user requirements for community creation.
Linked Issues check ✅ Passed All requirements from issue #838 are implemented: minimum days, orders, volume, and reputation checks with environment-based configuration.
Out of Scope Changes check ✅ Passed All changes directly relate to implementing configurable community creation requirements and localization support; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/community-creation-requirements

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ermeme ermeme Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Summary

Verdict: Approve

Looks Good

  • The previous fail-open config issue is fixed: invalid or negative threshold values are now rejected instead of silently disabling enforcement.
  • The new eligibility gate is scoped to /community and the locale/config updates are complete for the touched surface.

@grunch grunch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review estricto del PR. La funcionalidad es correcta y está bien estructurada (fail-closed en config inválida, i18n completo en los 10 idiomas, campos del modelo User verificados: trades_completed, volume_traded, total_rating —promedio 0–5— y created_at).

El único cambio recomendado antes de merge es el nivel de log (comentario 1). El resto son mejoras opcionales/no bloqueantes. Dejo sugerencias de código inline para que las apliques tú.

(minReputation === null || user.total_rating >= minReputation);

if (!meetsRequirements) {
logger.error(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nivel de log incorrecto (recomendado antes de merge). Que un usuario no cumpla los requisitos es comportamiento esperado enforced por los umbrales, no un error de sistema. Usar logger.error contamina los logs de error, distorsiona alertas/métricas y registra PII (tg_id, volume_traded) en cada intento fallido. Mejor logger.warn (o logger.info).

Suggested change
logger.error(
logger.warn(

Comment thread bot/modules/community/index.ts Outdated
Comment on lines +64 to +66
const daysUsing = Math.floor(
(Date.now() - new Date(user.created_at).getTime()) / 86400000,
);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Guard opcional para created_at (no bloqueante). Si created_at fuese inválido/ausente, getTime() devuelve NaN y daysUsing queda NaN; la comparación NaN >= minDays falla cerrado (correcto), pero el modo de fallo es implícito y difícil de depurar. En la práctica created_at tiene default: Date.now, así que el riesgo real es bajo. Si quieres hacerlo explícito:

Suggested change
const daysUsing = Math.floor(
(Date.now() - new Date(user.created_at).getTime()) / 86400000,
);
const createdAtTime = new Date(user.created_at).getTime();
if (!Number.isFinite(createdAtTime)) {
logger.error(
`User ${user.tg_id} has invalid created_at timestamp: ${user.created_at}`,
);
return ctx.reply(ctx.i18n.t('generic_error'));
}
const daysUsing = Math.floor(
(Date.now() - createdAtTime) / 86400000,
);

Comment thread bot/modules/community/index.ts Outdated
return { value: null, isValid: false };
};

const thresholdResults = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validación en runtime + lógica inline (no bloqueante, decisión de diseño). Estos ~50 líneas se parsean y evalúan en cada invocación de /community, y una configuración inválida solo se detecta cuando un usuario ejecuta el comando (recibe generic_error). Dos mejoras a considerar:

  1. Parsear/validar los umbrales una vez al arranque (en start.ts) para que un despliegue mal configurado falle al boot, no ante el usuario.
  2. Extraer parseOptionalNumber y la evaluación de meetsRequirements a un helper en util/ para legibilidad y para poder testearlos de forma aislada.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 - Ahora se parsean unicamente al inicializar el modulo que declara el comando /community
2 - Debido a que meetsRequirements y parseOptionalNumber solo son usados dentro de community/index.ts me pareció mas propicio dejarlas en el archivo community/index.ts ya que son funciones helper solo usadas internamente en ese modulo

Comment thread .env-sample
# COMMUNITY_CREATION_MIN_ORDERS=100
# COMMUNITY_CREATION_MIN_VOLUME=10000000
# COMMUNITY_CREATION_MIN_DAYS_USING_BOT=365
# COMMUNITY_CREATION_MIN_REPUTATION=4.8

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nota sobre MIN_REPUTATION. total_rating es un promedio que parte de 0 y puede inflarse con una sola reseña de 5★ (1 review = 5.0), por lo que por sí solo es gameable. Queda mitigado al combinarlo con MIN_ORDERS. Quizá valga la pena un comentario aquí recomendando usar reputación junto a un mínimo de órdenes.

…osed configuration checks, improved error logging levels, added explicit user date validation, and updated all locales to provide detailed feedback to the user on unmet requirements.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add user requirements before allowing community creation

3 participants