Skip to content

Commit

Permalink
chore: improve admin notification message
Browse files Browse the repository at this point in the history
  • Loading branch information
Anyitechs committed Jan 20, 2025
1 parent 9a547c9 commit bf0258f
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 34 deletions.
18 changes: 7 additions & 11 deletions bot/modules/community/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ async function findCommunities(currency) {
const communities = await Community.find({
currencies: currency,
public: true,
is_disabled: false,
});
const orderCount = await getOrderCountByCommunity();
return communities.map(comm => {
Expand Down Expand Up @@ -51,9 +50,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, is_disabled: false });
community = await Community.findOne({ group: regex });
} else if (groupName[0] == '-') {
community = await Community.findOne({ group: groupName, is_disabled: false });
community = await Community.findOne({ group: groupName });
}
if (!community) {
return await ctx.reply(ctx.i18n.t('community_not_found'));
Expand All @@ -73,7 +72,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, is_disabled: false });
const [community] = await Community.find({ group, creator_id });
if (!community) throw new Error('CommunityNotFound');
await ctx.scene.enter('COMMUNITY_ADMIN', { community });
} catch (err) {
Expand All @@ -92,7 +91,7 @@ exports.myComms = async ctx => {
try {
const { user } = ctx;

const communities = await Community.find({ creator_id: user._id, is_disabled: false });
const communities = await Community.find({ creator_id: user._id });

if (!communities.length)
return await ctx.reply(ctx.i18n.t('you_dont_have_communities'));
Expand Down Expand Up @@ -144,8 +143,7 @@ exports.updateCommunity = async (ctx, id, field, bot) => {
if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findOne({
_id: id,
creator_id: user._id,
is_disabled: false,
creator_id: user._id
});

if (!community) {
Expand Down Expand Up @@ -213,8 +211,7 @@ exports.deleteCommunity = async ctx => {
if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findOne({
_id: id,
creator_id: ctx.user._id,
is_disabled: false,
creator_id: ctx.user._id
});

if (!community) {
Expand All @@ -236,8 +233,7 @@ exports.changeVisibility = async ctx => {
if (!(await validateObjectId(ctx, id))) return;
const community = await Community.findOne({
_id: id,
creator_id: ctx.user._id,
is_disabled: false,
creator_id: ctx.user._id
});

if (!community) {
Expand Down
8 changes: 4 additions & 4 deletions bot/modules/orders/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ const sell = async ctx => {
['^', '@' + ctx.message.chat.username, '$'].join(''),
'i'
);
community = await Community.findOne({ group: regex, is_disabled: false });
community = await Community.findOne({ group: regex });
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, is_disabled: false });
community = await Community.findOne({ _id: communityId });
if (!community) {
user.default_community_id = null;
await user.save();
Expand Down Expand Up @@ -114,15 +114,15 @@ const buy = async ctx => {
['^', '@' + ctx.message.chat.username, '$'].join(''),
'i'
);
community = await Community.findOne({ group: regex, is_disabled: false });
community = await Community.findOne({ group: regex });
if (!community) {
ctx.deleteMessage();
return;
}
communityId = community._id;
} else if (user.default_community_id) {
communityId = user.default_community_id;
community = await Community.findOne({ _id: communityId, is_disabled: false });
community = await Community.findOne({ _id: communityId });
if (!community) {
user.default_community_id = null;
await user.save();
Expand Down
16 changes: 10 additions & 6 deletions jobs/check_solvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getUserI18nContext } from '../util';

const checkSolvers = async (bot: Telegraf<MainContext>) => {
try {
const communities = await Community.find({ is_disabled: false });
const communities = await Community.find();

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

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

logger.info(`Community: ${community.name} has been disabled due to lack of solvers.`);
logger.info(`Community: ${community.name} has been deleted due to lack of solvers.`);
return;
}

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

if (admin) {
const i18nCtx: I18nContext = await getUserI18nContext(admin);
const remainingDays: number = (Number(process.env.MAX_MESSAGES) - 1) - community.messages_sent_count;

const message = remainingDays === 0 ? i18nCtx.t('check_solvers_last_warning', { communityName: community.name }) : i18nCtx.t('check_solvers', { communityName: community.name, remainingDays: remainingDays });

await bot.telegram.sendMessage(
admin.tg_id,
i18nCtx.t('check_solvers', { communityName: community.name })
message
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion jobs/communities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { logger } from "../logger";

const deleteCommunity = async (bot: Telegraf<MainContext>) => {
try {
const communities = await Community.find({ is_disabled: false });
const communities = await Community.find();
for (const community of communities) {
// Delete communities with COMMUNITY_TTL days without a successful order
const days = 86400 * Number(process.env.COMMUNITY_TTL);
Expand Down
3 changes: 2 additions & 1 deletion locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -634,4 +634,5 @@ 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.
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.
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.
3 changes: 2 additions & 1 deletion locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -635,4 +635,5 @@ 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.
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.
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.
3 changes: 2 additions & 1 deletion locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -634,4 +634,5 @@ 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.
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.
check_solvers_last_warning: Tu comunidad ${communityName} no tiene ningún solucionador. Agregue al menos uno hoy para evitar que la comunidad quede inhabilitada.
3 changes: 2 additions & 1 deletion locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -633,4 +633,5 @@ privacy: |
*۲. نحوه استفاده ما از اطلاعات:*
- _سیستم اعتبار:_ برای ایجاد و حفظ سیستم اعتبار برای هر کاربر.
- _حل اختلافات:_ در صورت بروز اختلاف، اطلاعات زیر را در اختیار میانجی (حل‌کننده) قرار می‌دهیم: نام کاربری شما، شناسه تلگرام، تعداد تراکنش‌های انجام شده، امتیاز طرف مقابل، تعداد روزهایی که از ربات استفاده کرده‌اید و تعداد اختلافات جمع شده.
check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً برای جلوگیری از غیرفعال شدن حداقل یک حل کننده اضافه کنید.
check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً حداقل یک مورد را ظرف ${remainingDays} روز اضافه کنید تا از غیرفعال شدن انجمن جلوگیری کنید.
check_solvers_last_warning: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً امروز حداقل یکی اضافه کنید تا از غیرفعال شدن انجمن جلوگیری کنید.
3 changes: 2 additions & 1 deletion locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -633,4 +633,5 @@ 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é.
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.
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.
3 changes: 2 additions & 1 deletion locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -631,4 +631,5 @@ 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.
check_solvers: La tua community ${communityName} non ha risolutori. Aggiungine almeno uno entro ${remainingDays} giorni per evitare che la community venga disabilitata.
check_solvers_last_warning: La tua community ${communityName} non ha risolutori. Per favore aggiungine almeno uno oggi per evitare che la community venga disabilitata.
3 changes: 2 additions & 1 deletion locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -629,4 +629,5 @@ privacy: |
*2. 정보 사용 방법:*
- _평판 시스템:_ 각 사용자의 평판 시스템을 구축하고 유지하기 위해 사용됩니다.
- _분쟁 해결:_ 분쟁이 발생할 경우, 중재자(해결자)에게 사용자 이름, Telegram ID, 완료된 거래 수, 상대방의 평가, 봇 사용 일수, 누적된 분쟁 수와 같은 정보를 제공합니다.
check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 비활성화되지 않도록 하려면 솔버를 하나 이상 추가하세요.
check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 커뮤니티가 비활성화되는 것을 방지하려면 ${remainingDays}일 이내에 하나 이상 추가하세요.
check_solvers_last_warning: ${communityName} 커뮤니티에 해결사가 없습니다. 커뮤니티가 비활성화되는 것을 방지하려면 오늘 하나 이상 추가하세요.
3 changes: 2 additions & 1 deletion locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -631,4 +631,5 @@ 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.
check_solvers: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um dentro de ${remainingDays} dias para evitar que a comunidade seja desativada.
check_solvers_last_warning: Sua comunidade ${communityName} não possui solucionadores. Adicione pelo menos um hoje para evitar que a comunidade seja desativada.
3 changes: 2 additions & 1 deletion locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -634,4 +634,5 @@ privacy: |
*2. Как мы используем информацию:*
- _Система репутации:_ Для создания и поддержания системы репутации каждого пользователя.
- _Разрешение споров:_ В случае спора мы предоставляем медиатору (решателю) следующую информацию: ваше имя пользователя, ID Telegram, количество завершенных транзакций, рейтинг контрагента, количество дней использования бота и количество накопленных споров.
check_solvers: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один решатель, чтобы его не отключили.
check_solvers: В вашем сообществе ${communityName} нет решателей. Добавьте хотя бы одно в течение ${remainingDays} дн., чтобы сообщество не было отключено.
check_solvers_last_warning: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один сегодня, чтобы предотвратить отключение сообщества.
3 changes: 2 additions & 1 deletion locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -630,4 +630,5 @@ privacy: |
*2. Як ми використовуємо інформацію:*
- _Система репутації:_ Для створення та підтримки системи репутації для кожного користувача.
- _Розв'язання спорів:_ У разі спору ми надаємо медіатору (розв'язувачу) наступну інформацію: ваше ім’я користувача, ID Telegram, кількість завершених транзакцій, рейтинг контрагента, кількість днів використання бота та кількість накопичених спорів.
check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Щоб уникнути вимкнення, додайте принаймні один розв’язувач.
check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Додайте принаймні одну протягом ${remainingDays} днів, щоб запобігти вимкненню спільноти.
check_solvers_last_warning: У вашій спільноті ${communityName} немає розв’язувачів. Будь ласка, додайте принаймні одну сьогодні, щоб запобігти вимкненню спільноти.
2 changes: 0 additions & 2 deletions models/community.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export interface ICommunity extends Document {
created_at: Date;
nostr_public_key: string;
messages_sent_count: number;
is_disabled: boolean;
}

const CommunitySchema = new Schema<ICommunity>({
Expand Down Expand Up @@ -84,7 +83,6 @@ const CommunitySchema = new Schema<ICommunity>({
created_at: { type: Date, default: Date.now },
nostr_public_key: { type: String },
messages_sent_count: { type: Number, default: 0 },
is_disabled: { type: Boolean, default: false },
});


Expand Down

0 comments on commit bf0258f

Please sign in to comment.