diff --git a/.env-sample b/.env-sample index 8aa836f9..d7e18624 100644 --- a/.env-sample +++ b/.env-sample @@ -80,4 +80,7 @@ COMMUNITY_CURRENCIES=20 RELAYS='ws://localhost:7000,ws://localhost:8000,ws://localhost:9000' # Seconds to wait to allow disputes to be started -DISPUTE_START_WINDOW=600 \ No newline at end of file +DISPUTE_START_WINDOW=600 + +# Number of notification messages sent to the admin, informing them of lack of solvers before disabling the community +MAX_MESSAGES=10 diff --git a/bot/modules/community/commands.js b/bot/modules/community/commands.js index 47e6f997..bea09470 100644 --- a/bot/modules/community/commands.js +++ b/bot/modules/community/commands.js @@ -19,6 +19,7 @@ async function findCommunities(currency) { const communities = await Community.find({ currencies: currency, public: true, + is_disabled: false, }); const orderCount = await getOrderCountByCommunity(); return communities.map(comm => { @@ -50,9 +51,9 @@ exports.setComm = async ctx => { if (groupName[0] == '@') { // Allow find communities case insensitive const regex = new RegExp(['^', groupName, '$'].join(''), 'i'); - community = await Community.findOne({ group: regex }); + community = await Community.findOne({ group: regex, is_disabled: false }); } else if (groupName[0] == '-') { - community = await Community.findOne({ group: groupName }); + community = await Community.findOne({ group: groupName, is_disabled: false }); } if (!community) { return await ctx.reply(ctx.i18n.t('community_not_found')); @@ -72,7 +73,7 @@ exports.communityAdmin = async ctx => { const [group] = await validateParams(ctx, 2, '\\<_community_\\>'); if (!group) return; const creator_id = ctx.user.id; - const [community] = await Community.find({ group, creator_id }); + const [community] = await Community.find({ group, creator_id, is_disabled: false }); if (!community) throw new Error('CommunityNotFound'); await ctx.scene.enter('COMMUNITY_ADMIN', { community }); } catch (err) { @@ -91,7 +92,7 @@ exports.myComms = async ctx => { try { const { user } = ctx; - const communities = await Community.find({ creator_id: user._id }); + const communities = await Community.find({ creator_id: user._id, is_disabled: false }); if (!communities.length) return await ctx.reply(ctx.i18n.t('you_dont_have_communities')); @@ -144,6 +145,7 @@ exports.updateCommunity = async (ctx, id, field, bot) => { const community = await Community.findOne({ _id: id, creator_id: user._id, + is_disabled: false, }); if (!community) { @@ -212,6 +214,7 @@ exports.deleteCommunity = async ctx => { const community = await Community.findOne({ _id: id, creator_id: ctx.user._id, + is_disabled: false, }); if (!community) { @@ -234,6 +237,7 @@ exports.changeVisibility = async ctx => { const community = await Community.findOne({ _id: id, creator_id: ctx.user._id, + is_disabled: false, }); if (!community) { diff --git a/bot/modules/orders/commands.js b/bot/modules/orders/commands.js index a62fce99..5526c384 100644 --- a/bot/modules/orders/commands.js +++ b/bot/modules/orders/commands.js @@ -48,13 +48,13 @@ const sell = async ctx => { ['^', '@' + ctx.message.chat.username, '$'].join(''), 'i' ); - community = await Community.findOne({ group: regex }); + community = await Community.findOne({ group: regex, is_disabled: false }); if (!community) return ctx.deleteMessage(); communityId = community._id; } else if (user.default_community_id) { communityId = user.default_community_id; - community = await Community.findOne({ _id: communityId }); + community = await Community.findOne({ _id: communityId, is_disabled: false }); if (!community) { user.default_community_id = null; await user.save(); @@ -114,7 +114,7 @@ const buy = async ctx => { ['^', '@' + ctx.message.chat.username, '$'].join(''), 'i' ); - community = await Community.findOne({ group: regex }); + community = await Community.findOne({ group: regex, is_disabled: false }); if (!community) { ctx.deleteMessage(); return; @@ -122,7 +122,7 @@ const buy = async ctx => { communityId = community._id; } else if (user.default_community_id) { communityId = user.default_community_id; - community = await Community.findOne({ _id: communityId }); + community = await Community.findOne({ _id: communityId, is_disabled: false }); if (!community) { user.default_community_id = null; await user.save(); diff --git a/jobs/check_solvers.ts b/jobs/check_solvers.ts index 90674722..affe0bf2 100644 --- a/jobs/check_solvers.ts +++ b/jobs/check_solvers.ts @@ -4,8 +4,9 @@ import { MainContext } from '../bot/start'; import { Community, User, } from '../models'; import { ICommunity } from '../models/community'; import { logger } from '../logger'; +import { I18nContext } from '@grammyjs/i18n'; +import { getUserI18nContext } from '../util'; -const MAX_MESSAGES = 5; // Number of messages before disabling the community const checkSolvers = async (bot: Telegraf) => { try { @@ -27,7 +28,7 @@ const checkSolvers = async (bot: Telegraf) => { const notifyAdmin = async (community: ICommunity, bot: Telegraf) => { community.messages_sent_count += 1; // The community is disabled if the admin has received the maximum notification message to add a solver - if (community.messages_sent_count >= MAX_MESSAGES) { + if (community.messages_sent_count >= Number(process.env.MAX_MESSAGES)) { community.is_disabled = true; await community.save(); @@ -36,12 +37,14 @@ const notifyAdmin = async (community: ICommunity, bot: Telegraf) => } await community.save(); - const admin = await User.findOne({ tg_id: community.creator_id }); + const admin = await User.findById(community.creator_id); if (admin) { + const i18nCtx: I18nContext = await getUserI18nContext(admin); + await bot.telegram.sendMessage( - admin.tg_id, - `Your community ${community.name} doesn't have any solvers. Please add at least one solver to avoid being disabled.` + admin.tg_id, + i18nCtx.t('check_solvers', { communityName: community.name }) ); } } diff --git a/jobs/communities.ts b/jobs/communities.ts index a3599506..c1fe4973 100644 --- a/jobs/communities.ts +++ b/jobs/communities.ts @@ -6,7 +6,7 @@ import { logger } from "../logger"; const deleteCommunity = async (bot: Telegraf) => { try { - const communities = await Community.find(); + const communities = await Community.find({ is_disabled: false }); for (const community of communities) { // Delete communities with COMMUNITY_TTL days without a successful order const days = 86400 * Number(process.env.COMMUNITY_TTL); diff --git a/locales/de.yaml b/locales/de.yaml index d3182561..7135354d 100644 --- a/locales/de.yaml +++ b/locales/de.yaml @@ -634,3 +634,4 @@ privacy: | *2. Wie wir die Informationen verwenden:* - _Reputationssystem:_ Um das Reputationssystem für jeden Benutzer aufzubauen und zu pflegen. - _Streitbeilegung:_ Im Falle eines Streits stellen wir dem Mediator (Löser) die folgenden Informationen zur Verfügung: Ihren Benutzernamen, Ihre Telegram-ID, die Anzahl der abgeschlossenen Transaktionen, die Bewertung des Gegenübers, die Anzahl der Tage, an denen Sie den Bot verwendet haben, und die Anzahl der angesammelten Streitfälle. +check_solvers: Ihre Community ${communityName} hat keine Solver. Bitte fügen Sie mindestens einen Solver hinzu, um eine Deaktivierung zu vermeiden. diff --git a/locales/en.yaml b/locales/en.yaml index a9d73982..a6b46da6 100644 --- a/locales/en.yaml +++ b/locales/en.yaml @@ -635,3 +635,4 @@ privacy: | *2. How We Use the Information:* - _Reputation System:_ To build and maintain the reputation system for each user. - _Dispute Resolution:_ In case of a dispute, we provide the mediator (solver) with the following information: your username, Telegram ID, number of completed transactions, counterpart's rating, number of days using the bot, and the number of accumulated disputes. +check_solvers: Your community ${communityName} doesn't have any solvers. Please add at least one solver to avoid being disabled. diff --git a/locales/es.yaml b/locales/es.yaml index 26cbc22a..2da210c8 100644 --- a/locales/es.yaml +++ b/locales/es.yaml @@ -634,3 +634,4 @@ privacy: | *2. Cómo Utilizamos la Información:* - _Sistema de Reputación:_ Para construir y mantener el sistema de reputación de cada usuario. - _Resolución de Disputas:_ En caso de una disputa, proporcionamos al mediador (solver) la siguiente información: tu nombre de usuario, ID de Telegram, número de transacciones concretadas, calificación de la contraparte, cantidad de días usando el bot y el número de disputas acumuladas. +check_solvers: Tu comunidad ${communityName} no tiene ningún solucionador. Agregue al menos un solucionador para evitar que se deshabilite. diff --git a/locales/fa.yaml b/locales/fa.yaml index 64fa703a..0eec59b7 100644 --- a/locales/fa.yaml +++ b/locales/fa.yaml @@ -633,3 +633,4 @@ privacy: | *۲. نحوه استفاده ما از اطلاعات:* - _سیستم اعتبار:_ برای ایجاد و حفظ سیستم اعتبار برای هر کاربر. - _حل اختلافات:_ در صورت بروز اختلاف، اطلاعات زیر را در اختیار میانجی (حل‌کننده) قرار می‌دهیم: نام کاربری شما، شناسه تلگرام، تعداد تراکنش‌های انجام شده، امتیاز طرف مقابل، تعداد روزهایی که از ربات استفاده کرده‌اید و تعداد اختلافات جمع شده. +check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً برای جلوگیری از غیرفعال شدن حداقل یک حل کننده اضافه کنید. diff --git a/locales/fr.yaml b/locales/fr.yaml index 7fe68d21..fd397d35 100644 --- a/locales/fr.yaml +++ b/locales/fr.yaml @@ -633,3 +633,4 @@ privacy: | *2. Comment nous utilisons les informations:* - _Système de réputation:_ Pour construire et maintenir le système de réputation de chaque utilisateur. - _Résolution des litiges:_ En cas de litige, nous fournissons au médiateur (solver) les informations suivantes : votre nom d'utilisateur, votre identifiant Telegram, le nombre de transactions effectuées, la note de la contrepartie, le nombre de jours d'utilisation du bot et le nombre de litiges accumulés. +check_solvers: Votre communauté ${communityName} n'a aucun solveur. Veuillez ajouter au moins un solveur pour éviter d'être désactivé. diff --git a/locales/it.yaml b/locales/it.yaml index b46301fe..2ef3610c 100644 --- a/locales/it.yaml +++ b/locales/it.yaml @@ -631,3 +631,4 @@ privacy: | *2. Come utilizziamo le informazioni:* - _Sistema di reputazione:_ Per costruire e mantenere il sistema di reputazione di ciascun utente. - _Risoluzione delle controversie:_ In caso di controversia, forniamo al mediatore (solver) le seguenti informazioni: il tuo nome utente, ID Telegram, numero di transazioni completate, valutazione della controparte, numero di giorni di utilizzo del bot e numero di controversie accumulate. +check_solvers: La tua community ${communityName} non ha risolutori. Aggiungi almeno un risolutore per evitare di essere disabilitato. diff --git a/locales/ko.yaml b/locales/ko.yaml index cd019dab..6ff4ea1a 100644 --- a/locales/ko.yaml +++ b/locales/ko.yaml @@ -629,3 +629,4 @@ privacy: | *2. 정보 사용 방법:* - _평판 시스템:_ 각 사용자의 평판 시스템을 구축하고 유지하기 위해 사용됩니다. - _분쟁 해결:_ 분쟁이 발생할 경우, 중재자(해결자)에게 사용자 이름, Telegram ID, 완료된 거래 수, 상대방의 평가, 봇 사용 일수, 누적된 분쟁 수와 같은 정보를 제공합니다. +check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 비활성화되지 않도록 하려면 솔버를 하나 이상 추가하세요. diff --git a/locales/pt.yaml b/locales/pt.yaml index 21c518e0..d0c8ec25 100644 --- a/locales/pt.yaml +++ b/locales/pt.yaml @@ -631,3 +631,4 @@ privacy: | *2. Como Usamos as Informações:* - _Sistema de Reputação:_ Para construir e manter o sistema de reputação de cada usuário. - _Resolução de Disputas:_ Em caso de uma disputa, fornecemos ao mediador (solver) as seguintes informações: seu nome de usuário, ID do Telegram, número de transações concluídas, classificação da contraparte, número de dias usando o bot e o número de disputas acumuladas. +check_solvers: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um solucionador para evitar ser desativado. diff --git a/locales/ru.yaml b/locales/ru.yaml index 32c5c2d2..531554c1 100644 --- a/locales/ru.yaml +++ b/locales/ru.yaml @@ -634,3 +634,4 @@ privacy: | *2. Как мы используем информацию:* - _Система репутации:_ Для создания и поддержания системы репутации каждого пользователя. - _Разрешение споров:_ В случае спора мы предоставляем медиатору (решателю) следующую информацию: ваше имя пользователя, ID Telegram, количество завершенных транзакций, рейтинг контрагента, количество дней использования бота и количество накопленных споров. +check_solvers: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один решатель, чтобы его не отключили. diff --git a/locales/uk.yaml b/locales/uk.yaml index 60ef8e2c..d6944f41 100644 --- a/locales/uk.yaml +++ b/locales/uk.yaml @@ -630,3 +630,4 @@ privacy: | *2. Як ми використовуємо інформацію:* - _Система репутації:_ Для створення та підтримки системи репутації для кожного користувача. - _Розв'язання спорів:_ У разі спору ми надаємо медіатору (розв'язувачу) наступну інформацію: ваше ім’я користувача, ID Telegram, кількість завершених транзакцій, рейтинг контрагента, кількість днів використання бота та кількість накопичених спорів. +check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Щоб уникнути вимкнення, додайте принаймні один розв’язувач.