Skip to content
Merged
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
47 changes: 39 additions & 8 deletions bot/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
subscribeInvoice,
cancelHoldInvoice,
settleHoldInvoice,
getInvoice,
} from '../ln';
import { Order, User, Dispute } from '../models';
import * as messages from './messages';
Expand All @@ -13,12 +14,10 @@ import * as OrderEvents from './modules/events/orders';

import { resolvLightningAddress } from '../lnurl/lnurl-pay';
import { logger } from '../logger';
import { Telegraf } from 'telegraf';
import { IOrder } from '../models/order';
import { UserDocument } from '../models/user';
import { HasTelegram, MainContext } from './start';
import { CommunityContext } from './modules/community/communityContext';
import { Types } from 'mongoose';

const waitPayment = async (ctx: MainContext, bot: HasTelegram, buyer: UserDocument, seller: UserDocument, order: IOrder, buyerInvoice: any) => {
try {
Expand Down Expand Up @@ -55,7 +54,7 @@ const waitPayment = async (ctx: MainContext, bot: HasTelegram, buyer: UserDocume
fiatAmount: order.fiat_amount,
});
const amount = Math.floor(order.amount + order.fee);
const { request, hash, secret } = await createHoldInvoice({
const { _request, hash, secret } = await createHoldInvoice({
amount,
description,
});
Expand All @@ -74,7 +73,6 @@ const waitPayment = async (ctx: MainContext, bot: HasTelegram, buyer: UserDocume
await messages.invoicePaymentRequestMessage(
ctx,
seller,
request,
order,
i18nCtx,
buyer
Expand Down Expand Up @@ -618,14 +616,14 @@ const cancelOrder = async (ctx: CommunityContext, orderId: string, user: UserDoc
return await cancelAddInvoice(ctx, order);
}

// If a seller is taking a buy offer and accidentally touch continue button we
// let the user to cancel
if (order.type === 'buy' && order.status === 'WAITING_PAYMENT') {
// let the user to cancel if the order is waiting for payment
if (order.status === 'WAITING_PAYMENT') {
return await cancelShowHoldInvoice(ctx, order);
}

if (order.status === 'CANCELED')
if (order.status === 'CANCELED') {
return await messages.orderIsAlreadyCanceledMessage(ctx);
}

if (
!(
Expand Down Expand Up @@ -772,6 +770,38 @@ const release = async (ctx: MainContext, orderId: string, user: UserDocument | n
}
};

const showQrCode = async (ctx: MainContext, orderId: string, user: UserDocument | null = null) => {
try {
if (!user) {
const tgUser = (ctx.update as any).callback_query.from;
if (!tgUser) return;

user = await User.findOne({ tg_id: tgUser.id });

// If user didn't initialize the bot we can't do anything
if (!user) return;
}
if (user.banned) return await messages.bannedUserErrorMessage(ctx, user);
const order = await ordersActions.getOrder(ctx, user, orderId);

if (!order) return;

if (!order.hash) return;

const invoice = await getInvoice({ hash: order.hash });

return await messages.showQRCodeMessage(
ctx,
order,
invoice.request,
user,
);

} catch (error) {
logger.error(error);
}
};

export {
rateUser,
saveUserReview,
Expand All @@ -784,4 +814,5 @@ export {
cancelOrder,
fiatSent,
release,
showQrCode,
};
34 changes: 31 additions & 3 deletions bot/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ const initBotErrorMessage = async (ctx: MainContext, bot: MainContext, user: Use
const invoicePaymentRequestMessage = async (
ctx: MainContext,
user: UserDocument,
request: string,
order: IOrder,
i18n: I18nContext,
buyer: UserDocument
Expand All @@ -77,7 +76,8 @@ const invoicePaymentRequestMessage = async (
// We need the buyer rating
const stars = getEmojiRate(buyer.total_rating);
const roundedRating = decimalRound(buyer.total_rating, -1);
const rate = `${roundedRating} ${stars} (${buyer.total_reviews})`;
let rate = `${roundedRating} ${stars} (${buyer.total_reviews})`;
rate = sanitizeMD(rate);
// Extracting the buyer's days in the platform
const ageInDays = getUserAge(buyer);

Expand All @@ -89,8 +89,34 @@ const invoicePaymentRequestMessage = async (
days: ageInDays,
});

await ctx.telegram.sendMessage(user.tg_id, message);
await ctx.telegram.sendMessage(user.tg_id, message, { parse_mode: 'MarkdownV2' });

await ctx.telegram.sendMessage(user.tg_id, order._id, {
reply_markup: {
inline_keyboard: [
[
{ text: ctx.i18n.t('continue'), callback_data: `showqrcode_${order._id}`, },
{
text: ctx.i18n.t('cancel'),
callback_data: `cancel_${order._id}`,
},
],
],
},
});
} catch (error) {
logger.error(error);
}
};

const showQRCodeMessage = async (
ctx: MainContext,
order: IOrder,
request: string,
user: UserDocument
) => {
try {
//
// Create QR code
const qrBytes = await generateQRWithImage(request, order.random_image);
// Send payment request in QR and text
Expand Down Expand Up @@ -121,6 +147,7 @@ const pendingSellMessage = async (ctx: MainContext, user: UserDocument, order: I
type: 'photo',
media: { source: Buffer.from(order.random_image, 'base64') },
caption: pendingSellCaption,
parse_mode: 'MarkdownV2',
}]
);

Expand Down Expand Up @@ -1774,4 +1801,5 @@ export {
showConfirmationButtons,
counterPartyCancelOrderMessage,
checkInvoiceMessage,
showQRCodeMessage,
};
9 changes: 9 additions & 0 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
cancelOrder,
fiatSent,
release,
showQrCode,
} from './commands';
import {
settleHoldInvoice,
Expand Down Expand Up @@ -828,6 +829,14 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<Communit
await release(ctx, ctx.match[1]);
});

bot.action(/^showqrcode_([0-9a-f]{24})$/, userMiddleware, async (ctx: CommunityContext) => {
if (ctx.match === null) {
throw new Error("ctx.match should not be null");
}
ctx.deleteMessage();
await showQrCode(ctx, ctx.match[1]);
});

bot.command('paytobuyer', adminMiddleware, async (ctx: MainContext) => {
try {
const [orderId] = (await validateParams(ctx, 2, '\\<_order id_\\>'))!;
Expand Down
25 changes: 17 additions & 8 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,30 @@ start: |
init_bot_error: Um diesen Bot zu verwenden, musst du zuerst den Boot mit dem Befehl /start initialisieren
non_handle_error: 👤 Um diesen Bot zu nutzen, musst du deinen Telegram-Benutzernamen aktivieren. Um ihn zu aktivieren, öffne das Hamburger-Menü oben links und wähle Einstellungen -> Profil bearbeiten -> Benutzernamen
invoice_payment_request: |
Jemand möchte ${order.amount} Sats für ${currency} ${order.fiat_amount} kaufen.
Ein Benutzer möchte ${order.amount} sats für ${currency} ${order.fiat_amount} von dir kaufen

Buyer Reputation: ${rate}, Tage mit dem Bot: ${days}
Ruf des Käufers: ${rate}, Tage der Nutzung des Bots: ${days}

Hinweis: Vergewissern Sie sich vor der Zahlung der Rechnung, dass das beigefügte Bild mit dem bei der Bestellung gesendeten Bild übereinstimmt
🚨🚨🚨 *ACHTUNG:* 🚨🚨🚨
*Bevor du auf den Button "Weiter" drückst, GEHE ZURÜCK UND ÜBERPRÜFE NOCH EINMAL DAS BILD, das mit diesem Auftrag verknüpft ist*

Wenn du auf den Button "Weiter" drückst, wirst du einen QR Code mit einem Bild im Zentrum sehen, bestätige, dass die Bilder übereinstimmen, bevor du die Rechnung bezahlst

Bitte bezahle diese LN-Rechnung, um deinen Verkaufsprozess zu starten. Diese LN-Rechnung läuft in ${expirationTime} Minuten ab
*Wenn sie nicht übereinstimmen, ist diese Rechnung nicht von @lnp2pbot, BEZAHLEN SIE NICHT die Rechnung*

Entscheide, wie du weiter verfahren möchtest 👇
pending_sell: |
📝 Dein Angebot wurde im Kanal ${channel} veröffentlicht
📝 Angebot im ${channel} Kanal veröffentlicht

Du musst warten, bis ein anderer Nutzer deinen Auftrag auswählt. Sie wird für ${orderExpirationWindow} Stunden im Kanal verfügbar sein
Warte darauf, dass jemand deinen Verkauf übernimmt, wenn der Auftrag innerhalb von ${orderExpirationWindow} Stunden nicht übernommen wird, wird er aus dem Kanal gelöscht

Hinweis: Merken Sie sich dieses Bild, da Sie es später in der Zahlungsrechnung wiedersehen werden
*🚨 ERINNERE DICH AN DIESES BILD, da du es erneut in der zu bezahlenden Rechnung sehen wirst*

Bevor ein anderer Benutzer dein Angebot annimmt, kannst du diesen mit dem folgenden Befehl stornieren 👇
*Weder die Entwickler noch die Streitbeilegungs Schiedsrichter sind verantwortlich für Verluste oder Schäden, die dem Benutzer entstehen, wenn er die Anweisungen nicht befolgt*

Durch das Starten des Bots akzeptiert der Benutzer die Nutzungsbedingungen sowie die Datenschutzrichtlinie, weitere Informationen findest du unter /disclaimer

Du kannst diese Bestellung stornieren, bevor sie jemand übernimmt, indem du 👇 ausführst
cancel_order_cmd: |
/cancel ${orderId}
pending_buy: |
Expand Down
25 changes: 17 additions & 8 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,30 @@ start: |
init_bot_error: to use this bot, you need to first initialize the boot with the command /start
non_handle_error: 👤 To use this bot, you need to activate your Telegram Username. To activate it open the hamburger menu on the top left and select settings -> edit profile -> username
invoice_payment_request: |
Somebody wants to buy you ${order.amount} sats for ${currency} ${order.fiat_amount}.
A user wants to buy ${order.amount} sats from you for ${currency} ${order.fiat_amount}

Buyer Reputation: ${rate}, days using the bot: ${days}
Buyer's reputation: ${rate}, days using the bot: ${days}

Note: Confirm that the attached image matches the one sent during order creation before paying the invoice
🚨🚨🚨 *ATTENTION:* 🚨🚨🚨
*Before pressing the "Continue" button, GO BACK AND CHECK AGAIN THE IMAGE associated with this order*

By pressing the "Continue" button, you will see a QR code with an image in the center, make sure the images match before paying the invoice

Please pay this invoice to start up your selling process, it will expire in ${expirationTime} minutes
*If they don't match, that invoice is not from @lnp2pbot, DO NOT PAY the invoice*

Decide how you want to proceed 👇
pending_sell: |
📝 Your offer has been published in the ${channel} channel
📝 Offer posted in the ${channel} channel

You have to wait until another user picks your order, it will be available for ${orderExpirationWindow} hours in the channel
Wait for someone to take your sale, if the order is not taken within ${orderExpirationWindow} hours, it will be deleted from the channel

Note: Remember this image because you will see it again inside the invoice to pay
*🚨 REMEMBER THIS IMAGE because you will see it again in the invoice to be paid*

You can cancel this order before another user picks it up by executing the command 👇
*Neither the developers nor the dispute arbitrators are responsible for any loss or damage the user may suffer if they do not follow the instructions*

By starting the bot, the user accepts the terms and conditions of its use, as well as the privacy policy, for more information, go to /disclaimer

You can cancel this order before someone takes it by executing 👇
cancel_order_cmd: |
/cancel ${orderId}
pending_buy: |
Expand Down
19 changes: 14 additions & 5 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,28 @@ start: |
init_bot_error: Para usar este Bot primero debes inicializar el bot con el comando /start
non_handle_error: 👤 Para usar este bot debes activar tu username de telegram, para activarlo abre el menú de hamburguesa arriba a la izquierda, selecciona ajustes -> editar perfil -> username
invoice_payment_request: |
Un usuario quiere comprarte ${order.amount} sats por ${currency} ${order.fiat_amount}.
Un usuario quiere comprarte ${order.amount} sats por ${currency} ${order.fiat_amount}

Reputación del comprador: ${rate}, días utilizando el bot: ${days}

Nota: Confirme que la imagen adjunta coincide con la enviada durante la creación del pedido antes de pagar la factura
🚨🚨🚨 *ATENCIÓN:* 🚨🚨🚨
*Antes de presionar el botón "Continuar" REGRESA Y MIRA NUEVAMENTE LA IMAGEN asociada a esta orden*

Al presionar el botón "Continuar" verás un código QR con una imágen en el centro, confirma que las imágenes coincidan antes de pagar la factura

*Si no coinciden, esa factura no es de @lnp2pbot, NO PAGUES la factura*

Si deseas continuar por favor paga esta factura, esta factura expira en ${expirationTime} minutos
Decide cómo quieres proceder 👇
pending_sell: |
📝 Publicada la oferta en el canal ${channel}

Espera que alguien tome tu venta, si la orden no es tomada en ${orderExpirationWindow} horas será borrada del canal.
Espera que alguien tome tu venta, si la orden no es tomada en ${orderExpirationWindow} horas será borrada del canal

Nota: Recuerde esta imagen porque la verá nuevamente dentro de la factura a pagar
*🚨 RECUERDA ESTA IMAGEN porque la verás nuevamente dentro de la factura a pagar*

*Ni los desarrolladores ni los árbitros de disputas son responsables de las pérdidas o daños que el usuario pueda sufrir si no sigue las instrucciones*

Al iniciar el bot el usuario acepta los términos y condiciones de su uso, así como la política de privacidad, para más información ve a /disclaimer

Puedes cancelar esta orden antes de que alguien la tome ejecutando 👇
cancel_order_cmd: |
Expand Down
25 changes: 17 additions & 8 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,30 @@ start: |
init_bot_error: برای استفاده از این ربات، ابتدا باید دستور /start را وارد کنید
non_handle_error: 👤 برای استفاده از این ربات باید نام کاربری تلگرام خود را فعال کنید. جهت فعالسازی نام کاربری از سه‌خط بالا سمت راست تلگرام وارد بخش تنظیمات--ویرایش پروفایل شده و یک نام‌کاربری اضافه کنید
invoice_payment_request: |
یک نفر میخواهد از شما ${order.amount} ساتوشی در ازا ${currency} ${order.fiat_amount} بخرد.
یک کاربر می‌خواهد ${order.amount} sats را به ${currency} ${order.fiat_amount} از شما بخرد

Buyer Reputation: ${rate}, days using the bot: ${days}
شهرت خریدار: ${rate} ، روزهای استفاده از ربات: ${days}

توجه: قبل از پرداخت فاکتور، تأیید کنید که تصویر پیوست شده با تصویر ارسال شده در هنگام ایجاد سفارش مطابقت دارد
🚨🚨🚨 *توجه:* 🚨🚨🚨
*قبل از فشار دادن دکمه "ادامه"، به عقب بازگشته و دوباره تصویر مربوط به این سفارش را بررسی کنید*

وقتی دکمه "ادامه" را فشار می‌دهید، یک کد QR با تصویری در مرکز مشاهده خواهید کرد، قبل از پرداخت فاکتور، مطمئن شوید که تصاویر مطابقت دارند

*اگر تطابق نداشته باشند، این فاکتور متعلق به @lnp2pbot نیست، فاکتور را پرداخت نکنید*

لطفاً برای شروع فرآیند فروش خود، این فاکتور را بپردازید، این درخواست در ${expirationTime} دقیقه منقضی می شود
تصمیم بگیرید که چگونه می‌خواهید ادامه دهید 👇
pending_sell: |
📝 سفارش فروش sat شما در کانال ${channel} منتشر شده است
📝 پیشنهاد در کانال ${channel} منتشر شد

باید منتظر بمانید تا کاربر دیگری سفارش شما را انتخاب کند، این سفارش برای ${orderExpirationWindow} ساعت در کانال در دسترس خواهد بود.
منتظر بمانید تا کسی فروش شما را قبول کند، اگر سفارش در ${orderExpirationWindow} ساعت گرفته نشود، از کانال حذف خواهد شد

توجه: این تصویر را به خاطر بسپارید زیرا آن را دوباره در فاکتور پرداخت خواهید دید
*🚨 این تصویر را به خاطر بسپارید، زیرا آن را دوباره در صورتحساب قابل پرداخت خواهید دید*

*نه توسعه‌دهندگان و نه داوران اختلافات مسئول خسارت یا آسیبی نیستند که کاربر ممکن است در صورت عدم پیروی از دستورالعمل‌ها متحمل شود*

با شروع استفاده از ربات، کاربر شرایط و ضوابط استفاده از آن و همچنین سیاست حفظ حریم خصوصی را می‌پذیرد، برای اطلاعات بیشتر به /disclaimer مراجعه کنید

شما می توانید این سفارش را قبل از اینکه کاربر دیگری آن را انتخاب کند با اجرای دستور زیر لغو کنید 👇
شما می‌توانید این سفارش را قبل از آنکه کسی آن را بپذیرد با اجرای 👇 لغو کنید
cancel_order_cmd: |
/cancel ${orderId}
pending_buy: |
Expand Down
25 changes: 17 additions & 8 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,30 @@ start: |
init_bot_error: pour utiliser ce bot, tu dois d'abord initialiser le démarrage avec la commande /start
non_handle_error: 👤 Pour utiliser ce bot, tu dois d'abord activer ton nom d'utilisateur Telegram. Pour ce faire, ouvre le menu en haut à gauche et sélectionne Paramètres -> Nom d'utilisateur
invoice_payment_request: |
Quelqu'un veut t'acheter ${order.amount} sats à ${order.fiat_amount} ${currency}.
Un utilisateur veut vous acheter ${order.amount} sats pour ${currency} ${order.fiat_amount}

Buyer Reputation: ${rate}, jours d'utilisation du bot: ${days}
Réputation de l'acheteur : ${rate}, jours d'utilisation du bot : ${days}

Note : Vérifiez que l'image jointe correspond à celle envoyée lors de la création de la commande avant de payer la facture
🚨🚨🚨 *ATTENTION :* 🚨🚨🚨
*Avant de presser le bouton "Continuer", RETOURNEZ ET VÉRIFIEZ À NOUVEAU L'IMAGE associée à cette commande*

En appuyant sur le bouton "Continuer", vous verrez un code QR avec une image au centre, confirmez que les images correspondent avant de payer la facture

*Si elles ne correspondent pas, cette facture ne provient pas de @lnp2pbot, NE PAYEZ PAS la facture*

Merci de régler cette facture pour démarrer le processus de vente, elle expirera dans ${expirationTime} minutes
Décidez de la manière dont vous souhaitez procéder 👇
pending_sell: |
📝 Ton offre a été publiée dans le canal ${channel}
📝 Offre publiée dans le canal ${channel}

Tu dois attendre jusqu'à ce que quelqu'un récupère ton offre, elle sera visible pendant ${orderExpirationWindow} heures dans le canal
Attendez qu'un utilisateur prenne votre vente, si la commande n'est pas prise dans ${orderExpirationWindow} heures, elle sera supprimée du canal

Note : Mémorisez cette image car vous la reverrez dans la facture à payer
*🚨 RAPPELEZ VOUS DE CETTE IMAGE car vous la verrez à nouveau dans la facture à payer*

*Ni les développeurs ni les arbitres de litiges ne sont responsables des pertes ou dommages que l'utilisateur pourrait subir s'il ne suit pas les instructions*

En démarrant le bot, l'utilisateur accepte les termes et conditions d'utilisation, ainsi que la politique de confidentialité, pour plus d'informations, allez sur /disclaimer

Tu peux annuler cette offre avant qu'un autre utilisateur ne la prenne en exécutant la commande 👇
Vous pouvez annuler cette commande avant qu'elle soit prise en exécutant 👇
cancel_order_cmd: |
/cancel ${orderId}
pending_buy: |
Expand Down
Loading