Compare commits

...
2 Commits
Author SHA1 Message Date
MichilisandGitHub ccbf036ae9 Update bot.go 2024-07-17 19:29:46 +02:00
MichilisandGitHub f68481ba0e Create cashu_module.go 2024-07-17 19:29:09 +02:00
2 changed files with 65 additions and 140 deletions
+35
View File
@@ -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
}
+30 -140
View File
@@ -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)
}
}
}