Skip to content

Allow blocking an user by its telegram id - #773

Merged
grunch merged 5 commits into
mainfrom
issue701
Apr 6, 2026
Merged

Allow blocking an user by its telegram id#773
grunch merged 5 commits into
mainfrom
issue701

Conversation

@Luquitasjeffrey

@Luquitasjeffrey Luquitasjeffrey commented Mar 28, 2026

Copy link
Copy Markdown
Collaborator

Fixes #701
Now the name of the parameter of the function that handles the block operations is changed to usernameOrId
new behaviour:
now command accepts:
/ban @TelegramUsername
and
/ban 12345 (telegram user id)
If usernameOrId starts with '@' then it is interpreted as an username
else it will attempt to handle it as an id
if its not a valid telegram id, then it displays a message to the user saying the user was not found

Summary by CodeRabbit

  • New Features

    • /block and /unblock accept either @username or numeric Telegram IDs.
  • Bug Fixes

    • Non-@ inputs that aren't valid numeric IDs are rejected immediately with a "user not found" message.
    • Command handlers now reply with usage when arguments are invalid and surface failure messages if an operation errors.
  • Documentation

    • Added localized usage/help and failure strings for /block, /unblock, and /blocklist in multiple languages.

@coderabbitai

coderabbitai Bot commented Mar 28, 2026

Copy link
Copy Markdown
Contributor

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: 34a7333e-58c6-466d-b390-fb698ac90249

📥 Commits

Reviewing files that changed from the base of the PR and between f5854ef and cf3dffa.

📒 Files selected for processing (12)
  • bot/modules/block/index.ts
  • bot/modules/block/messages.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 (3)
  • locales/en.yaml
  • locales/de.yaml
  • locales/ko.yaml
🚧 Files skipped from review as they are similar to previous changes (4)
  • locales/pt.yaml
  • bot/modules/block/messages.ts
  • locales/ru.yaml
  • locales/fa.yaml

Walkthrough

The block/unblock command handlers and messages were updated to accept a usernameOrId argument, resolve targets by @username or numeric Telegram ID with early invalid-id returns, and to surface usage/failure messages via new message functions; multiple locale files were extended with usage and error strings.

Changes

