Skip to content
18 changes: 15 additions & 3 deletions bot/modules/community/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ const getVolumeNDays = async (

export const onCommunityInfo = async (ctx: MainContext) => {
const commId = ctx.match?.[1];
const community = await Community.findById(commId);
if (community === null) throw new Error('community not found');
const community = await Community.findOne({
_id: commId,
enabled: { $ne: false },
});
if (community === null) return ctx.reply(ctx.i18n.t('community_not_found'));
const userCount = await User.countDocuments({ default_community_id: commId });
Comment thread
Matobi98 marked this conversation as resolved.
const orderCount = await getOrdersNDays(1, commId);
const volume = await getVolumeNDays(1, commId);
Expand Down Expand Up @@ -111,6 +114,11 @@ export const onCommunityInfo = async (ctx: MainContext) => {
export const onSetCommunity = async (ctx: CommunityContext) => {
const tgId = (ctx.update as any).callback_query.from.id;
const defaultCommunityId = ctx.match?.[1];
const community = await Community.findOne({
_id: defaultCommunityId,
enabled: { $ne: false },
});
if (!community) return ctx.reply(ctx.i18n.t('community_not_found'));
await User.findOneAndUpdate(
{ tg_id: tgId },
{ default_community_id: defaultCommunityId },
Expand All @@ -120,7 +128,11 @@ export const onSetCommunity = async (ctx: CommunityContext) => {

export const withdrawEarnings = async (ctx: CommunityContext) => {
ctx.deleteMessage();
const community = await Community.findById(ctx.match?.[1]);
const community = await Community.findOne({
_id: ctx.match?.[1],
enabled: { $ne: false },
});
if (!community) return ctx.reply(ctx.i18n.t('community_not_found'));
ctx.scene.enter('ADD_EARNINGS_INVOICE_WIZARD_SCENE_ID', {
community,
});
Expand Down
127 changes: 122 additions & 5 deletions bot/modules/community/commands.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* eslint-disable no-underscore-dangle */
import { logger } from '../../../logger';
import { showUserCommunitiesMessage } from './messages';
import { Community, Order } from '../../../models';
import { Community, Order, User } from '../../../models';
import { validateParams, validateObjectId } from '../../validations';
import { MainContext } from '../../start';
import { CommunityContext } from './communityContext';
import { Telegraf } from 'telegraf';
import { getUserI18nContext } from '../../../util';

async function getOrderCountByCommunity(): Promise<number[]> {
const data = await Order.aggregate([
Expand All @@ -21,6 +22,7 @@ async function findCommunities(currency: string) {
const communities = await Community.find({
currencies: currency,
public: true,
enabled: { $ne: false },
});
const orderCount = await getOrderCountByCommunity();
return communities.map(comm => {
Expand Down Expand Up @@ -49,9 +51,15 @@ export const setComm = async (ctx: MainContext) => {
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,
enabled: { $ne: false },
});
} else if (groupName[0] == '-') {
community = await Community.findOne({ group: groupName });
community = await Community.findOne({
group: groupName,
enabled: { $ne: false },
});
}
if (!community) {
return await ctx.reply(ctx.i18n.t('community_not_found'));
Expand All @@ -70,7 +78,11 @@ export const communityAdmin = async (ctx: CommunityContext) => {
try {
const [group] = (await validateParams(ctx, 2, '\\<_community_\\>'))!;
const creator_id = ctx.user.id;
const [community] = await Community.find({ group, creator_id });
const [community] = await Community.find({
group,
creator_id,
enabled: { $ne: false },
});
if (!community) throw new Error('CommunityNotFound');
await ctx.scene.enter('COMMUNITY_ADMIN', { community });
} catch (err: any) {
Expand All @@ -89,7 +101,10 @@ export const myComms = async (ctx: MainContext) => {
try {
const { user } = ctx;

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

if (!communities.length)
return await ctx.reply(ctx.i18n.t('you_dont_have_communities'));
Expand Down Expand Up @@ -147,6 +162,7 @@ export const updateCommunity = async (
const community = await Community.findOne({
_id: id,
creator_id: user._id,
enabled: { $ne: false },
});

if (!community) {
Expand Down Expand Up @@ -228,6 +244,7 @@ export const deleteCommunity = async (ctx: CommunityContext) => {
const community = await Community.findOne({
_id: id,
creator_id: ctx.user._id,
enabled: { $ne: false },
});

if (!community) {
Expand All @@ -241,6 +258,105 @@ export const deleteCommunity = async (ctx: CommunityContext) => {
}
};

async function findCommunityByInput(
ctx: MainContext,
input: string,
): Promise<typeof Community.prototype | null> {
if (input[0] === '@') {
const regex = new RegExp(
`^${input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`,
'i',
);
const matches = await Community.find({ group: regex }).limit(2);
if (matches.length > 1) throw new Error('AmbiguousCommunityInput');
return matches[0] ?? null;
}
if (!(await validateObjectId(ctx, input))) return null;
return Community.findOne({ _id: input });
}
Comment thread
Matobi98 marked this conversation as resolved.

export const disableCommunity = async (ctx: MainContext) => {
try {
const [input] = (await validateParams(
ctx,
2,
'\\<_community id \\| @groupUsername_\\>',
))!;
if (!input) return;

const community = await findCommunityByInput(ctx, input);
if (!community) return ctx.reply(ctx.i18n.t('community_not_found'));
if (community.enabled === false)
return ctx.reply(ctx.i18n.t('community_already_disabled'));

community.enabled = false;
await community.save();

const creator = await User.findById(community.creator_id);
if (creator) {
try {
const creatorI18n = await getUserI18nContext(creator);
await ctx.telegram.sendMessage(
creator.tg_id,
creatorI18n.t('community_disabled_by_admin', {
communityName: community.name,
}),
);
} catch (notifyError) {
logger.error(notifyError);
}
}

return ctx.reply(ctx.i18n.t('operation_successful'));
} catch (error: any) {
if (error.message === 'AmbiguousCommunityInput')
return ctx.reply(ctx.i18n.t('ambiguous_community_input'));
logger.error(error);
await ctx.reply(ctx.i18n.t('generic_error'));
}
};

export const enableCommunity = async (ctx: MainContext) => {
try {
const [input] = (await validateParams(
ctx,
2,
'\\<_community id \\| @groupUsername_\\>',
))!;
if (!input) return;

const community = await findCommunityByInput(ctx, input);
if (!community) return ctx.reply(ctx.i18n.t('community_not_found'));
if (community.enabled !== false)
return ctx.reply(ctx.i18n.t('community_already_enabled'));

community.enabled = true;
await community.save();

const creator = await User.findById(community.creator_id);
if (creator) {
try {
const creatorI18n = await getUserI18nContext(creator);
await ctx.telegram.sendMessage(
creator.tg_id,
creatorI18n.t('community_enabled_by_admin', {
communityName: community.name,
}),
);
} catch (notifyError) {
logger.error(notifyError);
}
}

return ctx.reply(ctx.i18n.t('operation_successful'));
} catch (error: any) {
if (error.message === 'AmbiguousCommunityInput')
return ctx.reply(ctx.i18n.t('ambiguous_community_input'));
logger.error(error);
await ctx.reply(ctx.i18n.t('generic_error'));
}
};

export const changeVisibility = async (ctx: CommunityContext) => {
try {
ctx.deleteMessage();
Expand All @@ -251,6 +367,7 @@ export const changeVisibility = async (ctx: CommunityContext) => {
const community = await Community.findOne({
_id: id,
creator_id: ctx.user._id,
enabled: { $ne: false },
});

if (!community) {
Expand Down
13 changes: 12 additions & 1 deletion bot/modules/community/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Telegraf } from 'telegraf';
import { userMiddleware } from '../../middleware/user';
import { userMiddleware, superAdminMiddleware } from '../../middleware/user';
import * as actions from './actions';
import * as commands from './commands';
import {
Expand Down Expand Up @@ -65,6 +65,17 @@ export const configure = (bot: Telegraf<CommunityContext>) => {
},
);

bot.command(
'disablecommunity',
superAdminMiddleware,
commands.disableCommunity,
);
bot.command(
'enablecommunity',
superAdminMiddleware,
commands.enableCommunity,
);

bot.command('findcomms', userMiddleware, commands.findCommunity);
bot.action(
/^communityInfo_([0-9a-f]{24})$/,
Expand Down
16 changes: 12 additions & 4 deletions bot/modules/community/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,12 @@ export const updateCommunityMessage = async (ctx: MainContext) => {
try {
await ctx.deleteMessage();
const id = ctx.match?.[1];
const community = await Community.findById(id);
if (community == null) throw new Error('community was not found');
const community = await Community.findOne({
_id: id,
enabled: { $ne: false },
});
if (community == null)
return await ctx.reply(ctx.i18n.t('community_not_found'));
let text = ctx.i18n.t('community') + `: ${community.name}\n`;
text += ctx.i18n.t('what_to_do');
const visibilityText = community.public
Expand Down Expand Up @@ -170,8 +174,12 @@ export const earningsMessage = async (ctx: MainContext) => {
if (isScheduled)
return await ctx.reply(ctx.i18n.t('invoice_already_being_paid'));

const community = await Community.findById(communityId);
if (community == null) throw new Error('community was not found');
const community = await Community.findOne({
_id: communityId,
enabled: { $ne: false },
});
if (community == null)
return await ctx.reply(ctx.i18n.t('community_not_found'));
const button =
community.earnings > 0
? {
Expand Down
2 changes: 1 addition & 1 deletion bot/modules/orders/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ async function enterWizard(
const { community, isBanned } = communityInfo;

if (!community) {
throw new Error('Default community not found');
return deletedCommunityMessage(ctx);
}

// Check if user is banned
Expand Down
5 changes: 4 additions & 1 deletion bot/modules/orders/scenes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,10 @@ const createOrderSteps = {
const stateComm = ctx.wizard.state.community;
const loadedComm =
!stateComm && user?.default_community_id
? await Community.findById(user.default_community_id)
? await Community.findOne({
_id: user.default_community_id,
enabled: { $ne: false },
})
: null;
const community = stateComm ?? loadedComm;
if (loadedComm) ctx.wizard.state.community = loadedComm;
Expand Down
8 changes: 5 additions & 3 deletions bot/modules/user/scenes/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ function make() {
lightning_address: '',
};
if (user.default_community_id) {
const community = await Community.findById(user.default_community_id);
if (community == null) throw new Error('community not found');
data.community = community.group;
const community = await Community.findOne({
_id: user.default_community_id,
enabled: { $ne: false },
});
if (community) data.community = community.group;
}
if (user.nostr_public_key) {
data.npub = NostrLib.encodeNpub(user.nostr_public_key);
Expand Down
5 changes: 4 additions & 1 deletion bot/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,10 @@ const validateAdmin = async (ctx: MainContext, id?: string) => {

let community = null;
if (user.default_community_id)
community = await Community.findOne({ _id: user.default_community_id });
community = await Community.findOne({
_id: user.default_community_id,
enabled: { $ne: false },
});

const isSolver = isDisputeSolver(community, user);

Expand Down
5 changes: 5 additions & 0 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -717,3 +717,8 @@ payment_methods_saved: "Zahlungsmethoden gespeichert ✅"
custom_payment_method: "✍️ Benutzerdefinierte Zahlungsmethode"
payment_methods_reset: "Zahlungsmethoden entfernt. Benutzer können jetzt beliebige Zahlungsmethoden frei eingeben."
payment_methods_wizard_commands: "/reset — alle Zahlungsmethoden entfernen und Standardverhalten wiederherstellen\n/exit — ohne Speichern beenden"
community_disabled_by_admin: Ein Administrator hat deine Community ${communityName} deaktiviert
community_enabled_by_admin: Ein Administrator hat deine Community ${communityName} wieder aktiviert
community_already_disabled: Diese Community ist bereits deaktiviert
community_already_enabled: Diese Community ist bereits aktiviert
ambiguous_community_input: Mehrere Communities stimmen mit diesem Benutzernamen überein, bitte verwende stattdessen die Community-ID
5 changes: 5 additions & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -722,3 +722,8 @@ payment_methods_saved: "Payment methods saved ✅"
custom_payment_method: "✍️ Custom payment method"
payment_methods_reset: "Payment methods removed. Users can now enter any payment method freely."
payment_methods_wizard_commands: "/reset — remove all payment methods and restore default behavior\n/exit — exit without saving"
community_disabled_by_admin: An administrator has disabled your community ${communityName}
community_enabled_by_admin: An administrator has re-enabled your community ${communityName}
community_already_disabled: This community is already disabled
community_already_enabled: This community is already enabled
ambiguous_community_input: Multiple communities match that username, please use the community ID instead
5 changes: 5 additions & 0 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -719,3 +719,8 @@ payment_methods_saved: "Métodos de pago guardados ✅"
custom_payment_method: "✍️ Método de pago personalizado"
payment_methods_reset: "Métodos de pago eliminados. Los usuarios ahora pueden ingresar cualquier método de pago libremente."
payment_methods_wizard_commands: "/reset — eliminar todos los métodos de pago y restaurar el comportamiento predeterminado\n/exit — salir sin guardar"
community_disabled_by_admin: Un administrador ha deshabilitado tu comunidad ${communityName}
community_enabled_by_admin: Un administrador ha reactivado tu comunidad ${communityName}
community_already_disabled: Esta comunidad ya está deshabilitada
community_already_enabled: Esta comunidad ya está habilitada
ambiguous_community_input: Varias comunidades coinciden con ese nombre de usuario, por favor usa el ID de la comunidad
5 changes: 5 additions & 0 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -816,3 +816,8 @@ payment_methods_saved: "روش‌های پرداخت ذخیره شد ✅"
custom_payment_method: "✍️ روش پرداخت سفارشی"
payment_methods_reset: "روش‌های پرداخت حذف شدند. کاربران اکنون می‌توانند هر روش پرداختی را آزادانه وارد کنند."
payment_methods_wizard_commands: "/reset — حذف همه روش‌های پرداخت و بازگرداندن رفتار پیش‌فرض\n/exit — خروج بدون ذخیره"
community_disabled_by_admin: یک مدیر جامعه ${communityName} شما را غیرفعال کرد
community_enabled_by_admin: یک مدیر جامعه ${communityName} شما را دوباره فعال کرد
community_already_disabled: این جامعه از قبل غیرفعال است
community_already_enabled: این جامعه از قبل فعال است
ambiguous_community_input: چندین جامعه با این نام کاربری مطابقت دارند، لطفاً از شناسه جامعه استفاده کنید
5 changes: 5 additions & 0 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,8 @@ payment_methods_saved: "Méthodes de paiement enregistrées ✅"
custom_payment_method: "✍️ Méthode de paiement personnalisée"
payment_methods_reset: "Méthodes de paiement supprimées. Les utilisateurs peuvent désormais saisir n'importe quelle méthode de paiement librement."
payment_methods_wizard_commands: "/reset — supprimer toutes les méthodes de paiement et restaurer le comportement par défaut\n/exit — quitter sans enregistrer"
community_disabled_by_admin: Un administrateur a désactivé votre communauté ${communityName}
community_enabled_by_admin: Un administrateur a réactivé votre communauté ${communityName}
community_already_disabled: Cette communauté est déjà désactivée
community_already_enabled: Cette communauté est déjà activée
ambiguous_community_input: Plusieurs communautés correspondent à ce nom d'utilisateur, veuillez utiliser l'ID de la communauté à la place
5 changes: 5 additions & 0 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,8 @@ payment_methods_saved: "Metodi di pagamento salvati ✅"
custom_payment_method: "✍️ Metodo di pagamento personalizzato"
payment_methods_reset: "Metodi di pagamento rimossi. Gli utenti possono ora inserire qualsiasi metodo di pagamento liberamente."
payment_methods_wizard_commands: "/reset — rimuovere tutti i metodi di pagamento e ripristinare il comportamento predefinito\n/exit — uscire senza salvare"
community_disabled_by_admin: Un amministratore ha disabilitato la tua comunità ${communityName}
community_enabled_by_admin: Un amministratore ha riabilitato la tua comunità ${communityName}
community_already_disabled: Questa comunità è già disabilitata
community_already_enabled: Questa comunità è già abilitata
ambiguous_community_input: Più comunità corrispondono a quel nome utente, usa invece l'ID della comunità
5 changes: 5 additions & 0 deletions locales/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,8 @@ payment_methods_saved: "결제 방법이 저장되었습니다 ✅"
custom_payment_method: "✍️ 사용자 지정 결제 방법"
payment_methods_reset: "결제 방법이 삭제되었습니다. 이제 사용자는 어떤 결제 방법이든 자유롭게 입력할 수 있습니다."
payment_methods_wizard_commands: "/reset — 모든 결제 방법을 삭제하고 기본 동작을 복원합니다\n/exit — 저장하지 않고 종료"
community_disabled_by_admin: 관리자가 커뮤니티 ${communityName}을(를) 비활성화했습니다
community_enabled_by_admin: 관리자가 커뮤니티 ${communityName}을(를) 다시 활성화했습니다
community_already_disabled: 이 커뮤니티는 이미 비활성화되어 있습니다
community_already_enabled: 이 커뮤니티는 이미 활성화되어 있습니다
ambiguous_community_input: 해당 사용자 이름과 일치하는 커뮤니티가 여러 개 있습니다. 커뮤니티 ID를 사용해 주세요
Loading
Loading