Skip to content

Commit 1772689

Browse files
committed
chore: improve admin notification message
1 parent 9a547c9 commit 1772689

File tree

15 files changed

+39
-31
lines changed

15 files changed

+39
-31
lines changed

Diff for: bot/modules/community/commands.js

+4-8
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ async function findCommunities(currency) {
1919
const communities = await Community.find({
2020
currencies: currency,
2121
public: true,
22-
is_disabled: false,
2322
});
2423
const orderCount = await getOrderCountByCommunity();
2524
return communities.map(comm => {
@@ -51,9 +50,9 @@ exports.setComm = async ctx => {
5150
if (groupName[0] == '@') {
5251
// Allow find communities case insensitive
5352
const regex = new RegExp(['^', groupName, '$'].join(''), 'i');
54-
community = await Community.findOne({ group: regex, is_disabled: false });
53+
community = await Community.findOne({ group: regex });
5554
} else if (groupName[0] == '-') {
56-
community = await Community.findOne({ group: groupName, is_disabled: false });
55+
community = await Community.findOne({ group: groupName });
5756
}
5857
if (!community) {
5958
return await ctx.reply(ctx.i18n.t('community_not_found'));
@@ -73,7 +72,7 @@ exports.communityAdmin = async ctx => {
7372
const [group] = await validateParams(ctx, 2, '\\<_community_\\>');
7473
if (!group) return;
7574
const creator_id = ctx.user.id;
76-
const [community] = await Community.find({ group, creator_id, is_disabled: false });
75+
const [community] = await Community.find({ group, creator_id });
7776
if (!community) throw new Error('CommunityNotFound');
7877
await ctx.scene.enter('COMMUNITY_ADMIN', { community });
7978
} catch (err) {
@@ -92,7 +91,7 @@ exports.myComms = async ctx => {
9291
try {
9392
const { user } = ctx;
9493

95-
const communities = await Community.find({ creator_id: user._id, is_disabled: false });
94+
const communities = await Community.find({ creator_id: user._id });
9695

9796
if (!communities.length)
9897
return await ctx.reply(ctx.i18n.t('you_dont_have_communities'));
@@ -145,7 +144,6 @@ exports.updateCommunity = async (ctx, id, field, bot) => {
145144
const community = await Community.findOne({
146145
_id: id,
147146
creator_id: user._id,
148-
is_disabled: false,
149147
});
150148

151149
if (!community) {
@@ -214,7 +212,6 @@ exports.deleteCommunity = async ctx => {
214212
const community = await Community.findOne({
215213
_id: id,
216214
creator_id: ctx.user._id,
217-
is_disabled: false,
218215
});
219216

220217
if (!community) {
@@ -237,7 +234,6 @@ exports.changeVisibility = async ctx => {
237234
const community = await Community.findOne({
238235
_id: id,
239236
creator_id: ctx.user._id,
240-
is_disabled: false,
241237
});
242238

243239
if (!community) {

Diff for: bot/modules/orders/commands.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,13 @@ const sell = async ctx => {
4848
['^', '@' + ctx.message.chat.username, '$'].join(''),
4949
'i'
5050
);
51-
community = await Community.findOne({ group: regex, is_disabled: false });
51+
community = await Community.findOne({ group: regex });
5252
if (!community) return ctx.deleteMessage();
5353

5454
communityId = community._id;
5555
} else if (user.default_community_id) {
5656
communityId = user.default_community_id;
57-
community = await Community.findOne({ _id: communityId, is_disabled: false });
57+
community = await Community.findOne({ _id: communityId });
5858
if (!community) {
5959
user.default_community_id = null;
6060
await user.save();
@@ -114,15 +114,15 @@ const buy = async ctx => {
114114
['^', '@' + ctx.message.chat.username, '$'].join(''),
115115
'i'
116116
);
117-
community = await Community.findOne({ group: regex, is_disabled: false });
117+
community = await Community.findOne({ group: regex });
118118
if (!community) {
119119
ctx.deleteMessage();
120120
return;
121121
}
122122
communityId = community._id;
123123
} else if (user.default_community_id) {
124124
communityId = user.default_community_id;
125-
community = await Community.findOne({ _id: communityId, is_disabled: false });
125+
community = await Community.findOne({ _id: communityId });
126126
if (!community) {
127127
user.default_community_id = null;
128128
await user.save();

Diff for: jobs/check_solvers.ts

+10-6
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { getUserI18nContext } from '../util';
1010

1111
const checkSolvers = async (bot: Telegraf<MainContext>) => {
1212
try {
13-
const communities = await Community.find({ is_disabled: false });
13+
const communities = await Community.find();
1414

1515
for (const community of communities) {
1616
if (community.solvers.length > 0) {
@@ -27,12 +27,13 @@ const checkSolvers = async (bot: Telegraf<MainContext>) => {
2727

2828
const notifyAdmin = async (community: ICommunity, bot: Telegraf<MainContext>) => {
2929
community.messages_sent_count += 1;
30-
// The community is disabled if the admin has received the maximum notification message to add a solver
30+
/**
31+
* The community is disabled if the admin has received the maximum notification message (MAX_MESSAGES - 1) to add a solver.
32+
*/
3133
if (community.messages_sent_count >= Number(process.env.MAX_MESSAGES)) {
32-
community.is_disabled = true;
33-
await community.save();
34+
await community.delete();
3435

35-
logger.info(`Community: ${community.name} has been disabled due to lack of solvers.`);
36+
logger.info(`Community: ${community.name} has been deleted due to lack of solvers.`);
3637
return;
3738
}
3839

@@ -41,10 +42,13 @@ const notifyAdmin = async (community: ICommunity, bot: Telegraf<MainContext>) =>
4142

4243
if (admin) {
4344
const i18nCtx: I18nContext = await getUserI18nContext(admin);
45+
const remainingDays: number = (Number(process.env.MAX_MESSAGES) - 1) - community.messages_sent_count;
46+
47+
const message = remainingDays === 0 ? i18nCtx.t('check_solvers_last_warning', { communityName: community.name }) : i18nCtx.t('check_solvers', { communityName: community.name, remainingDays: remainingDays });
4448

4549
await bot.telegram.sendMessage(
4650
admin.tg_id,
47-
i18nCtx.t('check_solvers', { communityName: community.name })
51+
message,
4852
);
4953
}
5054
}

Diff for: jobs/communities.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { logger } from "../logger";
66

77
const deleteCommunity = async (bot: Telegraf<MainContext>) => {
88
try {
9-
const communities = await Community.find({ is_disabled: false });
9+
const communities = await Community.find();
1010
for (const community of communities) {
1111
// Delete communities with COMMUNITY_TTL days without a successful order
1212
const days = 86400 * Number(process.env.COMMUNITY_TTL);

Diff for: locales/de.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -634,4 +634,5 @@ privacy: |
634634
*2. Wie wir die Informationen verwenden:*
635635
- _Reputationssystem:_ Um das Reputationssystem für jeden Benutzer aufzubauen und zu pflegen.
636636
- _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.
637-
check_solvers: Ihre Community ${communityName} hat keine Solver. Bitte fügen Sie mindestens einen Solver hinzu, um eine Deaktivierung zu vermeiden.
637+
check_solvers: Ihre Community ${communityName} hat keine Solver. Bitte fügen Sie innerhalb von ${remainingDays} Tagen mindestens einen hinzu, um zu verhindern, dass die Community deaktiviert wird.
638+
check_solvers_last_warning: Ihre Community ${communityName} hat keine Solver. Bitte fügen Sie noch heute mindestens einen hinzu, um zu verhindern, dass die Community deaktiviert wird.

Diff for: locales/en.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -635,4 +635,5 @@ privacy: |
635635
*2. How We Use the Information:*
636636
- _Reputation System:_ To build and maintain the reputation system for each user.
637637
- _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.
638-
check_solvers: Your community ${communityName} doesn't have any solvers. Please add at least one solver to avoid being disabled.
638+
check_solvers: Your community ${communityName} does not have any solvers. Please add at least one within ${remainingDays} days to prevent the community from being disabled.
639+
check_solvers_last_warning: Your community ${communityName} does not have any solvers. Please add at least one today to prevent the community from being disabled.

Diff for: locales/es.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -634,4 +634,5 @@ privacy: |
634634
*2. Cómo Utilizamos la Información:*
635635
- _Sistema de Reputación:_ Para construir y mantener el sistema de reputación de cada usuario.
636636
- _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.
637-
check_solvers: Tu comunidad ${communityName} no tiene ningún solucionador. Agregue al menos un solucionador para evitar que se deshabilite.
637+
check_solvers: Tu comunidad ${communityName} no tiene ningún solucionador. Agregue al menos uno dentro de ${remainingDays} días para evitar que se deshabilite la comunidad.
638+
check_solvers_last_warning: Tu comunidad ${communityName} no tiene ningún solucionador. Agregue al menos uno hoy para evitar que la comunidad quede inhabilitada.

Diff for: locales/fa.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -633,4 +633,5 @@ privacy: |
633633
*۲. نحوه استفاده ما از اطلاعات:*
634634
- _سیستم اعتبار:_ برای ایجاد و حفظ سیستم اعتبار برای هر کاربر.
635635
- _حل اختلافات:_ در صورت بروز اختلاف، اطلاعات زیر را در اختیار میانجی (حل‌کننده) قرار می‌دهیم: نام کاربری شما، شناسه تلگرام، تعداد تراکنش‌های انجام شده، امتیاز طرف مقابل، تعداد روزهایی که از ربات استفاده کرده‌اید و تعداد اختلافات جمع شده.
636-
check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً برای جلوگیری از غیرفعال شدن حداقل یک حل کننده اضافه کنید.
636+
check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً حداقل یک مورد را ظرف ${remainingDays} روز اضافه کنید تا از غیرفعال شدن انجمن جلوگیری کنید.
637+
check_solvers_last_warning: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً امروز حداقل یکی اضافه کنید تا از غیرفعال شدن انجمن جلوگیری کنید.

Diff for: locales/fr.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -633,4 +633,5 @@ privacy: |
633633
*2. Comment nous utilisons les informations:*
634634
- _Système de réputation:_ Pour construire et maintenir le système de réputation de chaque utilisateur.
635635
- _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.
636-
check_solvers: Votre communauté ${communityName} n'a aucun solveur. Veuillez ajouter au moins un solveur pour éviter d'être désactivé.
636+
check_solvers: Votre communauté ${communityName} ne possède aucun solveur. Veuillez en ajouter au moins un dans les ${remainingDays} jours pour éviter que la communauté ne soit désactivée.
637+
check_solvers_last_warning: Votre communauté ${communityName} ne possède aucun solveur. Veuillez en ajouter au moins un aujourd'hui pour éviter que la communauté ne soit désactivée.

Diff for: locales/it.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -631,4 +631,5 @@ privacy: |
631631
*2. Come utilizziamo le informazioni:*
632632
- _Sistema di reputazione:_ Per costruire e mantenere il sistema di reputazione di ciascun utente.
633633
- _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.
634-
check_solvers: La tua community ${communityName} non ha risolutori. Aggiungi almeno un risolutore per evitare di essere disabilitato.
634+
check_solvers: La tua community ${communityName} non ha risolutori. Aggiungine almeno uno entro ${remainingDays} giorni per evitare che la community venga disabilitata.
635+
check_solvers_last_warning: La tua community ${communityName} non ha risolutori. Per favore aggiungine almeno uno oggi per evitare che la community venga disabilitata.

Diff for: locales/ko.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -629,4 +629,5 @@ privacy: |
629629
*2. 정보 사용 방법:*
630630
- _평판 시스템:_ 각 사용자의 평판 시스템을 구축하고 유지하기 위해 사용됩니다.
631631
- _분쟁 해결:_ 분쟁이 발생할 경우, 중재자(해결자)에게 사용자 이름, Telegram ID, 완료된 거래 수, 상대방의 평가, 봇 사용 일수, 누적된 분쟁 수와 같은 정보를 제공합니다.
632-
check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 비활성화되지 않도록 하려면 솔버를 하나 이상 추가하세요.
632+
check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 커뮤니티가 비활성화되는 것을 방지하려면 ${remainingDays}일 이내에 하나 이상 추가하세요.
633+
check_solvers_last_warning: ${communityName} 커뮤니티에 해결사가 없습니다. 커뮤니티가 비활성화되는 것을 방지하려면 오늘 하나 이상 추가하세요.

Diff for: locales/pt.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -631,4 +631,5 @@ privacy: |
631631
*2. Como Usamos as Informações:*
632632
- _Sistema de Reputação:_ Para construir e manter o sistema de reputação de cada usuário.
633633
- _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.
634-
check_solvers: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um solucionador para evitar ser desativado.
634+
check_solvers: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um dentro de ${remainingDays} dias para evitar que a comunidade seja desativada.
635+
check_solvers_last_warning: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um hoje para evitar que a comunidade seja desativada.

Diff for: locales/ru.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -634,4 +634,5 @@ privacy: |
634634
*2. Как мы используем информацию:*
635635
- _Система репутации:_ Для создания и поддержания системы репутации каждого пользователя.
636636
- _Разрешение споров:_ В случае спора мы предоставляем медиатору (решателю) следующую информацию: ваше имя пользователя, ID Telegram, количество завершенных транзакций, рейтинг контрагента, количество дней использования бота и количество накопленных споров.
637-
check_solvers: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один решатель, чтобы его не отключили.
637+
check_solvers: В вашем сообществе ${communityName} нет решателей. Добавьте хотя бы одно в течение ${remainingDays} дн., чтобы сообщество не было отключено.
638+
check_solvers_last_warning: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один сегодня, чтобы предотвратить отключение сообщества.

Diff for: locales/uk.yaml

+2-1
Original file line numberDiff line numberDiff line change
@@ -630,4 +630,5 @@ privacy: |
630630
*2. Як ми використовуємо інформацію:*
631631
- _Система репутації:_ Для створення та підтримки системи репутації для кожного користувача.
632632
- _Розв'язання спорів:_ У разі спору ми надаємо медіатору (розв'язувачу) наступну інформацію: ваше ім’я користувача, ID Telegram, кількість завершених транзакцій, рейтинг контрагента, кількість днів використання бота та кількість накопичених спорів.
633-
check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Щоб уникнути вимкнення, додайте принаймні один розв’язувач.
633+
check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Додайте принаймні одну протягом ${remainingDays} днів, щоб запобігти вимкненню спільноти.
634+
check_solvers_last_warning: У вашій спільноті ${communityName} немає розв’язувачів. Будь ласка, додайте принаймні одну сьогодні, щоб запобігти вимкненню спільноти.

Diff for: models/community.ts

-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ export interface ICommunity extends Document {
5050
created_at: Date;
5151
nostr_public_key: string;
5252
messages_sent_count: number;
53-
is_disabled: boolean;
5453
}
5554

5655
const CommunitySchema = new Schema<ICommunity>({
@@ -84,7 +83,6 @@ const CommunitySchema = new Schema<ICommunity>({
8483
created_at: { type: Date, default: Date.now },
8584
nostr_public_key: { type: String },
8685
messages_sent_count: { type: Number, default: 0 },
87-
is_disabled: { type: Boolean, default: false },
8886
});
8987

9088

0 commit comments

Comments
 (0)