Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccbf036ae9 | ||
|
|
f68481ba0e | ||
|
|
7c55e40966 | ||
|
|
5adf090969 | ||
|
|
0be3d26e56 | ||
|
|
8b2fb73fe8 |
@@ -0,0 +1,35 @@
|
||||
package cashu
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cashu-ts/cashu-ts"
|
||||
)
|
||||
|
||||
var (
|
||||
mintUrl = "https://your-cashu-mint-url"
|
||||
wallet = cashuts.NewCashuWallet(cashuts.NewCashuMint(mintUrl))
|
||||
)
|
||||
|
||||
func DecodeToken(token string) (cashuts.Token, error) {
|
||||
decoded, err := wallet.DecodeToken(token)
|
||||
if err != nil {
|
||||
return cashuts.Token{}, errors.New("invalid Cashu token")
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func RedeemToken(token string, userLightningAddress string) (string, error) {
|
||||
proofs, err := wallet.Receive(token)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to receive Cashu token")
|
||||
}
|
||||
invoice, err := wallet.CreateInvoice(proofs.Amount, userLightningAddress)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to create invoice")
|
||||
}
|
||||
result, err := wallet.PayLnInvoiceWithToken(invoice.PaymentRequest, token)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to pay Lightning invoice with Cashu token")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -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
@@ -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{
|
||||
|
||||
@@ -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)
|
||||
|
||||
+30
-140
@@ -1,146 +1,36 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
|
||||
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"strings"
|
||||
"github.com/LightningTipBot/LightningTipBot/cashu"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
DB *Databases
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
}
|
||||
type Cache struct {
|
||||
*store.GoCacheStore
|
||||
}
|
||||
|
||||
var (
|
||||
botWalletInitialisation = sync.Once{}
|
||||
telegramHandlerRegistration = sync.Once{}
|
||||
)
|
||||
|
||||
// NewBot migrates data and creates a new bot
|
||||
func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
dbs := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
DB: dbs,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
}
|
||||
}
|
||||
|
||||
// newTelegramBot will create a new Telegram bot.
|
||||
func newTelegramBot() *tb.Bot {
|
||||
tgb, err := tb.NewBot(tb.Settings{
|
||||
Token: internal.Configuration.Telegram.ApiKey,
|
||||
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
|
||||
ParseMode: tb.ModeMarkdown,
|
||||
Verbose: false,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tgb
|
||||
}
|
||||
|
||||
// initBotWallet will create / initialize the bot wallet
|
||||
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
|
||||
func (bot TipBot) initBotWallet() error {
|
||||
botWalletInitialisation.Do(func() {
|
||||
_, err := bot.initWallet(bot.Telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// GracefulShutdown will gracefully shutdown the bot
|
||||
// It will wait for all mutex locks to unlock before shutdown.
|
||||
func (bot *TipBot) GracefulShutdown() {
|
||||
t := time.NewTicker(time.Second * 10)
|
||||
log.Infof("[shutdown] Graceful shutdown (timeout=10s).")
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
// timer expired
|
||||
log.Infof("[shutdown] Graceful shutdown timeout reached. Forcing shutdown.")
|
||||
return
|
||||
default:
|
||||
// check if all mutex locks are unlocked
|
||||
if mutex.IsEmpty() {
|
||||
log.Infof("[shutdown] Graceful shutdown successful.")
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
log.Tracef("[shutdown] Trying graceful shutdown...")
|
||||
}
|
||||
}
|
||||
|
||||
// Start will initialize the Telegram bot and lnbits.
|
||||
func (bot *TipBot) Start() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
}
|
||||
|
||||
// register telegram handlers
|
||||
bot.registerTelegramHandlers()
|
||||
|
||||
// download bot avatar once
|
||||
bot.downloadMyProfilePicture()
|
||||
|
||||
// edit worker collects messages to edit and
|
||||
// periodically edits them
|
||||
bot.startEditWorker()
|
||||
|
||||
// register callbacks for invoices
|
||||
initInvoiceEventCallbacks(bot)
|
||||
|
||||
// register callbacks for user state changes
|
||||
initializeStateCallbackMessage(bot)
|
||||
|
||||
// start the telegram bot
|
||||
go bot.Telegram.Start()
|
||||
|
||||
go bot.restartPersistedTickets()
|
||||
// gracefully shutdown
|
||||
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
|
||||
// we need to catch SIGTERM and SIGSTOP
|
||||
signal.Notify(exit, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP)
|
||||
<-exit
|
||||
// gracefully shutdown
|
||||
bot.GracefulShutdown()
|
||||
func handleMessage(msg *tgbotapi.Message) {
|
||||
if strings.HasPrefix(msg.Text, "cashu-token:") {
|
||||
cashuToken := strings.TrimPrefix(msg.Text, "cashu-token:")
|
||||
cashuToken = strings.TrimSpace(cashuToken)
|
||||
|
||||
if msg.Chat.IsPrivate() {
|
||||
// Handle DM
|
||||
userLightningAddress, err := getUserLightningAddress(msg.From.ID)
|
||||
if err != nil {
|
||||
bot.Send(msg.Chat.ID, "Failed to retrieve your Lightning address.")
|
||||
return
|
||||
}
|
||||
result, err := cashu.RedeemToken(cashuToken, userLightningAddress)
|
||||
if err != nil {
|
||||
bot.Send(msg.Chat.ID, "Failed to redeem Cashu token.")
|
||||
return
|
||||
}
|
||||
bot.Send(msg.Chat.ID, "Cashu token successfully redeemed to your Lightning wallet.")
|
||||
} else {
|
||||
// Handle group message
|
||||
redeemButton := tgbotapi.NewInlineKeyboardButtonData("Redeem Cashu Token", "redeem:"+cashuToken)
|
||||
markup := tgbotapi.NewInlineKeyboardMarkup([]tgbotapi.InlineKeyboardButton{redeemButton})
|
||||
msg := tgbotapi.NewMessage(msg.Chat.ID, "A Cashu token has been sent. Click the button to redeem it.")
|
||||
msg.ReplyMarkup = &markup
|
||||
bot.Send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -187,6 +187,7 @@ sendHelpText = """📖 Упс, это не сработало. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Вы получили %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
invoiceHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user