Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: notify admin to update solvers in the community #618

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
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
5 changes: 5 additions & 0 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
attemptCommunitiesPendingPayments,
deleteCommunity,
nodeInfo,
checkSolvers,
} from '../jobs';
import { logger } from "../logger";
import { ICommunity, IUsernameId } from '../models/community';
Expand Down Expand Up @@ -199,6 +200,10 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
await nodeInfo(bot);
});

schedule.scheduleJob(`0 0 * * *`, async () => {
await checkSolvers(bot);
});

bot.start(async (ctx: MainContext) => {
try {
if (!('message' in ctx.update) || !('text' in ctx.update.message)){
Expand Down
56 changes: 56 additions & 0 deletions jobs/check_solvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Telegraf } from 'telegraf';
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 checkSolvers = async (bot: Telegraf<MainContext>) => {
try {
const communities = await Community.find();

for (const community of communities) {
if (community.solvers.length > 0) {
continue;
} else {
await notifyAdmin(community, bot);
}
}
} catch (error) {
const message = String(error);
logger.error(`checkSolvers catch error: ${message}`);
}
};

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 (MAX_MESSAGES - 1) to add a solver.
*/
if (community.messages_sent_count >= Number(process.env.MAX_MESSAGES)) {
await community.delete();

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

await community.save();
const admin = await User.findById(community.creator_id);

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,
message,
);
}
}

export default checkSolvers;
2 changes: 2 additions & 0 deletions jobs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import deleteOrders from "./delete_published_orders";
import calculateEarnings from './calculate_community_earnings'
import deleteCommunity from './communities'
import nodeInfo from './node_info'
import checkSolvers from "./check_solvers";

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

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


Expand Down