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

Add cronjob to notify admin about missing solvers (#314) #563

Closed
wants to merge 5 commits into from
Closed
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 messages before disabling the community
COMMUNITY_MESSAGES=5
5 changes: 5 additions & 0 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const {
attemptCommunitiesPendingPayments,
deleteCommunity,
nodeInfo,
checkSolvers,
} = require('../jobs');
const { logger } = require('../logger');
export interface MainContext extends Context {
Expand Down Expand Up @@ -197,6 +198,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
37 changes: 37 additions & 0 deletions jobs/check_solvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Community, User } from '../models';
import { Telegraf } from 'telegraf';
import { MainContext } from '../bot/start';
import { logger } from '../logger';

const MESSAGES: number = parseInt(process.env.COMMUNITY_MESSAGES || '5');

exports.checkSolvers = async (ctx: MainContext, bot: Telegraf<MainContext>): Promise<void> => {
try {
const communities = await Community.find({ isDisabled: false });

for (const community of communities) {
const solvers = await User.find({ default_community_id: community._id, role: 'solver' });

if (solvers.length === 0) {
community.messagesSent += 1;

if (community.messagesSent >= MESSAGES) {
community.isDisabled = true;
await community.save();
logger.info(`Community ${community._id} has been disabled due to lack of solvers.`);
} else {
await community.save();
const admin = await User.findOne({ tg_id: community.creator_id, admin: true });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

user.admin is only used for global admin, not community admins, we don't need to add it on this findOne() request

if (admin) {
await bot.telegram.sendMessage(admin.tg_id, ctx.i18n.t('check_solvers'));
}
}
} else {
community.messagesSent = 0; // Reset the counter if solvers are added
await community.save();
}
}
} catch (error) {
logger.error(error);
}
};
2 changes: 2 additions & 0 deletions jobs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const deleteOrders = require('./delete_published_orders');
const calculateEarnings = require('./calculate_community_earnings');
const deleteCommunity = require('./communities');
const nodeInfo = require('./node_info');
const checkSolvers = require('./check_solvers');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @doitwithnotepad please test the code before push a commit, that way you'll see if it works or not

we are getting the same error

error: Unhandled Rejection: TypeError: checkSolvers is not a function

this is because the function checkSolvers() is not well imported, please replace with:

const { checkSolvers } = require('./check_solvers');


module.exports = {
attemptPendingPayments,
Expand All @@ -16,4 +17,5 @@ module.exports = {
attemptCommunitiesPendingPayments,
deleteCommunity,
nodeInfo,
checkSolvers,
};
4 changes: 4 additions & 0 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -619,3 +619,7 @@ order_frozen: Sie haben die Bestellung eingefroren
dispute_solver: 👮‍♂️ Ein Löser wird sich um Ihren Streitfall kümmern, Sie können ihn/sie direkt anschreiben, indem Sie auf seinen/ihren Benutzernamen tippen => @${solver} <=, wenn der Löser Sie zuerst anschreibt, sollten Sie ihn/sie bitten, Ihnen mitzuteilen, was das Token Ihres Streitfalls ist, Ihr Token ist ${token}.
setinvoice_no_response: Sie haben keine zu bezahlenden Aufträge
already_cancelled: Die Bestellung wurde bereits storniert!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -620,3 +620,7 @@ disclaimer: |
order_frozen: You have frozen the order
dispute_solver: 👮‍♂️ A solver will be attending your dispute, you can write to him/her directly by tapping his/her username => @${solver} <=, if the solver writes to you first, you should ask him/her to tell you what is the token of your dispute, your token is ${token}.
setinvoice_no_response: You have no orders to be paid

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,7 @@ order_frozen: Has congelado la orden
dispute_solver: 👮‍♂️ Un solver estará atendiendo tu disputa, puedes escribirle directamente tocando su username => @${solver} <=, si el/la solver te escribe primero, debes pedirle que te diga cuál es el token de tu disputa, tu token es ${token}.
setinvoice_no_response: No tienes ordenes a ser pagadas
already_cancelled: ¡La orden ya ha sido cancelada!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,7 @@ order_frozen: شما سفارش را مسدود کردید
dispute_solver: 👮‍♂️ یک حل‌کننده در دعوای شما شرکت خواهد کرد، می‌توانید با ضربه زدن روی نام کاربری او مستقیماً برای او بنویسید => @${solver} <=، اگر حل‌کننده ابتدا برای شما نامه نوشت، باید از او بخواهید که به شما بگویم که نشانه اختلاف شما چیست، رمز شما ${token} است.
setinvoice_no_response: هیچ سفارشی برای پرداخت ندارید
already_cancelled: سفارش قبلاً لغو شده است!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,7 @@ order_frozen: Vous avez gelé la commande
dispute_solver: 👮‍♂️ Un résolveur va s'occuper de votre litige, vous pouvez lui écrire directement en tapant son nom d'utilisateur => @${solver} <=, si le résolveur vous écrit en premier, vous devriez lui demander de vous dire quel est le jeton de votre litige, votre jeton est ${token}.
setinvoice_no_response : Vous n'avez pas d'ordre à payer
already_cancelled: L'offre a déjà été annulée !

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -616,3 +616,7 @@ order_frozen: hai congelato l'ordine
dispute_solver: 👮‍♂️ Un solutore si occuperà della vostra controversia, potete scrivergli direttamente toccando il suo nome utente => @${solver} <=, se il solutore vi scrive per primo, dovreste chiedergli di dirvi qual è il token della vostra controversia, il vostro token è ${token}.
setinvoice_no_response: Non ci sono ordini da pagare.
already_cancelled: L'offerta è già stata annullata!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -614,3 +614,7 @@ disclaimer: |
dispute_solver: 👮‍♂️ 분쟁 해결사가 분쟁에 참석할 것이며, 사용자 아이디 => @${해결사} <=를 눌러 해결사에게 직접 편지를 보낼 수 있으며, 해결사가 먼저 편지를 보내면 분쟁의 토큰이 무엇인지 물어봐야 하며, 토큰은 ${토큰}입니다.
setinvoice_no_response: 결제할 주문이 없습니다.
already_cancelled: 오퍼가 이미 취소되었습니다!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -616,3 +616,7 @@ order_frozen: Você congelou o pedido
dispute_solver: 👮‍♂️ Um solucionador atenderá sua disputa. Você pode escrever para ele diretamente tocando no nome de usuário dele => @${solver} <=, se o solucionador escrever para você primeiro, você deve pedir a ele que lhe diga qual é o token de sua disputa, seu token é ${token}.
setinvoice_no_response: Você não tem ordens a serem pagas
already_cancelled: A oferta já foi cancelada!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -619,3 +619,7 @@ order_frozen: вы заморозили заказ
dispute_solver: 👮‍♂️ На вашем споре будет присутствовать решатель, вы можете написать ему напрямую, нажав его имя пользователя => @${solver} <=, если решатель напишет вам первым, вы должны попросить его сообщить вам, какой токен у вашего спора, ваш токен - ${token}.
setinvoice_no_response: У вас нет заказов для оплаты
already_cancelled: Предложение уже отменено!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
4 changes: 4 additions & 0 deletions locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -615,3 +615,7 @@ order_frozen: Ви заморозили замовлення
dispute_solver: 👮‍♂️ У вашій суперечці буде присутній розв'язувач, ви можете написати йому безпосередньо, натиснувши його ім'я користувача => @${solver} <=, якщо розв'язувач напише вам першим, ви повинні попросити його повідомити вам токен вашої суперечки, вашим токеном буде ${token}.
setinvoice_no_response: У вас немає замовлень для оплати
already_cancelled: Пропозицію вже скасовано!

# START jobs/check_solvers
check_solvers: Your community ${community.name} doesn't have any solvers. Please add at least one solver.
# END jobs/check_solvers
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;
messagesSent: number;
isDisabled: 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 },
messagesSent: { type: Number, default: 0 },
isDisabled: { type: Boolean, default: false },
});


Expand Down
Loading