Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a87eac37b8 | ||
|
|
250c036c47 | ||
|
|
df303ae186 | ||
|
|
d0d844fd4f | ||
|
|
dbe94b9494 | ||
|
|
d9f373cebb | ||
|
|
d066fa9e27 | ||
|
|
127f95b8de | ||
|
|
98401546fa | ||
|
|
fbc47c0fb9 | ||
|
|
0c29fec19f | ||
|
|
4bcbd2fefe | ||
|
|
a669ea86ac | ||
|
|
b396219792 | ||
|
|
4871b42f22 | ||
|
|
6ff264ab18 | ||
|
|
fff933e413 | ||
|
|
36d94ecff8 | ||
|
|
aaba02020b | ||
|
|
02bbc8e5a3 | ||
|
|
61fb20e132 | ||
|
|
7707fbf4a5 | ||
|
|
dfcf576dce | ||
|
|
796abe7f96 | ||
|
|
52e1fc043a | ||
|
|
3f64ceb6c1 | ||
|
|
30e0ba9cdf | ||
|
|
f474988606 | ||
|
|
865592b0a6 | ||
|
|
41a4946071 | ||
|
|
d7dc6f71aa | ||
|
|
d9f2f87739 | ||
|
|
29f03807f2 | ||
|
|
042ccaf8ef | ||
|
|
4ecc65fb27 | ||
|
|
f73e027e9c | ||
|
|
b4e8721e3e | ||
|
|
dd87d4f6f8 | ||
|
|
8033d05f7e | ||
|
|
c27de372a5 | ||
|
|
bc849c5b03 | ||
|
|
6f2a95609e | ||
|
|
d6e9f49cd1 | ||
|
|
d2a63c07a3 | ||
|
|
8729011aaf | ||
|
|
5199e4c8c6 | ||
|
|
e5928defd0 | ||
|
|
1167392140 | ||
|
|
cf68245012 | ||
|
|
6c06a4972e | ||
|
|
e7fa555506 | ||
|
|
666eecf207 | ||
|
|
0eaf96749f | ||
|
|
672402616e | ||
|
|
cfde78e639 | ||
|
|
fce4fb9ecc | ||
|
|
1946a0e873 | ||
|
|
fd531e6719 | ||
|
|
94ff302d15 | ||
|
|
631c314b31 | ||
|
|
307967b61a | ||
|
|
a53f8e307a | ||
|
|
6f14fab93b | ||
|
|
99a866854b | ||
|
|
21f5abbb25 | ||
|
|
158990f46d | ||
|
|
c00196e9d6 | ||
|
|
410f56aaf5 | ||
|
|
0631fd53eb | ||
|
|
afcd530d06 | ||
|
|
5aaf9452b5 | ||
|
|
b07053172b | ||
|
|
6ebb5688fd | ||
|
|
2e3a1fe087 | ||
|
|
997faa2c45 | ||
|
|
048141908e | ||
|
|
900ce09aa6 |
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img alt="logo" src="resources/logo_round.png" >
|
||||
<img alt="logo" width="150" src="resources/logo_round.png" >
|
||||
</p>
|
||||
|
||||
# @LightningTipBot 🏅
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
|
||||
help - Read the help.
|
||||
balance - Check balance.
|
||||
transactions - List transactions
|
||||
tip - Reply to a message to tip: /tip 50
|
||||
send - Send funds to a user: /send 100 @LightningTipBot
|
||||
invoice - Receive with Lightning: /invoice 1000
|
||||
pay - Pay with Lightning: /pay lnbc10n1ps...
|
||||
donate - Donate: /donate 1000
|
||||
faucet - Create a faucet: /faucet 2100 21
|
||||
tipjar - Create a tipjar: /tipjar 100 10
|
||||
advanced - Advanced help
|
||||
@@ -1,4 +1,10 @@
|
||||
bot:
|
||||
socks_proxy:
|
||||
host: 127.0.0.1:9996
|
||||
username: test
|
||||
password: username
|
||||
tor_proxy:
|
||||
host: 127.0.0.1:9050
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
|
||||
@@ -1,31 +1,95 @@
|
||||
module github.com/LightningTipBot/LightningTipBot
|
||||
|
||||
go 1.15
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.8.0
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.2.0
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/go-lnurl v1.11.2
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/sethvargo/go-limiter v0.7.2
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/sirupsen/logrus v1.7.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.v3 v3.0.0-20220326213923-f323bb71ac8e // indirect
|
||||
github.com/tidwall/gjson v1.12.1
|
||||
github.com/tidwall/sjson v1.2.4
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
|
||||
golang.org/x/text v0.3.7
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
|
||||
github.com/aead/siphash v1.0.1 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.1 // indirect
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
|
||||
github.com/btcsuite/btcd v0.23.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil v1.1.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
|
||||
github.com/btcsuite/btcwallet v0.15.1 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
|
||||
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
|
||||
github.com/decred/dcrd/lru v1.0.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/go-errors/errors v1.0.1 // indirect
|
||||
github.com/go-redis/redis/v8 v8.8.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.2 // indirect
|
||||
github.com/kkdai/bstream v1.0.0 // indirect
|
||||
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
|
||||
github.com/lightninglabs/neutrino v0.14.2 // indirect
|
||||
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
|
||||
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
|
||||
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.5 // indirect
|
||||
github.com/miekg/dns v1.1.43 // indirect
|
||||
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
|
||||
github.com/pegasus-kv/thrift v0.13.0 // indirect
|
||||
github.com/spf13/cast v1.3.1 // indirect
|
||||
github.com/tidwall/btree v0.6.1 // indirect
|
||||
github.com/tidwall/grect v0.1.3 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tidwall/rtred v0.1.2 // indirect
|
||||
github.com/tidwall/tinyqueue v0.1.1 // indirect
|
||||
go.opentelemetry.io/otel v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
|
||||
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 // indirect
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -68,7 +68,7 @@ func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
|
||||
if v["id"] == "" {
|
||||
return nil, fmt.Errorf("invalid id")
|
||||
}
|
||||
tx := s.bot.Database.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
|
||||
tx := s.bot.DB.Users.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package api
|
||||
|
||||
type BalanceResponse struct {
|
||||
Balance int64 `json:"balance"`
|
||||
}
|
||||
|
||||
type InvoiceStatusResponse struct {
|
||||
State string `json:"state,omitempty"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Preimage int64 `json:"preimage"`
|
||||
}
|
||||
|
||||
type CreateInvoiceResponse struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PayRequest string `json:"pay_request"`
|
||||
Preimage string `json:"preimage,omitempty"`
|
||||
}
|
||||
type CreateInvoiceRequest struct {
|
||||
Memo string `json:"memo"`
|
||||
Amount int64 `json:"amount"`
|
||||
DescriptionHash string `json:"description_hash"`
|
||||
UnhashedDescription string `json:"unhashed_description"`
|
||||
}
|
||||
|
||||
type PayInvoiceRequest struct {
|
||||
PayRequest string `json:"pay_req"`
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Bot *telegram.TipBot
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Message string `json:"error"`
|
||||
}
|
||||
|
||||
func RespondError(w http.ResponseWriter, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
|
||||
}
|
||||
|
||||
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
balance, err := s.Bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
RespondError(w, "balance check failed")
|
||||
return
|
||||
}
|
||||
|
||||
balanceResponse := BalanceResponse{
|
||||
Balance: balance,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(balanceResponse)
|
||||
}
|
||||
|
||||
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var createInvoiceRequest CreateInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: createInvoiceRequest.Amount,
|
||||
Out: false,
|
||||
DescriptionHash: createInvoiceRequest.DescriptionHash,
|
||||
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not create invoice")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(invoice)
|
||||
}
|
||||
|
||||
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var payInvoiceRequest PayInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not pay invoice: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
|
||||
if err != nil {
|
||||
// we assume that it's paid since thre was no error earlier
|
||||
payment.Paid = true
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get payment")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
// InvoiceStatus
|
||||
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get invoice")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"gorm.io/gorm"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -16,6 +24,82 @@ func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
type AuthType struct {
|
||||
Type string
|
||||
Decoder func(s string) ([]byte, error)
|
||||
}
|
||||
|
||||
var AuthTypeBasic = AuthType{Type: "Basic"}
|
||||
var AuthTypeBearerBase64 = AuthType{Type: "Basic", Decoder: base64.StdEncoding.DecodeString}
|
||||
|
||||
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
// check if the user is banned
|
||||
if auth == "" {
|
||||
w.WriteHeader(401)
|
||||
log.Warn("[AuthorizationMiddleware] no auth")
|
||||
return
|
||||
}
|
||||
_, password, ok := parseAuth(authType, auth)
|
||||
if !ok {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
w.WriteHeader(401)
|
||||
log.Warnf("[AuthorizationMiddleware] Banned user %s. Not forwarding request", password)
|
||||
return
|
||||
}
|
||||
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
|
||||
user := &lnbits.User{}
|
||||
tx := database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
if tx.Error != nil {
|
||||
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
|
||||
log.Warnf("[AuthorizationMiddleware] Could not get wallet admin key %s: %v", password, tx.Error)
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[AuthorizationMiddleware] need admin key to pay invoice %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/payinvoice" {
|
||||
log.Warnf("[AuthorizationMiddleware] need admin key to pay invoice %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Debugf("[AuthorizationMiddleware] User: %s", telegram.GetUserStr(user.Telegram))
|
||||
r = r.WithContext(context.WithValue(r.Context(), "user", user))
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// parseAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
|
||||
parse := func(prefix string) (username, password string, ok bool) {
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
if authType.Decoder != nil {
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
return auth[len(prefix):], auth[len(prefix):], true
|
||||
|
||||
}
|
||||
return parse(fmt.Sprintf("%s ", authType.Type))
|
||||
|
||||
}
|
||||
|
||||
func dump(r *http.Request) string {
|
||||
x, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,16 +2,17 @@ package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
|
||||
|
||||
client := &http.Client{Timeout: time.Second * 10}
|
||||
client := &http.Client{Timeout: time.Second * 30}
|
||||
|
||||
//http: Request.RequestURI can't be set in client requests.
|
||||
//http://golang.org/src/pkg/net/http/client.go
|
||||
|
||||
@@ -2,10 +2,10 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -33,7 +33,7 @@ func NewServer(address string) *Server {
|
||||
apiServer.router = mux.NewRouter()
|
||||
apiServer.httpServer.Handler = apiServer.router
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
log.Infof("[API] Server started at %s", address)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
@@ -43,6 +43,12 @@ func (w *Server) ListenAndServe() {
|
||||
func (w *Server) PathPrefix(path string, handler http.Handler) {
|
||||
w.router.PathPrefix(path).Handler(handler)
|
||||
}
|
||||
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, handler)))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
|
||||
if len(methods) > 0 {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<!-- @format -->
|
||||
|
||||
{{define "userpage"}}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8" />
|
||||
<meta property="og:title" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta property="og:site_name" content="{{.Username}}@ln.tips">
|
||||
<meta property="og:description" content="Send bitcoin to {{.Username}} over Lightning. Get your own Lightning address at https://ln.tips 👈">
|
||||
<meta property="og:type" content="article" />
|
||||
<meta property="og:image" content="{{.Image}}">
|
||||
<meta property="og:url" content="https://ln.tips/@{{.Username}}">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:image:alt" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta name="lightning" content="lnurlp:{{.Username}}@ln.tips"/>
|
||||
|
||||
<title>{{.Username}}@ln.tips</title>
|
||||
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: rgb(36,71,247);
|
||||
background: radial-gradient(circle, rgba(36,71,247,1) 0%, rgba(249,42,84,1) 100%);
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
font-family: monospace;
|
||||
width: 600px;
|
||||
color: #f3f3f3c5 !important;
|
||||
}
|
||||
.image-cropper {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 50%;
|
||||
}
|
||||
#photo {
|
||||
margin-top: 50px;
|
||||
width: 100px;
|
||||
}
|
||||
.white {
|
||||
color: #f3f3f3c5;
|
||||
}
|
||||
.sm {
|
||||
color: #f3f3f3c5;
|
||||
font-size: 1rem;
|
||||
}
|
||||
#qr {
|
||||
display: block;
|
||||
margin-top: 50px;
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
#invoice {
|
||||
margin: 10px;
|
||||
padding-bottom: 10px;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
word-break: break-all;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<a href="https://t.me/{{.Username}}"><img id="photo" class="image-cropper" src="{{.Image}}"/></a>
|
||||
<h1>Pay to <a class="white" href="https://t.me/{{.Username}}">{{.Username}}@ln.tips</a></h1>
|
||||
|
||||
<div><a href="lightning:{{.LNURLPay}}" id="qr"></a></div>
|
||||
<div class="white" id="invoice">{{.LNURLPay}}</div>
|
||||
<div class="sm">Get your own Lightning address here: <a class="sm" href="https://ln.tips">ln.tips</a></div>
|
||||
<script>
|
||||
qr.appendChild(
|
||||
kjua({
|
||||
text: invoice.innerHTML,
|
||||
rounded: 50,
|
||||
size: 500,
|
||||
render: 'canvas',
|
||||
})
|
||||
)
|
||||
</script>
|
||||
|
||||
{{end}}
|
||||
@@ -0,0 +1,92 @@
|
||||
package userpage
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(b *telegram.TipBot) Service {
|
||||
return Service{
|
||||
bot: b,
|
||||
}
|
||||
}
|
||||
|
||||
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
//go:embed static
|
||||
var templates embed.FS
|
||||
var tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// thank you fiatjaf for this code
|
||||
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
// with proxy:
|
||||
// client, err := s.network.GetHttpClient()
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
client := http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
resp, err := client.Get("https://t.me/" + username)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
url, ok := doc.Find(`meta[property="og:image"]`).First().Attr("content")
|
||||
if !ok {
|
||||
return "", errors.New("no image available for this user")
|
||||
}
|
||||
|
||||
return url, nil
|
||||
}
|
||||
|
||||
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/.well-known/lnurlp/<username>
|
||||
username := strings.ToLower(mux.Vars(r)["username"])
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
|
||||
log.Infof("[UserPage] rendering page of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
return
|
||||
}
|
||||
image, err := s.getTelegramUserPictureURL(username)
|
||||
if err != nil || image == "https://telegram.org/img/t_logo.png" {
|
||||
// replace the default image
|
||||
image = botImage
|
||||
}
|
||||
|
||||
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
Username string
|
||||
Image string
|
||||
LNURLPay string
|
||||
}{username, image, lnurlEncode}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
+13
-6
@@ -16,13 +16,20 @@ var Configuration = struct {
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
}{}
|
||||
|
||||
type SocksConfiguration struct {
|
||||
Host string `yaml:"host"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
type BotConfiguration struct {
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
|
||||
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
@@ -83,7 +85,7 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
|
||||
}
|
||||
|
||||
// Invoice creates an invoice associated with this wallet.
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
@@ -130,6 +132,54 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Payments returns wallet payments
|
||||
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?limit=60", 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
|
||||
}
|
||||
|
||||
// Payment state of a payment
|
||||
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, 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+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&payment)
|
||||
return
|
||||
}
|
||||
|
||||
// Wallets returns all wallets belonging to an user
|
||||
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
|
||||
@@ -149,7 +199,7 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
|
||||
// custom header with admin key
|
||||
adminHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
|
||||
+52
-15
@@ -6,7 +6,9 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/btcsuite/btcd/btcec/v2"
|
||||
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -33,6 +35,18 @@ type User struct {
|
||||
AnonIDSha256 string `json:"anon_id_sha256"`
|
||||
UUID string `json:"uuid"`
|
||||
Banned bool `json:"banned"`
|
||||
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
ID string `json:"id" gorm:"primarykey"`
|
||||
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
|
||||
}
|
||||
|
||||
type NodeSettings struct {
|
||||
NodeType string `json:"nodetype"`
|
||||
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
|
||||
LNbitsParams *satdress.LNBitsParams `gorm:"embedded;embeddedPrefix:lnbitsparams_"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -61,11 +75,12 @@ func (u *User) ResetState() {
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in MilliSatoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in Satoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
@@ -87,14 +102,11 @@ type TransferParams struct {
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Name string `json:"name"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Status int `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
func (err Error) Error() string {
|
||||
return err.Message
|
||||
return err.Detail
|
||||
}
|
||||
|
||||
type Wallet struct {
|
||||
@@ -105,17 +117,42 @@ type Wallet struct {
|
||||
Name string `json:"name"`
|
||||
User string `json:"user"`
|
||||
}
|
||||
type BitInvoice struct {
|
||||
|
||||
type Payment struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `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"`
|
||||
}
|
||||
|
||||
type LNbitsPayment struct {
|
||||
Paid bool `json:"paid"`
|
||||
Preimage string `json:"preimage"`
|
||||
Details Payment `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
type Payments []Payment
|
||||
|
||||
type Invoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
|
||||
// from fiatjaf/lnurl-go
|
||||
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
|
||||
seedhash := sha256.Sum256([]byte(
|
||||
seedHash := sha256.Sum256([]byte(
|
||||
fmt.Sprintf("lnurlkeyseed:%s:%s",
|
||||
domain, u.ID)))
|
||||
return btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
|
||||
return btcec.PrivKeyFromBytes(seedHash[:])
|
||||
}
|
||||
|
||||
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
|
||||
@@ -127,7 +164,7 @@ func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string,
|
||||
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
|
||||
}
|
||||
|
||||
signature, err := sk.Sign(k1)
|
||||
signature := ecdsa.Sign(sk, k1)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("error signing k1: %w", err)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func NewServer(bot *telegram.TipBot) *Server {
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
database: bot.DB.Users,
|
||||
bot: bot.Telegram,
|
||||
httpServer: srv,
|
||||
buntdb: bot.Bunt,
|
||||
|
||||
@@ -18,7 +18,7 @@ type LndHub struct {
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) LndHub {
|
||||
return LndHub{database: bot.Database}
|
||||
return LndHub{database: bot.DB.Users}
|
||||
}
|
||||
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
auth := request.Header.Get("Authorization")
|
||||
|
||||
@@ -57,7 +57,7 @@ type Lnurl struct {
|
||||
func New(bot *telegram.TipBot) Lnurl {
|
||||
return Lnurl{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
database: bot.DB.Users,
|
||||
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
|
||||
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
|
||||
buntdb: bot.Bunt,
|
||||
@@ -229,7 +229,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
|
||||
descriptionHash, err := w.DescriptionHash(metadata, string(payerDataByte))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -281,8 +281,8 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
|
||||
}
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type ClientType string
|
||||
|
||||
const (
|
||||
ClientTypeClearNet = "clearnet"
|
||||
ClientTypeTor = "tor"
|
||||
)
|
||||
|
||||
func GetClient(clientType ClientType) (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
var cfg *internal.SocksConfiguration
|
||||
switch clientType {
|
||||
case ClientTypeClearNet:
|
||||
cfg = internal.Configuration.Bot.SocksProxy
|
||||
case ClientTypeTor:
|
||||
cfg = internal.Configuration.Bot.TorProxy
|
||||
default:
|
||||
return nil, fmt.Errorf("[GetClient] invalid clientType")
|
||||
}
|
||||
if cfg == nil {
|
||||
return &client, nil
|
||||
}
|
||||
proxyURL, _ := url.Parse(cfg.Host)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
var auth *proxy.Auth
|
||||
if cfg.Username != "" && cfg.Password != "" {
|
||||
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
|
||||
}
|
||||
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return &client, nil
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
client.Transport = specialTransport
|
||||
return &client, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// var retryMap cmap.ConcurrentMap
|
||||
|
||||
// func init() {
|
||||
// retryMap = cmap.New()
|
||||
// }
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type FunctionRetry struct {
|
||||
Ticker *time.Ticker
|
||||
duration time.Duration
|
||||
ctx context.Context
|
||||
name string
|
||||
}
|
||||
|
||||
type FunctionRetryOption func(*FunctionRetry)
|
||||
|
||||
func WithRetryDuration(d time.Duration) FunctionRetryOption {
|
||||
return func(a *FunctionRetry) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOption) *FunctionRetry {
|
||||
t := &FunctionRetry{
|
||||
name: name,
|
||||
ctx: ctx,
|
||||
}
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
case <-t.ctx.Done():
|
||||
if t.ctx.Err() == context.DeadlineExceeded {
|
||||
deadline_f()
|
||||
}
|
||||
if t.ctx.Err() == context.Canceled {
|
||||
cancel_f()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package satdress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Much of this is from github.com/fiatjaf/makeinvoice
|
||||
// but with added "checkInvoice" and http proxy support
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" gorm:"-"`
|
||||
CertString string `json:"certstring"`
|
||||
Host string `json:"host"`
|
||||
Macaroon string `json:"macaroon"`
|
||||
}
|
||||
|
||||
func (l LNDParams) getCert() []byte { return l.Cert }
|
||||
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
|
||||
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
|
||||
|
||||
type LNBitsParams struct {
|
||||
Cert string `json:"certstring"`
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
|
||||
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
|
||||
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
|
||||
|
||||
type BackendParams interface {
|
||||
getCert() []byte
|
||||
isTor() bool
|
||||
isLocal() bool
|
||||
}
|
||||
|
||||
type Params struct {
|
||||
Backend BackendParams
|
||||
Msatoshi int64
|
||||
Description string
|
||||
DescriptionHash []byte
|
||||
|
||||
Label string // only used for c-lightning
|
||||
}
|
||||
|
||||
type CheckInvoiceParams struct {
|
||||
Backend BackendParams
|
||||
PR string
|
||||
Hash []byte
|
||||
Status string
|
||||
}
|
||||
|
||||
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
|
||||
var client *http.Client
|
||||
if !useProxy {
|
||||
client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
client, err = network.GetClient(network.ClientTypeTor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
}
|
||||
// use a cert or skip TLS verification?
|
||||
if len(cert) > 0 {
|
||||
caCertPool := x509.NewCertPool()
|
||||
ok := caCertPool.AppendCertsFromPEM(cert)
|
||||
if !ok {
|
||||
return client, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// description hash?
|
||||
var hexh, b64h string
|
||||
if params.DescriptionHash != nil {
|
||||
hexh = hex.EncodeToString(params.DescriptionHash)
|
||||
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[MakeInvoice] LND invoice at %s", backend.Host)
|
||||
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
body, _ = sjson.Set(body, "memo", params.Description)
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "description_hash", b64h)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST",
|
||||
backend.Host+"/v1/invoices",
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// macaroon must be hex, so if it is on base64 we adjust that
|
||||
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
|
||||
backend.Macaroon = hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
checkInvoiceParams := CheckInvoiceParams{
|
||||
Backend: params.Backend,
|
||||
PR: gjson.ParseBytes(b).Get("payment_request").String(),
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[MakeInvoice] LNBits invoice at %s", backend.Host)
|
||||
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
|
||||
body, _ = sjson.Set(body, "out", false)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
if params.Description == "" {
|
||||
body, _ = sjson.Set(body, "memo", "invoice")
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "memo", params.Description)
|
||||
}
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "description_hash", hexh)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST",
|
||||
backend.Host+"/api/v1/payments",
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
checkInvoiceParams := CheckInvoiceParams{
|
||||
Backend: params.Backend,
|
||||
PR: gjson.ParseBytes(b).Get("payment_request").String(),
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("wrong backend type")
|
||||
}
|
||||
}
|
||||
|
||||
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[CheckInvoice] LND invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
|
||||
}
|
||||
hexHash := hex.EncodeToString(p)
|
||||
requestUrl, err := url.Parse(fmt.Sprintf("%s/v1/invoice/%s?r_hash=%s", backend.Host, hexHash, base64.StdEncoding.EncodeToString(params.Hash)))
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
requestUrl.Scheme = "https"
|
||||
req, err := http.NewRequest("GET",
|
||||
requestUrl.String(), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
// macaroon must be hex, so if it is on base64 we adjust that
|
||||
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
|
||||
backend.Macaroon = hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
params.Status = gjson.ParseBytes(b).Get("state").String()
|
||||
return params, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[CheckInvoice] LNBits invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
log.Debug("Getting ", backend.Host+"/api/v1/payments/"+string(params.Hash))
|
||||
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
status := strings.ToLower(gjson.ParseBytes(b).Get("paid").String())
|
||||
if status == "true" {
|
||||
params.Status = "SETTLED"
|
||||
} else {
|
||||
params.Status = "OPEN"
|
||||
}
|
||||
return params, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
}
|
||||
@@ -20,15 +20,12 @@ import (
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
DB *Databases
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
GroupsDb *gorm.DB
|
||||
logger *gorm.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
@@ -48,17 +45,15 @@ func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger, groupsDb := AutoMigration()
|
||||
dbs := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
Database: db,
|
||||
DB: dbs,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
logger: txLogger,
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
GroupsDb: groupsDb,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@ var (
|
||||
|
||||
func init() {
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
|
||||
user := LoadUser(ctx)
|
||||
// get 5 most recent transactions by from_id with distint to_user
|
||||
// where to_user starts with an @ and is not the user itself
|
||||
bot.logger.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
|
||||
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
|
||||
log.Debugf("[makeContactsButtons] found %d records", len(records))
|
||||
|
||||
// get all contacts and add them to the buttons
|
||||
|
||||
@@ -28,6 +28,12 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Databases struct {
|
||||
Users *gorm.DB
|
||||
Transactions *gorm.DB
|
||||
Groups *gorm.DB
|
||||
}
|
||||
|
||||
const (
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
@@ -86,7 +92,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
func AutoMigration() *Databases {
|
||||
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
@@ -100,7 +106,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
@@ -109,7 +115,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
groupsDb, err = gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
groupsDb, err := gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
@@ -117,7 +123,12 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return orm, txLogger, groupsDb
|
||||
|
||||
return &Databases{
|
||||
Users: orm,
|
||||
Transactions: txLogger,
|
||||
Groups: groupsDb,
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
@@ -126,7 +137,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
|
||||
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)
|
||||
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil {
|
||||
err := tx.Error
|
||||
if toUserDb.Wallet == nil {
|
||||
@@ -153,7 +164,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
// 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)}
|
||||
tx := bot.Database.First(user)
|
||||
tx := bot.DB.Users.First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
@@ -164,6 +175,21 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
tx := bot.DB.Users.Preload("Settings").First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetLnbitsUserWithSettings] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
user.Telegram = u
|
||||
return user, tx.Error
|
||||
}
|
||||
if user.Settings == nil {
|
||||
user.Settings = &lnbits.Settings{ID: user.ID}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetUser from Telegram user. Update the user if user information changed.
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
var user *lnbits.User
|
||||
@@ -245,7 +271,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
|
||||
}
|
||||
|
||||
tx := bot.Database.Save(user)
|
||||
tx := bot.DB.Users.Save(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
|
||||
@@ -304,7 +304,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Faucet from %s to %s (%d sat).", fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
|
||||
transactionMemo := fmt.Sprintf("🚰 Faucet from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineFaucet.PerUserAmount, TransactionType("faucet"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
|
||||
+38
-29
@@ -5,9 +5,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
@@ -83,23 +84,23 @@ var (
|
||||
)
|
||||
|
||||
var (
|
||||
groupAddGroupHelpMessage = "📖 Oops, that didn't work. Please try again.\nUsage: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"
|
||||
grouJoinGroupHelpMessage = "📖 Oops, that didn't work. Please try again.\nUsage: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"
|
||||
groupClickToJoinMessage = "🎟 [Click here](%s) 👈 to join `%s`."
|
||||
groupInvoiceMemo = "Ticket for group %s"
|
||||
groupPayInvoiceMessage = "🎟 To join the group %s, pay the invoice above."
|
||||
groupBotIsNotAdminMessage = "🚫 Oops, that didn't work. You must make me admin and grant me rights to invite users."
|
||||
groupNameExists = "🚫 A group with this name already exists. Please choose a different name."
|
||||
groupAddedMessage = "🎟 Tickets for group `%s` added.\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."
|
||||
groupNotFoundMessage = "🚫 Could not find a group with this name."
|
||||
groupReceiveTicketInvoiceCommission = "🎟 You received *%d sat* (excl. %d sat commission) for a ticket for group `%s` paid by user %s."
|
||||
groupReceiveTicketInvoice = "🎟 You received *%d sat* for a ticket for group `%s` paid by user %s."
|
||||
groupInvoiceMemo = "🎟 Ticket for group %s"
|
||||
)
|
||||
|
||||
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
|
||||
// handler to call depending on the <cmd> passed.
|
||||
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
user := LoadUser(ctx)
|
||||
if len(splits) == 1 {
|
||||
if ctx.Message().Private() {
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "groupHelpMessage"), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me)))
|
||||
} else {
|
||||
if bot.isOwner(ctx.Message().Chat, user.Telegram) {
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
} else if len(splits) > 1 {
|
||||
if splits[1] == "join" {
|
||||
@@ -132,15 +133,15 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
|
||||
splitIdx = 0
|
||||
}
|
||||
if len(splits) != splitIdx+2 || len(ctx.Message().Text) > 100 {
|
||||
bot.trySendMessage(ctx.Message().Chat, grouJoinGroupHelpMessage)
|
||||
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupJoinGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strings.ToLower(splits[splitIdx+1])
|
||||
|
||||
group := &Group{}
|
||||
tx := bot.GroupsDb.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error != nil {
|
||||
bot.trySendMessage(ctx.Message().Chat, groupNotFoundMessage)
|
||||
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupNotFoundMessage"))
|
||||
return ctx, fmt.Errorf("group not found")
|
||||
}
|
||||
|
||||
@@ -205,10 +206,12 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
|
||||
return ctx, err
|
||||
}
|
||||
ticketEvent.Message = bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoiceEvent.PaymentRequest)})
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(groupPayInvoiceMessage, groupName))
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "groupPayInvoiceMessage"), groupName))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
|
||||
// pay button is sent to the user.
|
||||
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
|
||||
// object that holds all information about the send payment
|
||||
// // // create inline buttons
|
||||
@@ -225,6 +228,7 @@ func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket Ticke
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
|
||||
func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &TicketEvent{Base: storage.New(storage.ID(c.Data))}
|
||||
@@ -316,7 +320,11 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidText"))
|
||||
}
|
||||
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(groupClickToJoinMessage, resp.Result.InviteLink, ticketEvent.Group.Title))
|
||||
// send confirmation text with the ticket to the user
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
|
||||
|
||||
// send a notification to the group that sold the ticket
|
||||
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
|
||||
// take a commission
|
||||
ticketSat := ticketEvent.Group.Ticket.Price
|
||||
@@ -326,7 +334,6 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
log.Errorf("[groupGetInviteLinkHandler] Could not get bot user from DB: %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 2% cut + 100 sat base fee
|
||||
commissionSat := ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.Cut/100 + ticketEvent.Group.Ticket.BaseFee
|
||||
if ticketEvent.Group.Ticket.Price <= 1000 {
|
||||
@@ -339,7 +346,7 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: commissionSat,
|
||||
Memo: "Ticket commission for group " + ticketEvent.Group.Title,
|
||||
Memo: "🎟 Ticket commission for group " + ticketEvent.Group.Title,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
@@ -350,7 +357,6 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
_, err = ticketEvent.User.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[groupGetInviteLinkHandler] Could not pay commission of %s: %s", GetUserStr(ticketEvent.User.Telegram), err)
|
||||
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
@@ -360,22 +366,23 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(groupReceiveTicketInvoiceCommission, ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
} else {
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(groupReceiveTicketInvoice, ticketSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// addGroupHandler is invoked if the user calls the "/group add" command
|
||||
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type == tb.ChatPrivate {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, fmt.Errorf("not in group")
|
||||
}
|
||||
// parse command "/group add <grou_name> [<amount>]"
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) < 3 || len(m.Text) > 100 {
|
||||
bot.trySendMessage(m.Chat, groupAddGroupHelpMessage)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strings.ToLower(splits[2])
|
||||
@@ -387,18 +394,18 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
}
|
||||
|
||||
if !bot.isAdminAndCanInviteUsers(m.Chat, bot.Telegram.Me) {
|
||||
bot.trySendMessage(m.Chat, groupBotIsNotAdminMessage)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupBotIsNotAdminMessage"))
|
||||
return ctx, fmt.Errorf("bot is not admin")
|
||||
}
|
||||
|
||||
// check if the group with this name is already in db
|
||||
// only if a group with this name is owned by this user, it can be overwritten
|
||||
group := &Group{}
|
||||
tx := bot.GroupsDb.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error == nil {
|
||||
// if it is already added, check if this user is the admin
|
||||
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
|
||||
bot.trySendMessage(m.Chat, groupNameExists)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
}
|
||||
@@ -430,13 +437,15 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
Ticket: ticket,
|
||||
}
|
||||
|
||||
bot.GroupsDb.Save(group)
|
||||
bot.DB.Groups.Save(group)
|
||||
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
|
||||
bot.trySendMessage(m.Chat, fmt.Sprintf(groupAddedMessage, str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// createGroupTicketInvoice produces an invoice for the group ticket with a
|
||||
// callback that then calls groupGetInviteLinkHandler upton payment
|
||||
func (bot *TipBot) createGroupTicketInvoice(ctx context.Context, payer *lnbits.User, group *Group, memo string, callback int, callbackData string) (*InvoiceEvent, error) {
|
||||
invoice, err := group.Ticket.Creator.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
|
||||
@@ -120,6 +120,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Handler: bot.payHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -136,6 +137,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -146,6 +148,37 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/node"},
|
||||
Handler: bot.nodeHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnSatdressCheckInvoice},
|
||||
Handler: bot.satdressCheckInvoiceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/shops"},
|
||||
Handler: bot.shopsHandler,
|
||||
@@ -183,6 +216,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -227,11 +261,51 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/transactions"},
|
||||
Handler: bot.transactionsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnLeftTransactionsButton},
|
||||
Handler: bot.transactionsScrollLeftHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnRightTransactionsButton},
|
||||
Handler: bot.transactionsScrollRightHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
|
||||
Handler: bot.faucetHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
|
||||
@@ -3,6 +3,7 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -60,11 +61,11 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
|
||||
// we print the anonymous ln address in the advanced help
|
||||
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous Lightning address: `%s`\n", lnaddr)
|
||||
}
|
||||
lnurl, err := UserGetLNURL(fromUser)
|
||||
lnurl, err := UserGetAnonLNURL(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
|
||||
}
|
||||
|
||||
// this is so stupid:
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
func (bot TipBot) inlineQueryInstructions(ctx intercept.Context) (intercept.Context, error) {
|
||||
instructions := []struct {
|
||||
|
||||
@@ -251,7 +251,7 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Co
|
||||
inlineReceive.Inactivate(inlineReceive, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineReceive from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
transactionMemo := fmt.Sprintf("💸 Receive from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineReceive.Amount, TransactionType("inline receive"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
|
||||
@@ -224,7 +224,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
inlineSend.Inactivate(inlineSend, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineSend from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
@@ -38,6 +39,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallbackInlineReceive: EventHandler{Function: bot.inlineReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +50,7 @@ const (
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -3,9 +3,10 @@ package telegram
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -52,7 +53,7 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"), tb.Silent)
|
||||
}()
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
@@ -105,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
}
|
||||
|
||||
var sentsigres lnurl.LNURLResponse
|
||||
client, err := bot.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
@@ -23,21 +26,22 @@ import (
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
DescriptionHash string `json:"descriptionHash,omitempty"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) {
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
@@ -74,11 +78,18 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
payParams.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// calculate description hash of the metadata and save it
|
||||
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payParams.DescriptionHash = descriptionHash
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
|
||||
|
||||
@@ -89,7 +100,7 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
} else if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
@@ -97,12 +108,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandlerSend(ctx)
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
@@ -143,7 +154,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
@@ -185,11 +196,28 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
|
||||
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
|
||||
}
|
||||
|
||||
// todo: doesn't work with lnurls from lnbits??
|
||||
// check whether description hash matches with expected hash
|
||||
// decode invoice
|
||||
// bolt11, err := decodepay.Decodepay(response2.PR)
|
||||
// if err != nil {
|
||||
// bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
// errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
|
||||
// log.Errorln(errmsg)
|
||||
// return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
// }
|
||||
// if bolt11.DescriptionHash != lnurlPayState.DescriptionHash {
|
||||
// log.Errorf("[lnurlPayHandlerSend] Error: description hash doesn't match")
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "description hash doesn't match.\nExpected: `"+lnurlPayState.DescriptionHash+"` Received: `"+bolt11.DescriptionHash+"`"))
|
||||
// return ctx, fmt.Errorf("description hash doesn't match")
|
||||
// }
|
||||
|
||||
// all good
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
@@ -4,10 +4,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -40,7 +42,7 @@ type LnurlWithdrawState struct {
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
Invoice lnbits.BitInvoice `json:"invoice"`
|
||||
Invoice lnbits.Invoice `json:"invoice"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
@@ -264,7 +266,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := bot.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
|
||||
+41
-23
@@ -2,13 +2,16 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
@@ -21,19 +24,7 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
client := http.Client{}
|
||||
if internal.Configuration.Bot.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
@@ -76,7 +67,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
@@ -102,7 +93,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{
|
||||
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
|
||||
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
|
||||
Caption: payParams.LNURLPayParams.Metadata.Description})
|
||||
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
|
||||
// display the metadata text from the first LNURL-p response
|
||||
// if there was no photo in the last step
|
||||
@@ -144,7 +135,6 @@ func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
name := fmt.Sprint(user.UUID)
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
|
||||
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
|
||||
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
@@ -153,8 +143,17 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
@@ -179,7 +178,7 @@ func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context,
|
||||
}
|
||||
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
|
||||
@@ -214,8 +213,13 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// rerun LNURLDecode to convert lnurlp/keyauth schemes to https://
|
||||
rawurl, err = lnurl.LNURLDecode(rawurl)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug("[HandleLNURL] rawurl: ", rawurl)
|
||||
parsed, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
@@ -239,7 +243,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -276,6 +280,20 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
|
||||
return rawurl, nil, fmt.Errorf("unkown LNURL response")
|
||||
}
|
||||
}
|
||||
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (bot *TipBot) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
} else {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
}
|
||||
return hashString, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
)
|
||||
|
||||
var (
|
||||
registerNodeMessage = "📖 Connect your Lightning node with your wallet.\n\nCurrently supported backends: `lnd` and `lnbits`\nTo register a node, type: `/node add <type> <info>`\n\n*LND (REST):* `/node add lnd <host> <macaroon> <cert>`\n*LNbits:* `/node add lnbits <host> <key>`\n\nℹ️ Always use `https://` for the `<host>`, even if you use a Tor node. Certificates and macaroons need to be in base64 format.\n\n⚠️ For security reasons, you should *only use an invoice macaroon* for LND and an *invoice key* for LNbits."
|
||||
nodeHelpMessage = "⚙️ *Commands:*\n`/node add <type> <info>` ✅ Add your node.\n`/node invoice <admount>` ⤵️ Fetch an invoice from your node.\n`/node proxy <amount>` 🔀 Proxy a payment to your node (privacy feature).\n`/node help` 📖 Show help."
|
||||
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
|
||||
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
|
||||
checkInvoiceButtonMessage = "🔄 Check invoice"
|
||||
routingInvoiceMessage = "🔄 Getting invoice from your node..."
|
||||
checkingNodeMessage = "🔄 Checking your node..."
|
||||
errorCouldNotAddNodeMessage = "❌ Could not add node. Please check your node details."
|
||||
gettingInvoiceOnlyErrorMessage = "❌ Error getting invoice from your node."
|
||||
gettingInvoiceErrorMessage = "❌ Error getting invoice from your node. Your funds are still available."
|
||||
payingInvoiceErrorMessage = "❌ Could not route payment. Your funds are still available."
|
||||
invoiceRoutedMessage = "✅ *Payment routed to your node.*"
|
||||
invoiceSettledMessage = "✅ *Invoice settled.*"
|
||||
nodeAddedMessage = "✅ *Node added.*"
|
||||
satdressCheckInvoicenMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnSatdressCheckInvoice = satdressCheckInvoicenMenu.Data(checkInvoiceButtonMessage, "satdress_check_invoice")
|
||||
)
|
||||
|
||||
// todo -- rename to something better like parse node settings or something
|
||||
func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.BackendParams, error) {
|
||||
// input is "/node add <Type> <Host> <Macaroon> <Cert>"
|
||||
params := satdress.LNDParams{}
|
||||
splits := strings.Split(m.Text, " ")
|
||||
splitlen := len(splits)
|
||||
if splitlen < 4 {
|
||||
return params, fmt.Errorf("not enough arguments")
|
||||
}
|
||||
switch strings.ToLower(splits[2]) {
|
||||
case "lnd":
|
||||
if splitlen < 5 || splitlen > 7 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> [<Cert>]")
|
||||
}
|
||||
host := splits[3]
|
||||
macaroon := splits[4]
|
||||
var pem []byte
|
||||
if splitlen == 6 {
|
||||
cert := splits[5]
|
||||
pem := parseCertificateToPem(cert)
|
||||
if len(pem) < 1 {
|
||||
return params, fmt.Errorf("certificate has invalid format")
|
||||
}
|
||||
}
|
||||
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
|
||||
return satdress.LNDParams{
|
||||
Cert: pem,
|
||||
Host: host,
|
||||
Macaroon: macaroon,
|
||||
CertString: string(pem),
|
||||
}, nil
|
||||
case "lnbits":
|
||||
if splitlen < 5 || splitlen > 6 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
|
||||
}
|
||||
host := splits[3]
|
||||
key := splits[4]
|
||||
|
||||
host = strings.TrimSuffix(host, "/")
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
return satdress.LNBitsParams{
|
||||
Host: host,
|
||||
Key: key,
|
||||
}, nil
|
||||
default:
|
||||
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
|
||||
}
|
||||
}
|
||||
|
||||
func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
|
||||
if len(node.NodeType) == 0 {
|
||||
return "", fmt.Errorf("node type is empty")
|
||||
}
|
||||
var node_info_str_filled string
|
||||
var node_info_str string
|
||||
switch strings.ToLower(node.NodeType) {
|
||||
case "lnd":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Macaroon:*\n\n`%s`\n\n*Cert:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNDParams.Host, node.LNDParams.Macaroon, node.LNDParams.CertString)
|
||||
case "lnbits":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Key:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNbitsParams.Host, node.LNbitsParams.Key)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown node type")
|
||||
}
|
||||
return fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled), nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.trySendMessage(ctx.Message().Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if user.Settings == nil {
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, fmt.Errorf("no node registered")
|
||||
}
|
||||
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, node_info_str)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) == 1 {
|
||||
return bot.getNodeHandler(ctx)
|
||||
} else if len(splits) > 1 {
|
||||
switch strings.ToLower(splits[1]) {
|
||||
case "invoice":
|
||||
return bot.invHandler(ctx)
|
||||
case "add":
|
||||
return bot.registerNodeHandler(ctx)
|
||||
case "check":
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
case "proxy":
|
||||
return bot.satdressProxyHandler(ctx)
|
||||
case "help":
|
||||
return bot.nodeHelpHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, checkingNodeMessage)
|
||||
|
||||
backendParams, err := parseUserSettingInput(ctx, m)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
switch backend := backendParams.(type) {
|
||||
case satdress.LNDParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// save node in db
|
||||
user.Settings.Node.LNDParams = &backend
|
||||
user.Settings.Node.NodeType = "lnd"
|
||||
case satdress.LNBitsParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
// save node in db
|
||||
user.Settings.Node.LNbitsParams = &backend
|
||||
user.Settings.Node.NodeType = "lnbits"
|
||||
|
||||
}
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
return ctx, err
|
||||
}
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
|
||||
|
||||
log.Infof("[node:add] Added node of user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.NodeType == "" {
|
||||
bot.trySendMessage(m.Sender, "You did not register a node yet.")
|
||||
return ctx, fmt.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
}
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = getAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("[node:invoice] Getting invoice for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
|
||||
switch user.Settings.Node.NodeType {
|
||||
case "lnd":
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
case "lnbits":
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
default:
|
||||
return ctx, fmt.Errorf("unknown node type %s", user.Settings.Node.NodeType)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceOnlyErrorMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(getInvoiceParams.PR, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", getInvoiceParams.PR)})
|
||||
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
log.Infof("[node:invoice] Invoice created for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// check if invoice settles
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
tgUser := LoadUser(ctx).Telegram
|
||||
user, err := GetLnbitsUserWithSettings(tgUser, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// get the getInvoiceParams from cache
|
||||
log.Debugf("[Cache] Getting key: %s", fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
|
||||
|
||||
// check the invoice
|
||||
|
||||
// check if there is an invoice check message in cache already
|
||||
check_message_interface, err := bot.Cache.Get(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash))
|
||||
var check_message *tb.Message
|
||||
if err != nil {
|
||||
// send a new message if there isn't one in the cache
|
||||
check_message = bot.trySendMessageEditable(tgUser, checkingInvoiceMessage)
|
||||
} else {
|
||||
check_message = check_message_interface.(*tb.Message)
|
||||
check_message, err = bot.tryEditMessage(check_message, checkingInvoiceMessage)
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// save it in the cache for another call later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash), check_message, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
|
||||
runtime.NewRetryTicker(deadLineCtx, "node_invoice_check", runtime.WithRetryDuration(5*time.Second)).Do(func() {
|
||||
// get invoice from user's node
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Checking invoice: %s", getInvoiceParams.Hash)
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
if getInvoiceParams.Status == "SETTLED" {
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice settled: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceSettledMessage)
|
||||
cancel()
|
||||
}
|
||||
|
||||
}, func() {
|
||||
// cancel
|
||||
},
|
||||
func() {
|
||||
// deadline
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice check expired: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceNotSettledMessage,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: checkInvoiceButtonMessage, Unique: "satdress_check_invoice"}},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func parseCertificateToPem(cert string) []byte {
|
||||
block, _ := pem.Decode([]byte(cert))
|
||||
if block != nil {
|
||||
// already PEM
|
||||
return []byte(cert)
|
||||
} else {
|
||||
var dec []byte
|
||||
|
||||
dec, err := hex.DecodeString(cert)
|
||||
if err != nil {
|
||||
// not HEX
|
||||
dec, err = base64.StdEncoding.DecodeString(cert)
|
||||
if err != nil {
|
||||
// not base54, we have a problem huston
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if block, _ := pem.Decode(dec); block != nil {
|
||||
return dec
|
||||
}
|
||||
// decoding went wrong
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return ctx, fmt.Errorf("no node settings.")
|
||||
}
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = getAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
memo := "🔀 Payment proxy in."
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
|
||||
log.Infof("[node] Proxy payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
user := invoiceEvent.User
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[node:proxy] Relaying payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
|
||||
// now relay the payment to the user's node
|
||||
var amount int64 = invoiceEvent.Amount
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
var err error
|
||||
if user.Settings.Node.NodeType == "lnd" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
} else if user.Settings.Node.NodeType == "lnbits" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
log.Infof("[node:proxy] Retrieved invoice for payment of user %s backend %s. Paying...", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
// verbose error message, turned off for now
|
||||
// if len(err.Error()) == 0 {
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(check_message, payingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("proxypay:%d:%d:%s", user.Telegram.ID, amount, RandStringRunes(8))
|
||||
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
Invoice: invoice.PaymentRequest,
|
||||
Hash: invoice.PaymentHash,
|
||||
Amount: amount,
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
|
||||
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(check_message, invoiceRoutedMessage)
|
||||
|
||||
log.Infof("[node:proxy] Proxy paid for user %s backend %s.", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
return
|
||||
}
|
||||
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -306,7 +307,7 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
|
||||
@@ -858,7 +858,7 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Conte
|
||||
log.Errorf("[shopConfirmBuyHandler] item has no price.")
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
transactionMemo := fmt.Sprintf("Buy item %s (%d sat).", toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("🛍 Shop from %s.", toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("shop"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
@@ -106,16 +107,16 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("🏅 Tip from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s: %s", Translate(ctx, "tipErrorMessage"), Translate(ctx, "tipUndefinedErrorMsg")))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
|
||||
@@ -279,7 +279,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
transactionMemo := fmt.Sprintf("🍯 Tipjar from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
|
||||
@@ -11,26 +11,26 @@ import (
|
||||
)
|
||||
|
||||
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 int64 `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 int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `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.Invoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
@@ -76,7 +76,7 @@ func (t *Transaction) Send() (success bool, err error) {
|
||||
}
|
||||
|
||||
// save transaction to db
|
||||
tx := t.Bot.logger.Save(t)
|
||||
tx := t.Bot.DB.Transactions.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
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 intercept.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 := start; i <= end; i++ {
|
||||
p := payments[i]
|
||||
if p.Pending {
|
||||
txstr += "🔄"
|
||||
} else {
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔴"
|
||||
} else {
|
||||
txstr += "🟢"
|
||||
}
|
||||
}
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2 Jan 06 15:04")
|
||||
txstr += fmt.Sprintf("` %s`", timestr)
|
||||
txstr += fmt.Sprintf("` %+d sat`", p.Amount/1000)
|
||||
if p.Fee > 0 {
|
||||
fee := p.Fee
|
||||
if fee < 1000 {
|
||||
fee = 1000
|
||||
}
|
||||
txstr += fmt.Sprintf(" _(fee: %d sat)_", fee/1000)
|
||||
}
|
||||
memo := p.Memo
|
||||
memo_maxlen := 50
|
||||
if len(memo) > memo_maxlen {
|
||||
memo = memo[:memo_maxlen] + "..."
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
txstr += fmt.Sprintf("\n✉️ %s", str.MarkdownEscape(memo))
|
||||
}
|
||||
txstr += "\n"
|
||||
}
|
||||
txstr += fmt.Sprintf("\nShowing %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
return txstr
|
||||
}
|
||||
|
||||
var (
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
|
||||
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
|
||||
)
|
||||
|
||||
func (bot *TipBot) makeTransactionsKeyboard(ctx intercept.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions", txlist.ID)
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions", txlist.ID)
|
||||
|
||||
if txlist.CurrentPage == 0 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton),
|
||||
)
|
||||
} else if txlist.CurrentPage == txlist.MaxPages-1 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
rightTransactionsButton),
|
||||
)
|
||||
} else {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
}
|
||||
return transactionsMeno
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
tx_per_page := 10
|
||||
transactionsList := 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,
|
||||
}
|
||||
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))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.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 ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
|
||||
transactionsList.CurrentPage++
|
||||
} else {
|
||||
return ctx, err
|
||||
}
|
||||
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 ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.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 ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage > 0 {
|
||||
transactionsList.CurrentPage--
|
||||
} else {
|
||||
return ctx, nil
|
||||
}
|
||||
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 ctx, nil
|
||||
}
|
||||
@@ -71,6 +71,10 @@ func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err er
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
if user.Wallet == nil {
|
||||
return 0, errors.New("User has no wallet")
|
||||
}
|
||||
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api/userpage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -53,12 +54,24 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
// append lnurl ctx functions
|
||||
lnUrl := lnurl.New(bot)
|
||||
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
|
||||
s.AppendRoute("/@{username}", lnUrl.Handle, http.MethodGet)
|
||||
// userpage server
|
||||
userpage := userpage.New(bot)
|
||||
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
|
||||
|
||||
// append lndhub ctx functions
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
|
||||
s.AppendRoute(`/lndhub/ext`, hub.Handle)
|
||||
//s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
|
||||
//s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
|
||||
|
||||
// starting api service
|
||||
apiService := api.Service{Bot: bot}
|
||||
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, bot.DB.Users, apiService.Balance, http.MethodGet)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
@@ -71,6 +84,9 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
|
||||
}
|
||||
|
||||
func withMiddleware(mw func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
|
||||
return mw
|
||||
}
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 282 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
@@ -118,15 +118,19 @@ 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 der Transaktionen
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
|
||||
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
|
||||
*/shop* 🛍 Durchsuche shops: `/shop` oder `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
enterAmountRangeMessage = """💯 Gebe Betrag zwuschen %d und %d sat ein."""
|
||||
enterAmountMessage = """💯 Gebe Betrag ein."""
|
||||
enterUserMessage = """👤 Gebe Benutzernamen ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
|
||||
+38
-2
@@ -121,10 +121,13 @@ 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*
|
||||
*/transactions* 📊 List 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>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
@@ -264,7 +267,7 @@ walletConnectMessage = """🔗 *Link your wallet*
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
|
||||
|
||||
- *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*."""
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, select *LNDHub* as Node interface, enter the URL, *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
|
||||
|
||||
@@ -348,3 +351,36 @@ inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/tipjar <capacity> <per_user>`
|
||||
*Example:* `/tipjar 210 21`"""
|
||||
|
||||
# GROUP TICKETS
|
||||
groupAddGroupHelpMessage = """📖 Oops, that didn't work. This command only works in a group chat. Only group owners can use this command.\nUsage: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"""
|
||||
groupJoinGroupHelpMessage = """📖 Oops, that didn't work. Please try again.\nUsage: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
groupClickToJoinMessage = """🎟 [Click here](%s) 👈 to join `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 User %s has received a ticket for this group."""
|
||||
groupPayInvoiceMessage = """🎟 To join the group %s, pay the invoice above."""
|
||||
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite users."""
|
||||
groupNameExists = """🚫 A group with this name already exists. Please choose a different name."""
|
||||
groupAddedMessage = """🎟 Tickets for group `%s` added.\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
|
||||
groupNotFoundMessage = """🚫 Could not find a group with this name."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 You received *%d sat* (excl. %d sat commission) for a ticket for group `%s` paid by user %s."""
|
||||
groupReceiveTicketInvoice = """🎟 You received *%d sat* for a ticket for group `%s` paid by user %s."""
|
||||
commandPrivateMessage = """Please use this command in a private chat with %s."""
|
||||
groupHelpMessage = """🎟 Private group tickets 🎟
|
||||
|
||||
Sell tickets for your _private Group_ and get rid of spam bots.
|
||||
|
||||
*Instructions for group admins:*
|
||||
|
||||
1) Invite %s to your group and make it admin.
|
||||
2) Make your group private.
|
||||
3) In your group, you (the group owner) write `/group add <mygroup> [<ticket_price>]`.
|
||||
|
||||
_Fees: The bot takes a 10%% +10 sat commission for cheap tickets. If the ticket is >= 1000 sat, the commission is 2%% + 100 sat._
|
||||
|
||||
*Instructions for group members:*
|
||||
|
||||
To join a group, talk to %s and write in a private message `/join <mygroup>`.
|
||||
|
||||
📖 *Usage:*
|
||||
*For admins (in group chat):* `/group add <group_name> [<ticket_price>]`\nExample: `/group add TheBestBitcoinGroup 1000`
|
||||
*For users (in private chat):* `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ 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 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>`"""
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
|
||||
@@ -121,10 +121,13 @@ advancedMessage = """%s
|
||||
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
|
||||
|
||||
⚙️ *Продвинутые команды*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
|
||||
|
||||
@@ -117,10 +117,13 @@ advancedMessage = """%s
|
||||
📖 İnline komutları her sohbette ve hatta özel mesajlarda kullanabilirsin. Komutu yazdıktan sonra bir saniye bekle ve Enter yazmak yerine sonuca *tıkla*.
|
||||
|
||||
⚙️ *Gelişmiş komutlar*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
|
||||
|
||||
Reference in New Issue
Block a user