Compare commits

..
Author SHA1 Message Date
callebtcandGitHub 7c55e40966 Add setting file (#497)
* add user currency for incoming payments

* also add currency to incoming LNURL payments

* add setting file
2023-12-05 16:02:42 +01:00
callebtcandGitHub 5adf090969 Display fiat currency (#496)
* add user currency for incoming payments

* also add currency to incoming LNURL payments
2023-12-05 15:54:53 +01:00
callebtcandGitHub 0be3d26e56 do not store lnurl comments below amount threshold (#493) 2023-11-23 11:59:35 -03:00
callebtcandGitHub 8b2fb73fe8 allow lnurlp comments only for 21 sats or more (#491) 2023-11-15 21:36:37 -03:00
22 changed files with 171 additions and 29 deletions
+7 -3
View File
@@ -39,11 +39,15 @@ type User struct {
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
ID string `json:"id" gorm:"primarykey"`
Display DisplaySettings `gorm:"embedded;embeddedPrefix:display_"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
}
type DisplaySettings struct {
DisplayCurrency string `json:"displaycurrency"`
}
type NostrSettings struct {
PubKey string `json:"pubkey"`
}
+15 -3
View File
@@ -267,6 +267,10 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
// get rid of LNURL spam
if amount_msat < 21_000 {
comment = ""
}
user, tx := db.FindUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
@@ -282,6 +286,13 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
}
// get user settings
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
if err != nil {
fmt.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
} else {
user = user2
}
// user is ok now create invoice
// set wallet lnbits client
@@ -403,9 +414,10 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
telegram.InvoiceEvent{
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
UserCurrency: user.Settings.Display.DisplayCurrency,
}))
return &lnurl.LNURLPayValues{
+8
View File
@@ -98,6 +98,14 @@ func GetAmount(input string) (amount int64, err error) {
return amount, err
}
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
if !(price.Price[currency] > 0) {
return 0, fmt.Errorf("price is zero")
}
fiat = float64(amount) / 100_000_000 * price.Price[currency]
return fiat, nil
}
type EnterAmountStateData struct {
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
+1 -1
View File
@@ -65,7 +65,7 @@ func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Conte
if err != nil {
return ctx, err
}
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), InvoiceCallbackGenerateDalle, prompt)
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), "", InvoiceCallbackGenerateDalle, prompt)
invoice.Payer = user
if err != nil {
return ctx, err
+32 -16
View File
@@ -99,22 +99,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
{
Endpoints: []interface{}{"/generate"},
Handler: bot.generateImages,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
// {
// Endpoints: []interface{}{"/generate"},
// Handler: bot.generateImages,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.requirePrivateChatInterceptor,
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.loadUserInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/tip", "/t", "/honk", "/zap"},
Handler: bot.tipHandler,
@@ -164,6 +164,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
{
Endpoints: []interface{}{"/set"},
Handler: bot.settingHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/nostr"},
Handler: bot.nostrHandler,
+1 -1
View File
@@ -274,7 +274,7 @@ func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *In
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), "", InvoiceCallbackInlineReceive, inlineReceive.ID)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
+24 -3
View File
@@ -89,6 +89,7 @@ type InvoiceEvent struct {
CallbackData string `json:"callbackdata"` // add some data for the callback
Chat *tb.Chat `json:"chat,omitempty"` // if invoice is supposed to be sent to a particular chat
Payer *lnbits.User `json:"payer,omitempty"` // if a particular user is supposed to pay this
UserCurrency string `json:"usercurrency,omitempty"` // the currency a user selected
}
func (invoiceEvent InvoiceEvent) Type() EventType {
@@ -116,6 +117,8 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
// check and print all commands
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
// load user settings
user, err := GetLnbitsUserWithSettings(user.Telegram, *bot)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -147,7 +150,13 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
currency := user.Settings.Display.DisplayCurrency
if currency == "" {
currency = "BTC"
}
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, currency, InvoiceCallbackGeneric, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
@@ -173,7 +182,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
return ctx, nil
}
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, currency string, callback int, callbackData string) (InvoiceEvent, error) {
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
@@ -195,6 +204,7 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
UserCurrency: currency,
}
// save invoice struct for later use
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
@@ -210,7 +220,18 @@ func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
log.Errorln(errmsg)
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
if invoiceEvent.UserCurrency == "" || strings.ToLower(invoiceEvent.UserCurrency) == "btc" {
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
} else {
fiatAmount, err := SatoshisToFiat(invoiceEvent.Amount, strings.ToUpper(invoiceEvent.UserCurrency))
if err != nil {
log.Errorln(err)
// fallback to satoshis
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
return
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedCurrencyMessage"), invoiceEvent.Amount, fiatAmount, strings.ToUpper(invoiceEvent.UserCurrency)))
}
}
type LNURLInvoice struct {
+1 -1
View File
@@ -431,7 +431,7 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
}
memo := "🔀 Payment proxy in."
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, "", InvoiceCallbackSatdressProxy, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
+68
View File
@@ -0,0 +1,68 @@
package telegram
import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
)
var (
settingsHelpMessage = "📖 Change user settings\n\n`/set unit <BTC|USD|EUR|GBP>` 💶 Change your default currency."
)
func (bot *TipBot) settingHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
bot.trySendMessage(m.Sender, settingsHelpMessage)
} else if len(splits) > 1 {
switch strings.ToLower(splits[1]) {
case "unit":
return bot.addFiatCurrency(ctx)
case "help":
return bot.nostrHelpHandler(ctx)
}
}
return ctx, nil
}
func (bot *TipBot) addFiatCurrency(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 3 {
// display users current fiat currency
currentCurrency := strings.ToUpper(user.Settings.Display.DisplayCurrency)
if currentCurrency == "" {
currentCurrency = "BTC"
}
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf("🌍 Your current default currency is `%s`", currentCurrency))
return ctx, nil
}
currencyInput := splits[2]
// convert to lowercase and check if in [usd, eur, gbp, btc, sat]
currencyInput = strings.ToLower(currencyInput)
if currencyInput != "usd" && currencyInput != "eur" && currencyInput != "gbp" && currencyInput != "btc" && currencyInput != "sat" {
bot.trySendMessage(ctx.Message().Sender, "🚫 Invalid currency. Please use one of the following: `BTC`, `USD`, `EUR`")
return ctx, fmt.Errorf("invalid currency")
}
if currencyInput == "sat" {
currencyInput = "BTC"
}
// save node in db
user.Settings.Display.DisplayCurrency = currencyInput
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
return ctx, err
}
bot.trySendMessage(ctx.Message().Sender, "✅ Your default currency has been updated.")
return ctx, nil
}
+2 -1
View File
@@ -188,7 +188,8 @@ sendHelpText = """📖 Ou, tohle se nezdařilo. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Obdržel jsi %d sats."""
invoiceReceivedMessage = """⚡️ Obdržel jsi %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Obdržel jsi %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Zadal jsi částku?"""
invoiceValidAmountMessage = """Zadal jsi platnou částku?"""
invoiceHelpText = """📖 Ou, tohle se nezdařilo. %s
+1
View File
@@ -186,6 +186,7 @@ sendHelpText = """📖 Ups, das hat nicht geklappt. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Du hast %d sat erhalten."""
invoiceReceivedCurrencyMessage = """⚡️ Du hast %d sat (%.2f %s) erhalten."""
invoiceEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
invoiceValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
invoiceHelpText = """📖 Ups, das hat nicht geklappt. %s
+1
View File
@@ -189,6 +189,7 @@ sendHelpText = """📖 Oops, that didn't work. %s
# INVOICE
invoiceReceivedMessage = """⚡️ You received %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ You received %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Did you enter an amount?"""
invoiceValidAmountMessage = """Did you enter a valid amount?"""
invoiceHelpText = """📖 Oops, that didn't work. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Oops, eso no funcionó. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Recibiste %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Recibiste %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """¿Ingresaste un monto?"""
invoiceValidAmountMessage = """¿Ingresaste un monto válido?"""
invoiceHelpText = """📖 Oops, eso no funcionó. %s
+1
View File
@@ -189,6 +189,7 @@ sendHelpText = """📖 Hups, sepä ei toiminutkaan. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Vastaanotit %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Vastaanotit %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Syötithän määrän?"""
invoiceValidAmountMessage = """Syötithän määrän oikein?"""
invoiceHelpText = """📖 Hups, sepä ei toiminutkaan. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Oops, cela n'a pas fonctionné. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Vous avez reçu %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Vous avez reçu %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Avez-vous choisi un montant ?"""
invoiceValidAmountMessage = """Avez-vous choisi un montant correct ?"""
invoiceHelpText = """📖 Oops, cela n'a pas fonctionné. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Waduh, itu tidak berhasil. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Kamu menerima %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Kamu menerima %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
invoiceValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
invoiceHelpText = """📖 Waduh, itu tidak berhasil. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Ops, non ha funzionato. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Hai ricevuto %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
invoiceHelpText = """📖 Ops, non ha funzionato. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Oeps, dat werkte niet. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Je hebt %d sat ontvangen ."""
invoiceReceivedCurrencyMessage = """⚡️ Je hebt %d sat (%.2f %s) ontvangen."""
invoiceEnterAmountMessage = """Heb je een bedrag ingevoerd?"""
invoiceValidAmountMessage = """Heeft u een geldig bedrag ingevoerd?"""
invoiceHelpText = """📖 Oeps, dat werkte niet. %s
+1
View File
@@ -190,6 +190,7 @@ sendHelpText = """📖 Ojej, to nie zadziałało. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Otrzymujesz %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Otrzymujesz %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Czy wprowadzono kwotę?"""
invoiceValidAmountMessage = """Czy wprowadzono poprawną kwotę?"""
invoiceHelpText = """📖 Ojej, to nie zadziałało. %s
+1
View File
@@ -184,6 +184,7 @@ sendHelpText = """📖 Opa, isso não funcionou. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Recebeu %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Recebeu %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Você inseriu uma quantia?"""
invoiceValidAmountMessage = """Você inseriu uma quantia válida?"""
invoiceHelpText = """📖 Opa, isso não funcionou. %s
+1
View File
@@ -187,6 +187,7 @@ sendHelpText = """📖 Упс, это не сработало. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Вы получили %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
invoiceHelpText = """📖 Упс, это не сработало. %s
+1
View File
@@ -183,6 +183,7 @@ sendHelpText = """📖 Hoppalaa… olmadı. %s
# INVOICE
invoiceReceivedMessage = """⚡️ %d sat sana geldi."""
invoiceReceivedCurrencyMessage = """⚡️ %d sat (%.2f %s) sana geldi."""
invoiceEnterAmountMessage = """Miktar girdin mi?"""
invoiceValidAmountMessage = """Geçerli bir miktar girdin mi?"""
invoiceHelpText = """📖 Hoppalaa… olmadı. %s