Skip to content
Closed
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
30 changes: 25 additions & 5 deletions bot/modules/block/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,22 @@ import * as messages from './messages';
import * as globalMessages from '../../messages';
import { MainContext } from '../../start';

const block = async (ctx: MainContext, username: string): Promise<void> => {
const userToBlock = await User.findOne({ username: username.substring(1) });
/**
* Resolve a user by @username or numeric Telegram ID.
* Returns null if the argument format is invalid or the user is not found.
*/
const resolveUser = async (arg: string) => {
if (arg.startsWith('@')) {
return User.findOne({ username: arg.substring(1) });
}
if (/^\d+$/.test(arg)) {
return User.findOne({ tg_id: arg });
}
return null;
};

const block = async (ctx: MainContext, target: string): Promise<void> => {
const userToBlock = await resolveUser(target);
const user = ctx.user;

if (!userToBlock) {
Expand Down Expand Up @@ -52,8 +66,8 @@ const block = async (ctx: MainContext, username: string): Promise<void> => {
await messages.userBlocked(ctx);
};

const unblock = async (ctx: MainContext, username: string): Promise<void> => {
const userToUnblock = await User.findOne({ username: username.substring(1) });
const unblock = async (ctx: MainContext, target: string): Promise<void> => {
const userToUnblock = await resolveUser(target);
if (!userToUnblock) {
await globalMessages.notFoundUserMessage(ctx);
return;
Expand Down Expand Up @@ -84,7 +98,13 @@ const blocklist = async (ctx: MainContext): Promise<void> => {
}

const usersBlocked = await User.find({ tg_id: { $in: tgIdBlocks } });
await messages.blocklistMessage(ctx, usersBlocked);

// For tg_ids that have no matching user record, pass the raw id so the
// message layer can still display something meaningful.
const foundIds = new Set(usersBlocked.map(u => u.tg_id));
const unknownIds = tgIdBlocks.filter((id: string) => !foundIds.has(id));

await messages.blocklistMessage(ctx, usersBlocked, unknownIds);
};

export { block, unblock, blocklist };
12 changes: 12 additions & 0 deletions bot/modules/block/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,28 @@ import { logger } from '../../../logger';
const commands = require('./commands');
const { userMiddleware } = require('../../middleware/user');

/** Returns true for @username or a numeric Telegram user ID */
const isValidBlockTarget = (arg: string) =>
arg.startsWith('@') || /^\d+$/.test(arg);

export const configure = (bot: Telegraf<CommunityContext>) => {
bot.command('block', userMiddleware, async (ctx, next) => {
const args = ctx.message.text.split(' ') || [];
if (args.length !== 2) return next();
if (!isValidBlockTarget(args[1])) {
await ctx.reply(ctx.i18n.t('invalid_block_target'));
return;
}
commands.block(ctx, args[1]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
});

bot.command('unblock', userMiddleware, async (ctx, next) => {
const args = ctx.message.text.split(' ') || [];
if (args.length !== 2) return next();
if (!isValidBlockTarget(args[1])) {
await ctx.reply(ctx.i18n.t('invalid_block_target'));
return;
}
commands.unblock(ctx, args[1]);
});

Expand Down
10 changes: 7 additions & 3 deletions bot/modules/block/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ const userUnblocked = async (ctx: MainContext) => {
const blocklistMessage = async (
ctx: MainContext,
usersBlocked: UserDocument[],
unknownIds: string[] = [],
) => {
try {
if (!usersBlocked?.length) {
if (!usersBlocked?.length && !unknownIds.length) {
return await blocklistEmptyMessage(ctx);
}
const userList = usersBlocked.map(block => '@' + block.username);
ctx.reply(userList.join('\n'));
const lines: string[] = [
...usersBlocked.map(u => (u.username ? '@' + u.username : `ID: ${u.tg_id}`)),
...unknownIds.map(id => `ID: ${id}`),
];
ctx.reply(lines.join('\n'));
} catch (error) {
logger.error(error);
}
Expand Down
1 change: 1 addition & 0 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ user_already_blocked: Benutzer ist bereits gesperrt
user_blocked: Benutzer erfolgreich gesperrt
user_unblocked: Benutzer erfolgreich entsperrt
blocklist_empty: Du hast keine gesperrten Benutzer
invalid_block_target: "Bitte gib einen gültigen @username oder eine numerische Telegram-Benutzer-ID an"
orders_in_process: Es gibt laufende Aufträge mit diesem Benutzer
user_order_is_blocked_by_user_taker: Du kannst diesen Auftrag nicht annehmen, da du seinen Ersteller gesperrt hast
user_taker_is_blocked_by_user_order: Du kannst diesen Auftrag nicht annehmen, da dich sein Ersteller gesperrt hat
Expand Down
1 change: 1 addition & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,7 @@ user_already_blocked: User is already blocked
user_blocked: User successfully blocked
user_unblocked: User successfully unblocked
blocklist_empty: You do not have any blocked user
invalid_block_target: "Please provide a valid @username or numeric Telegram user ID"
orders_in_process: There are orders in process with this user
user_order_is_blocked_by_user_taker: You can't take this order because you blocked its maker
user_taker_is_blocked_by_user_order: You can't take this order because its maker blocked you
Expand Down
1 change: 1 addition & 0 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,7 @@ user_already_blocked: El usuario ya está bloqueado
user_blocked: Usuario bloqueado correctamente
user_unblocked: Usuario desbloqueado correctamente
blocklist_empty: No tienes ningun usuario bloqueado
invalid_block_target: "Por favor proporciona un @username válido o un ID numérico de Telegram"
orders_in_process: Hay ordenes en proceso con este usuario
user_order_is_blocked_by_user_taker: No puedes aceptar esta oferta porque has bloqueado a su creador
user_taker_is_blocked_by_user_order: No puedes aceptar esta oferta porque su creador te ha bloqueado
Expand Down
1 change: 1 addition & 0 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ user_already_blocked: کاربر از پیش مسدود شده بود.
user_blocked: کاربر با موفقیت مسدود شد.
user_unblocked: انسداد کاربر با موفقیت خاتمه یافت.
blocklist_empty: شما هیچ کاربر مسدود شده‌ای ندارید.
invalid_block_target: 'لطفاً یک @username معتبر یا شناسه عددی کاربر تلگرام وارد کنید'
orders_in_process: سفارش‌های در جریانی وجود دارند که این کاربر در آن‌ها دخیل است.
user_order_is_blocked_by_user_taker: شما نمی‌توانید این سفارش را بردارید زیرا گذارنده آن را مسدود کرده‌اید.
user_taker_is_blocked_by_user_order: شما نمی‌توانید این سفارش را بردارید زیرا توسط گذارنده آن مسدود شده‌اید.
Expand Down
1 change: 1 addition & 0 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,7 @@ user_already_blocked: L'utilisateur est déjà bloqué
user_blocked: Utilisateur bloqué avec succès
user_unblocked: Utilisateur débloqué avec succès
blocklist_empty: Vous n'avez aucun utilisateur bloqué
invalid_block_target: "Veuillez fournir un @username valide ou un ID numérique d'utilisateur Telegram"
orders_in_process: Il y a des ordres en cours avec cet utilisateur
user_order_is_blocked_by_user_taker: Vous ne pouvez pas accepter cette offre car vous avez bloqué son créateur
user_taker_is_blocked_by_user_order: Vous ne pouvez pas accepter cette offre car son créateur vous a bloqué
Expand Down
1 change: 1 addition & 0 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ user_already_blocked: L'utente è già bloccato
user_blocked: Utente bloccato con successo
user_unblocked: Utente sbloccato con successo
blocklist_empty: Non hai alcun utente bloccato
invalid_block_target: "Fornisci un @username valido o un ID numerico utente Telegram"
orders_in_process: Ci sono ordini in corso con questo utente
user_order_is_blocked_by_user_taker: Non puoi accettare questo ordine perché hai bloccato il suo creatore
user_taker_is_blocked_by_user_order: Non puoi accettare questo ordine perché il suo creatore ti ha bloccato
Expand Down
1 change: 1 addition & 0 deletions locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ user_already_blocked: User is already blocked
user_blocked: User successfully blocked
user_unblocked: User successfully unblocked
blocklist_empty: You do not have any blocked user
invalid_block_target: "유효한 @username 또는 숫자로 된 텔레그램 사용자 ID를 입력해 주세요"
orders_in_process: There are orders in process with this user
user_order_is_blocked_by_user_taker: You can't take this order because you blocked its maker
user_taker_is_blocked_by_user_order: You can't take this order because its maker blocked you
Expand Down
1 change: 1 addition & 0 deletions locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,7 @@ user_already_blocked: Usuário já está bloqueado
user_blocked: Usuário bloqueado com sucesso
user_unblocked: Usuário desbloqueado com sucesso
blocklist_empty: Você não tem nenhum usuário bloqueado
invalid_block_target: "Por favor, forneça um @username válido ou um ID numérico de usuário do Telegram"
orders_in_process: Existem ordens em andamento com este usuário
user_order_is_blocked_by_user_taker: Você não pode aceitar esta oferta porque bloqueou seu criador
user_taker_is_blocked_by_user_order: Você não pode aceitar esta oferta porque seu criador bloqueou você
Expand Down
1 change: 1 addition & 0 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ user_already_blocked: User is already blocked
user_blocked: User successfully blocked
user_unblocked: User successfully unblocked
blocklist_empty: You do not have any blocked user
invalid_block_target: "Пожалуйста, укажите действительный @username или числовой Telegram ID пользователя"
orders_in_process: There are orders in process with this user
user_order_is_blocked_by_user_taker: You can't take this order because you blocked its maker
user_taker_is_blocked_by_user_order: You can't take this order because its maker blocked you
Expand Down
1 change: 1 addition & 0 deletions locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,7 @@ user_already_blocked: User is already blocked
user_blocked: User successfully blocked
user_unblocked: User successfully unblocked
blocklist_empty: You do not have any blocked user
invalid_block_target: "Будь ласка, вкажіть дійсний @username або числовий Telegram ID користувача"
orders_in_process: There are orders in process with this user
user_order_is_blocked_by_user_taker: You can't take this order because you blocked its maker
user_taker_is_blocked_by_user_order: You can't take this order because its maker blocked you
Expand Down
Loading
Loading