Skip to content

Commit

Permalink
fix: notification messages not being sent to the admin and ensure mes…
Browse files Browse the repository at this point in the history
…sages are localized
  • Loading branch information
Anyitechs committed Jan 3, 2025
1 parent 6ad31a8 commit 9a547c9
Show file tree
Hide file tree
Showing 15 changed files with 35 additions and 15 deletions.
5 changes: 4 additions & 1 deletion .env-sample
Original file line number Diff line number Diff line change
Expand Up @@ -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
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
12 changes: 8 additions & 4 deletions bot/modules/community/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -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'));
Expand All @@ -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) {
Expand All @@ -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'));
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
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 });
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();
Expand Down Expand Up @@ -114,15 +114,15 @@ 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;
}
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();
Expand Down
13 changes: 8 additions & 5 deletions jobs/check_solvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MainContext>) => {
try {
Expand All @@ -27,7 +28,7 @@ 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
if (community.messages_sent_count >= MAX_MESSAGES) {
if (community.messages_sent_count >= Number(process.env.MAX_MESSAGES)) {
community.is_disabled = true;
await community.save();

Expand All @@ -36,12 +37,14 @@ const notifyAdmin = async (community: ICommunity, bot: Telegraf<MainContext>) =>
}

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 })
);
}
}
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();
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);
Expand Down
1 change: 1 addition & 0 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -633,3 +633,4 @@ privacy: |
*۲. نحوه استفاده ما از اطلاعات:*
- _سیستم اعتبار:_ برای ایجاد و حفظ سیستم اعتبار برای هر کاربر.
- _حل اختلافات:_ در صورت بروز اختلاف، اطلاعات زیر را در اختیار میانجی (حل‌کننده) قرار می‌دهیم: نام کاربری شما، شناسه تلگرام، تعداد تراکنش‌های انجام شده، امتیاز طرف مقابل، تعداد روزهایی که از ربات استفاده کرده‌اید و تعداد اختلافات جمع شده.
check_solvers: انجمن ${communityName} شما هیچ راه حلی ندارد. لطفاً برای جلوگیری از غیرفعال شدن حداقل یک حل کننده اضافه کنید.
1 change: 1 addition & 0 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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é.
1 change: 1 addition & 0 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -629,3 +629,4 @@ privacy: |
*2. 정보 사용 방법:*
- _평판 시스템:_ 각 사용자의 평판 시스템을 구축하고 유지하기 위해 사용됩니다.
- _분쟁 해결:_ 분쟁이 발생할 경우, 중재자(해결자)에게 사용자 이름, Telegram ID, 완료된 거래 수, 상대방의 평가, 봇 사용 일수, 누적된 분쟁 수와 같은 정보를 제공합니다.
check_solvers: ${communityName} 커뮤니티에 해결사가 없습니다. 비활성화되지 않도록 하려면 솔버를 하나 이상 추가하세요.
1 change: 1 addition & 0 deletions locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -634,3 +634,4 @@ privacy: |
*2. Как мы используем информацию:*
- _Система репутации:_ Для создания и поддержания системы репутации каждого пользователя.
- _Разрешение споров:_ В случае спора мы предоставляем медиатору (решателю) следующую информацию: ваше имя пользователя, ID Telegram, количество завершенных транзакций, рейтинг контрагента, количество дней использования бота и количество накопленных споров.
check_solvers: В вашем сообществе ${communityName} нет решателей. Пожалуйста, добавьте хотя бы один решатель, чтобы его не отключили.
1 change: 1 addition & 0 deletions locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -630,3 +630,4 @@ privacy: |
*2. Як ми використовуємо інформацію:*
- _Система репутації:_ Для створення та підтримки системи репутації для кожного користувача.
- _Розв'язання спорів:_ У разі спору ми надаємо медіатору (розв'язувачу) наступну інформацію: ваше ім’я користувача, ID Telegram, кількість завершених транзакцій, рейтинг контрагента, кількість днів використання бота та кількість накопичених спорів.
check_solvers: У вашій спільноті ${communityName} немає розв’язувачів. Щоб уникнути вимкнення, додайте принаймні один розв’язувач.

0 comments on commit 9a547c9

Please sign in to comment.