Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc650ac23d | ||
|
|
e82b933f31 | ||
|
|
0509d107d7 | ||
|
|
ca5dc07d4e | ||
|
|
cc034d5fcf |
@@ -5,7 +5,7 @@ go 1.15
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/go-lnurl v1.4.0
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
@@ -13,16 +13,12 @@ require (
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/sethvargo/go-limiter v0.7.2
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
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/tucnak/telebot.v2 v2.3.5
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -137,10 +137,6 @@ github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3 h1:ONQUQsXIZKkzrzax2SMUr5W0PreluhO4tct1JM0V/MA=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4 h1:uVH8833lVgvNqW3S0qr0I8VsIId5mVw0lE0KnEjgh/o=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
|
||||
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
|
||||
@@ -453,8 +449,6 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/sethvargo/go-limiter v0.7.2 h1:FgC4N7RMpV5gMrUdda15FaFTkQ/L4fEqM7seXMs4oO8=
|
||||
github.com/sethvargo/go-limiter v0.7.2/go.mod h1:C0kbSFbiriE5k2FFOe18M1YZbAR2Fiwf72uGu0CXCcU=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
@@ -651,9 +645,7 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 h1:+DCIGbF/swA92ohVg0//6X2IVY3KZs6p9mix0ziNYJM=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@@ -720,14 +712,6 @@ gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYlAEmRJi8YEcSbXO6PlAVwl7WpKJvMqkijHZmO8Gw=
|
||||
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/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 +722,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.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5/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=
|
||||
|
||||
@@ -25,7 +25,6 @@ func RegisterLanguages() *i18n.Bundle {
|
||||
bundle.LoadMessageFile("translations/pt-br.toml")
|
||||
bundle.LoadMessageFile("translations/tr.toml")
|
||||
bundle.LoadMessageFile("translations/id.toml")
|
||||
bundle.LoadMessageFile("translations/ru.toml")
|
||||
return bundle
|
||||
}
|
||||
func Translate(languageCode string, MessgeID string) string {
|
||||
|
||||
@@ -2,7 +2,6 @@ package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
@@ -106,6 +105,30 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err e
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/payments", invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
// custom header with invoice key
|
||||
@@ -156,9 +179,7 @@ func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error)
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Adminkey,
|
||||
}
|
||||
r := req.New()
|
||||
r.SetTimeout(time.Hour * 24)
|
||||
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -34,8 +34,6 @@ const (
|
||||
UserStateConfirmLNURLPay
|
||||
UserEnterAmount
|
||||
UserHasEnteredAmount
|
||||
UserEnterUser
|
||||
UserHasEnteredUser
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
@@ -94,3 +92,20 @@ type BitInvoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
|
||||
type Payments []struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `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"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook interface{} `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
@@ -3,23 +3,21 @@ package webhook
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
@@ -102,7 +100,7 @@ func (w Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
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))
|
||||
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, 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)
|
||||
|
||||
+28
-19
@@ -3,6 +3,7 @@ package lnurl
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -40,17 +41,17 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
} else {
|
||||
stringAmount := request.FormValue("amount")
|
||||
if stringAmount == "" {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
}
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Comment is too long"))
|
||||
return
|
||||
}
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
|
||||
@@ -77,32 +78,37 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
|
||||
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
|
||||
// to call and the metadata that matches the description hash of the second response
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayResponse1, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata := w.metaData(username)
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &lnurl.LNURLPayParams{
|
||||
return &lnurl.LNURLPayResponse1{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
Tag: payRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
CallbackURL: callbackURL, // probably no need to set this here
|
||||
MinSendable: minSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: metadata.Encode(),
|
||||
EncodedMetadata: string(jsonMeta),
|
||||
CommentAllowed: CommentAllowed,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// 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 int64, comment string) (*lnurl.LNURLPayResponse2, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount < minSendable || amount > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
@@ -110,7 +116,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
@@ -130,14 +136,14 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
@@ -146,7 +152,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
// user is ok now create invoice
|
||||
// set wallet lnbits client
|
||||
|
||||
var resp *lnurl.LNURLPayValues
|
||||
var resp *lnurl.LNURLPayResponse2
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.metaData(username)
|
||||
@@ -163,7 +169,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
w.c)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
resp = &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: "Couldn't create invoice."},
|
||||
@@ -181,10 +187,10 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
CreatedAt: time.Now(),
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([]struct{}, 0),
|
||||
Routes: make([][]lnurl.RouteInfo, 0),
|
||||
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
|
||||
}, nil
|
||||
|
||||
@@ -192,7 +198,11 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
hash := sha256.Sum256([]byte(metadata.Encode()))
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := sha256.Sum256([]byte(string(jsonMeta)))
|
||||
hashString := hex.EncodeToString(hash[:])
|
||||
return hashString, nil
|
||||
}
|
||||
@@ -201,7 +211,6 @@ func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
// and is used again in the second response to verify the description hash
|
||||
func (w Server) metaData(username string) lnurl.Metadata {
|
||||
return lnurl.Metadata{
|
||||
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
|
||||
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
|
||||
}
|
||||
{"text/identifier", fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname())},
|
||||
{"text/plain", fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname())}}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package price
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -84,7 +85,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
|
||||
coinbaseEndpoint, err := url.Parse(fmt.Sprintf("https://api.coinbase.com/v2/prices/spot?currency=%s", currency))
|
||||
response, err := p.client.Get(coinbaseEndpoint.String())
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
@@ -110,7 +111,7 @@ func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
|
||||
pair := bitfinexCurrencyToPair[currency]
|
||||
bitfinexEndpoint, err := url.Parse(fmt.Sprintf("https://api.bitfinex.com/v1/pubticker/%s", pair))
|
||||
response, err := p.client.Get(bitfinexEndpoint.String())
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Limiter
|
||||
type Limiter struct {
|
||||
keys map[string]*rate.Limiter
|
||||
mu *sync.RWMutex
|
||||
r rate.Limit
|
||||
b int
|
||||
}
|
||||
|
||||
var idLimiter *Limiter
|
||||
var globalLimiter *rate.Limiter
|
||||
|
||||
// NewLimiter creates both chat and global rate limiters.
|
||||
func Start() {
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.3), 20)
|
||||
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
|
||||
}
|
||||
|
||||
// NewRateLimiter .
|
||||
func newIdRateLimiter(r rate.Limit, b int) *Limiter {
|
||||
i := &Limiter{
|
||||
keys: make(map[string]*rate.Limiter),
|
||||
mu: &sync.RWMutex{},
|
||||
r: r,
|
||||
b: b,
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func CheckLimit(to interface{}) {
|
||||
globalLimiter.Wait(context.Background())
|
||||
var id string
|
||||
switch to.(type) {
|
||||
case *tb.Chat:
|
||||
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
|
||||
case *tb.User:
|
||||
id = strconv.FormatInt(to.(*tb.User).ID, 10)
|
||||
case tb.Recipient:
|
||||
id = to.(tb.Recipient).Recipient()
|
||||
case *tb.Message:
|
||||
if to.(*tb.Message).Chat != nil {
|
||||
id = strconv.FormatInt(to.(*tb.Message).Chat.ID, 10)
|
||||
}
|
||||
}
|
||||
if len(id) > 0 {
|
||||
idLimiter.GetLimiter(id).Wait(context.Background())
|
||||
}
|
||||
}
|
||||
|
||||
// Add creates a new rate limiter and adds it to the keys map,
|
||||
// using the key
|
||||
func (i *Limiter) Add(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
|
||||
limiter := rate.NewLimiter(i.r, i.b)
|
||||
|
||||
i.keys[key] = limiter
|
||||
|
||||
return limiter
|
||||
}
|
||||
|
||||
// GetLimiter returns the rate limiter for the provided key if it exists.
|
||||
// Otherwise, calls Add to add key address to the map
|
||||
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
limiter, exists := i.keys[key]
|
||||
|
||||
if !exists {
|
||||
i.mu.Unlock()
|
||||
return i.Add(key)
|
||||
}
|
||||
|
||||
i.mu.Unlock()
|
||||
|
||||
return limiter
|
||||
}
|
||||
@@ -13,6 +13,9 @@ type Base struct {
|
||||
InTransaction bool `json:"intransaction"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
MessageID string `json:"messageid"`
|
||||
ChatID string `json:"chatid"`
|
||||
MessageURL string `json:"messageurl"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
@@ -75,13 +78,13 @@ func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error
|
||||
}
|
||||
// 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)
|
||||
ticker := time.NewTicker(time.Second * 10)
|
||||
for tx.InTransaction {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
return nil, fmt.Errorf("transaction timeout")
|
||||
default:
|
||||
time.Sleep(time.Duration(200) * time.Millisecond)
|
||||
time.Sleep(time.Duration(500) * time.Millisecond)
|
||||
err = db.Get(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
@@ -98,16 +98,16 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
|
||||
AmountMax: amountMax,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
// set LNURLPayResponse1 in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
|
||||
askAmountText := Translate(ctx, "enterAmountMessage")
|
||||
askAmountText := Translate(ctx, "lnurlEnterAmountMessage")
|
||||
if amountMin > 0 && amountMax >= amountMin {
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "lnurlEnterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
}
|
||||
// Let the user enter an amount and return
|
||||
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
|
||||
@@ -176,26 +176,6 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
case "LnurlWithdrawState":
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
LnurlWithdrawState := sn.(*LnurlWithdrawState)
|
||||
LnurlWithdrawState.Amount = amount * 1000 // mSat
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
case "CreateInvoiceState":
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
@@ -2,20 +2,17 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/eko/gocache/store"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -25,7 +22,6 @@ type TipBot struct {
|
||||
logger *gorm.DB
|
||||
Telegram *telebot.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
}
|
||||
type Cache struct {
|
||||
@@ -43,7 +39,6 @@ func NewBot() TipBot {
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
Database: db,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
|
||||
@@ -2,12 +2,11 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/eko/gocache/store"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
@@ -16,7 +15,7 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -80,10 +79,6 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
toUserDb := &lnbits.User{}
|
||||
// return error if username is too long
|
||||
if len(toUserStrWithoutAt) > 100 {
|
||||
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
|
||||
}
|
||||
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil {
|
||||
err := tx.Error
|
||||
@@ -95,7 +90,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
|
||||
return toUserDb, nil
|
||||
}
|
||||
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
if us, err := bot.Cache.Get(user.Name); err == nil {
|
||||
return us.(*lnbits.User), nil
|
||||
}
|
||||
@@ -110,7 +105,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
// &tb.User{ID: toId, Username: username}
|
||||
// without updating the user in storage.
|
||||
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
tx := bot.Database.First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
@@ -48,7 +48,7 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessage(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
msg := bot.trySendMessage(user.Telegram, Translate(ctx, "donationProgressMessage"))
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
|
||||
if err != nil {
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
@@ -135,6 +135,16 @@ func (bot TipBot) getHandler() []Handler {
|
||||
bot.loadUserInterceptor,
|
||||
}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/transactions"},
|
||||
Handler: bot.transactionsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.logMessageInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/send"},
|
||||
Handler: bot.sendHandler,
|
||||
@@ -338,15 +348,15 @@ func (bot TipBot) getHandler() []Handler {
|
||||
Before: []intercept.Func{bot.loadUserInterceptor}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnWithdraw},
|
||||
Handler: bot.confirmWithdrawHandler,
|
||||
Endpoints: []interface{}{&btnLeftTransactionsButton},
|
||||
Handler: bot.transactionsScrollLeftHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{bot.loadUserInterceptor}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnCancelWithdraw},
|
||||
Handler: bot.cancelWithdrawHandler,
|
||||
Endpoints: []interface{}{&btnRightTransactionsButton},
|
||||
Handler: bot.transactionsScrollRightHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{bot.loadUserInterceptor}},
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
|
||||
@@ -4,9 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
@@ -16,7 +13,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -188,7 +185,13 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
|
||||
return
|
||||
}
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
faucetMsg := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
|
||||
inlineFaucet.Base.MessageID = fmt.Sprint(faucetMsg.ID)
|
||||
inlineFaucet.Base.ChatID = fmt.Sprint(-faucetMsg.Chat.ID)
|
||||
inlineFaucet.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineFaucet.ChatID[3:], inlineFaucet.Base.MessageID)
|
||||
|
||||
bot.trySendMessage(m.Chat, inlineFaucet.Base.MessageURL)
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
@@ -217,7 +220,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
@@ -299,7 +302,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
|
||||
log.Infof("[faucet] faucet %s: %d sat from %s to %s ", inlineFaucet.ID, inlineFaucet.PerUserAmount, fromUserStr, toUserStr)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
|
||||
@@ -308,7 +311,8 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
_, 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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// build faucet message
|
||||
|
||||
@@ -3,17 +3,13 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
@@ -96,20 +92,7 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
|
||||
}
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
switch inlineObject.(type) {
|
||||
case storage.Storable:
|
||||
// persist inline object in bunt
|
||||
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
|
||||
default:
|
||||
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), q.Query)
|
||||
}
|
||||
fmt.Printf(q.Query)
|
||||
}
|
||||
|
||||
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
|
||||
|
||||
@@ -4,9 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
@@ -14,7 +11,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -124,7 +121,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
From_SpecificUser: from_SpecificUser,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
bot.Cache.Set(inlineReceive.ID, inlineReceive, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -215,7 +212,7 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
log.Infof("[acceptInlineReceiveHandler] %d sat from %s to %s", inlineReceive.Amount, fromUserStr, toUserStr)
|
||||
|
||||
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineReceive.Memo
|
||||
@@ -233,7 +230,8 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
_, err = bot.Telegram.Send(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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
@@ -15,7 +12,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -143,7 +140,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
}
|
||||
|
||||
// add result to persistent struct
|
||||
bot.Cache.Set(inlineSend.ID, inlineSend, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -230,7 +227,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[sendInline] %d sat from %s to %s", amount, fromUserStr, toUserStr)
|
||||
|
||||
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineSend.Memo
|
||||
@@ -246,7 +243,8 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
_, err = bot.Telegram.Send(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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
@@ -15,7 +12,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -71,7 +68,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
inlineMessage := fmt.Sprintf(
|
||||
Translate(ctx, "inlineTipjarMessage"),
|
||||
perUserAmount,
|
||||
GetUserStrMd(toUser.Telegram),
|
||||
GetUserStr(toUser.Telegram),
|
||||
0,
|
||||
amount,
|
||||
0,
|
||||
@@ -181,11 +178,17 @@ 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)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
tipjarMsg := bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
|
||||
inlineTipjar.Base.MessageID = fmt.Sprint(tipjarMsg.ID)
|
||||
inlineTipjar.Base.ChatID = fmt.Sprint(-tipjarMsg.Chat.ID)
|
||||
inlineTipjar.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineTipjar.ChatID[3:], inlineTipjar.Base.MessageID)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Base.MessageURL)
|
||||
|
||||
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
@@ -214,7 +217,7 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
|
||||
bot.Cache.Set(inlineTipjar.ID, inlineTipjar, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
log.Infof("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
}
|
||||
|
||||
@@ -284,7 +287,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
log.Infof("[tipjar] tipjar %s: %d sat from %s to %s ", inlineTipjar.ID, inlineTipjar.PerUserAmount, fromUserStr, toUserStr)
|
||||
inlineTipjar.NGiven += 1
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
@@ -293,14 +296,15 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
_, err = bot.Telegram.Send(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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// build tipjar message
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
|
||||
inlineTipjar.PerUserAmount,
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.GivenAmount,
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
@@ -321,7 +325,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
// tipjar is full
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ package intercept
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
|
||||
|
||||
@@ -2,9 +2,8 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type MessageInterface interface {
|
||||
|
||||
@@ -2,9 +2,8 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type InterceptorType int
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
|
||||
@@ -4,17 +4,15 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return
|
||||
@@ -30,11 +28,6 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
fromUser := LoadUser(ctx)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
// do not respond to banned users
|
||||
if strings.HasPrefix(fromUser.Wallet.Adminkey, "banned") || strings.HasPrefix(fromUser.Wallet.Adminkey, "_") {
|
||||
return
|
||||
}
|
||||
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
|
||||
|
||||
// create qr code
|
||||
@@ -45,12 +38,6 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
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)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
}
|
||||
|
||||
@@ -14,18 +14,18 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayResponse1 lnurl.LNURLPayResponse1 `json:"LNURLPayResponse1"`
|
||||
LNURLPayResponse2 lnurl.LNURLPayResponse2 `json:"LNURLPayResponse2"`
|
||||
Amount int `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
@@ -38,57 +38,47 @@ 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)),
|
||||
From: user,
|
||||
LNURLPayParams: payParams.LNURLPayParams,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
LNURLPayResponse1: payParams.LNURLPayResponse1,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// we need to figure out whether the memo starts at position 2 or 3
|
||||
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
|
||||
memoStartsAt := 2
|
||||
if amount_err == nil {
|
||||
// amount was present
|
||||
memoStartsAt = 3
|
||||
}
|
||||
// check if memo is present in command
|
||||
memo := GetMemoFromCommand(m.Text, memoStartsAt)
|
||||
// shorten memo to allowed length
|
||||
if len(memo) > int(lnurlPayState.LNURLPayParams.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayParams.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
lnurlPayState.Comment = memo
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayResponse1.MinSendable, lnurlPayState.LNURLPayResponse1.MaxSendable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
|
||||
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
if int64(amount) > (lnurlPayState.LNURLPayResponse1.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayResponse1.MinSendable/1000) {
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayResponse1.MinSendable/1000, lnurlPayState.LNURLPayResponse1.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
lnurlPayState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// check if comment is presentin lnrul-p
|
||||
memo := GetMemoFromCommand(m.Text, 3)
|
||||
// shorten comment to allowed length
|
||||
if len(memo) > int(lnurlPayState.LNURLPayResponse1.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayResponse1.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
lnurlPayState.Comment = memo
|
||||
}
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
// not necessary to save this in the state data, but till doing it
|
||||
paramsJson, err := json.Marshal(lnurlPayState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
@@ -101,7 +91,7 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
@@ -111,7 +101,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
log.Errorln("[lnurlPayHandler] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
@@ -120,7 +110,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
@@ -129,7 +119,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
@@ -139,13 +129,15 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayResponse1.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
@@ -162,29 +154,31 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
var response2 lnurl.LNURLPayValues
|
||||
var response2 lnurl.LNURLPayResponse2
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "ERROR" || len(response2.PR) < 1 {
|
||||
error_reason := "Could not receive invoice."
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayResponse2: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return
|
||||
}
|
||||
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
lnurlPayState.LNURLPayResponse2 = response2
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
bot.Telegram.Delete(statusMsg)
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"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"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
|
||||
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
|
||||
)
|
||||
|
||||
// LnurlWithdrawState saves the state of the user for an LNURL payment
|
||||
type LnurlWithdrawState struct {
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
|
||||
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
|
||||
Amount int `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
Invoice lnbits.BitInvoice `json:"invoice"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
|
||||
bot.tryEditMessage(
|
||||
m,
|
||||
message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: button}},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// 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)),
|
||||
From: user,
|
||||
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
|
||||
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
// 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_err = nil
|
||||
}
|
||||
|
||||
// set also amount in the state of the user
|
||||
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
paramsJson, err := json.Marshal(LnurlWithdrawState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
|
||||
if len(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription))
|
||||
}
|
||||
lnurlWithdrawState.Message = confirmText
|
||||
|
||||
// create inline buttons
|
||||
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw")
|
||||
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
|
||||
withdrawButton.Data = lnurlWithdrawState.ID
|
||||
btnCancelWithdraw.Data = lnurlWithdrawState.ID
|
||||
|
||||
withdrawConfirmationMenu.Inline(
|
||||
withdrawConfirmationMenu.Row(
|
||||
withdrawButton,
|
||||
btnCancelWithdraw),
|
||||
)
|
||||
|
||||
bot.tryEditMessage(statusMsg, confirmText, withdrawConfirmationMenu)
|
||||
|
||||
// // add response to persistent struct
|
||||
// lnurlWithdrawState.LNURResponse = response2
|
||||
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
|
||||
}
|
||||
|
||||
// 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))}
|
||||
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:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[confirmWithdrawHandler] invalid type")
|
||||
return
|
||||
}
|
||||
// onnly the correct user can press
|
||||
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)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
|
||||
|
||||
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// generate an invoice and add the pr to the request
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(lnurlWithdrawState.Amount) / 1000,
|
||||
Memo: "Withdraw",
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
lnurlWithdrawState.Invoice = invoice
|
||||
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("pr", invoice.PaymentRequest)
|
||||
qs.Set("k1", lnurlWithdrawState.LNURLWithdrawResponse.K1)
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil || res.StatusCode >= 300 {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// parse the response
|
||||
var response2 lnurl.LNURLResponse
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "OK" {
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
|
||||
|
||||
} else {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
|
||||
return
|
||||
}
|
||||
|
||||
// add response to persistent struct
|
||||
lnurlWithdrawState.LNURResponse = response2
|
||||
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
|
||||
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
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))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[cancelWithdrawHandler] invalid type")
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
lnurlWithdrawState.InTransaction = false
|
||||
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
+154
-74
@@ -11,13 +11,13 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"github.com/tidwall/gjson"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
@@ -55,49 +55,27 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.lnurlReceiveHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
|
||||
var lnurlSplit string
|
||||
split := strings.Split(m.Text, " ")
|
||||
if _, err := decodeAmountFromCommand(m.Text); err == nil {
|
||||
// command is /lnurl 123 <LNURL> [memo]
|
||||
if len(split) > 2 {
|
||||
lnurlSplit = split[2]
|
||||
}
|
||||
} else if len(split) > 1 {
|
||||
lnurlSplit = split[1]
|
||||
} else {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
|
||||
log.Warnln("[/lnurl] Could not parse command.")
|
||||
return
|
||||
}
|
||||
|
||||
// assume payment
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
_, params, err := bot.HandleLNURL(m.Text)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLPayParams:
|
||||
payParams := LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
|
||||
case lnurl.LNURLPayResponse1:
|
||||
payParams := LnurlPayState{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
|
||||
log.Infof("[lnurlHandler] %s", payParams.LNURLPayResponse1.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlPayHandler(ctx, m, payParams)
|
||||
return
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
|
||||
default:
|
||||
if err == nil {
|
||||
err = errors.New("Invalid LNURL type.")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
err := fmt.Errorf("invalid LNURL type.")
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -157,8 +135,131 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
|
||||
}
|
||||
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
// // lnurlEnterAmountHandler is invoked if the user didn't deliver an amount for the lnurl payment
|
||||
// func (bot *TipBot) lnurlEnterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
// a, err := strconv.Atoi(m.Text)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// amount := int64(a)
|
||||
// var stateResponse LnurlPayState
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// // amount not in allowed range from LNURL
|
||||
// if amount > (stateResponse.LNURLPayResponse1.MaxSendable/1000) || amount < (stateResponse.LNURLPayResponse1.MinSendable/1000) {
|
||||
// err = fmt.Errorf("amount not in range")
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.LNURLPayResponse1.MinSendable/1000, stateResponse.LNURLPayResponse1.MaxSendable/1000))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// stateResponse.Amount = a
|
||||
// state, err := json.Marshal(stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(state))
|
||||
// bot.lnurlPayHandler(ctx, m)
|
||||
// }
|
||||
// }
|
||||
|
||||
// // LnurlStateResponse saves the state of the user for an LNURL payment
|
||||
// type LnurlStateResponse struct {
|
||||
// lnurl.LNURLPayResponse1
|
||||
// Amount int `json:"amount"`
|
||||
// Comment string `json:"comment"`
|
||||
// }
|
||||
|
||||
// // lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
// func (bot *TipBot) lnurlPayHandler(ctx context.Context, c *tb.Message) {
|
||||
// msg := bot.trySendMessage(c.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateConfirmLNURLPay {
|
||||
// client, err := getHttpClient()
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var stateResponse LnurlStateResponse
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// callbackUrl, err := url.Parse(stateResponse.Callback)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// qs := callbackUrl.Query()
|
||||
// // add amount to query string
|
||||
// qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
|
||||
// // add comment to query string
|
||||
// if len(stateResponse.Comment) > 0 {
|
||||
// qs.Set("comment", stateResponse.Comment)
|
||||
// }
|
||||
|
||||
// callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// res, err := client.Get(callbackUrl.String())
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var response2 lnurl.LNURLPayResponse2
|
||||
// body, err := ioutil.ReadAll(res.Body)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// json.Unmarshal(body, &response2)
|
||||
|
||||
// if len(response2.PR) < 1 {
|
||||
// error_reason := "Could not receive invoice."
|
||||
// if len(response2.Reason) > 0 {
|
||||
// error_reason = response2.Reason
|
||||
// }
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
// return
|
||||
// }
|
||||
// bot.Telegram.Delete(msg)
|
||||
// c.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
// bot.payHandler(ctx, c)
|
||||
// }
|
||||
// }
|
||||
|
||||
// from https://github.com/fiatjaf/go-lnurl
|
||||
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
|
||||
@@ -172,24 +273,13 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
}
|
||||
} else if strings.HasPrefix(rawlnurl, "http") {
|
||||
rawurl = rawlnurl
|
||||
} else if strings.HasPrefix(rawlnurl, "lnurlp://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurlw://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurla://") ||
|
||||
strings.HasPrefix(rawlnurl, "keyauth://") {
|
||||
|
||||
scheme := "https:"
|
||||
if strings.Contains(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
|
||||
scheme = "http:"
|
||||
}
|
||||
location := strings.SplitN(rawlnurl, ":", 2)[1]
|
||||
rawurl = scheme + location
|
||||
} else {
|
||||
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
foundUrl, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
if !ok {
|
||||
return "", nil,
|
||||
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
rawurl, err = lnurl.LNURLDecode(foundUrl)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -200,24 +290,17 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
return rawurl, nil, err
|
||||
}
|
||||
|
||||
query := parsed.Query()
|
||||
// query := parsed.Query()
|
||||
|
||||
switch query.Get("tag") {
|
||||
case "login":
|
||||
value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
return rawurl, value, err
|
||||
case "withdrawRequest":
|
||||
if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
return rawurl, value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// // original withouth proxy
|
||||
// resp, err := http.Get(rawurl)
|
||||
// if err != nil {
|
||||
// return rawurl, nil, err
|
||||
// switch query.Get("tag") {
|
||||
// case "login":
|
||||
// value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
// return rawurl, value, err
|
||||
// case "withdrawRequest":
|
||||
// if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
// return rawurl, value, nil
|
||||
// }
|
||||
// }
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -226,9 +309,6 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return rawurl, nil, errors.New("HTTP error: " + resp.Status)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
@@ -245,16 +325,16 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
}
|
||||
|
||||
switch j.Get("tag").String() {
|
||||
case "withdrawRequest":
|
||||
value, err := lnurl.HandleWithdraw(b)
|
||||
return rawurl, value, err
|
||||
// case "withdrawRequest":
|
||||
// value, err := lnurl.HandleWithdraw(j)
|
||||
// return rawurl, value, err
|
||||
case "payRequest":
|
||||
value, err := lnurl.HandlePay(b)
|
||||
value, err := lnurl.HandlePay(j)
|
||||
return rawurl, value, err
|
||||
// case "channelRequest":
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// value, err := lnurl.HandleChannel(j)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, errors.New("Unkown LNURL response.")
|
||||
return rawurl, nil, errors.New("unknown response tag " + j.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -85,21 +85,23 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
// check user balance first
|
||||
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)
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return
|
||||
}
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
|
||||
@@ -110,7 +112,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(bolt11.Description))
|
||||
}
|
||||
|
||||
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
|
||||
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
@@ -225,7 +227,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
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.Printf("[pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/makiuchi-d/gozxing"
|
||||
"github.com/makiuchi-d/gozxing/qrcode"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
|
||||
+12
-22
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -41,7 +41,7 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
|
||||
type SendData struct {
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
ToTelegramId int64 `json:"to_telegram_id"`
|
||||
ToTelegramId int `json:"to_telegram_id"`
|
||||
ToTelegramUser string `json:"to_telegram_user"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
@@ -68,11 +68,11 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
// NewMessage(m, WithDuration(0, bot))
|
||||
// return
|
||||
// }
|
||||
if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return
|
||||
}
|
||||
|
||||
// get send amount, returns 0 if no amount is given
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
@@ -98,14 +98,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
}
|
||||
|
||||
// is a user given?
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForUser(ctx, "", "CreateSendState", m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// is an amount given?
|
||||
// todo: this error might have been overwritten by the functions above
|
||||
// we should only check for a valid amount here, instead of error and amount
|
||||
amount, err = decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
@@ -139,8 +133,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
@@ -151,11 +145,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
// cut username if it's too long
|
||||
if len(toUserStrMention) > 100 {
|
||||
toUserStrMention = toUserStrMention[:100]
|
||||
}
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -273,7 +263,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
|
||||
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[send] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify to user
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -24,7 +24,7 @@ func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
@@ -80,7 +80,7 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
UserStr)
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"time"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
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...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
@@ -18,7 +13,6 @@ func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options .
|
||||
return
|
||||
}
|
||||
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...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
@@ -27,7 +21,6 @@ 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...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
@@ -36,78 +29,16 @@ func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...i
|
||||
}
|
||||
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
if !allowedToPerformAction(bot, to, isAdminAndCanEdit) {
|
||||
return
|
||||
}
|
||||
rate.CheckLimit(to)
|
||||
var err error
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
msg, err := bot.Telegram.Edit(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
if !allowedToPerformAction(bot, msg, isAdminAndCanDelete) {
|
||||
return
|
||||
}
|
||||
rate.CheckLimit(msg)
|
||||
err := bot.Telegram.Delete(msg)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// allowedToPerformAction will check if bot is allowed to perform an action on the tb.Editable.
|
||||
// this function will persist the admins list in cache for 5 minutes.
|
||||
// if no admins list is found for this group, bot will always fetch a fresh list.
|
||||
func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(members []tb.ChatMember, me *tb.User) bool) bool {
|
||||
switch editable.(type) {
|
||||
case *tb.Message:
|
||||
message := editable.(*tb.Message)
|
||||
if message.Sender.ID == bot.Telegram.Me.ID {
|
||||
break
|
||||
}
|
||||
chat := message.Chat
|
||||
if chat.Type == tb.ChatSuperGroup || chat.Type == tb.ChatGroup {
|
||||
admins, err := bot.Cache.Get(fmt.Sprintf("admins-%d", chat.ID))
|
||||
if err != nil {
|
||||
admins, err = bot.Telegram.AdminsOf(message.Chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
if action(admins.([]tb.ChatMember), bot.Telegram.Me) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isAdminAndCanDelete will check if me is in members list and allowed to delete messages
|
||||
func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return admin.CanDeleteMessages
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -2,14 +2,11 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
@@ -39,86 +36,8 @@ func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
// 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 user.StateKey == lnbits.UserEnterUser {
|
||||
bot.enterUserHandler(ctx, m)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type EnterUserStateData struct {
|
||||
ID string `json:"ID"` // holds the ID of the tx object in bunt db
|
||||
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
|
||||
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
|
||||
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
|
||||
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
|
||||
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
|
||||
}
|
||||
|
||||
func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string, originalCommand string) (enterUserStateData *EnterUserStateData, err error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
enterUserStateData = &EnterUserStateData{
|
||||
ID: id,
|
||||
Type: eventType,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
|
||||
// Let the user enter a user and return
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "enterUserMessage"), tb.ForceReply)
|
||||
return
|
||||
}
|
||||
|
||||
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
|
||||
// the amount is then stored as an entry in the user's stateKey in the user database
|
||||
// any other handler that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterUser) {
|
||||
ResetUserState(user, bot)
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") {
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
var EnterUserStateData EnterUserStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
userstr := m.Text
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterUserStateData.Type {
|
||||
case "CreateSendState":
|
||||
m.Text = fmt.Sprintf("/send %s", userstr)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func helpTipUsage(ctx context.Context, errormsg string) string {
|
||||
@@ -31,6 +31,8 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
defer NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
@@ -119,13 +121,14 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
|
||||
|
||||
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[tip] Transaction sent 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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// forward tipped message to user once
|
||||
@@ -137,7 +140,5 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
if len(tipMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tipMemo)))
|
||||
}
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -161,7 +161,7 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
runtime.IgnoreError(bot.Bunt.View(func(tx *buntdb.Tx) error {
|
||||
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
|
||||
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
|
||||
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
|
||||
if replyToUserId.String() == strconv.Itoa(user.ID) {
|
||||
log.Debugln("loading persistent tip tool tip messages")
|
||||
ttt := &TipTooltip{}
|
||||
err := json.Unmarshal([]byte(value), ttt)
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -7,30 +7,29 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.BitInvoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int `json:"from_id" `
|
||||
ToId int `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
@@ -87,7 +86,7 @@ func (t *Transaction) Send() (success bool, err error) {
|
||||
// save transaction to db
|
||||
tx := t.Bot.logger.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
|
||||
@@ -129,7 +128,6 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.Invoice = invoice
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type TransactionsList struct {
|
||||
ID string `json:"id"`
|
||||
User *lnbits.User `json:"from"`
|
||||
Payments lnbits.Payments `json:"payments"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
CurrentPage int `json:"currentpage"`
|
||||
MaxPages int `json:"maxpages"`
|
||||
TxPerPage int `json:"txperpage"`
|
||||
}
|
||||
|
||||
func (txlist *TransactionsList) printTransactions(ctx context.Context) string {
|
||||
txstr := ""
|
||||
// for _, p := range payments {
|
||||
payments := txlist.Payments
|
||||
pagenr := txlist.CurrentPage
|
||||
tx_per_page := txlist.TxPerPage
|
||||
if pagenr > (len(payments)+1)/tx_per_page {
|
||||
pagenr = 0
|
||||
}
|
||||
if len(payments) < tx_per_page {
|
||||
tx_per_page = len(payments)
|
||||
}
|
||||
start := pagenr * (tx_per_page - 1)
|
||||
end := start + tx_per_page
|
||||
if end >= len(payments) {
|
||||
end = len(payments) - 1
|
||||
}
|
||||
for i := len(payments) - 1 - start; i >= len(payments)-1-end; i-- {
|
||||
p := payments[i]
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔼"
|
||||
} else {
|
||||
txstr += "🔽"
|
||||
}
|
||||
if p.Pending {
|
||||
txstr += "🔄"
|
||||
}
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2006-01-02 15:04:05")
|
||||
txstr += fmt.Sprintf(" %s:", timestr)
|
||||
txstr += fmt.Sprintf(" %+d sat", p.Amount/1000)
|
||||
if p.Fee > 0 {
|
||||
txstr += fmt.Sprintf("\t(fee: %d sat)", p.Fee/1000)
|
||||
}
|
||||
memo := p.Memo
|
||||
memo_maxlen := 50
|
||||
if len(memo) > memo_maxlen {
|
||||
memo = memo[:memo_maxlen] + "..."
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
txstr += fmt.Sprintf("\t✉️ %s", memo)
|
||||
}
|
||||
txstr += "\n"
|
||||
}
|
||||
txstr += fmt.Sprintf("\nTotal: %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
return txstr
|
||||
}
|
||||
|
||||
var (
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
|
||||
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
|
||||
)
|
||||
|
||||
func (bot TipBot) makeTransactionsKeyboard(ctx context.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
// transactionsMeno := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions")
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions")
|
||||
leftTransactionsButton.Data = txlist.ID
|
||||
rightTransactionsButton.Data = txlist.ID
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
return transactionsMeno
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
// var payments lnbits.Payments
|
||||
// paymentsInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
// if err != nil {
|
||||
// log.Info("Getting from lnbits")
|
||||
// paymentsInterface, err = bot.Client.Payments(*user.Wallet)
|
||||
// if err != nil {
|
||||
// log.Errorf("[transactions] Error: %s", err.Error())
|
||||
// return
|
||||
// }
|
||||
// bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), paymentsInterface, &store.Options{Expiration: 1 * time.Minute})
|
||||
// }
|
||||
// payments = paymentsInterface.(lnbits.Payments)
|
||||
tx_per_page := 20
|
||||
transactionsListInterface = TransactionsList{
|
||||
ID: fmt.Sprintf("txlist-%d-%s", user.Telegram.ID, RandStringRunes(5)),
|
||||
User: user,
|
||||
Payments: payments,
|
||||
LanguageCode: ctx.Value("userLanguageCode").(string),
|
||||
CurrentPage: 0,
|
||||
TxPerPage: tx_per_page,
|
||||
MaxPages: (len(payments)+1)/tx_per_page + 1,
|
||||
}
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
txstr := transactionsList.printTransactions(ctx)
|
||||
bot.trySendMessage(m.Sender, txstr, bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx context.Context, c *tb.Callback) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
|
||||
transactionsList.CurrentPage++
|
||||
} else {
|
||||
return
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx context.Context, c *tb.Callback) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage > 0 {
|
||||
transactionsList.CurrentPage--
|
||||
} else {
|
||||
return
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -3,14 +3,13 @@ package telegram
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
|
||||
|
||||
+2
-14
@@ -40,7 +40,6 @@ sendButtonMessage = """✅ Senden"""
|
||||
payButtonMessage = """✅ Bezahlen"""
|
||||
payReceiveButtonMessage = """💸 Bezahlen"""
|
||||
receiveButtonMessage = """✅ Empfangen"""
|
||||
withdrawButtonMessage = """✅ Abheben"""
|
||||
cancelButtonMessage = """🚫 Abbrechen"""
|
||||
collectButtonMessage = """✅ Einsammeln"""
|
||||
nextButtonMessage = """Vor"""
|
||||
@@ -118,16 +117,12 @@ advancedMessage = """%s
|
||||
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
|
||||
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/transactions* 📃 Liste deiner Transaktionen.
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Richte dein Wallet ein..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Zahlung fehlgeschlagen: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ungültiger Betrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Betrag muss zwischen %d und %d sat liegen."""
|
||||
lnurlNoUsernameMessage = """🚫 Du musst einen Telegram Username anlegen, um per LNURL Zahlungen zu empfangen."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/lnurl [betrag] <lnurl>`
|
||||
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Möchtest du diese Abhebung tätigen?\n\n💸 Betrag: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Bereite Abhebung vor..."""
|
||||
lnurlWithdrawFailed = """🚫 Abhebung gescheitert."""
|
||||
lnurlWithdrawCancelled = """🚫 Abhebung abgebrochen."""
|
||||
lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Verbinde dein Wallet*
|
||||
|
||||
+5
-18
@@ -40,7 +40,6 @@ sendButtonMessage = """✅ Send"""
|
||||
payButtonMessage = """✅ Pay"""
|
||||
payReceiveButtonMessage = """💸 Pay"""
|
||||
receiveButtonMessage = """✅ Receive"""
|
||||
withdrawButtonMessage = """✅ Withdraw"""
|
||||
cancelButtonMessage = """🚫 Cancel"""
|
||||
collectButtonMessage = """✅ Collect"""
|
||||
nextButtonMessage = """Next"""
|
||||
@@ -121,17 +120,12 @@ advancedMessage = """%s
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Advanced commands*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/).
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
enterAmountMessage = """💯 Enter an amount."""
|
||||
enterUserMessage = """👤 Enter a user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Setting up your wallet..."""
|
||||
@@ -236,19 +230,13 @@ lnurlPaymentFailed = """🚫 Payment failed: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Invalid amount."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Amount must be between %d and %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 You need to set a Telegram username to receive payments via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Enter an amount between %d and %d sat."""
|
||||
lnurlEnterAmountMessage = """⌨️ Enter an amount."""
|
||||
lnurlHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/lnurl [amount] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Do you want to make this withdrawal?\n\n💸 Amount: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparing withdrawal..."""
|
||||
lnurlWithdrawFailed = """🚫 Withdrawal failed."""
|
||||
lnurlWithdrawCancelled = """🚫 Withdrawal cancelled."""
|
||||
lnurlWithdrawSuccess = """✅ Withdrawal requested."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Link your wallet*
|
||||
@@ -257,8 +245,7 @@ walletConnectMessage = """🔗 *Link your wallet*
|
||||
|
||||
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
|
||||
+4
-40
@@ -17,7 +17,7 @@ linkCommandStr = """enlace"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """grifo"""
|
||||
|
||||
tipjarCommandStr = """alcancía"""
|
||||
tipjarCommandStr = """bote"""
|
||||
receiveCommandStr = """recibir"""
|
||||
hideCommandStr = """ocultar"""
|
||||
volcanoCommandStr = """volcán"""
|
||||
@@ -117,20 +117,15 @@ advancedMessage = """%s
|
||||
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
|
||||
|
||||
⚙️ *Comandos avanzados*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
enterAmountMessage = """💯 Introduce un monto."""
|
||||
enterUserMessage = """👤 Introduce un usuario."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Configurando tu monedero..."""
|
||||
startSettingWalletMessage = """🧮 Configurar tu monedero..."""
|
||||
startWalletCreatedMessage = """🧮 Monedero creado."""
|
||||
startWalletReadyMessage = """✅ *Tu monedero está listo.*"""
|
||||
startWalletErrorMessage = """🚫 Error al iniciar tu monedero. Vuelve a intentarlo más tarde."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Pago fallido: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 El monto debe estar entre %d y %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Tienes que establecer un nombre de usuario de Telegram para recibir pagos a través de LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Introduce un monto entre %d y %d sat."""
|
||||
lnurlHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/lnurl [monto] <lnurl>`
|
||||
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """¿Desea realizar este retiro?\n\n💸 Monto: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando retiro..."""
|
||||
lnurlWithdrawFailed = """🚫 Retiro fallido."""
|
||||
lnurlWithdrawCancelled = """🚫 Retiro cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Retiro solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Enlaza tu monedero*
|
||||
@@ -310,27 +298,3 @@ inlineReceiveCreateWalletMessage = """Chatea con %s 👈 para gestionar tu carte
|
||||
inlineReceiveYourselfMessage = """📖 No puedes pagarte a ti mismo."""
|
||||
inlineReceiveFailedMessage = """🚫 Recepción fallida."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepción cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Crear una alcancía."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s alcancía <capacidad> <por_usuario>"""
|
||||
inlineResultTipjarTitle = """🍯 Crear una alcancía de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Haz clic aquí para crear una alcancía en este chat."""
|
||||
|
||||
inlineTipjarMessage = """Pulsa 💸 para *pagar %d sat* a esa alcancía de %s.
|
||||
|
||||
🙏 Dados: *%d*/%d sat (por %d usuarios)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 La alcancía de %s está llena ⭐️\n\n🏅 %d sat dados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Alcancía cancelada."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 El monto por usuario no es divisor de la capacidad."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s te envió %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Crea una alcancía en un grupo con el bot dentro o utiliza el 👉 comando _inline_ (/advanced para más)."""
|
||||
inlineTipjarHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidad> <por_usuario>`
|
||||
*Ejemplo:* `/tipjar 210 21`"""
|
||||
|
||||
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
|
||||
|
||||
⚙️ *Commandes avancées*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
enterAmountMessage = """💯 Choisissez un montant."""
|
||||
enterUserMessage = """👤 Choisissez un utilisateur."""
|
||||
errorReasonMessage = """🚫 Erreur: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Création de votre wallet..."""
|
||||
@@ -232,6 +227,7 @@ lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Montant incorrect."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Le montant doit être entre %d et %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Vous devez avoir un nom d'utilisateur Telegram pour recevoir un paiement via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
|
||||
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/lnurl [montant] <lnurl>`
|
||||
|
||||
+2
-14
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
|
||||
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
enterAmountMessage = """💯 Masukkan jumlah."""
|
||||
enterUserMessage = """👤 Masukkan user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sedang menyiapkan dompet mu..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Pembayaran gagal: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Jumlah tidak benar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Jumlah harus diantara %d dan %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Kamu harus mengatur nama pengguna Telegram untuk menerima pembayaran melalui LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Masukkan jumlah diantara %d dan %d sat."""
|
||||
lnurlHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/lnurl [jumlah] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL PENARIKAN
|
||||
|
||||
confirmLnurlWithdrawMessage = """Apakah anda ingin melakukan penarikan ini?\n\n💸 Jumlah: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Mempersiapkan penarikan..."""
|
||||
lnurlWithdrawFailed = """🚫 Penarikan gagal."""
|
||||
lnurlWithdrawCancelled = """🚫 Penarikan dibatalkan."""
|
||||
lnurlWithdrawSuccess = """✅ Penarikan diajukan."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Hubungkan dompet mu*
|
||||
|
||||
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
|
||||
|
||||
⚙️ *Comandi avanzati*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
enterAmountMessage = """💯 Imposta un ammontare."""
|
||||
enterUserMessage = """👤 Imposta un utente."""
|
||||
errorReasonMessage = """🚫 Errore: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
|
||||
@@ -232,6 +227,7 @@ lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Imposta un ammontare tra %d e %d sat."""
|
||||
lnurlHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/lnurl [ammontare] <lnurl>`
|
||||
|
||||
+2
-14
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
|
||||
|
||||
⚙️ *Geavanceerde opdrachten*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
enterAmountMessage = """💯 Voer een bedrag."""
|
||||
enterUserMessage = """👤 Voer een gebruiker."""
|
||||
errorReasonMessage = """🚫 Fout: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Uw wallet instellen..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Betaling mislukt: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ongeldig bedrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Bedrag moet liggen tussen %d en %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 U moet een Telegram gebruikersnaam instellen om betalingen te ontvangen via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Voer een bedrag in tussen %d en %d sat."""
|
||||
lnurlHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/lnurl [bedrag] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?💸 Bedrag: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Opname aan het voorbereiden..."""
|
||||
lnurlWithdrawFailed = """🚫 Opname mislukt."""
|
||||
lnurlWithdrawCancelled = """🚫 Opname geannuleerd."""
|
||||
lnurlWithdrawSuccess = """✅ Opname aangevraagd."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Koppel uw wallet*
|
||||
|
||||
+2
-38
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
|
||||
|
||||
⚙️ *Comandos avançados*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
enterAmountMessage = """💯 Insira uma quantia."""
|
||||
enterUserMessage = """👤 Insira um usuário."""
|
||||
errorReasonMessage = """🚫 Erro: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Preparando sua carteira..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Falha no pagamento: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 A quantia deve estar entre %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Você precisa configurar um nome de usuário de Telegram para receber pagamentos através do LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Insira uma quantia entre %d e %d sat."""
|
||||
lnurlHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/lnurl [quantidade] <lnurl>`
|
||||
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando o saque..."""
|
||||
lnurlWithdrawFailed = """🚫 Saque falhou."""
|
||||
lnurlWithdrawCancelled = """🚫 Saque cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Saque solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Vincule sua carteira*
|
||||
@@ -310,27 +298,3 @@ inlineReceiveCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua
|
||||
inlineReceiveYourselfMessage = """📖 Você não pode pagar a si mesmo."""
|
||||
inlineReceiveFailedMessage = """🚫 O recebimento falhou."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepção cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Criar um cofrinho."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s cofrinho <capacidade> <por_usuário>"""
|
||||
inlineResultTipjarTitle = """🍯 Criar um cofrinho de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Clique aqui para criar um cofrinho neste chat."""
|
||||
|
||||
inlineTipjarMessage = """Pressione 💸 para *pagar %d sat* a esse cofrinho de %s.
|
||||
|
||||
🙏 Doados: *%d*/%d sat (por %d usuários)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 O cofrinho de %s está cheio ⭐️\n\n🏅 %d sat doados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Cofrinho cancelado."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Quantidade por usuário não divisor da capacidade."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s lhe enviou %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Criar uma cofrinho em grupo com o bot dentro ou usar o 👉 comando_inline_ (/advanced para mais)."""
|
||||
inlineTipjarHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidade> <por_usuário>`
|
||||
*Exemplo:* `/tipjar 210 21`"""
|
||||
|
||||
@@ -1,340 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """справка"""
|
||||
basicsCommandStr = """основы"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """баланс"""
|
||||
sendCommandStr = """отправить"""
|
||||
invoiceCommandStr = """инвойс"""
|
||||
payCommandStr = """оплатить"""
|
||||
donateCommandStr = """пожертвовать"""
|
||||
advancedCommandStr = """детально"""
|
||||
transactionsCommandStr = """транзакции"""
|
||||
logCommandStr = """лог"""
|
||||
listCommandStr = """список"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """получить"""
|
||||
hideCommandStr = """спрятать"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """показать"""
|
||||
optionsCommandStr = """опции"""
|
||||
settingsCommandStr = """настройки"""
|
||||
saveCommandStr = """сохранить"""
|
||||
deleteCommandStr = """удалить"""
|
||||
infoCommandStr = """инфо"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Вы не можете это сделать."""
|
||||
cantClickMessage = """Вы не можете нажать на эту кнопку."""
|
||||
balanceTooLowMessage = """Недостаточно средств."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Отправить"""
|
||||
payButtonMessage = """✅ Оплатить"""
|
||||
payReceiveButtonMessage = """💸 Оплатить"""
|
||||
receiveButtonMessage = """✅ Получить"""
|
||||
withdrawButtonMessage = """✅ Вывести"""
|
||||
cancelButtonMessage = """🚫 Отмена"""
|
||||
collectButtonMessage = """✅ Забрать"""
|
||||
nextButtonMessage = """Вперед"""
|
||||
backButtonMessage = """Назад"""
|
||||
acceptButtonMessage = """Принять"""
|
||||
denyButtonMessage = """Запретить"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Развернуть"""
|
||||
showButtonMessage = """Показать"""
|
||||
hideButtonMessage = """Спрятать"""
|
||||
joinButtonMessage = """Присоединиться"""
|
||||
optionsButtonMessage = """Опции"""
|
||||
settingsButtonMessage = """Настройки"""
|
||||
saveButtonMessage = """Сохранить"""
|
||||
deleteButtonMessage = """Удалить"""
|
||||
infoButtonMessage = """Инфо"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Этот бот представляет собой кошелек Bitcoin Lightning, который может отправлять Tip (небольшие сумму в Сатоши) через Telegram. Чтобы отправить Tip, добавьте бота в групповой чат. Основной единицей чаевых являются сатоши (sat). 100 000 000 сат = 1 биткоин. Введите 📚 /basics для получения дополнительной информации._
|
||||
|
||||
❤️ *Donate*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Команды*
|
||||
*/tip* 🏅 Ответьте на сообщение чтобы отправить Tip (небольшую сумму в Сатоши): `/tip <amount> [<memo>]`
|
||||
*/balance* 👑 Проверить баланс: `/balance`
|
||||
*/send* 💸 Отправить ссредства пользователю: `/send <количество> @<user> или <user>@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Получить через Lightning: `/invoice <количество> [<memo>]`
|
||||
*/pay* ⚡️ Оплатить через Lightning: `/pay <инвойс>`
|
||||
*/donate* ❤️ Отправить пожертвование проекту: `/donate 1000`
|
||||
*/advanced* 🤖 Продвинутые возможности.
|
||||
*/help* 📖 Прочитайте справку."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Ваш адрес в системе Lightning - `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Биткоин*
|
||||
_Биткоин - это валюта интернета. Она не имеет ограничений и децентрализована, у нее нет хозяев и контролирующих органов. Биткойн - это разумные деньги, которые быстрее, надежнее и всеохватнее, чем традиционная финансовая система._
|
||||
|
||||
🧮 *Экономика*
|
||||
_Наименьшей единицей Биткоина являются "Сатоши" (sat), а 100 000 000 sat = 1 Биткойн. В мире существует только 21 миллион биткоинов. Стоимость Биткойна выражаемая в фиатной валюте может меняться ежедневно. Однако, если вы живете по стандарту Биткойна, то 1 sat всегда будет равен 1 sat._
|
||||
|
||||
⚡️ *The Lightning Network*
|
||||
_The Lightning Network - это платежный протокол, который обеспечивает быстрые и дешевые платежи Биткоинами, практически не требующие энергии. Именно благодаря ему Биткоин доступен миллиардам людей по всему миру._
|
||||
|
||||
📲 *Lightning-кошельки*
|
||||
_Ваши средства на этом боте могут быть отправлены на любой другой Lightning-кошелек и наоборот. Рекомендуемые Lightning-кошельки для вашего телефона:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (не требующие обслуживания), или_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(простой)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Этот бот является бесплатным и_ [с открытым исходным кодом](https://github.com/LightningTipBot/LightningTipBot) _. Вы можете запустить его на своем компьютере и использовать в своем сообществе._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Добавьте этого бота в чат вашей группы Telegram для /tip сообщений. Если вы сделаете бота администратором группы, он также будет очищать команды для поддержания чистоты в чате._
|
||||
|
||||
🏛 *Условия*
|
||||
_Мы не являемся хранителями ваших средств. Мы будем действовать в ваших интересах, но мы также понимаем, что ситуация без поддержки стандарта KYC - немного сложная, до тех пор, пока мы не придумаем что-нибудь. Любая сумма, которую вы загрузите на свой кошелек, будет считаться пожертвованием. Не отдавайте нам все свои деньги. Имейте в виду, что этот бот находится в стадии бета-разработки. Используйте на свой страх и риск._
|
||||
|
||||
❤️ *Пожертвования*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Пожалуйста, установите имя пользователя в Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Команды*
|
||||
*send* 💸 Отправить Сатоши в чате: `%s send <количество> [<user>] [<memo>]`
|
||||
*receive* 🏅 Запросить оплату: `... receive <количество> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Создать криптораздачу: `... faucet <ёмкость> <на_пользователя> [<memo>]`
|
||||
*tipjar* 🍯 Создать копилку: `... tipjar <ёмкость> <на_пользователя> [<memo>]`
|
||||
|
||||
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
|
||||
|
||||
⚙️ *Продвинутые команды*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
|
||||
enterAmountMessage = """💯 Введите количество."""
|
||||
enterUserMessage = """👤 введите пользователя."""
|
||||
errorReasonMessage = """🚫 Ошибка: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Настраиваю кошелёк для вас..."""
|
||||
startWalletCreatedMessage = """🧮 Кошелёк создан."""
|
||||
startWalletReadyMessage = """✅ *Кошелёк готов к использованию.*"""
|
||||
startWalletErrorMessage = """🚫 Ошибка инициализации кошелька. Попробуйте позже."""
|
||||
startNoUsernameMessage = """☝️ Похоже, что у вас еще нет @имени_пользователя в Telegram. Это нормально, оно не обязательно для использования этого бота. Однако, чтобы лучше использовать свой кошелек, установите имя пользователя в настройках Telegram. Затем введите /balance, чтобы бот мог обновить свои данные о вас."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Ваш баланс:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Не удалось получить ваш баланс. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Вы ответили на сообщение чтобы отправить Сатоши? Чтобы ответить на любое сообщение, нажмите правой кнопкой мыши -> Ответить на компьютере или проведите пальцем по сообщению на телефоне. Если вы хотите отправить Сатоши непосредственно другому пользователю, используйте команду /send."""
|
||||
tipInviteGroupMessage = """ℹ️ Кстати, вы можете пригласить этого бота в любую группу, чтобы можно было отправлять чаевые там."""
|
||||
tipEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
tipValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
tipYourselfMessage = """📖 Вы не можете отправлять самому себе."""
|
||||
tipSentMessage = """💸 %d sat отправлено %s."""
|
||||
tipReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
tipErrorMessage = """🚫 Отправка не удалась."""
|
||||
tipUndefinedErrorMsg = """пожалуйста попробуйте позжа."""
|
||||
tipHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/tip <количество> [<memo>]`
|
||||
*Пример:* `/tip 1000 Спасибо!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Пользователь %s не создал кошелёк."""
|
||||
sendSentMessage = """💸 %d sat отправлено %s."""
|
||||
sendPublicSentMessage = """💸 %d sat отправил(а) %s для %s."""
|
||||
sendReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
sendErrorMessage = """🚫 Неуспешная отправка."""
|
||||
confirmSendMessage = """Вы хотите отправить Сатоши %s?\n\n💸 Amount: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Отправка отменена."""
|
||||
errorTryLaterMessage = """🚫 Ошибка. Пожалуйста попробуйте позже."""
|
||||
sendSyntaxErrorMessage = """Вы ввели сумму и получателя? Вы можете использовать команду /send для отправки либо пользователям Telegram, например %s, либо на адрес Lightning, например LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/send <количество> <пользователь> [<memo>]`
|
||||
*Пример:* `/send 1000 @LightningTipBot I just like the bot ❤️`
|
||||
*Пример:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
|
||||
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
invoiceHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/invoice <количество> [<memo>]`
|
||||
*Пример:* `/invoice 1000 Спасибо!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Платёж отменён."""
|
||||
invoicePaidMessage = """⚡️ Платёж отправлен."""
|
||||
invoicePublicPaidMessage = """⚡️ %s отправил(а) платёж."""
|
||||
invalidInvoiceHelpMessage = """Вы ввели существующий счет в Lightning? Попробуйте /send, если вы хотите отправить пользователю Telegram или по адресу Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Невозможно оплатить инвойс без указания суммы."""
|
||||
insufficientFundsMessage = """🚫 Недостаточно средств. У вас есть %d sat, но вам нужно не менее %d sat."""
|
||||
feeReserveMessage = """⚠️ Отправка всего вашего баланса может провалиться из-за сетевых сборов. Если это не удается, попробуйте отправить немного меньше."""
|
||||
invoicePaymentFailedMessage = """🚫 Платёж не прошёл: %s"""
|
||||
invoiceUndefinedErrorMessage = """Невозможно оплатить счёт."""
|
||||
confirmPayInvoiceMessage = """Хотите ли вы отправить этот платеж?\n\n💸 Amount: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/pay <инвойс>`
|
||||
*Пример:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Спасибо за ваше пожертвование."""
|
||||
donationErrorMessage = """🚫 О нет! Пожертвование не удалось."""
|
||||
donationProgressMessage = """🧮 Подготовка вашего пожертвования..."""
|
||||
donationFailedMessage = """🚫 Пожертвование не удалось: %s"""
|
||||
donateEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
donateValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
donateHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/donate <количество>`
|
||||
*Пример:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Не удалось распознать счет Lightning или LNURL. Попробуйте отцентрировать QR-код, обрезать фотографию или увеличить масштаб."""
|
||||
photoQrRecognizedMessage = """✅ QR код:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Вы можете использовать этот статический LNURL для приема платежей."""
|
||||
lnurlResolvingUrlMessage = """🧮 Уточнение адреса..."""
|
||||
lnurlGettingUserMessage = """🧮 Подготовка платежа..."""
|
||||
lnurlPaymentFailed = """🚫 Платеж не прошел: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Неверная сумма."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Сумма должна быть от %d до %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Вам нужно установить имя пользователя Telegram для получения платежей через LNURL."""
|
||||
lnurlHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/lnurl [количество] <lnurl>`
|
||||
*Пример:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Вы хотите вывести средства?\n\n💸 Сумма: %d сб"""
|
||||
lnurlPreparingWithdraw = """🧮 Подготовка к выводу средств..."""
|
||||
lnurlWithdrawFailed = """🚫 Вывод средств не удался."""
|
||||
lnurlWithdrawCancelled = """🚫 Вывод средств отменен."""
|
||||
lnurlWithdrawSuccess = """✅ Вывод средств запрошен."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Подключение кошелька*
|
||||
|
||||
⚠️ Никогда и никому не сообщайте URL или QR-код, иначе они смогут получить доступ к вашим средствам.
|
||||
|
||||
- *BlueWallet:* Нажмите *New wallet*, *Import wallet*, *Scan or import a file*, и отсканируйте QR-код.
|
||||
- *Zeus:* Скопируйте URL ниже, нажмите *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Не удалось связать ваш кошелек. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Создать криптораздачу."""
|
||||
inlineQueryFaucetDescription = """Использование: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
|
||||
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
|
||||
|
||||
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи.
|
||||
|
||||
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Криптораздача завершена 🍺\n\n🏅 %d sat отдано %d пользователям."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineFaucetCancelledMessage = """🚫 Криптораздача отменена."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Неверное количество."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat отправлено %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s отправил вам %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Создайте криптораздачу в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineFaucetHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/faucet <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Отправьте платеж в чат."""
|
||||
inlineQuerySendDescription = """Использование: @%s send <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Отправить %d sat."""
|
||||
inlineResultSendDescription = """👉 Нажмите, чтобы отправить %d сат в этот чат."""
|
||||
|
||||
inlineSendMessage = """Нажмите ✅ для получения платежа от %s.\n\n💸 Сумма: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat отправлено с %s на %s."""
|
||||
inlineSendCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
sendYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineSendFailedMessage = """🚫 Отправка не удалась."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Сумма должна быть больше 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Ваш баланс слишком низкий."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Запросить платёж в чате."""
|
||||
inlineQueryReceiveDescription = """Использование: @%s receive <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Получить %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Нажмите, чтобы запросить выплату в размере %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Нажмите 💸 чтобы отправить Сатоши %s.\n\n💸 Количество: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat отправлено от %s, получатель - %s."""
|
||||
inlineReceiveCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineReceiveYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineReceiveFailedMessage = """🚫 Получение не удалось."""
|
||||
inlineReceiveCancelledMessage = """🚫 Получение отменено."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Создать копилку."""
|
||||
inlineQueryTipjarDescription = """Использование: @%s tipjar <ёмкость> <на_пользователя>"""
|
||||
inlineResultTipjarTitle = """🍯 Создать копилку на %d sat ."""
|
||||
inlineResultTipjarDescription = """👉 Нажмите здесь, чтобы создать копилку в этом чате."""
|
||||
|
||||
inlineTipjarMessage = """Нажмите 💸 чтобы *отправить %d sat* в эту копилку, созданную %s.
|
||||
|
||||
🙏 Накоплено: *%d*/%d sat (от %d пользователей)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s's копилка заполнена ⭐️\n\n🏅 %d sat отправи(л/ли) %d пользовате(ль/ли)."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Копилка отозвана."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Отправка не удалась."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat отправлено в пользу %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s отправил вам %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Создайте копилку в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Использование:* `/tipjar <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/tipjar 210 21`"""
|
||||
@@ -122,12 +122,6 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
|
||||
enterAmountMessage = """💯 Bir miktar gir."""
|
||||
enterUserMessage = """👤 Bir kullanıcı gir."""
|
||||
errorReasonMessage = """🚫 Hata: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Cüzdanın hazırlanıyor…"""
|
||||
@@ -232,6 +226,7 @@ lnurlPaymentFailed = """🚫 Ödeme başarısız: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Geçersiz miktar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Miktar %d ve %d sat arasında olmalı."""
|
||||
lnurlNoUsernameMessage = """🚫 LNURL ödemesi almak için bir Telegram kullanıcı ismi seçmelisin."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ %d ve %d sat arasında bir miktar gir."""
|
||||
lnurlHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/lnurl [miktar] <lnurl>`
|
||||
|
||||
Reference in New Issue
Block a user