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 2 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
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
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
52 changes: 52 additions & 0 deletions jobs/check_solvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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({ is_disabled: false });

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 to add a solver
if (community.messages_sent_count >= Number(process.env.MAX_MESSAGES)) {
community.is_disabled = true;
await community.save();

logger.info(`Community: ${community.name} has been disabled 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);

await bot.telegram.sendMessage(
admin.tg_id,
i18nCtx.t('check_solvers', { communityName: community.name })
);
}
}

export default checkSolvers;
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
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,
};
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} немає розв’язувачів. Щоб уникнути вимкнення, додайте принаймні один розв’язувач.
4 changes: 4 additions & 0 deletions models/community.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export interface ICommunity extends Document {
currencies: Array<string>;
created_at: Date;
nostr_public_key: string;
messages_sent_count: number;
is_disabled: boolean;
}

const CommunitySchema = new Schema<ICommunity>({
Expand Down Expand Up @@ -81,6 +83,8 @@ 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