Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f978d98252 | ||
|
|
25dc9d7b34 | ||
|
|
01423827b7 | ||
|
|
f1df1e6377 | ||
|
|
1e5f7b1169 | ||
|
|
9c6062f317 | ||
|
|
fc7247c72a | ||
|
|
c23d69e8f1 | ||
|
|
35d5ed8d8e | ||
|
|
07ccc6cc28 | ||
|
|
2ef798e56a | ||
|
|
24e4212a93 | ||
|
|
6851badfab | ||
|
|
cbedc5c147 | ||
|
|
373ee844da | ||
|
|
151ed39b04 | ||
|
|
24108f6a1f | ||
|
|
737ab115bd | ||
|
|
13957342df | ||
|
|
fe1a921440 | ||
|
|
39ff25beca | ||
|
|
ec15f26c13 | ||
|
|
0218191793 | ||
|
|
5065f5af86 | ||
|
|
6aca41835d | ||
|
|
6b746447e5 | ||
|
|
ca60b271fd | ||
|
|
1b720b498c | ||
|
|
2066470cba | ||
|
|
73ada1f25b | ||
|
|
43a77fd1b2 | ||
|
|
f968310902 | ||
|
|
32a5a7c264 | ||
|
|
776de88041 | ||
|
|
192a100f8d | ||
|
|
b796db1979 | ||
|
|
eb07cdf117 | ||
|
|
9f1ce26d6e | ||
|
|
0ce42e8f1f | ||
|
|
46d77de38e | ||
|
|
09d3af411e | ||
|
|
5414c82339 | ||
|
|
2edc2953dc | ||
|
|
2bc9555b53 | ||
|
|
47ef5baee3 | ||
|
|
78eadf1a0e | ||
|
|
6aa05c8faa | ||
|
|
8f8644a1d2 | ||
|
|
f9aed70869 | ||
|
|
036ac12f41 | ||
|
|
67cff58c63 | ||
|
|
4730c94c84 | ||
|
|
e53ef94306 | ||
|
|
a9f2728c93 | ||
|
|
657fc7af1d | ||
|
|
1b24072020 | ||
|
|
d912541391 | ||
|
|
72381d0071 | ||
|
|
a644c465cd | ||
|
|
bc0d3df897 | ||
|
|
fa234d4073 | ||
|
|
dd88c93474 | ||
|
|
2469898f9f | ||
|
|
ee656dc5f0 | ||
|
|
3eba0de851 | ||
|
|
f8fadb1729 | ||
|
|
6b5e30dbe4 | ||
|
|
72ef490538 | ||
|
|
7e2404eaf5 | ||
|
|
64f9492af2 | ||
|
|
f85ec34bcc | ||
|
|
8b40253169 | ||
|
|
91d38b5bb4 | ||
|
|
a59a7c226d | ||
|
|
4b620186f1 | ||
|
|
f313b5cdbe | ||
|
|
179d40178c | ||
|
|
15d711a6fd | ||
|
|
a4f5b21f1d | ||
|
|
307d9cd873 | ||
|
|
0f6c37a40c | ||
|
|
9e4b612c26 | ||
|
|
1815bcfaf9 | ||
|
|
6299adf633 | ||
|
|
5b93d43bc5 | ||
|
|
0cfb693619 | ||
|
|
1ea9268698 | ||
|
|
f50e6ced71 | ||
|
|
1b922c03a9 | ||
|
|
f6768b72ea | ||
|
|
236b095bbe | ||
|
|
a0799b1b32 |
@@ -12,6 +12,7 @@ require (
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/sethvargo/go-limiter v0.7.2
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
@@ -20,7 +21,7 @@ require (
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
golang.org/x/text v0.3.5
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
@@ -397,6 +397,8 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
|
||||
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
|
||||
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY=
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
|
||||
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
@@ -728,6 +730,10 @@ gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYl
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955 h1:uhQUyDqilPUh58BWtIeSAupjovs1QQjC6pEoErqD86o=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad h1:HR3vqf1DS7hEQ0j77J4ctumZgzDIHNXZtag60U9OOig=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac h1:EcXyrTUaQJYiHtLQstXdW04sRH9HwH9mpaxy9Lkcomc=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/macaroon-bakery.v2 v2.0.1/go.mod h1:B4/T17l+ZWGwxFSZQmlBwp25x+og7OkhETfr3S9MbIA=
|
||||
gopkg.in/macaroon.v2 v2.0.0/go.mod h1:+I6LnTMkm/uV5ew/0nsulNjL16SK4+C8yDmRUzHR17I=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
|
||||
@@ -738,6 +744,8 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkep
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
|
||||
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
|
||||
@@ -30,6 +30,7 @@ type TelegramConfiguration struct {
|
||||
}
|
||||
type DatabaseConfiguration struct {
|
||||
DbPath string `yaml:"db_path"`
|
||||
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
|
||||
BuntDbPath string `yaml:"buntdb_path"`
|
||||
TransactionsPath string `yaml:"transactions_path"`
|
||||
}
|
||||
|
||||
@@ -36,6 +36,13 @@ const (
|
||||
UserHasEnteredAmount
|
||||
UserEnterUser
|
||||
UserHasEnteredUser
|
||||
UserEnterShopTitle
|
||||
UserStateShopItemSendPhoto
|
||||
UserStateShopItemSendTitle
|
||||
UserStateShopItemSendDescription
|
||||
UserStateShopItemSendPrice
|
||||
UserStateShopItemSendItemFile
|
||||
UserEnterShopsDescription
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -15,7 +14,6 @@ import (
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -24,10 +22,6 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
|
||||
const (
|
||||
// invoiceReceivedMessage = "⚡️ You received %d sat."
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
@@ -37,17 +31,16 @@ type Server struct {
|
||||
}
|
||||
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int64 `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct{} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
@@ -55,8 +48,7 @@ type Webhook struct {
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
@@ -88,38 +80,43 @@ func (w *Server) newRouter() *mux.Router {
|
||||
return router
|
||||
}
|
||||
|
||||
func (w Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
depositEvent := Webhook{}
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
webhookEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&depositEvent)
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(depositEvent.WalletID)
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, depositEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
|
||||
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
|
||||
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
|
||||
err = w.buntdb.Get(tx)
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// trigger invoice events
|
||||
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
} else {
|
||||
if len(tx.Comment) > 0 {
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
|
||||
c(txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// fallback: send a message to the user if there is no callback for this invoice
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
+33
-24
@@ -11,24 +11,23 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
ToUser *lnbits.User `json:"to_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
type LNURLInvoice struct {
|
||||
*telegram.Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
}
|
||||
|
||||
func (msg Invoice) Key() string {
|
||||
return fmt.Sprintf("payment-hash:%s", msg.PaymentHash)
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
@@ -58,7 +57,7 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
// log the error
|
||||
log.Errorf("[LNURL] %v", err)
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = writeResponse(writer, response)
|
||||
@@ -98,9 +97,9 @@ func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Server) serveLNURLpSecond(username string, amount int64, comment string) (*lnurl.LNURLPayValues, error) {
|
||||
func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment string) (*lnurl.LNURLPayValues, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount < minSendable || amount > MaxSendable {
|
||||
if amount_msat < minSendable || amount_msat > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
@@ -156,13 +155,13 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
}
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount / 1000,
|
||||
Amount: amount_msat / 1000,
|
||||
Out: false,
|
||||
DescriptionHash: descriptionHash,
|
||||
Webhook: w.WebhookServer},
|
||||
w.c)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
@@ -170,15 +169,25 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
// save invoice struct for later use
|
||||
invoiceStruct := &telegram.Invoice{
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
Amount: amount_msat / 1000,
|
||||
}
|
||||
// save lnurl invoice struct for later use (will hold the comment or other metdata for a notification when paid)
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
Invoice{
|
||||
ToUser: user,
|
||||
Amount: amount,
|
||||
Comment: comment,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
CreatedAt: time.Now(),
|
||||
LNURLInvoice{
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Comment: comment,
|
||||
CreatedAt: time.Now(),
|
||||
}))
|
||||
// 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,
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
|
||||
@@ -62,7 +62,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
for currency, _ := range p.Currencies {
|
||||
avg_price := 0.0
|
||||
n_responses := 0
|
||||
for exchange, getPrice := range p.Exchanges {
|
||||
for _, getPrice := range p.Exchanges {
|
||||
fprice, err := getPrice(currency)
|
||||
if err != nil {
|
||||
// log.Debug(err)
|
||||
@@ -71,11 +71,11 @@ func (p *PriceWatcher) Watch() error {
|
||||
}
|
||||
n_responses++
|
||||
avg_price += fprice
|
||||
log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
time.Sleep(time.Second * time.Duration(2))
|
||||
}
|
||||
Price[currency] = avg_price / float64(n_responses)
|
||||
log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
}
|
||||
time.Sleep(p.UpdateInterval)
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@ package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// Limiter
|
||||
@@ -21,7 +23,7 @@ var globalLimiter *rate.Limiter
|
||||
|
||||
// NewLimiter creates both chat and global rate limiters.
|
||||
func Start() {
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.3), 20)
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
|
||||
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
|
||||
}
|
||||
|
||||
@@ -41,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:
|
||||
@@ -53,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,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
Quit chan struct{}
|
||||
Wg sync.WaitGroup
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
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 {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
Quit: make(chan struct{}, 1),
|
||||
Wg: sync.WaitGroup{},
|
||||
name: name,
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
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()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package mutex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var mutexMap cmap.ConcurrentMap
|
||||
|
||||
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
|
||||
// the same mutex.
|
||||
func checkSoftLock(s string) int {
|
||||
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
|
||||
return v.(int)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
|
||||
// LockWithContext should be used to lock objects like faucets etc.
|
||||
// The context carries a uid that is unique the each request (message, button press, etc.).
|
||||
// If the uid has a lock already *for a certain object*, it increments the
|
||||
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
|
||||
func LockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
// sync mutex to sync checkSoftLock with the increment of nLocks
|
||||
// same user can't lock the same object multiple times
|
||||
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
var nLocks = checkSoftLock(uid)
|
||||
if nLocks == 0 {
|
||||
Lock(s)
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
|
||||
}
|
||||
nLocks++
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
}
|
||||
|
||||
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
|
||||
// If it has been locked more than once
|
||||
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
|
||||
// nLocks == 1
|
||||
func UnlockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
var nLocks = checkSoftLock(uid)
|
||||
nLocks--
|
||||
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))
|
||||
}
|
||||
|
||||
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
|
||||
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
|
||||
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
|
||||
func Lock(s string) {
|
||||
log.Tracef("[Mutex] Attempt Lock %s", s)
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
m.(*sync.Mutex).Lock()
|
||||
mutexMap.Set(s, m)
|
||||
} else {
|
||||
m := &sync.Mutex{}
|
||||
m.Lock()
|
||||
mutexMap.Set(s, m)
|
||||
}
|
||||
log.Tracef("[Mutex] Locked %s", s)
|
||||
}
|
||||
|
||||
// Unlock unlocks a mutex in the mutexMap.
|
||||
func Unlock(s string) {
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
mutexMap.Remove(s)
|
||||
m.(*sync.Mutex).Unlock()
|
||||
log.Tracef("[Mutex] Unlocked %s", s)
|
||||
} else {
|
||||
// this should never happen. Mutex should have been in the mutexMap.
|
||||
log.Errorf("[Mutex] ⚠⚠⚠️ Unlock %s not in mutexMap. Skip.", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package once
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var onceMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
onceMap = cmap.New()
|
||||
}
|
||||
|
||||
func New(objectKey string) {
|
||||
onceMap.Set(objectKey, cmap.New())
|
||||
}
|
||||
|
||||
// Once creates a map of keys k1 with a map of keys k2.
|
||||
// The idea is that an object with ID k1 can create a list of users k2
|
||||
// that have already interacted with the object. If the user k2 is in the list,
|
||||
// the object is not allowed to accessed again.
|
||||
func Once(k1, k2 string) error {
|
||||
i, ok := onceMap.Get(k1)
|
||||
if ok {
|
||||
return setOrReturn(i.(cmap.ConcurrentMap), k2)
|
||||
}
|
||||
userMap := cmap.New()
|
||||
onceMap.Set(k1, userMap)
|
||||
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
return setOrReturn(userMap, k2)
|
||||
}
|
||||
|
||||
// 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("[Once] %s already consumed object", k2)
|
||||
}
|
||||
objectMap.Set(k2, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes the key k1 from the map. Should be called after Once was called and
|
||||
// the object k1 finished.
|
||||
func Remove(k1 string) {
|
||||
onceMap.Remove(k1)
|
||||
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
Canceled bool `json:"canceled"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s Storable, db *DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt Inactivate] %s", tx.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
|
||||
cacheTx, err := transactionCache.Get(s.Key())
|
||||
if err != nil {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
log.Tracef("[Bunt] get object %s", s.Key())
|
||||
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
log.Tracef("[Bunt Cache] get object %s", s.Key())
|
||||
return cacheTx.(Storable), err
|
||||
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s Storable, db *DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
err := db.Set(s)
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt] could not set object: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt] set object %s", s.Key())
|
||||
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
|
||||
}
|
||||
log.Tracef("[Bunt Cache] set object: %s", s.Key())
|
||||
return err
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
+23
-15
@@ -2,7 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
)
|
||||
@@ -78,23 +78,31 @@ func (db *DB) Set(object Storable) error {
|
||||
}
|
||||
|
||||
// Delete a storable item.
|
||||
// todo -- not ascend users index
|
||||
func (db *DB) Delete(index string, object Storable) error {
|
||||
return db.Update(func(tx *buntdb.Tx) error {
|
||||
var delkeys []string
|
||||
runtime.IgnoreError(
|
||||
tx.Ascend(index, func(key, value string) bool {
|
||||
if key == object.Key() {
|
||||
delkeys = append(delkeys, key)
|
||||
}
|
||||
return true
|
||||
}),
|
||||
)
|
||||
for _, k := range delkeys {
|
||||
if _, err := tx.Delete(k); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Get(object.Key())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Delete(object.Key()); err != nil {
|
||||
return err
|
||||
}
|
||||
// OLD: from gohumble:
|
||||
// todo -- not ascend users index
|
||||
// var delkeys []string
|
||||
// runtime.IgnoreError(
|
||||
// tx.Ascend(index, func(key, value string) bool {
|
||||
// if key == object.Key() {
|
||||
// delkeys = append(delkeys, key)
|
||||
// }
|
||||
// return true
|
||||
// }),
|
||||
// )
|
||||
// for _, k := range delkeys {
|
||||
// if _, err := tx.Delete(k); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
package transaction
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
InTransaction bool `json:"intransaction"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
InTransaction: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = true
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
// to avoid race conditions, we block the call if there is
|
||||
// already an active transaction by loop until InTransaction is false
|
||||
ticker := time.NewTicker(time.Second * 3)
|
||||
for tx.InTransaction {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
return nil, fmt.Errorf("transaction timeout")
|
||||
default:
|
||||
time.Sleep(time.Duration(200) * time.Millisecond)
|
||||
err = db.Get(s)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not get transaction")
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
return db.Set(s)
|
||||
}
|
||||
@@ -8,10 +8,12 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
@@ -24,7 +26,7 @@ func getArgumentFromCommand(input string, which int) (output string, err error)
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int, err error) {
|
||||
func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
@@ -34,14 +36,14 @@ func decodeAmountFromCommand(input string) (amount int, err error) {
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int, err error) {
|
||||
func getAmount(input string) (amount int64, err error) {
|
||||
// convert something like 1.2k into 1200
|
||||
if strings.HasSuffix(strings.ToLower(input), "k") {
|
||||
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = int(fmount * 1000)
|
||||
amount = int64(fmount * 1000)
|
||||
return amount, err
|
||||
}
|
||||
|
||||
@@ -61,13 +63,13 @@ func getAmount(input string) (amount int, err error) {
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, errors.New("price is zero")
|
||||
}
|
||||
amount = int(fmount / price.Price[currency] * float64(100_000_000))
|
||||
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
|
||||
return amount, nil
|
||||
}
|
||||
}
|
||||
|
||||
// use plain integer as satoshis
|
||||
amount, err = strconv.Atoi(input)
|
||||
amount, err = strconv.ParseInt(input, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -145,7 +147,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int(EnterAmountStateData.AmountMax/1000) || amount < int(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
@@ -157,7 +159,9 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterAmountStateData.Type {
|
||||
case "LnurlPayState":
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -177,7 +181,9 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
case "LnurlWithdrawState":
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -22,8 +21,9 @@ import (
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
logger *gorm.DB
|
||||
Telegram *telebot.Bot
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
@@ -48,7 +48,8 @@ func NewBot() TipBot {
|
||||
Database: db,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
logger: txLogger,
|
||||
Bunt: createBunt(),
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
}
|
||||
@@ -81,13 +82,16 @@ func (bot TipBot) initBotWallet() error {
|
||||
}
|
||||
|
||||
// Start will initialize the Telegram bot and lnbits.
|
||||
func (bot TipBot) Start() {
|
||||
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())
|
||||
}
|
||||
bot.startEditWorker()
|
||||
bot.registerTelegramHandlers()
|
||||
initInvoiceEventCallbacks(bot)
|
||||
initializeStateCallbackMessage(bot)
|
||||
bot.Telegram.Start()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package telegram
|
||||
|
||||
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 (
|
||||
MainMenuCommandSend = "💸 Send"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
|
||||
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
|
||||
)
|
||||
|
||||
func init() {
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
// buttonWrapper wrap buttons slice in rows of length i
|
||||
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
|
||||
buttonLength := len(buttons)
|
||||
rows := make([]tb.Row, 0)
|
||||
|
||||
if buttonLength > length {
|
||||
for i := 0; i < buttonLength; i = i + length {
|
||||
buttonRow := make([]tb.Btn, length)
|
||||
if i+length < buttonLength {
|
||||
buttonRow = buttons[i : i+length]
|
||||
} else {
|
||||
buttonRow = buttons[i:]
|
||||
}
|
||||
rows = append(rows, markup.Row(buttonRow...))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -26,9 +26,9 @@ const (
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
|
||||
func createBunt() *storage.DB {
|
||||
func createBunt(file string) *storage.DB {
|
||||
// create bunt database
|
||||
bunt := storage.NewBunt(internal.Configuration.Database.BuntDbPath)
|
||||
bunt := storage.NewBunt(file)
|
||||
// create bunt database index for ascending (searching) TipTooltips
|
||||
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
|
||||
if err != nil {
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -3,16 +3,20 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -22,15 +26,15 @@ 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 {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
Message string `json:"inline_faucet_message"`
|
||||
Amount int `json:"inline_faucet_amount"`
|
||||
RemainingAmount int `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int `json:"inline_faucet_peruseramount"`
|
||||
Amount int64 `json:"inline_faucet_amount"`
|
||||
RemainingAmount int64 `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int64 `json:"inline_faucet_peruseramount"`
|
||||
From *lnbits.User `json:"inline_faucet_from"`
|
||||
To []*lnbits.User `json:"inline_faucet_to"`
|
||||
Memo string `json:"inline_faucet_memo"`
|
||||
@@ -61,10 +65,10 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
if perUserAmount < 5 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := amount / perUserAmount
|
||||
nTotal := int(amount / perUserAmount)
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
@@ -73,7 +77,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low: %v", fromUserStr, err))
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low", fromUserStr))
|
||||
}
|
||||
// // check for memo in command
|
||||
memo := GetMemoFromCommand(text, 3)
|
||||
@@ -85,7 +89,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineFaucet{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
From: fromUser,
|
||||
@@ -184,19 +188,25 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] %s", err)
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
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))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[faucet] %s", err)
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
@@ -218,7 +228,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
log.Infof("[faucet] %s:%d created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.From.Telegram.ID, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -226,33 +236,35 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
CacheTime: 1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.Errorln(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] %s", err)
|
||||
log.Debugf("[acceptInlineFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
from := inlineFaucet.From
|
||||
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
|
||||
return
|
||||
// log faucet link if possible
|
||||
if c.Message != nil && c.Message.Chat != nil {
|
||||
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.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
|
||||
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return
|
||||
}
|
||||
// release faucet no matter what
|
||||
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
@@ -260,11 +272,13 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
for _, a := range inlineFaucet.To {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
// log.Infof("[faucet] %s already took from faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -273,7 +287,6 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
log.Infof("[faucet] User %s has no wallet.", toUserStr)
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
@@ -294,22 +307,23 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
// if faucet fails, cancel it:
|
||||
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
|
||||
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
|
||||
// bot.cancelInlineFaucet(ctx, c, true) // cancel without ID check
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
|
||||
|
||||
_, 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)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
go func() {
|
||||
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
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
|
||||
@@ -322,34 +336,57 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineFaucet.Message)
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
|
||||
// update the message if the faucet still has some sats left after this tx
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
go func() {
|
||||
bot.tryEditStack(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
}()
|
||||
}
|
||||
|
||||
}
|
||||
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
|
||||
// faucet is depleted
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message)
|
||||
inlineFaucet.Active = false
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) {
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
bot.tryEditStack(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.InTransaction = false
|
||||
inlineFaucet.Canceled = true
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *InlineFaucet) {
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditStack(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
|
||||
inlineFaucet.Active = false
|
||||
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
bot.cancelInlineFaucet(ctx, c, false)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found handler for this state
|
||||
// now looking for user state reset ticker
|
||||
ticker := runtime.GetTicker(user.ID)
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
ResetUserState(user, bot)
|
||||
// removing ticker asap done
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
runtime.RemoveTicker(user.ID)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
|
||||
c(ctx, m)
|
||||
return
|
||||
}
|
||||
}
|
||||
+771
-67
File diff suppressed because it is too large
Load Diff
@@ -34,7 +34,7 @@ func GetMemoFromCommand(command string, fromWord int) string {
|
||||
return memo
|
||||
}
|
||||
|
||||
func MakeProgressbar(current int, total int) string {
|
||||
func MakeProgressbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🟩", int(progress))
|
||||
@@ -42,7 +42,7 @@ func MakeProgressbar(current int, total int) string {
|
||||
return progressbar
|
||||
}
|
||||
|
||||
func MakeTipjarbar(current int, total int) string {
|
||||
func MakeTipjarbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🍯", int(progress))
|
||||
|
||||
@@ -95,12 +95,14 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
|
||||
}
|
||||
}
|
||||
|
||||
// anyChosenInlineHandler will load any inline object from cache and store into bunt.
|
||||
// this is used to decrease bunt db write ops.
|
||||
func (bot TipBot) anyChosenInlineHandler(q *tb.ChosenInlineResult) {
|
||||
// load inline object from cache
|
||||
inlineObject, err := bot.Cache.Get(q.ResultID)
|
||||
// check error
|
||||
if err != nil {
|
||||
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err)
|
||||
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
|
||||
return
|
||||
}
|
||||
switch inlineObject.(type) {
|
||||
@@ -144,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 {
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
"github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -24,9 +28,10 @@ var (
|
||||
)
|
||||
|
||||
type InlineReceive struct {
|
||||
*transaction.Base
|
||||
Message string `json:"inline_receive_message"`
|
||||
Amount int `json:"inline_receive_amount"`
|
||||
*storage.Base
|
||||
MessageText string `json:"inline_receive_messagetext"`
|
||||
Message *tb.Message `json:"inline_receive_message"`
|
||||
Amount int64 `json:"inline_receive_amount"`
|
||||
From *lnbits.User `json:"inline_receive_from"`
|
||||
To *lnbits.User `json:"inline_receive_to"`
|
||||
From_SpecificUser bool `json:"from_specific_user"`
|
||||
@@ -41,8 +46,9 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
|
||||
cancelInlineReceiveButton.Data = id
|
||||
inlineReceiveMenu.Inline(
|
||||
inlineReceiveMenu.Row(
|
||||
cancelInlineReceiveButton,
|
||||
acceptInlineReceiveButton,
|
||||
cancelInlineReceiveButton),
|
||||
),
|
||||
)
|
||||
return inlineReceiveMenu
|
||||
}
|
||||
@@ -115,8 +121,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
results[i].SetResultID(id)
|
||||
// create persistend inline send struct
|
||||
inlineReceive := InlineReceive{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
MessageText: inlineMessage,
|
||||
To: to,
|
||||
Memo: memo,
|
||||
Amount: amount,
|
||||
@@ -138,33 +144,24 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err)
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
err = inlineReceive.Lock(inlineReceive, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineReceiveHandler] %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// user `from` is the one who is SENDING
|
||||
// user `to` is the one who is RECEIVING
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// check if this payment is requested from a specific user
|
||||
if inlineReceive.From_SpecificUser {
|
||||
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
|
||||
@@ -174,18 +171,60 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
inlineReceive.From = from
|
||||
|
||||
}
|
||||
inlineReceive.Message = c.Message
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
if from.Wallet == nil || balance < inlineReceive.Amount {
|
||||
// if user has no wallet, show invoice
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
|
||||
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
bot.inlineReceiveInvoice(ctx, c, inlineReceive)
|
||||
return
|
||||
} else {
|
||||
// else, do an internal transaction
|
||||
bot.sendInlineReceiveHandler(ctx, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// from := inlineReceive.From
|
||||
from := LoadUser(ctx)
|
||||
to := inlineReceive.To
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// balance check of the user
|
||||
balance, err := bot.GetUserBalanceCached(from)
|
||||
if err != nil {
|
||||
@@ -209,40 +248,104 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
bot.finishInlineReceiveHandler(ctx, c)
|
||||
}
|
||||
|
||||
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
|
||||
if !inlineReceive.Active {
|
||||
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)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
var msg *tb.Message
|
||||
if inlineReceive.Message.Chat != nil {
|
||||
msg = bot.trySendMessage(inlineReceive.Message.Chat, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
} else {
|
||||
msg = bot.trySendMessage(c.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
bot.tryEditMessage(inlineReceive.Message, fmt.Sprintf("%s\n\nPay this invoice:\n```%s```", inlineReceive.MessageText, invoice.PaymentRequest))
|
||||
}
|
||||
invoice.InvoiceMessage = msg
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", GetUserStr(inlineReceive.To.Telegram), inlineReceive.Amount)
|
||||
|
||||
}
|
||||
func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
|
||||
bot.tryDeleteMessage(invoiceEvent.InvoiceMessage)
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
from := inlineReceive.From
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
inlineReceive.MessageText = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineReceive.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
|
||||
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)
|
||||
}
|
||||
// inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err)
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
@@ -250,7 +353,6 @@ func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
inlineReceive.InTransaction = false
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
return
|
||||
|
||||
@@ -6,12 +6,14 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -25,9 +27,9 @@ var (
|
||||
)
|
||||
|
||||
type InlineSend struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
Message string `json:"inline_send_message"`
|
||||
Amount int `json:"inline_send_amount"`
|
||||
Amount int64 `json:"inline_send_amount"`
|
||||
From *lnbits.User `json:"inline_send_from"`
|
||||
To *lnbits.User `json:"inline_send_to"`
|
||||
To_SpecificUser bool `json:"to_specific_user"`
|
||||
@@ -132,7 +134,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
|
||||
// add data to persistent object
|
||||
inlineSend := InlineSend{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
From: fromUser,
|
||||
To: toUserDb,
|
||||
@@ -158,28 +160,24 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineSendHandler] %s", err)
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = inlineSend.Lock(inlineSend, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineSend] %s", err)
|
||||
return
|
||||
}
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
defer inlineSend.Release(inlineSend, bot.Bunt)
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
|
||||
amount := inlineSend.Amount
|
||||
|
||||
@@ -224,7 +222,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
@@ -242,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)
|
||||
@@ -251,11 +249,13 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
@@ -263,7 +263,6 @@ func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
inlineSend.InTransaction = false
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
return
|
||||
|
||||
@@ -6,12 +6,14 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -25,11 +27,11 @@ var (
|
||||
)
|
||||
|
||||
type InlineTipjar struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
Message string `json:"inline_tipjar_message"`
|
||||
Amount int `json:"inline_tipjar_amount"`
|
||||
GivenAmount int `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int `json:"inline_tipjar_peruseramount"`
|
||||
Amount int64 `json:"inline_tipjar_amount"`
|
||||
GivenAmount int64 `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int64 `json:"inline_tipjar_peruseramount"`
|
||||
To *lnbits.User `json:"inline_tipjar_to"`
|
||||
From []*lnbits.User `json:"inline_tipjar_from"`
|
||||
Memo string `json:"inline_tipjar_memo"`
|
||||
@@ -62,7 +64,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := amount / perUserAmount
|
||||
nTotal := int(amount / perUserAmount)
|
||||
toUser := LoadUser(ctx)
|
||||
// toUserStr := GetUserStr(sender)
|
||||
// // check for memo in command
|
||||
@@ -83,7 +85,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineTipjar{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
To: toUser,
|
||||
@@ -162,10 +164,10 @@ func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTi
|
||||
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
// slice of buttons
|
||||
buttons := make([]tb.Btn, 0)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, cancelInlineTipjarButton)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
|
||||
inlineTipjarMenu.Inline(
|
||||
inlineTipjarMenu.Row(buttons...))
|
||||
@@ -181,7 +183,7 @@ func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
|
||||
ctx = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err)
|
||||
log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
@@ -193,7 +195,7 @@ func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err)
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
@@ -233,25 +235,20 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
}
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err)
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
err = inlineTipjar.Lock(inlineTipjar, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] LockTipjar %s error: %s", inlineTipjar.ID, err)
|
||||
return
|
||||
}
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
return
|
||||
}
|
||||
// release tipjar no matter what
|
||||
defer inlineTipjar.Release(inlineTipjar, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
@@ -259,7 +256,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
}
|
||||
// // check if to user has already given to the tipjar
|
||||
for _, a := range inlineTipjar.From {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
if a.Telegram.ID == from.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
|
||||
return
|
||||
@@ -279,7 +276,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
}
|
||||
@@ -289,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)
|
||||
@@ -335,10 +332,12 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
@@ -346,7 +345,6 @@ func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineTipjar inactive
|
||||
inlineTipjar.Active = false
|
||||
inlineTipjar.InTransaction = false
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
return
|
||||
|
||||
@@ -13,6 +13,7 @@ type handlerCallbackInterceptor struct {
|
||||
handler CallbackFuncHandler
|
||||
before CallbackChain
|
||||
after CallbackChain
|
||||
onDefer CallbackChain
|
||||
}
|
||||
type CallbackChain []Func
|
||||
type CallbackInterceptOption func(*handlerCallbackInterceptor)
|
||||
@@ -27,6 +28,11 @@ func WithAfterCallback(chain ...Func) CallbackInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -50,11 +56,13 @@ func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackIntercep
|
||||
opt(hm)
|
||||
}
|
||||
return func(c *tb.Callback) {
|
||||
ctx, err := interceptCallback(context.Background(), c, hm.before)
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptCallback(ctx, c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptCallback(ctx, c, hm.onDefer)
|
||||
hm.handler(ctx, c)
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
|
||||
@@ -16,6 +16,7 @@ type handlerMessageInterceptor struct {
|
||||
handler MessageFuncHandler
|
||||
before MessageChain
|
||||
after MessageChain
|
||||
onDefer MessageChain
|
||||
}
|
||||
type MessageChain []Func
|
||||
type MessageInterceptOption func(*handlerMessageInterceptor)
|
||||
@@ -30,6 +31,11 @@ func WithAfterMessage(chain ...Func) MessageInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -48,17 +54,18 @@ func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain)
|
||||
}
|
||||
|
||||
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
|
||||
|
||||
hm := &handlerMessageInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Message) {
|
||||
ctx, err := interceptMessage(context.Background(), message, hm.before)
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptMessage(ctx, message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptMessage(ctx, message, hm.onDefer)
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ type handlerQueryInterceptor struct {
|
||||
handler QueryFuncHandler
|
||||
before QueryChain
|
||||
after QueryChain
|
||||
onDefer QueryChain
|
||||
}
|
||||
type QueryChain []Func
|
||||
type QueryInterceptOption func(*handlerQueryInterceptor)
|
||||
@@ -27,6 +28,11 @@ func WithAfterQuery(chain ...Func) QueryInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptQuery(ctx context.Context, message *tb.Query, hm QueryChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -49,14 +55,16 @@ func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption)
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Query) {
|
||||
ctx, err := interceptQuery(context.Background(), message, hm.before)
|
||||
return func(query *tb.Query) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptQuery(context.Background(), query, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptQuery(ctx, message, hm.after)
|
||||
defer interceptQuery(ctx, query, hm.onDefer)
|
||||
hm.handler(ctx, query)
|
||||
_, err = interceptQuery(ctx, query, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
|
||||
@@ -3,6 +3,11 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
@@ -24,33 +29,96 @@ const (
|
||||
var invalidTypeError = fmt.Errorf("invalid type")
|
||||
|
||||
type Interceptor struct {
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
OnDefer []intercept.Func
|
||||
}
|
||||
|
||||
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
// singletonClickInterceptor uses the onceMap to determine whether the object k1 already interacted
|
||||
// with the user k2. If so, it will return an error.
|
||||
func (bot TipBot) singletonCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Query:
|
||||
user, err := GetUser(&i.(*tb.Query).From, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
m := *c.Message
|
||||
m.Sender = c.Sender
|
||||
user, err := GetUser(i.(*tb.Callback).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Message:
|
||||
user, err := GetUser(i.(*tb.Message).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
// unlockInterceptor invoked as onDefer interceptor
|
||||
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Unlock(strconv.FormatInt(user.ID, 10))
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
|
||||
}
|
||||
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
ctxcr := ctx.Value("callback_response")
|
||||
var res []*tb.CallbackResponse
|
||||
if ctxcr != nil {
|
||||
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
|
||||
}
|
||||
var err error
|
||||
err = bot.Telegram.Respond(c, res...)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
// lockInterceptor invoked as first before interceptor
|
||||
func (bot TipBot) lockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Lock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
// requireUserInterceptor will return an error if user is not found
|
||||
// user is here an lnbits.User
|
||||
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
u := getTelegramUserFromInterface(i)
|
||||
if u != nil {
|
||||
user, err = GetUser(u, bot)
|
||||
if user != nil {
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
}
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx, i)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// getTelegramUserFromInterface returns the tb user based in interface type
|
||||
func getTelegramUserFromInterface(i interface{}) (user *tb.User) {
|
||||
switch i.(type) {
|
||||
case *tb.Query:
|
||||
user = &i.(*tb.Query).From
|
||||
case *tb.Callback:
|
||||
user = i.(*tb.Callback).Sender
|
||||
case *tb.Message:
|
||||
user = i.(*tb.Message).Sender
|
||||
default:
|
||||
log.Tracef("[getTelegramUserFromInterface] invalid type %s", reflect.TypeOf(i).String())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
@@ -108,7 +176,7 @@ func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return nil, fmt.Errorf("no private chat")
|
||||
return nil, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+115
-12
@@ -5,16 +5,60 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type InvoiceEventCallback map[int]func(*InvoiceEvent)
|
||||
|
||||
var InvoiceCallback InvoiceEventCallback
|
||||
|
||||
func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallback = InvoiceEventCallback{
|
||||
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
|
||||
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
|
||||
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
|
||||
}
|
||||
}
|
||||
|
||||
type InvoiceEventKey int
|
||||
|
||||
const (
|
||||
InvoiceCallbackGeneric = iota + 1
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"`
|
||||
}
|
||||
type InvoiceEvent struct {
|
||||
*Invoice
|
||||
User *lnbits.User `json:"user"`
|
||||
Message *tb.Message `json:"message"`
|
||||
InvoiceMessage *tb.Message `json:"invoice_message"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Callback int `json:"func"`
|
||||
CallbackData string `json:"callbackdata"`
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Key() string {
|
||||
return fmt.Sprintf("invoice:%s", invoiceEvent.PaymentHash)
|
||||
}
|
||||
|
||||
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
@@ -23,7 +67,7 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
@@ -58,16 +102,9 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(amount),
|
||||
Memo: memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
@@ -76,15 +113,81 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
bot.tryDeleteMessage(creatingMsg)
|
||||
// deleting messages will delete the main menu.
|
||||
//bot.tryDeleteMessage(creatingMsg)
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(amount),
|
||||
Memo: memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return InvoiceEvent{}, err
|
||||
}
|
||||
invoiceEvent := InvoiceEvent{
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: amount,
|
||||
Memo: memo},
|
||||
User: user,
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
type LNURLInvoice struct {
|
||||
*Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
}
|
||||
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *InvoiceEvent) {
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
|
||||
err := bot.Bunt.Get(tx)
|
||||
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
if err == nil {
|
||||
if len(tx.Comment) > 0 {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,15 +40,18 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the link to the user
|
||||
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
}()
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
|
||||
@@ -9,9 +9,12 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
@@ -19,11 +22,11 @@ import (
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int `json:"amount"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
@@ -37,8 +40,8 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
lnurlPayState := LnurlPayState{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
lnurlPayState := &LnurlPayState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLPayParams: payParams.LNURLPayParams,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
@@ -126,7 +129,9 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
@@ -151,7 +156,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("amount", strconv.Itoa(lnurlPayState.Amount)) // msat
|
||||
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
|
||||
// add comment to query string
|
||||
if len(lnurlPayState.Comment) > 0 {
|
||||
qs.Set("comment", lnurlPayState.Comment)
|
||||
@@ -192,7 +197,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
bot.payHandler(ctx, m)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) error {
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) error {
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return fmt.Errorf("lightning address format wrong")
|
||||
|
||||
@@ -7,11 +7,14 @@ import (
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -26,11 +29,11 @@ var (
|
||||
|
||||
// LnurlWithdrawState saves the state of the user for an LNURL payment
|
||||
type LnurlWithdrawState struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
|
||||
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
|
||||
Amount int `json:"amount"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
@@ -60,7 +63,7 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
LnurlWithdrawState := LnurlWithdrawState{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
@@ -83,7 +86,7 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
|
||||
|
||||
// if no amount is entered, and if only one amount is possible, we use it
|
||||
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
|
||||
amount = int(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
amount_err = nil
|
||||
}
|
||||
|
||||
@@ -138,7 +141,9 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
@@ -182,12 +187,15 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[confirmWithdrawHandler] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
@@ -200,21 +208,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = lnurlWithdrawState.Lock(lnurlWithdrawState, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[confirmWithdrawHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
if !lnurlWithdrawState.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
defer lnurlWithdrawState.Release(lnurlWithdrawState, bot.Bunt)
|
||||
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
@@ -246,7 +246,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
@@ -307,7 +307,9 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
|
||||
@@ -325,6 +327,5 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
lnurlWithdrawState.InTransaction = false
|
||||
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,8 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
// assume payment
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
@@ -82,10 +83,10 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLPayParams:
|
||||
payParams := LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlPayHandler(ctx, m, payParams)
|
||||
bot.lnurlPayHandler(ctx, m, *payParams)
|
||||
return
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
@@ -140,14 +141,14 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err)
|
||||
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)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err)
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
+34
-25
@@ -5,10 +5,13 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -30,7 +33,7 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
|
||||
type PayData struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
@@ -60,7 +63,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
@@ -72,11 +75,11 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
amount := int(bolt11.MSatoshi / 1000)
|
||||
amount := int64(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
|
||||
@@ -89,7 +92,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
@@ -127,8 +130,8 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := PayData{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
Invoice: paymentRequest,
|
||||
Amount: int64(amount),
|
||||
@@ -145,11 +148,13 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[confirmPayHandler] %s", err)
|
||||
log.Errorf("[confirmPayHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
@@ -158,21 +163,13 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = payData.Lock(payData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
defer payData.Release(payData, bot.Bunt)
|
||||
defer payData.Set(payData, bot.Bunt)
|
||||
|
||||
// remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
@@ -200,6 +197,8 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
|
||||
if err != nil {
|
||||
@@ -215,17 +214,26 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
return
|
||||
}
|
||||
payData.Hash = invoice.PaymentHash
|
||||
payData.InTransaction = false
|
||||
|
||||
// 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"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
log.Printf("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -234,9 +242,11 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelPaymentHandler] %s", err.Error())
|
||||
return
|
||||
@@ -247,6 +257,5 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
payData.InTransaction = false
|
||||
payData.Inactivate(payData, bot.Bunt)
|
||||
}
|
||||
|
||||
@@ -34,29 +34,35 @@ func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
}
|
||||
|
||||
// photoHandler is the handler function for every photo from a private chat that the bot receives
|
||||
func (bot TipBot) photoHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
c(ctx, m)
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
// get file reader closer from Telegram api
|
||||
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err)
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err)
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err)
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
+29
-21
@@ -6,10 +6,13 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -39,7 +42,7 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
|
||||
}
|
||||
|
||||
type SendData struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
ToTelegramId int64 `json:"to_telegram_id"`
|
||||
ToTelegramUser string `json:"to_telegram_user"`
|
||||
@@ -159,6 +162,11 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
if user.ID == toUserDb.ID {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// entire text of the inline object
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmSendMessage"), str.MarkdownEscape(toUserStrMention), amount)
|
||||
if len(sendMemo) > 0 {
|
||||
@@ -166,9 +174,9 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := SendData{
|
||||
sendData := &SendData{
|
||||
From: user,
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Amount: int64(amount),
|
||||
ToTelegramId: toUserDb.Telegram.ID,
|
||||
ToTelegramUser: toUserStrWithoutAt,
|
||||
@@ -208,10 +216,12 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
// sendHandler invoked when user clicked send on payment confirmation
|
||||
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
@@ -219,19 +229,12 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = sendData.Lock(sendData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
defer sendData.Release(sendData, bot.Bunt)
|
||||
defer sendData.Set(sendData, bot.Bunt)
|
||||
|
||||
// // remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(sendData.Message), &tb.ReplyMarkup{})
|
||||
@@ -260,15 +263,15 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, int(amount), TransactionType("send"))
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success || err != nil {
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf("%s %s", i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), err), &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
@@ -280,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))
|
||||
@@ -299,12 +305,15 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
@@ -312,6 +321,5 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
}
|
||||
// remove buttons from confirmation message
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
sendData.InTransaction = false
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,291 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
|
||||
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
|
||||
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
|
||||
user := LoadUser(ctx)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if len(shops.Shops) > 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
|
||||
}
|
||||
if user.Telegram.ID == shops.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
|
||||
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
|
||||
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
|
||||
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
|
||||
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
|
||||
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
|
||||
// buttons := []tb.Row{
|
||||
// shopKeyboard.Row(shopLinkShopButton),
|
||||
// shopKeyboard.Row(shopDescriptionShopButton),
|
||||
// shopKeyboard.Row(shopRenameShopButton),
|
||||
// shopKeyboard.Row(shopDeleteShopButton),
|
||||
// // shopKeyboard.Row(shopResetShopButton),
|
||||
// shopKeyboard.Row(shopShopsButton),
|
||||
// }
|
||||
// shopKeyboard.Inline(
|
||||
// buttons...,
|
||||
// )
|
||||
|
||||
button := []tb.Btn{
|
||||
shopLinkShopButton,
|
||||
shopDescriptionShopButton,
|
||||
shopRenameShopButton,
|
||||
shopDeleteShopButton,
|
||||
shopShopsButton,
|
||||
}
|
||||
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemSettingsMenu builds the buttons of the item settings
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
|
||||
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
|
||||
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
|
||||
shopItemAddFileButton = shopKeyboard.Data("💾 Add file", "shop_itemaddfile", item.ID)
|
||||
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
|
||||
user := LoadUser(ctx)
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemDeleteButton, shopItemSettingsBackButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemTitleButton, shopItemPriceButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemAddFileButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
|
||||
func (bot TipBot) shopItemConfirmBuyMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemBuyButton = shopKeyboard.Data(fmt.Sprintf("💸 Pay %d sat", item.Price), "shop_itembuy", item.ID)
|
||||
shopItemCancelBuyButton = shopKeyboard.Data("⬅️ Back", "shop_itemcancelbuy", item.ID)
|
||||
buttons := []tb.Row{}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemBuyButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemCancelBuyButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopMenu builds the buttons in the item browser
|
||||
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
user := LoadUser(ctx)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shop.ShopsID)
|
||||
shopAddItemButton = shopKeyboard.Data("✅ New item", "shop_additem", shop.ID)
|
||||
shopItemSettingsButton = shopKeyboard.Data("⚙️ Settings", "shop_itemsettings", item.ID)
|
||||
shopNextitemButton = shopKeyboard.Data(">", "shop_nextitem", shop.ID)
|
||||
shopPrevitemButton = shopKeyboard.Data("<", "shop_previtem", shop.ID)
|
||||
buyButtonText := "📩 Get"
|
||||
if item.Price > 0 {
|
||||
buyButtonText = fmt.Sprintf("Buy (%d sat)", item.Price)
|
||||
}
|
||||
shopBuyitemButton = shopKeyboard.Data(buyButtonText, "shop_buyitem", item.ID)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
if len(shop.Items) == 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton))
|
||||
} else {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton, shopItemSettingsButton))
|
||||
}
|
||||
}
|
||||
// publicButtons := []tb.Row{}
|
||||
if len(shop.Items) > 0 {
|
||||
if shopView.Page == len(shop.Items)-1 {
|
||||
// last page
|
||||
shopNextitemButton = shopKeyboard.Data("x", "shop_nextitem", shop.ID)
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopPrevitemButton, shopBuyitemButton, shopNextitemButton))
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopShopsButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// makseShopSelectionButtons produces a list of all buttons with a uniqueString ID
|
||||
func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string) []tb.Btn {
|
||||
var buttons []tb.Btn
|
||||
for _, shop := range shops {
|
||||
buttons = append(buttons, shopKeyboard.Data(shop.Title, uniqueString, shop.ID))
|
||||
}
|
||||
return buttons
|
||||
}
|
||||
|
||||
// -------------- ShopView --------------
|
||||
|
||||
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
|
||||
func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
shopView = sv.(ShopView)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
deleteStatusMessages(shopView.StatusMessages, bot)
|
||||
shopView.StatusMessages = make([]*tb.Message, 0)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
return
|
||||
}
|
||||
|
||||
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
|
||||
// delete all status messages from telegram
|
||||
for _, msg := range messages {
|
||||
bot.tryDeleteMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// sendStatusMessage adds a status message to the shopVoew.statusMessages
|
||||
// slide and sends a status message to the user.
|
||||
func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
|
||||
// write into cache
|
||||
mutex.Lock(id)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
statusMsg := bot.trySendMessage(to, what, options...)
|
||||
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
mutex.Unlock(id)
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// sendStatusMessageAndDelete invokes sendStatusMessage and creates
|
||||
// a ticker to delete all status messages after 5 seconds.
|
||||
func (bot *TipBot) sendStatusMessageAndDelete(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
|
||||
// kick off ticker to remove all messages
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
// removing ticker asap done
|
||||
runtime.RemoveTicker(id)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// --------------- Shop ---------------
|
||||
|
||||
// initUserShops is a helper function for creating a Shops for the user in the database
|
||||
func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
|
||||
shops := &Shops{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Owner: user,
|
||||
Shops: []string{},
|
||||
MaxShops: MAX_SHOPS,
|
||||
}
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// getUserShops returns the Shops for the user
|
||||
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
|
||||
return &Shops{}, err
|
||||
}
|
||||
shops := sn.(*Shops)
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// addUserShop adds a new Shop to the Shops of a user
|
||||
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return &Shop{}, err
|
||||
}
|
||||
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
|
||||
shop := &Shop{
|
||||
Base: storage.New(storage.ID(shopId)),
|
||||
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
|
||||
Owner: user,
|
||||
Type: "photo",
|
||||
Items: make(map[string]ShopItem),
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
ShopsID: shops.ID,
|
||||
MaxItems: MAX_ITEMS_PER_SHOP,
|
||||
}
|
||||
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
|
||||
shops.Shops = append(shops.Shops, shopId)
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shop, nil
|
||||
}
|
||||
|
||||
// getShop returns the Shop for the given ID
|
||||
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
|
||||
tx := &Shop{Base: storage.New(storage.ID(shopId))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getShop] %s", err.Error())
|
||||
return &Shop{}, err
|
||||
}
|
||||
shop := sn.(*Shop)
|
||||
if shop.Owner == nil {
|
||||
return &Shop{}, fmt.Errorf("shop has no owner")
|
||||
}
|
||||
return shop, nil
|
||||
}
|
||||
@@ -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()))
|
||||
@@ -85,7 +85,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
@@ -94,7 +94,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message)
|
||||
|
||||
var stateCallbackMessage StateCallbackMessage
|
||||
|
||||
func initializeStateCallbackMessage(bot *TipBot) {
|
||||
stateCallbackMessage = StateCallbackMessage{
|
||||
lnbits.UserStateLNURLEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterUser: bot.enterUserHandler,
|
||||
lnbits.UserEnterShopTitle: bot.enterShopTitleHandler,
|
||||
lnbits.UserStateShopItemSendPhoto: bot.addShopItemPhoto,
|
||||
lnbits.UserStateShopItemSendPrice: bot.enterShopItemPriceHandler,
|
||||
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
|
||||
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
|
||||
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,33 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"time"
|
||||
)
|
||||
|
||||
// getChatIdFromRecipient will parse the recipient to int64
|
||||
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return chatId, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Forward(to, what, options...)
|
||||
// ChatId is used for the keyboard
|
||||
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, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -19,7 +36,13 @@ 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)
|
||||
msg, err := bot.Telegram.Send(to, what, options...)
|
||||
// ChatId is used for the keyboard
|
||||
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, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -28,25 +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, 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) {
|
||||
if !allowedToPerformAction(bot, to, isAdminAndCanEdit) {
|
||||
return
|
||||
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(to)
|
||||
var err error
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
rate.CheckLimit(sig)
|
||||
_, chatId := to.MessageSig()
|
||||
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) {
|
||||
@@ -101,13 +126,3 @@ func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAdminAndCanEdit will check if me is in members list and allowed to edit messages
|
||||
func isAdminAndCanEdit(members []tb.ChatMember, me *tb.User) bool {
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return admin.CanEditMessages
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
+14
-13
@@ -12,7 +12,7 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
@@ -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) {
|
||||
@@ -36,18 +46,10 @@ func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be a LNURL
|
||||
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
|
||||
|
||||
// inputs asked for
|
||||
if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
bot.enterAmountHandler(ctx, m)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
c(ctx, m)
|
||||
//ResetUserState(user, bot)
|
||||
}
|
||||
if user.StateKey == lnbits.UserEnterUser {
|
||||
bot.enterUserHandler(ctx, m)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type EnterUserStateData struct {
|
||||
@@ -114,7 +116,6 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
|
||||
switch EnterUserStateData.Type {
|
||||
case "CreateSendState":
|
||||
m.Text = fmt.Sprintf("/send %s", userstr)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
default:
|
||||
|
||||
@@ -69,7 +69,6 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
|
||||
to := LoadReplyToUser(ctx)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
@@ -110,8 +109,8 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return
|
||||
}
|
||||
@@ -122,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 {
|
||||
|
||||
@@ -26,17 +26,22 @@ const (
|
||||
|
||||
type TipTooltip struct {
|
||||
Message
|
||||
TipAmount int `json:"tip_amount"`
|
||||
ID string `json:"id"`
|
||||
TipAmount int64 `json:"tip_amount"`
|
||||
Ntips int `json:"ntips"`
|
||||
LastTip time.Time `json:"last_tip"`
|
||||
Tippers []*tb.User `json:"tippers"`
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
|
||||
}
|
||||
|
||||
const maxNamesInTipperMessage = 5
|
||||
|
||||
type TipTooltipOption func(m *TipTooltip)
|
||||
|
||||
func TipAmount(amount int) TipTooltipOption {
|
||||
func TipAmount(amount int64) TipTooltipOption {
|
||||
return func(m *TipTooltip) {
|
||||
m.TipAmount = amount
|
||||
}
|
||||
@@ -50,6 +55,7 @@ func Tips(nTips int) TipTooltipOption {
|
||||
|
||||
func NewTipTooltip(m *tb.Message, opts ...TipTooltipOption) *TipTooltip {
|
||||
tipTooltip := &TipTooltip{
|
||||
ID: fmt.Sprintf("%d-%d", m.Chat.ID, m.ReplyTo.ID),
|
||||
Message: Message{
|
||||
Message: m,
|
||||
},
|
||||
@@ -99,8 +105,8 @@ func getTippersString(tippers []*tb.User) string {
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{Chat: &tb.Chat{ID: m.Chat.ID}, ReplyTo: &tb.Message{ID: m.ReplyTo.ID}})
|
||||
err := bot.Bunt.Get(message)
|
||||
if err != nil {
|
||||
return false, message
|
||||
@@ -110,49 +116,48 @@ func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int, initializedWallet bool) (hasTip bool) {
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) (hasTip bool) {
|
||||
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
|
||||
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
|
||||
hasTip, ttt := tipTooltipExists(m, bot)
|
||||
log.Debugf("[tip] %s has tip: %t", ttt.ID, hasTip)
|
||||
if hasTip {
|
||||
// update the tooltip with new tippers
|
||||
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Errorln(err)
|
||||
// could not update the message (return false to )
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
|
||||
// todo: in case of error we should do something better than just return 0
|
||||
return false
|
||||
}
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
newToolTip(m, bot, amount, initializedWallet)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return hasTip
|
||||
}
|
||||
|
||||
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in Telegram
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, notInitializedWallet bool) error {
|
||||
ttt.TipAmount += amount
|
||||
ttt.Ntips += 1
|
||||
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
|
||||
ttt.LastTip = time.Now()
|
||||
err := ttt.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ttt.editTooltip(bot, notInitializedWallet)
|
||||
log.Debugf("[updateTooltip]: Update tip tooltip (Bunt: %s)", ttt.Key())
|
||||
return bot.Bunt.Set(ttt)
|
||||
}
|
||||
|
||||
@@ -162,16 +167,14 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
|
||||
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
|
||||
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
|
||||
log.Debugln("loading persistent tip tool tip messages")
|
||||
log.Debugln("[tipTooltipInitializedHandler] loading persistent tip tool tip messages")
|
||||
ttt := &TipTooltip{}
|
||||
err := json.Unmarshal([]byte(value), ttt)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = ttt.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
}
|
||||
// edit to remove the "chat with bot" message
|
||||
ttt.editTooltip(&bot, false)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -180,17 +183,9 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
}))
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
|
||||
}
|
||||
|
||||
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
|
||||
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
|
||||
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ttt.Message.Message.Text = m.Text
|
||||
return nil
|
||||
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
|
||||
// ttt.Message.Message.Text = m.Text
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ func Test_getTippersString(t *testing.T) {
|
||||
func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
type fields struct {
|
||||
Message Message
|
||||
TipAmount int
|
||||
TipAmount int64
|
||||
Ntips int
|
||||
LastTip time.Time
|
||||
Tippers []*tb.User
|
||||
|
||||
@@ -21,7 +21,7 @@ type Transaction struct {
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
@@ -48,7 +48,7 @@ func TransactionType(transactionType string) TransactionOption {
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, opts ...TransactionOption) *Transaction {
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
|
||||
t := &Transaction{
|
||||
Bot: bot,
|
||||
From: from,
|
||||
@@ -70,18 +70,9 @@ func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int,
|
||||
}
|
||||
|
||||
func (t *Transaction) Send() (success bool, err error) {
|
||||
// maybe remove comments, GTP-3 dreamed this up but it's nice:
|
||||
// if t.From.ID == t.To.ID {
|
||||
// err = fmt.Errorf("Can not send transaction to yourself.")
|
||||
// return false, err
|
||||
// }
|
||||
|
||||
// todo: remove this commend if the backend is back up
|
||||
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
|
||||
// success = true
|
||||
if success {
|
||||
t.Success = success
|
||||
// TODO: call post-send methods
|
||||
}
|
||||
|
||||
// save transaction to db
|
||||
@@ -90,16 +81,16 @@ func (t *Transaction) Send() (success bool, err error) {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
|
||||
return success, err
|
||||
}
|
||||
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
|
||||
t.FromWallet = from.Wallet.ID
|
||||
t.FromLNbitsID = from.ID
|
||||
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
@@ -125,7 +116,7 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
Memo: memo},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
|
||||
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
@@ -133,9 +124,24 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
|
||||
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
|
||||
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
|
||||
}
|
||||
|
||||
@@ -60,16 +60,16 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
return append(slice, i)
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int, err error) {
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
|
||||
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
|
||||
if err != nil {
|
||||
return bot.GetUserBalance(user)
|
||||
}
|
||||
cachedBalance := u.(int)
|
||||
cachedBalance := u.(int64)
|
||||
return cachedBalance, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
@@ -82,14 +82,14 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
|
||||
return
|
||||
}
|
||||
// msat to sat
|
||||
amount = int(wallet.Balance) / 1000
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
|
||||
// update user balance in cache
|
||||
bot.Cache.Set(
|
||||
fmt.Sprintf("%s_balance", user.Name),
|
||||
amount,
|
||||
&store.Options{Expiration: 30 * time.Second},
|
||||
&store.Options{Expiration: 1 * time.Hour},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
package main
|
||||
|
||||
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"
|
||||
@@ -12,7 +18,7 @@ import (
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
log.SetLevel(log.TraceLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -22,6 +28,11 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
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)
|
||||
|
||||
@@ -21,7 +21,7 @@ func IsInvoice(message string) bool {
|
||||
|
||||
func IsLnurl(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
if strings.HasPrefix(message, "lnurl") {
|
||||
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
|
||||
// string must be a single word
|
||||
if !strings.Contains(message, " ") {
|
||||
return true
|
||||
|
||||
Reference in New Issue
Block a user