Cohort / File(s) Summary
Core commands
bot/modules/block/commands.ts
Renamed parameters to usernameOrId. Resolve targets by @usernameUser.findOne({ username }) or numeric → User.findOne({ tg_id }). Add early-return when non-@ input is not numeric; keep existing block/unblock DB logic and outcomes.
Handlers & wiring
bot/modules/block/index.ts
Removed next() control flow; handlers now validate args length, await usage messages on bad args, await command execution inside try/catch, and logger.error + failure messages on exceptions. Added messages import.
Message helpers
bot/modules/block/messages.ts
Added exported blockUsage, unblockUsage, blockFailed, unblockFailed async handlers that reply with i18n strings and log errors. Updated exports.
Localizations
locales/*.yaml
locales/en.yaml, locales/de.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
Added help text entries for /block, /unblock, /blocklist and new block_usage, unblock_usage, block_failed, unblock_failed keys across multiple locales (usage guidance supports @Username or telegramId).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • grunch
  • mostronatorcoder

Poem

🐰 I nibble keys and hop through code,
I chase @names or IDs in a mode.
If digits fail, I stop with a thunk,
Else block or free — I do the thunk-thunk.
Carrots, logs, and i18n on the road.

🚥 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 Title accurately describes the main change: enabling blocking users by Telegram ID in addition to username.
Linked Issues check ✅ Passed Changes fully implement issue #701 requirements: block/unblock now accept both @username and numeric Telegram IDs with proper parameter and logic updates.
Out of Scope Changes check ✅ Passed All changes directly support blocking by Telegram ID. Localization updates and message handlers align with the core functionality requirements.
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 issue701

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
bot/modules/block/commands.ts (1)

6-16: Extract shared usernameOrId resolution to a helper.

block and unblock duplicate the same parse/lookup flow. A shared resolver reduces drift and keeps validation consistent.

♻️ Suggested refactor
+const resolveUserByUsernameOrId = async (
+  ctx: MainContext,
+  usernameOrId: string,
+) => {
+  if (usernameOrId.startsWith('@')) {
+    return User.findOne({ username: usernameOrId.substring(1) });
+  }
+
+  if (!/^\d+$/.test(usernameOrId)) {
+    await globalMessages.notFoundUserMessage(ctx);
+    return null;
+  }
+
+  return User.findOne({ tg_id: usernameOrId });
+};

 const block = async (ctx: MainContext, usernameOrId: string): Promise<void> => {
-  let userToBlock;
-  if (usernameOrId.startsWith('@')) {
-    userToBlock = await User.findOne({ username: usernameOrId.substring(1) });
-  } else {
-    if (!/^\d+$/.test(usernameOrId)) {
-      await globalMessages.notFoundUserMessage(ctx);
-      return;
-    }
-    userToBlock = await User.findOne({ tg_id: usernameOrId });
-  }
+  const userToBlock = await resolveUserByUsernameOrId(ctx, usernameOrId);

 const unblock = async (
   ctx: MainContext,
   usernameOrId: string,
 ): Promise<void> => {
-  let userToUnblock;
-  if (usernameOrId.startsWith('@')) {
-    userToUnblock = await User.findOne({ username: usernameOrId.substring(1) });
-  } else {
-    if (!/^\d+$/.test(usernameOrId)) {
-      await globalMessages.notFoundUserMessage(ctx);
-      return;
-    }
-    userToUnblock = await User.findOne({ tg_id: usernameOrId });
-  }
+  const userToUnblock = await resolveUserByUsernameOrId(ctx, usernameOrId);

Also applies to: 64-77

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bot/modules/block/commands.ts` around lines 6 - 16, The block() and unblock()
functions duplicate the usernameOrId parsing and User lookup; extract that logic
into a shared helper (e.g., resolveUserByUsernameOrId(usernameOrId, ctx)) that
accepts the raw string and context, validates whether it starts with '@' or is
an integer, performs User.findOne({ username: ... }) or User.findOne({ tg_id:
... }), and returns the found user (or null); update block and unblock to call
this helper and handle a null result by invoking
globalMessages.notFoundUserMessage(ctx) and returning, keeping all validation
and error handling centralized in the new resolver.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bot/modules/block/commands.ts`:
- Around line 11-16: The code converts usernameOrId with Number(...) before
querying tg_id causing a type mismatch with the schema (tg_id is String);
instead validate usernameOrId is a digits-only string (e.g., /^\d+$/) and if
valid use the raw string when querying User.findOne({ tg_id: usernameOrId });
update both the block flow that sets userToBlock (variable) and the other
similar lookup near lines 72-77 to stop using Number(...) and call
globalMessages.notFoundUserMessage(ctx) when validation fails.

---

Nitpick comments:
In `@bot/modules/block/commands.ts`:
- Around line 6-16: The block() and unblock() functions duplicate the
usernameOrId parsing and User lookup; extract that logic into a shared helper
(e.g., resolveUserByUsernameOrId(usernameOrId, ctx)) that accepts the raw string
and context, validates whether it starts with '@' or is an integer, performs
User.findOne({ username: ... }) or User.findOne({ tg_id: ... }), and returns the
found user (or null); update block and unblock to call this helper and handle a
null result by invoking globalMessages.notFoundUserMessage(ctx) and returning,
keeping all validation and error handling centralized in the new resolver.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: fe15124c-c6f5-4141-a91d-48fe59686d0b

📥 Commits

Reviewing files that changed from the base of the PR and between 8f3c413 and ae4fae5.

📒 Files selected for processing (1)
  • bot/modules/block/commands.ts

Comment thread bot/modules/block/commands.ts

@coderabbitai coderabbitai 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.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bot/modules/block/index.ts`:
- Around line 19-26: The unblock handler currently calls commands.unblock
without awaiting or handling errors; update bot.command('unblock',
userMiddleware, ...) to await commands.unblock(ctx, args[1]) inside a try/catch,
keep the existing args.length check and messages.unblockUsage(ctx) for bad
input, and in the catch block log the error (e.g., console.error or
ctx.logger.error) and notify the user via a failure message (e.g.,
messages.unblockFailed(ctx) or a suitable messages.error fallback).
- Around line 10-17: The bot.command handler for 'block' is calling
commands.block without awaiting or handling errors; update the async handler
(the function passed to bot.command('block', userMiddleware, async ctx => { ...
})) to await commands.block(ctx, args[1]) and wrap that call in a try/catch
similar to the blocklist handler: on invalid args call messages.blockUsage(ctx)
as before, and inside the try call await commands.block(...); in the catch call
messages.blockFailed(ctx) or an appropriate error message using ctx and log the
error so promise rejections are handled.

In `@locales/de.yaml`:
- Around line 700-701: The localization string for unblock_usage has a typo:
update the value of the key unblock_usage so it reads "Verwendung: /unblock
`@Username` oder /unblock telegramId" (replace the erroneous "/block telegramId"
with "/unblock telegramId") to match the documented command; change the value
associated with unblock_usage accordingly.

In `@locales/es.yaml`:
- Around line 702-703: Fix the typo in the Spanish locale entry for
unblock_usage: change the text value of the key unblock_usage (in
locales/es.yaml) from "Uso: /unblock `@Username` o /block telegramId" to use
"/unblock telegramId" so it reads "Uso: /unblock `@Username` o /unblock
telegramId"; ensure the key name remains unblock_usage and only the message
string is corrected.

In `@locales/ko.yaml`:
- Around line 697-698: Fix the typo in the localization string keyed by
unblock_usage: replace the copied "/block telegramId" text with "/unblock
telegramId" so the string reads "사용법: /unblock `@Username` 또는 /unblock
telegramId"; update the same unblock_usage key in all 10 locale files where the
copy-paste error appears to ensure consistency.

In `@locales/pt.yaml`:
- Line 257: The Portuguese translation for the message identified by the string
"/fiatsent <order id> - O comprador indica que já enviou o dinero Fiat para o
vendedor" uses the Spanish word "dinero"; update that message to use the
Portuguese word "dinheiro" so it reads "/fiatsent <order id> - O comprador
indica que já enviou o dinheiro Fiat para o vendedor", preserving surrounding
punctuation and spacing.
- Around line 699-700: The Portuguese locale has a copy-paste typo: the key
unblock_usage currently reads "/block telegramId" instead of "/unblock
telegramId"; update the value for the YAML key unblock_usage to use "/unblock
telegramId" (matching block_usage's structure) so it reads "Uso: /unblock
`@Username` ou /unblock telegramId" and ensure block_usage remains unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0289fb9c-88e1-4c0c-929b-5456631425eb

📥 Commits

Reviewing files that changed from the base of the PR and between afe8a57 and f5854ef.

📒 Files selected for processing (12)
  • bot/modules/block/index.ts
  • bot/modules/block/messages.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 (6)
  • locales/en.yaml
  • locales/ru.yaml
  • locales/it.yaml
  • locales/fa.yaml
  • locales/fr.yaml
  • locales/uk.yaml

Comment thread bot/modules/block/index.ts
Comment thread bot/modules/block/index.ts
Comment thread locales/de.yaml Outdated
Comment thread locales/es.yaml Outdated
Comment thread locales/ko.yaml Outdated
Comment thread locales/pt.yaml Outdated
Comment thread locales/pt.yaml Outdated

@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.

LGTM

@grunch
grunch merged commit c4f091a into main Apr 6, 2026
7 checks passed
@grunch
grunch deleted the issue701 branch April 6, 2026 19:10
@Luquitasjeffrey
Luquitasjeffrey restored the issue701 branch April 12, 2026 14:48
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.

Bloqueo del ID del Usuario usurpador de identidad

2 participants