Compare commits

...
Author SHA1 Message Date
lngohumble f978d98252 volcano initial commit 2021-12-27 11:58:19 +01:00
25dc9d7b34 add edit stack lifo (#231)
* add edit stack lifo

* remove log message

* Finish the faucet (#232)

* speed up tx lock

* yolo master

* finish the faucet when inactive

* delete comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add once + singleton click interceptor (#229)

* speed up tx lock

* yolo master

* add once + singleton click interceptor

* yoooo;

* stuff

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Log oncemap (#233)

* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance button (#236)

* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance on invoice (#237)

* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add mutex http endpoints (#238)

* Faucet balance update (#239)

* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Unlock admin (#240)

* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>

* fix nLocks (#241)

* using shop.base.id (#242)

* using shop.base.id

* using shop.base.id

* using shop.base.id

* Adjust log levels (#244)

* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* fix edit signature rate limiter (#234)

* Skip duplicate edits (#245)

* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* only remove on unlock (#246)

* add edit stack lifo

* finish faucet corrected

* improve edit stack

* edit.go

* uncomment faucet check

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 20:57:38 +01:00
gohumbleandGitHub 01423827b7 Fix shop v1 (#243)
* using shop.base.id

* using shop.base.id

* using shop.base.id

* remove index from delete status messages

* fix delete status messages
2021-12-26 20:46:56 +01:00
gohumbleandGitHub f1df1e6377 only remove on unlock (#246) 2021-12-26 16:58:05 +01:00
1e5f7b1169 Skip duplicate edits (#245)
* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:46:04 +01:00
gohumbleandGitHub 9c6062f317 fix edit signature rate limiter (#234) 2021-12-26 16:37:43 +01:00
fc7247c72a Adjust log levels (#244)
* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:30:27 +01:00
gohumbleandGitHub c23d69e8f1 using shop.base.id (#242)
* using shop.base.id

* using shop.base.id

* using shop.base.id
2021-12-26 15:38:26 +01:00
gohumbleandGitHub 35d5ed8d8e fix nLocks (#241) 2021-12-26 15:12:18 +01:00
07ccc6cc28 Unlock admin (#240)
* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-26 14:51:10 +01:00
2ef798e56a Faucet balance update (#239)
* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 14:46:09 +01:00
gohumbleandGitHub 24e4212a93 add mutex http endpoints (#238) 2021-12-26 14:20:50 +01:00
6851badfab Balance on invoice (#237)
* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:30:41 +01:00
cbedc5c147 Balance button (#236)
* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:05:25 +01:00
30 changed files with 369 additions and 116 deletions
+7 -1
View File
@@ -2,6 +2,7 @@ package rate
import (
"context"
log "github.com/sirupsen/logrus"
"strconv"
"sync"
@@ -22,7 +23,7 @@ var globalLimiter *rate.Limiter
// NewLimiter creates both chat and global rate limiters.
func Start() {
idLimiter = newIdRateLimiter(rate.Limit(0.25), 20)
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
}
@@ -42,6 +43,8 @@ func CheckLimit(to interface{}) {
globalLimiter.Wait(context.Background())
var id string
switch to.(type) {
case string:
id = to.(string)
case *tb.Chat:
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
case *tb.User:
@@ -54,8 +57,11 @@ func CheckLimit(to interface{}) {
}
}
if len(id) > 0 {
log.Tracef("[Check Limit] limiter for %+v", id)
idLimiter.GetLimiter(id).Wait(context.Background())
return
}
log.Tracef("[Check Limit] skipping id limiter for %+v", to)
}
// Add creates a new rate limiter and adds it to the keys map,
+14 -1
View File
@@ -2,6 +2,7 @@ package runtime
import (
cmap "github.com/orcaman/concurrent-map"
"sync"
"time"
)
@@ -20,6 +21,8 @@ type ResettableFunctionTicker struct {
duration time.Duration
Started bool
name string
Quit chan struct{}
Wg sync.WaitGroup
}
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
@@ -28,11 +31,11 @@ func WithDuration(d time.Duration) ResettableFunctionTickerOption {
a.duration = d
}
}
func RemoveTicker(name string) {
tickerMap.Remove(name)
}
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
if t, ok := tickerMap.Get(name); ok {
return t.(*ResettableFunctionTicker)
} else {
@@ -44,6 +47,8 @@ func GetTicker(name string, option ...ResettableFunctionTickerOption) *Resettabl
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
Quit: make(chan struct{}, 1),
Wg: sync.WaitGroup{},
name: name,
}
@@ -57,12 +62,20 @@ func NewResettableFunctionTicker(name string, option ...ResettableFunctionTicker
return t
}
func (t *ResettableFunctionTicker) DoWait(f func()) {
t.Do(f)
t.Wg.Wait()
}
func (t *ResettableFunctionTicker) Do(f func()) {
t.Started = true
tickerMap.Set(t.name, t)
t.Wg.Add(1)
go func() {
defer t.Wg.Done()
for {
select {
case <-t.Quit:
return
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
+19 -1
View File
@@ -3,6 +3,8 @@ package mutex
import (
"context"
"fmt"
"github.com/gorilla/mux"
"net/http"
"sync"
cmap "github.com/orcaman/concurrent-map"
@@ -15,6 +17,21 @@ func init() {
mutexMap = cmap.New()
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock endpoint to unlock all users", len(mutexMap.Keys()), mutexMap.Keys())))
}
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
m.(*sync.Mutex).Unlock()
w.Write([]byte(fmt.Sprintf("Unlocked %s mutexe.\nCurrent number of locks: %d\nLocks: %+v",
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
return
}
w.Write([]byte(fmt.Sprintf("Mutex %s not found!", vars["id"])))
}
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
// This happens if multiple handlers call each other and try to lock/unlock multiple times
@@ -59,11 +76,12 @@ func UnlockWithContext(ctx context.Context, s string) {
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
if nLocks == 0 {
Unlock(s)
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
}
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
+1 -1
View File
@@ -35,7 +35,7 @@ func Once(k1, k2 string) error {
// setOrReturn sets the key k2 in the map i if it is not already set.
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
if _, ok := objectMap.Get(k2); ok {
return fmt.Errorf("%s already consumed object", k2)
return fmt.Errorf("[Once] %s already consumed object", k2)
}
objectMap.Set(k2, true)
return nil
+2
View File
@@ -1,6 +1,7 @@
package storage
import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"time"
"github.com/eko/gocache/store"
@@ -87,5 +88,6 @@ func (tx *Base) Set(s Storable, db *DB) error {
func (tx *Base) Delete(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
runtime.IgnoreError(transactionCache.Delete(s.Key()))
return db.Delete(s.Key(), s)
}
+5 -2
View File
@@ -9,9 +9,12 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if len(m.Text) > 0 {
bot.anyTextHandler(ctx, m)
}
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
+1
View File
@@ -89,6 +89,7 @@ func (bot *TipBot) Start() {
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.startEditWorker()
bot.registerTelegramHandlers()
initInvoiceEventCallbacks(bot)
initializeStateCallbackMessage(bot)
+71 -9
View File
@@ -1,21 +1,27 @@
package telegram
import tb "gopkg.in/lightningtipbot/telebot.v2"
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
CommandSend = "💸 Send"
CommandBalance = "👑 Balance"
CommandInvoice = "⚡️ Invoice"
CommandHelp = "📖 Help"
MainMenuCommandSend = "💸 Send"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnHelpMainMenu = mainMenu.Text(CommandHelp)
btnSendMainMenu = mainMenu.Text(CommandSend)
btnBalanceMainMenu = mainMenu.Text(CommandBalance)
btnInvoiceMainMenu = mainMenu.Text(CommandInvoice)
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
)
func init() {
@@ -45,3 +51,59 @@ func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Ro
rows = append(rows, markup.Row(buttons...))
return rows
}
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
var user *lnbits.User
var err error
if user, err = getCachedUser(&tb.User{ID: to}, *bot); err != nil {
user, err = GetLnbitsUser(&tb.User{ID: to}, *bot)
if err != nil {
return
}
updateCachedUser(user, *bot)
}
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Debugf("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
}
}
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// appendMainMenu is called in telegram.go every time a user receives a PM from the bot.
// this function will only add a keyboard if this is a private chat and no force reply.
func (bot *TipBot) appendMainMenu(to int64, recipient interface{}, options []interface{}) []interface{} {
// update the balance button
if to > 0 {
bot.mainMenuBalanceButtonUpdate(to)
}
appendKeyboard := true
for _, option := range options {
if option == tb.ForceReply {
appendKeyboard = false
}
switch option.(type) {
case *tb.ReplyMarkup:
appendKeyboard = false
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
// options = append(options[:i], options[i+1:]...)
//}
}
}
// to > 0 is private chats
if to > 0 && appendKeyboard {
options = append(options, mainMenu)
}
return options
}
+1 -1
View File
@@ -163,7 +163,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
log.Errorln(errmsg)
return tx.Error
}
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
+73
View File
@@ -0,0 +1,73 @@
package telegram
import (
"fmt"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"time"
)
var editStack cmap.ConcurrentMap
type edit struct {
to tb.Editable
what interface{}
options []interface{}
lastEdit time.Time
edited bool
}
func init() {
editStack = cmap.New()
}
const resultTrueError = "telebot: result is True"
// startEditWorker will loop through the editStack and run tryEditMessage on not edited messages.
// if editFromStack is older than 5 seconds, editFromStack will be removed.
func (bot TipBot) startEditWorker() {
go func() {
for {
for _, k := range editStack.Keys() {
if e, ok := editStack.Get(k); ok {
editFromStack := e.(edit)
if !editFromStack.edited {
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
if err != nil && err.Error() != resultTrueError {
return
}
log.Tracef("[startEditWorker] message from stack edited %+v", editFromStack)
editFromStack.lastEdit = time.Now()
editFromStack.edited = true
editStack.Set(k, editFromStack)
} else {
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
log.Tracef("[startEditWorker] removing message edit from stack %+v", editFromStack)
editStack.Remove(k)
}
}
}
}
time.Sleep(time.Second)
}
}()
}
// tryEditStack will add the editable to the edit stack, if what (message) changed.
func (bot TipBot) tryEditStack(to tb.Editable, what interface{}, options ...interface{}) {
msgSig, chat := to.MessageSig()
var sig = fmt.Sprintf("%s-%d", msgSig, chat)
if e, ok := editStack.Get(sig); ok {
editFromStack := e.(edit)
if editFromStack.what == what.(string) {
log.Tracef("[tryEditMessage] message did not change, not attempting to edit")
return
}
}
e := edit{options: options, what: what, to: to}
editStack.Set(sig, e)
}
@@ -26,7 +26,7 @@ import (
var (
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Start", "confirm_faucet_inline")
)
type InlineFaucet struct {
@@ -192,8 +192,14 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
return
}
fromUserStr := GetUserStr(m.Sender)
bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
// log faucet link if possible
if mFaucet != nil && mFaucet.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
}
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
}
@@ -248,7 +254,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
from := inlineFaucet.From
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
log.Debugf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
}
if !inlineFaucet.Active {
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
@@ -315,12 +321,8 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
inlineFaucet.To = append(inlineFaucet.To, to)
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
go func() {
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err.Error())
log.Warnln(errmsg)
}
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
}()
// build faucet message
@@ -338,9 +340,10 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
// update the message if the faucet still has some sats left after this tx
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
go func() {
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
bot.tryEditStack(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}()
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
// faucet is depleted
@@ -361,7 +364,7 @@ func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignor
inlineFaucet := fn.(*InlineFaucet)
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
bot.tryEditStack(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineFaucet inactive
inlineFaucet.Active = false
inlineFaucet.Canceled = true
@@ -377,7 +380,7 @@ func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFauce
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
bot.tryEditStack(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
inlineFaucet.Active = false
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
+1 -1
View File
@@ -19,7 +19,7 @@ func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
ticker.Do(func() {
ResetUserState(user, bot)
// removing ticker asap done
bot.shopViewDeleteAllStatusMsgs(ctx, user, 0)
bot.shopViewDeleteAllStatusMsgs(ctx, user)
runtime.RemoveTicker(user.ID)
})
} else {
+47
View File
@@ -248,6 +248,22 @@ func (bot TipBot) getHandler() []Handler {
},
},
},
{
Endpoints: []interface{}{"/volcano"},
Handler: bot.volcanoHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/tipjar", "/spendendose"},
Handler: bot.tipjarHandler,
@@ -543,6 +559,37 @@ func (bot TipBot) getHandler() []Handler {
},
},
},
{
Endpoints: []interface{}{&btnAcceptInlineVolcano},
Handler: bot.acceptInlineVolcanoHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{
//bot.singletonCallbackInterceptor,
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnCancelInlineVolcano},
Handler: bot.cancelInlineVolcanoHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnAcceptInlineFaucet},
Handler: bot.acceptInlineFaucetHandler,
+3
View File
@@ -146,6 +146,9 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
bot.handleInlineSendQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "volcano") {
//bot.handleInlineVolcanoQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
if len(strings.Split(q.Text, " ")) > 1 {
+2 -2
View File
@@ -329,8 +329,8 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
+2 -2
View File
@@ -240,8 +240,8 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
}
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
+2 -2
View File
@@ -286,8 +286,8 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
inlineTipjar.From = append(inlineTipjar.From, from)
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
+7
View File
@@ -157,6 +157,13 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
}
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
// do balance check for keyboard update
_, err := bot.GetUserBalance(invoiceEvent.User)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
log.Errorln(errmsg)
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
}
+1 -1
View File
@@ -143,7 +143,7 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
if err != nil {
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
log.Errorln(errmsg)
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
}
// create qr code
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
+11 -1
View File
@@ -215,9 +215,19 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
}
payData.Hash = invoice.PaymentHash
// do balance check for keyboard update
_, err = bot.GetUserBalance(user)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", userStr)
log.Errorln(errmsg)
}
if c.Message.Private() {
// if the command was invoked in private chat
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
+4 -1
View File
@@ -283,7 +283,10 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
if c.Message.Private() {
// if the command was invoked in private chat
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
+8 -10
View File
@@ -44,7 +44,6 @@ type ShopItem struct {
type Shop struct {
*storage.Base
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Owner *lnbits.User `json:"owner"` // owner of the shop
Type string `json:"Type"` // type of the shop
Title string `json:"title"` // Title of the item
@@ -58,7 +57,6 @@ type Shop struct {
type Shops struct {
*storage.Base
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Owner *lnbits.User `json:"owner"` // owner of the shop
Shops []string `json:"shop"` //
MaxShops int `json:"maxShops"`
@@ -238,7 +236,7 @@ func (bot *TipBot) enterShopItemTitleHandler(ctx context.Context, m *tb.Message)
bot.sendStatusMessageAndDelete(ctx, m.Sender, "🚫 Action cancelled.")
go func() {
time.Sleep(time.Duration(5) * time.Second)
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
bot.shopViewDeleteAllStatusMsgs(ctx, user)
}()
return
}
@@ -417,7 +415,7 @@ func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Sho
if len(shop.Items) == 0 {
no_items_message := "There are no items in this shop yet."
if len(shopView.Message.Text) > 0 {
shopView.Message = bot.tryEditMessage(shopView.Message, no_items_message, bot.shopMenu(ctx, shop, &ShopItem{}))
shopView.Message, _ = bot.tryEditMessage(shopView.Message, no_items_message, bot.shopMenu(ctx, shop, &ShopItem{}))
} else {
bot.tryDeleteMessage(shopView.Message)
shopView.Message = bot.trySendMessage(shopView.Message.Chat, no_items_message, bot.shopMenu(ctx, shop, &ShopItem{}))
@@ -436,14 +434,14 @@ func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Sho
if item.TbPhoto != nil {
if shopView.Message.Photo != nil {
// can only edit photo messages with another photo
shopView.Message = bot.tryEditMessage(shopView.Message, item.TbPhoto, bot.shopMenu(ctx, shop, &item))
shopView.Message, _ = bot.tryEditMessage(shopView.Message, item.TbPhoto, bot.shopMenu(ctx, shop, &item))
} else {
// if editing failes
bot.tryDeleteMessage(shopView.Message)
shopView.Message = bot.trySendMessage(shopView.Message.Chat, item.TbPhoto, bot.shopMenu(ctx, shop, &item))
}
} else if item.Title != "" {
shopView.Message = bot.tryEditMessage(shopView.Message, item.Title, bot.shopMenu(ctx, shop, &item))
shopView.Message, _ = bot.tryEditMessage(shopView.Message, item.Title, bot.shopMenu(ctx, shop, &item))
if shopView.Message == nil {
shopView.Message = bot.trySendMessage(shopView.Message.Chat, item.Title, bot.shopMenu(ctx, shop, &item))
}
@@ -1013,7 +1011,7 @@ func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) {
if err == nil && !strings.HasPrefix(strings.Split(m.Text, " ")[0], "/shop") {
// the user is returning to a shops view from a back button callback
if shopView.Message.Photo == nil {
shopsMsg = bot.tryEditMessage(shopView.Message, ShopsText, bot.shopsMainMenu(ctx, shops))
shopsMsg, _ = bot.tryEditMessage(shopView.Message, ShopsText, bot.shopsMainMenu(ctx, shops))
}
if shopsMsg == nil {
// if editing has failed, we will send a new message
@@ -1163,7 +1161,7 @@ func (bot *TipBot) enterShopsDescriptionHandler(ctx context.Context, m *tb.Messa
bot.sendStatusMessageAndDelete(ctx, m.Sender, "🚫 Action cancelled.")
go func() {
time.Sleep(time.Duration(5) * time.Second)
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
bot.shopViewDeleteAllStatusMsgs(ctx, user)
}()
return
}
@@ -1280,7 +1278,7 @@ func (bot *TipBot) shopsBrowser(ctx context.Context, c *tb.Callback) {
}
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
shopKeyboard.Inline(buttonWrapper(append(bot.makseShopSelectionButtons(s, "select_shop"), shopShopsButton), shopKeyboard, 1)...)
shopMessage := bot.tryEditMessage(c.Message, "Select a shop you want to browse.", shopKeyboard)
shopMessage, _ := bot.tryEditMessage(c.Message, "Select a shop you want to browse.", shopKeyboard)
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
shopView.Message = shopMessage
@@ -1341,7 +1339,7 @@ func (bot *TipBot) enterShopTitleHandler(ctx context.Context, m *tb.Message) {
bot.sendStatusMessageAndDelete(ctx, m.Sender, "🚫 Action cancelled.")
go func() {
time.Sleep(time.Duration(5) * time.Second)
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
bot.shopViewDeleteAllStatusMsgs(ctx, user)
}()
return
}
+6 -11
View File
@@ -160,26 +160,23 @@ func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shop
shopView = sv.(ShopView)
return
}
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User, start int) (shopView ShopView, err error) {
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
return
}
statusMessages := shopView.StatusMessages
// delete all status messages from cache
shopView.StatusMessages = append([]*tb.Message{}, statusMessages[0:start]...)
deleteStatusMessages(shopView.StatusMessages, bot)
shopView.StatusMessages = make([]*tb.Message, 0)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
deleteStatusMessages(start, statusMessages, bot)
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
return
}
func deleteStatusMessages(start int, messages []*tb.Message, bot *TipBot) {
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
// delete all status messages from telegram
for _, msg := range messages[start:] {
for _, msg := range messages {
bot.tryDeleteMessage(msg)
}
}
@@ -213,7 +210,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx context.Context, to tb.Recipie
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
if !ticker.Started {
ticker.Do(func() {
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
bot.shopViewDeleteAllStatusMsgs(ctx, user)
// removing ticker asap done
runtime.RemoveTicker(id)
})
@@ -230,7 +227,6 @@ func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
shops := &Shops{
Base: storage.New(storage.ID(id)),
ID: id,
Owner: user,
Shops: []string{},
MaxShops: MAX_SHOPS,
@@ -262,7 +258,6 @@ func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, e
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
shop := &Shop{
Base: storage.New(storage.ID(shopId)),
ID: shopId,
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
Owner: user,
Type: "photo",
+1 -1
View File
@@ -25,7 +25,7 @@ func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
// bot.helpHandler(m)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
walletCreationMsg := bot.trySendMessage(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
+15 -35
View File
@@ -11,32 +11,8 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// this function will only add a keyboard if this is a private chat and no force reply.
func appendMainMenu(to int64, options []interface{}) []interface{} {
appendKeyboard := true
for _, option := range options {
if option == tb.ForceReply {
appendKeyboard = false
}
switch option.(type) {
case *tb.ReplyMarkup:
appendKeyboard = false
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
// options = append(options[:i], options[i+1:]...)
//}
}
}
// to > 0 is private chats
if to > 0 && appendKeyboard {
options = append(options, mainMenu)
}
return options
}
// getChatIdFromRecipient will parse the recipient to int64
func getChatIdFromRecipient(to tb.Recipient) (int64, error) {
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
if err != nil {
return 0, err
@@ -47,12 +23,12 @@ func getChatIdFromRecipient(to tb.Recipient) (int64, error) {
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
// ChatId is used for the keyboard
chatId, err := getChatIdFromRecipient(to)
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Forward(to, what, appendMainMenu(chatId, options)...)
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -61,12 +37,12 @@ func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options .
func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
// ChatId is used for the keyboard
chatId, err := getChatIdFromRecipient(to)
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Send(to, what, appendMainMenu(chatId, options)...)
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -75,23 +51,27 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
msg, err := bot.Telegram.Reply(to, what, appendMainMenu(to.Chat.ID, options)...)
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
return
}
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
var err error
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message, err error) {
// do not attempt edit if the message did not change
sig, chat := to.MessageSig()
if chat != 0 {
sig = strconv.FormatInt(chat, 10)
}
rate.CheckLimit(sig)
_, chatId := to.MessageSig()
msg, err = bot.Telegram.Edit(to, what, appendMainMenu(chatId, options)...)
msg, err = bot.Telegram.Edit(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
return
}
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
+10
View File
@@ -24,6 +24,16 @@ func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
return
}
// check if the user clicked on the balance button
if strings.HasPrefix(m.Text, MainMenuCommandBalance) {
bot.tryDeleteMessage(m)
// overwrite the message text so it doesn't cause an infinite loop
// because balanceHandler calls anyTextHAndler...
m.Text = ""
bot.balanceHandler(ctx, m)
return
}
// could be an invoice
anyText := strings.ToLower(m.Text)
if lightning.IsInvoice(anyText) {
+1 -5
View File
@@ -121,11 +121,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
// notify users
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
// forward tipped message to user once
if !messageHasTip {
+28 -13
View File
@@ -91,19 +91,19 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
t.FromWallet = from.Wallet.ID
t.FromLNbitsID = from.ID
// // check if fromUser has balance
// balance, err := bot.GetUserBalance(from)
// if err != nil {
// errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
// log.Errorln(errmsg)
// return false, err
// }
// // check if fromUser has balance
// if balance < amount {
// errmsg := fmt.Sprintf("balance too low.")
// log.Warnf("Balance of user %s too low", fromUserStr)
// return false, fmt.Errorf(errmsg)
// }
// check if fromUser has balance
balance, err := bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
// check if fromUser has balance
if balance < amount {
errmsg := fmt.Sprintf("balance too low.")
log.Warnf("Balance of user %s too low", fromUserStr)
return false, fmt.Errorf(errmsg)
}
t.ToWallet = to.ID
t.ToLNbitsID = to.ID
@@ -128,5 +128,20 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
log.Warnf(errmsg)
return false, err
}
// check if fromUser has balance
_, err = bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
_, err = bot.GetUserBalance(to)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
return true, err
}
+1 -1
View File
@@ -89,7 +89,7 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
bot.Cache.Set(
fmt.Sprintf("%s_balance", user.Name),
amount,
&store.Options{Expiration: 30 * time.Second},
&store.Options{Expiration: 1 * time.Hour},
)
return
}
+10 -2
View File
@@ -4,12 +4,16 @@ import (
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/gorilla/mux"
_ "net/http/pprof"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
_ "net/http/pprof"
)
// setLogger will initialize the log format
@@ -24,7 +28,11 @@ func setLogger() {
func main() {
// set logger
setLogger()
go http.ListenAndServe("0.0.0.0:6060", nil)
router := mux.NewRouter()
router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
router.Handle("/mutex", http.HandlerFunc(mutex.ServeHTTP))
router.Handle("/mutex/unlock/{id}", http.HandlerFunc(mutex.UnlockHTTP))
go http.ListenAndServe("0.0.0.0:6060", router)
defer withRecovery()
bot := telegram.NewBot()
webhook.NewServer(&bot)