Compare commits
163
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
863058ccb5 | ||
|
|
c561ae24d3 | ||
|
|
d5ff4867c0 | ||
|
|
1f5a6a5a31 | ||
|
|
e8f24d99ee | ||
|
|
b9bf071de9 | ||
|
|
ced9446287 | ||
|
|
94ed7d4692 | ||
|
|
d3c2fe7117 | ||
|
|
5c950ef1be | ||
|
|
51ac159072 | ||
|
|
857649150d | ||
|
|
842a037029 | ||
|
|
5aa76f86da | ||
|
|
e170394eb8 | ||
|
|
65842b056d | ||
|
|
979d3c58a2 | ||
|
|
b4cb695e33 | ||
|
|
89552a73b7 | ||
|
|
d5f18a0d3a | ||
|
|
e24490b05c | ||
|
|
f288bb05f6 | ||
|
|
3055f6d317 | ||
|
|
f19a6dd6cc | ||
|
|
cd55ee075b | ||
|
|
9d3f856d02 | ||
|
|
f2b59140fa | ||
|
|
c21d42d1e8 | ||
|
|
2dd2dde231 | ||
|
|
5e3432fe32 | ||
|
|
c6df59e51b | ||
|
|
b4081df2fa | ||
|
|
9b9ceb8793 | ||
|
|
3069126971 | ||
|
|
b56f5e73b0 | ||
|
|
42efc918c1 | ||
|
|
8c75f2f947 | ||
|
|
7d9c0d0c8a | ||
|
|
b77f92c9b2 | ||
|
|
ec2de611e4 | ||
|
|
1b69313fc5 | ||
|
|
55fc5eaa54 | ||
|
|
6bc6ef215a | ||
|
|
52ac3bfc13 | ||
|
|
fea7281e29 | ||
|
|
d992d5858f | ||
|
|
2569f0d12e | ||
|
|
6bdd24e4a3 | ||
|
|
3c862d59ff | ||
|
|
2c4d499cd9 | ||
|
|
2e4a793c20 | ||
|
|
890448ce81 | ||
|
|
08d6a0e369 | ||
|
|
069029fbb3 | ||
|
|
92f9ba1550 | ||
|
|
98bc70fc7c | ||
|
|
1ee38a2989 | ||
|
|
3353bedc7a | ||
|
|
30c1e3231d | ||
|
|
a3ed8ab931 | ||
|
|
3772f056a8 | ||
|
|
65d933a6d5 | ||
|
|
4038a03184 | ||
|
|
2c8a653c3a | ||
|
|
03509adcd1 | ||
|
|
74655219f3 | ||
|
|
74c057ce8e | ||
|
|
0aeec7e488 | ||
|
|
921395d283 | ||
|
|
9b2c23cab5 | ||
|
|
3c45a80627 | ||
|
|
62c2cbab5f | ||
|
|
ab82b49ff5 | ||
|
|
025261d595 | ||
|
|
ed6ea4d33c | ||
|
|
69559f8aff | ||
|
|
00406553e4 | ||
|
|
c237e55a29 | ||
|
|
24b2c2413c | ||
|
|
cb19e7375a | ||
|
|
55ba146592 | ||
|
|
52230d486e | ||
|
|
c8e45de27d | ||
|
|
6a01936c2e | ||
|
|
48374ad2a1 | ||
|
|
5b5f0ef6a2 | ||
|
|
b618b1aa41 | ||
|
|
c5f106187f | ||
|
|
f35473b010 | ||
|
|
359ae13057 | ||
|
|
8d0bf2cce7 | ||
|
|
f5c3d9fb55 | ||
|
|
56c391b24e | ||
|
|
cbdc8638bd | ||
|
|
046baab3e1 | ||
|
|
f0f3a7c5d0 | ||
|
|
43eb4966bc | ||
|
|
0d112e19de | ||
|
|
649be03c29 | ||
|
|
5e4c045312 | ||
|
|
44f397e2de | ||
|
|
9451032552 | ||
|
|
8180d3cfae | ||
|
|
f11ac3d807 | ||
|
|
cb02fd557f | ||
|
|
ac3ac51d7b | ||
|
|
ac9cc644eb | ||
|
|
545898dbbe | ||
|
|
d98aa26db9 | ||
|
|
13c0f3b70a | ||
|
|
3a4f99314d | ||
|
|
a0f7cf09e6 | ||
|
|
0ff0d889ff | ||
|
|
7009d3dedc | ||
|
|
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 | ||
|
|
8729011aaf | ||
|
|
e5928defd0 | ||
|
|
cf68245012 | ||
|
|
e7fa555506 | ||
|
|
0eaf96749f | ||
|
|
cfde78e639 |
@@ -58,7 +58,7 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
|
||||
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
|
||||
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
|
||||
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
|
||||
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zeus support, optional).
|
||||
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
|
||||
|
||||
## Features
|
||||
@@ -116,7 +116,7 @@ Users can send and receive via . For this to work, you need to set the `lnurl_pu
|
||||
|
||||
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
|
||||
|
||||
### Link to BlueWallet or Zap
|
||||
### Link to BlueWallet or Zeus
|
||||
|
||||
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
|
||||
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
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"
|
||||
lnurl_image: true
|
||||
admin_api_host: localhost:6060
|
||||
telegram:
|
||||
message_dispose_duration: 10
|
||||
api_key: "1234"
|
||||
@@ -18,3 +25,7 @@ database:
|
||||
transactions_path: "data/transactions.db"
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
groupsdb_path: "data/groups.db"
|
||||
generate:
|
||||
dalle_key: "asd"
|
||||
dalle_price: 1000
|
||||
worker: 2
|
||||
@@ -0,0 +1 @@
|
||||
this is where dalle images are stored
|
||||
@@ -5,9 +5,9 @@ go 1.17
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/PuerkitoBio/goquery v1.8.0
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
|
||||
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.3-0.20220819192234-5c5819dd0aa7
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
@@ -17,18 +17,82 @@ require (
|
||||
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/r3labs/sse v0.0.0-20210224172625-26fe804710bc
|
||||
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.12.1
|
||||
github.com/tidwall/sjson v1.2.4
|
||||
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8
|
||||
golang.org/x/text v0.3.6
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
|
||||
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
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
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/dillonstreator/dalle v0.0.0-20220826164958-b15c236ceadc // 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.5.0 // 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/cenkalti/backoff.v1 v1.1.0 // indirect
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd // 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.v3 => ../telebot
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (s Service) DisableDalle(w http.ResponseWriter, r *http.Request) {
|
||||
dalle.Enabled = false
|
||||
}
|
||||
|
||||
func (s Service) EnableDalle(w http.ResponseWriter, r *http.Request) {
|
||||
dalle.Enabled = true
|
||||
}
|
||||
@@ -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,163 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/r3labs/sse"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
type InvoiceStream struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
w.Header().Set("Content-Type", "application/stream+json")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
flusher, err := w.(http.Flusher)
|
||||
if !err {
|
||||
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
client := sse.NewClient(fmt.Sprintf("%s/api/v1/payments/sse", internal.Configuration.Lnbits.Url))
|
||||
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
|
||||
client.Subscribe("", func(msg *sse.Event) {
|
||||
if msg.Data != nil {
|
||||
fmt.Fprintf(w, "%s\n", string(msg.Data))
|
||||
flusher.Flush()
|
||||
}
|
||||
})
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
@@ -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,100 @@ 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: "Bearer", Decoder: base64.StdEncoding.DecodeString}
|
||||
var AuthTypeNone = AuthType{}
|
||||
|
||||
// invoice key or admin key requirement
|
||||
type AccessKeyType struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
|
||||
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
|
||||
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
|
||||
|
||||
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if accessType.Type == "none" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
auth := r.Header.Get("Authorization")
|
||||
// check if the user is banned
|
||||
if auth == "" {
|
||||
w.WriteHeader(401)
|
||||
log.Warn("[api] 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("[api] 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{}
|
||||
var tx *gorm.DB
|
||||
if accessType.Type == "admin" {
|
||||
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
} else if accessType.Type == "invoice" {
|
||||
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
|
||||
} else {
|
||||
log.Errorf("[api] route without access type")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[api] could not load access key: %v", tx.Error)
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
|
||||
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 := authType.Decoder(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 {
|
||||
|
||||
+11
-3
@@ -5,6 +5,8 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -23,8 +25,8 @@ func NewServer(address string) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: address,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 90 * time.Second,
|
||||
ReadTimeout: 90 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
httpServer: srv,
|
||||
@@ -32,7 +34,7 @@ func NewServer(address string) *Server {
|
||||
apiServer.router = mux.NewRouter()
|
||||
apiServer.httpServer.Handler = apiServer.router
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[API] Server started at %s", address)
|
||||
log.Infof("[api] Server started at %s", address)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
@@ -42,6 +44,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, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, accessType, 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,387 @@
|
||||
<!-- @format -->
|
||||
|
||||
{{define "webapp"}}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="MobileOptimized" content="176" />
|
||||
<meta name="HandheldFriendly" content="True" />
|
||||
<meta name="robots" content="noindex,nofollow" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
|
||||
|
||||
<title>@LightningTipBot</title>
|
||||
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
|
||||
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
|
||||
<script>
|
||||
function setThemeClass() {
|
||||
document.documentElement.className = Telegram.WebApp.colorScheme;
|
||||
}
|
||||
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
|
||||
setThemeClass();
|
||||
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
background-color: var(--tg-theme-bg-color, #ffffff);
|
||||
color: var(--tg-theme-text-color, #222222);
|
||||
font-size: 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color-scheme: var(--tg-color-scheme);
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--tg-theme-link-color, #2678b6);
|
||||
}
|
||||
|
||||
button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
border: none;
|
||||
background-color: var(--tg-theme-button-color, #50a8eb);
|
||||
color: var(--tg-theme-button-text-color, #ffffff);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--tg-theme-button-color, #50a8eb);
|
||||
color: var(--tg-theme-button-text-color, #ffffff);
|
||||
}
|
||||
|
||||
button[disabled] {
|
||||
opacity: 0.6;
|
||||
cursor: auto;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
input {
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
border: none;
|
||||
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
|
||||
color: var(--tg-theme-text-color, #1a1a1a) !important;
|
||||
}
|
||||
|
||||
.input-group-text {
|
||||
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
|
||||
color: var(--tg-theme-text-color, #1a1a1a) !important;
|
||||
}
|
||||
|
||||
section {
|
||||
padding: 5px 5px 65px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 40px 0 15px;
|
||||
}
|
||||
|
||||
ul {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
li {
|
||||
color: var(--tg-theme-hint-color, #a8a8a8);
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 7px;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: rgba(0, 0, 0, .07);
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
margin: 7px 0;
|
||||
word-break: break-all;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dark pre {
|
||||
background: rgba(255, 255, 255, .15);
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: .8em;
|
||||
color: var(--tg-theme-hint-color, #a8a8a8);
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: green;
|
||||
}
|
||||
|
||||
.err {
|
||||
color: red;
|
||||
}
|
||||
|
||||
#fixed_wrap {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
transform: translateY(100vh);
|
||||
}
|
||||
|
||||
.viewport_border,
|
||||
.viewport_stable_border {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
height: var(--tg-viewport-height, 100vh);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.viewport_stable_border {
|
||||
height: var(--tg-viewport-stable-height, 100vh);
|
||||
}
|
||||
|
||||
.viewport_border:before,
|
||||
.viewport_stable_border:before {
|
||||
content: attr(text);
|
||||
display: inline-block;
|
||||
position: absolute;
|
||||
background: gray;
|
||||
right: 0;
|
||||
top: 0;
|
||||
font-size: 7px;
|
||||
padding: 2px 4px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.viewport_stable_border:before {
|
||||
background: green;
|
||||
left: 0;
|
||||
right: auto;
|
||||
}
|
||||
|
||||
.viewport_border:after,
|
||||
.viewport_stable_border:after {
|
||||
content: '';
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
border: 2px dashed gray;
|
||||
}
|
||||
|
||||
.viewport_stable_border:after {
|
||||
border-color: green;
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 120%;
|
||||
word-wrap: break-word;
|
||||
margin: 0.5em;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.qr {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 0px;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
}
|
||||
|
||||
.qr > canvas {
|
||||
max-height: 800px;
|
||||
max-width: 800px;
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
display: grid;
|
||||
grid-template-columns: 3fr 2fr;
|
||||
padding: 12px 20px;
|
||||
column-gap: 10px;
|
||||
row-gap: 1em;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<section>
|
||||
<h1 id="greeting"></h1>
|
||||
|
||||
<div class="qr-container">
|
||||
<div class="qr" id="qr">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="buttons">
|
||||
<!-- <button onclick="webviewClose();">Close</button> -->
|
||||
<div class="wrapper">
|
||||
<label class="sr-only" for="inlineFormInputGroup">Username</label>
|
||||
<div class="input-group">
|
||||
<input type="number" class="form-control" min="1" inputmode="numeric" pattern="[0-9]*" id="invoiceAmount" placeholder="amount">
|
||||
<div class="input-group-append">
|
||||
<div class="input-group-text" id="inputCurrency"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn btn-primary" onclick="invoiceButtonClick();" style="display: inline;" id="requestInvoice">Invoice</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script type="application/javascript">
|
||||
Telegram.WebApp.ready();
|
||||
|
||||
// render the LNURL pay QR code
|
||||
var s = "{{.LNURLPay}}";
|
||||
const currencies = ["sat", "USD", "EUR"];
|
||||
var currency_idx = 0;
|
||||
document.getElementById("inputCurrency").innerHTML = currencies[0];
|
||||
|
||||
renderQr(s);
|
||||
|
||||
// data passed form telegram server
|
||||
const initData = Telegram.WebApp.initData || '';
|
||||
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
|
||||
|
||||
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
|
||||
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
|
||||
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
|
||||
|
||||
// react to theme changes
|
||||
try {
|
||||
document.querySelector('#themeData').html(JSON.stringify(Telegram.WebApp.themeParams, null, 2));
|
||||
Telegram.WebApp.onEvent('themeChanged', function() {
|
||||
document.querySelector('#themeData').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
|
||||
// listen for enter in input field
|
||||
var el = document.getElementById("invoiceAmount");
|
||||
el.addEventListener("keydown", function(event) {
|
||||
if (event.key === "Enter") {
|
||||
document.getElementById("requestInvoice").click();
|
||||
}
|
||||
document.getElementById("requestInvoice").innerHTML = "Invoice"
|
||||
// revert color of button
|
||||
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
|
||||
});
|
||||
|
||||
var el = document.getElementById("inputCurrency");
|
||||
el.addEventListener("click", function(event) {
|
||||
currency_idx += 1;
|
||||
$(this).html(currencies[currency_idx%(currencies.length)]);
|
||||
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
|
||||
});
|
||||
|
||||
// ------------------ functions ------------------
|
||||
|
||||
function invoiceButtonClick() {
|
||||
var c = "{{.Callback}}";
|
||||
getInvoice(this, c);
|
||||
// hide keyboard and scroll up
|
||||
document.getElementById("invoiceAmount").blur();
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
function invoiceButtonDisplayError(message) {
|
||||
btn = document.getElementById("requestInvoice")
|
||||
btn.innerHTML = message
|
||||
// update color of button
|
||||
$('#requestInvoice').removeClass('btn-primary').addClass('btn-danger');
|
||||
}
|
||||
|
||||
function webviewClose() {
|
||||
Telegram.WebApp.close();
|
||||
}
|
||||
|
||||
function renderQr(payload) {
|
||||
const qr = document.getElementById('qr');
|
||||
qr.innerHTML = '';
|
||||
if ( qr ) {
|
||||
const qrGfx = kjua({
|
||||
text: payload,
|
||||
rounded: 50,
|
||||
size: 500,
|
||||
render: 'canvas',
|
||||
});
|
||||
qr.appendChild( qrGfx );
|
||||
// var href_link = "lightning:" + payload;
|
||||
// qr.setAttribute('href', "javascript:window.open('"+ href_link+ "');" );
|
||||
}
|
||||
}
|
||||
|
||||
function getInvoice(el, callback) {
|
||||
curr_idx = currency_idx%currencies.length
|
||||
var invoiceAmount = Number(document.getElementById("invoiceAmount").value);
|
||||
if ((currencies[curr_idx] == "sat" && !Number.isInteger(invoiceAmount)) || invoiceAmount < 1) {
|
||||
invoiceButtonDisplayError("Invalid")
|
||||
return false;
|
||||
}
|
||||
var amountQueryParam;
|
||||
if (currencies[curr_idx] == "sat") {
|
||||
amountQueryParam = invoiceAmount * 1000 // sat to msat
|
||||
} else {
|
||||
amountQueryParam = invoiceAmount + currencies[curr_idx]
|
||||
}
|
||||
fetch(callback)
|
||||
.then(data => {
|
||||
return data.json();
|
||||
})
|
||||
.then(r => {
|
||||
console.log(r);
|
||||
console.log("requesting invoice with amount " + amountQueryParam);
|
||||
fetch(r.callback + '?amount='+ amountQueryParam).then(data => {
|
||||
return data.json();
|
||||
})
|
||||
.then(r => {
|
||||
console.log(r);
|
||||
if (r.status == "OK"){
|
||||
// update qr code
|
||||
renderQr(r.pr);
|
||||
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
|
||||
} else {
|
||||
invoiceButtonDisplayError("Error")
|
||||
return false;
|
||||
}
|
||||
|
||||
})
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
{{end}}
|
||||
@@ -31,7 +31,8 @@ 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 userpage_tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
|
||||
var qr_tmpl = template.Must(template.ParseFS(templates, "static/webapp.html"))
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
@@ -67,7 +68,7 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
}
|
||||
|
||||
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/.well-known/lnurlp/<username>
|
||||
// https://ln.tips/@<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)
|
||||
@@ -82,7 +83,7 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
image = botImage
|
||||
}
|
||||
|
||||
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
Username string
|
||||
Image string
|
||||
LNURLPay string
|
||||
@@ -90,3 +91,22 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/app/<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 webapp of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
return
|
||||
}
|
||||
if err := qr_tmpl.ExecuteTemplate(w, "webapp", struct {
|
||||
Username string
|
||||
LNURLPay string
|
||||
Callback string
|
||||
}{username, lnurlEncode, callback}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
|
||||
+21
-7
@@ -14,16 +14,30 @@ var Configuration = struct {
|
||||
Telegram TelegramConfiguration `yaml:"telegram"`
|
||||
Database DatabaseConfiguration `yaml:"database"`
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
Generate GenerateConfiguration `yaml:"generate"`
|
||||
}{}
|
||||
|
||||
type GenerateConfiguration struct {
|
||||
DalleKey string `yaml:"dalle_key"`
|
||||
DallePrice int64 `yaml:"dalle_price"`
|
||||
Worker int `yaml:"worker"`
|
||||
}
|
||||
|
||||
type SocksConfiguration struct {
|
||||
Host string `yaml:"host"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
type BotConfiguration struct {
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
SocksProxy string `yaml:"socks_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"`
|
||||
AdminAPIHost string `yaml:"admin_api_host"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package dalle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"io"
|
||||
)
|
||||
|
||||
var Enabled bool
|
||||
|
||||
func init() {
|
||||
if internal.Configuration.Generate.DalleKey != "" {
|
||||
Enabled = true
|
||||
}
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
Generate(ctx context.Context, prompt string) (*Task, error)
|
||||
ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error)
|
||||
GetTask(ctx context.Context, taskID string) (*Task, error)
|
||||
Download(ctx context.Context, generationID string) (io.ReadCloser, error)
|
||||
Share(ctx context.Context, generationID string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dalle
|
||||
|
||||
const (
|
||||
StatusPending = "pending"
|
||||
StatusRejected = "rejected"
|
||||
StatusSucceeded = "succeeded"
|
||||
|
||||
TaskTypeText2Im = "text2im"
|
||||
|
||||
defaultBatchSize = 4
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
package dalle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
libraryVersion = "1.0.0"
|
||||
defaultUserAgent = "dalle/" + libraryVersion
|
||||
baseURL = "https://labs.openai.com/api/labs"
|
||||
|
||||
defaultHTTPClientTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type option func(*HTTPClient) error
|
||||
|
||||
func WithHTTPClient(httpClient *http.Client) option {
|
||||
return func(c *HTTPClient) error {
|
||||
c.httpClient = httpClient
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithUserAgent(userAgent string) option {
|
||||
return func(c *HTTPClient) error {
|
||||
c.userAgent = userAgent
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type HTTPClient struct {
|
||||
httpClient *http.Client
|
||||
userAgent string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
var _ Client = (*HTTPClient)(nil)
|
||||
|
||||
func NewHTTPClient(apiKey string, opts ...option) (*HTTPClient, error) {
|
||||
c := &HTTPClient{
|
||||
httpClient: &http.Client{Timeout: defaultHTTPClientTimeout},
|
||||
userAgent: defaultUserAgent,
|
||||
apiKey: apiKey,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
if err := opt(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
Object string `json:"object"`
|
||||
ID string `json:"id"`
|
||||
Created int64 `json:"created"`
|
||||
TaskType string `json:"task_type"`
|
||||
Status string `json:"status"`
|
||||
PromptID string `json:"prompt_id"`
|
||||
Prompt Prompt `json:"prompt"`
|
||||
Generations Generations `json:"generations"`
|
||||
}
|
||||
type Generations struct {
|
||||
Data []GenerationData `json:"data"`
|
||||
Object string `json:"object"`
|
||||
}
|
||||
type GenerationData struct {
|
||||
Created int64 `json:"created"`
|
||||
Generation Generation `json:"generation"`
|
||||
GenerationType string `json:"generation_type"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
type Generation struct {
|
||||
ImagePath string `json:"image_path"`
|
||||
}
|
||||
|
||||
type Prompt struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
PromptType string `json:"prompt_type"`
|
||||
Prompt struct {
|
||||
Caption string `json:"caption"`
|
||||
} `json:"prompt"`
|
||||
ParentGenerationID string `json:"parent_generation_id"`
|
||||
}
|
||||
|
||||
type GenerateRequest struct {
|
||||
Prompt GenerateRequestPrompt `json:"prompt"`
|
||||
TaskType string `json:"task_type"`
|
||||
}
|
||||
type GenerateRequestPrompt struct {
|
||||
BatchSize int32 `json:"batch_size"`
|
||||
Caption string `json:"caption"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Generate(ctx context.Context, caption string) (*Task, error) {
|
||||
task := &Task{}
|
||||
req := &GenerateRequest{
|
||||
Prompt: GenerateRequestPrompt{
|
||||
BatchSize: defaultBatchSize,
|
||||
Caption: caption,
|
||||
},
|
||||
TaskType: TaskTypeText2Im,
|
||||
}
|
||||
return task, c.request(ctx, "POST", "/tasks", nil, req, task)
|
||||
}
|
||||
|
||||
type ListTasksResponse struct {
|
||||
Object string `json:"object"`
|
||||
Data []Task `json:"data"`
|
||||
}
|
||||
|
||||
type ListTasksRequest struct {
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
|
||||
res := &ListTasksResponse{}
|
||||
url := "/tasks"
|
||||
if req != nil {
|
||||
if req.Limit != 0 {
|
||||
url += fmt.Sprintf("?limit=%d", req.Limit)
|
||||
}
|
||||
}
|
||||
|
||||
return res, c.request(ctx, "GET", url, nil, nil, res)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetTask(ctx context.Context, taskID string) (*Task, error) {
|
||||
task := &Task{}
|
||||
return task, c.request(ctx, "GET", "/tasks/"+taskID, nil, nil, task)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Download(ctx context.Context, generationID string) (io.ReadCloser, error) {
|
||||
req, err := c.createRequest(ctx, "/generations/"+generationID+"/download", "GET", nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("performing request: %w", err)
|
||||
}
|
||||
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// Share makes the generation public and returns the public url
|
||||
func (c *HTTPClient) Share(ctx context.Context, generationID string) (string, error) {
|
||||
res := &GenerationData{}
|
||||
|
||||
err := c.request(ctx, "POST", "/generations/"+generationID+"/share", nil, nil, res)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return res.Generation.ImagePath, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) createRequest(ctx context.Context, path, method string, values *url.Values, data interface{}) (*http.Request, error) {
|
||||
url := baseURL + path
|
||||
|
||||
if values != nil {
|
||||
url += "?" + values.Encode()
|
||||
}
|
||||
|
||||
var body io.Reader
|
||||
if data != nil {
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing request data: %w", err)
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, url, body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("building request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Add("Authorization", "Bearer "+c.apiKey)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) request(ctx context.Context, method, path string, values *url.Values, body interface{}, result interface{}) error {
|
||||
req, err := c.createRequest(ctx, path, method, values, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("performing request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
|
||||
// TODO: improve error handling...
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return Error{
|
||||
Message: "unexpected non 200 status code",
|
||||
StatusCode: resp.StatusCode,
|
||||
Details: string(respBody),
|
||||
}
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(respBody, result); err != nil {
|
||||
return Error{
|
||||
Message: err.Error(),
|
||||
StatusCode: resp.StatusCode,
|
||||
Details: string(respBody),
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Message string
|
||||
StatusCode int
|
||||
Details string
|
||||
}
|
||||
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("dalle: %s (status: %d, details: %s)", e.Message, e.StatusCode, e.Details)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
@@ -84,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",
|
||||
@@ -131,7 +132,7 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet payments
|
||||
// Payments returns wallet payments
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
@@ -155,6 +156,30 @@ func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
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)
|
||||
@@ -174,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",
|
||||
|
||||
+24
-16
@@ -7,7 +7,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
"github.com/btcsuite/btcd/btcec/v2"
|
||||
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -64,6 +65,7 @@ const (
|
||||
UserStateShopItemSendPrice
|
||||
UserStateShopItemSendItemFile
|
||||
UserEnterShopsDescription
|
||||
UserEnterDallePrompt
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
@@ -74,11 +76,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 {
|
||||
@@ -100,14 +103,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 {
|
||||
@@ -119,7 +119,7 @@ type Wallet struct {
|
||||
User string `json:"user"`
|
||||
}
|
||||
|
||||
type Payments []struct {
|
||||
type Payment struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
@@ -135,17 +135,25 @@ type Payments []struct {
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
type BitInvoice struct {
|
||||
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) {
|
||||
@@ -157,7 +165,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)
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
c.Function(txInvoiceEvent)
|
||||
go c.Function(txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
package lndhub
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -21,48 +17,5 @@ func New(bot *telegram.TipBot) LndHub {
|
||||
return LndHub{database: bot.DB.Users}
|
||||
}
|
||||
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
auth := request.Header.Get("Authorization")
|
||||
|
||||
// check if the user is banned
|
||||
if auth != "" {
|
||||
_, password, ok := parseBearerAuth(auth)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
log.Warnf("[LNDHUB] 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 := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
|
||||
}
|
||||
// if not, proxy the request
|
||||
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
|
||||
}
|
||||
|
||||
// parseBearerAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseBearerAuth(auth string) (username, password string, ok bool) {
|
||||
const prefix = "Bearer "
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
+19
-11
@@ -81,11 +81,19 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
|
||||
var amount int64
|
||||
if amount, err = strconv.ParseInt(stringAmount, 10, 64); err != nil {
|
||||
// if the value wasn't a clean msat denomination, parse it
|
||||
amount, err = telegram.GetAmount(stringAmount)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int: %v", err))
|
||||
return
|
||||
}
|
||||
// GetAmount returns sat, we need msat
|
||||
amount *= 1000
|
||||
}
|
||||
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
@@ -95,11 +103,11 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
// payer data
|
||||
payerdata := request.FormValue("payerdata")
|
||||
var payerData lnurl.PayerDataValues
|
||||
err := json.Unmarshal([]byte(payerdata), &payerData)
|
||||
err = json.Unmarshal([]byte(payerdata), &payerData)
|
||||
if err != nil {
|
||||
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
|
||||
fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
|
||||
fmt.Errorf("[handleLnUrl] payerdata: %v", payerdata)
|
||||
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
|
||||
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
|
||||
}
|
||||
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
|
||||
@@ -184,7 +192,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d sat, max: %d sat).", MinSendable/1000, MaxSendable/1000)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
@@ -229,7 +237,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 +289,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 {
|
||||
|
||||
+40
-32
@@ -2,6 +2,7 @@ package network
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -12,41 +13,48 @@ import (
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
func GetHttpClient() (*http.Client, error) {
|
||||
type ClientType string
|
||||
|
||||
const (
|
||||
ClientTypeClearNet = "clearnet"
|
||||
ClientTypeTor = "tor"
|
||||
)
|
||||
|
||||
func GetClient(clientType ClientType) (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
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 GetSocksClient() (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
if internal.Configuration.Bot.SocksProxy != "" {
|
||||
proxyURL, _ := url.Parse(internal.Configuration.Bot.SocksProxy)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
d, err := proxy.SOCKS5("tcp", internal.Configuration.Bot.SocksProxy, nil, &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
|
||||
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
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@ package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -2,33 +2,26 @@ package satdress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
"golang.org/x/net/proxy"
|
||||
"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
|
||||
|
||||
var Client, _ = network.GetSocksClient()
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" gorm:"-"`
|
||||
CertString string `json:"certstring"`
|
||||
@@ -73,39 +66,31 @@ type CheckInvoiceParams struct {
|
||||
}
|
||||
|
||||
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
|
||||
specialTransport := &http.Transport{}
|
||||
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")
|
||||
return client, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
|
||||
// use a proxy?
|
||||
var HttpProxyURL = internal.Configuration.Bot.SocksProxy
|
||||
if useProxy && len(HttpProxyURL) > 0 {
|
||||
proxyURL, _ := url.Parse(HttpProxyURL)
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
d, err := proxy.SOCKS5("tcp", HttpProxyURL, nil, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
return Client, err
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
}
|
||||
Client.Transport = specialTransport
|
||||
return Client, nil
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -34,11 +35,13 @@ func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
// log.Errorln(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
}
|
||||
amount, err = getAmount(strings.Split(input, " ")[1])
|
||||
amount, err = GetAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int64, err error) {
|
||||
// GetAmount parses an amount from a string like 1.2k or 3.50€
|
||||
// and returns the value in satoshis
|
||||
func GetAmount(input string) (amount int64, err error) {
|
||||
// convert something like 1.2k into 1200
|
||||
if strings.HasSuffix(strings.ToLower(input), "k") {
|
||||
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
|
||||
@@ -140,7 +143,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
amount, err := getAmount(ctx.Message().Text)
|
||||
amount, err := GetAmount(ctx.Message().Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
|
||||
@@ -2,6 +2,7 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ func newTelegramBot() *tb.Bot {
|
||||
Token: internal.Configuration.Telegram.ApiKey,
|
||||
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
|
||||
ParseMode: tb.ModeMarkdown,
|
||||
Verbose: false,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -3,7 +3,9 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -11,16 +13,24 @@ import (
|
||||
|
||||
// we can't use space in the label of buttons, because string splitting will mess everything up.
|
||||
const (
|
||||
MainMenuCommandSend = "💸 Send"
|
||||
// MainMenuCommandWebApp = "⤵️ Recv"
|
||||
// MainMenuCommandBalance = "Balance"
|
||||
// MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
// MainMenuCommandHelp = "📖 Help"
|
||||
// MainMenuCommandSend = "⤴️ Send"
|
||||
// SendMenuCommandEnter = "👤 Enter"
|
||||
MainMenuCommandWebApp = "⤵️"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
MainMenuCommandSend = "⤴️"
|
||||
SendMenuCommandEnter = "👤 Enter"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
|
||||
btnWebAppMainMenu = mainMenu.Text(MainMenuCommandWebApp)
|
||||
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
|
||||
@@ -31,9 +41,10 @@ var (
|
||||
)
|
||||
|
||||
func init() {
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -58,6 +69,21 @@ func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Ro
|
||||
return rows
|
||||
}
|
||||
|
||||
// appendWebAppLinkToButton adds a WebApp object to a Button with the user's webapp page
|
||||
func (bot *TipBot) appendWebAppLinkToButton(btn *tb.Btn, user *lnbits.User) {
|
||||
var url string
|
||||
if len(user.Telegram.Username) > 0 {
|
||||
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.Telegram.Username)
|
||||
} else {
|
||||
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
|
||||
}
|
||||
if strings.HasPrefix(url, "https://") {
|
||||
// prevent adding a link if not https is used, otherwise
|
||||
// Telegram returns an error and does not show the keyboard
|
||||
btn.WebApp = &tb.WebAppInfo{Url: url}
|
||||
}
|
||||
}
|
||||
|
||||
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
|
||||
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
var user *lnbits.User
|
||||
@@ -75,11 +101,13 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
|
||||
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +126,7 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
|
||||
// get all contacts and add them to the buttons
|
||||
for i, r := range records {
|
||||
log.Tracef("[makeContactsButtons] toNames[%d] = %s (id=%d)", i, r.ToUser, r.ID)
|
||||
sendToButtons = append(sendToButtons, tb.Btn{Text: fmt.Sprintf("%s", r.ToUser)})
|
||||
sendToButtons = append(sendToButtons, tb.Btn{Text: r.ToUser})
|
||||
}
|
||||
|
||||
// add the "enter a username" button to the end
|
||||
|
||||
@@ -3,12 +3,13 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
@@ -62,7 +62,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
perUserAmount, err := GetAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// generateImages is called when the user enters /generate or /generate <prompt>
|
||||
// asks the user for a prompt if not given
|
||||
func (bot *TipBot) generateImages(ctx intercept.Context) (intercept.Context, error) {
|
||||
if !dalle.Enabled {
|
||||
bot.trySendMessage(ctx.Message().Sender, "🤖💤 Dalle image generation is currently not available. Please try again later.")
|
||||
return ctx, nil
|
||||
}
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
|
||||
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
SetUserState(user, bot, lnbits.UserEnterDallePrompt, "")
|
||||
bot.trySendMessage(ctx.Message().Sender, "⌨️ Enter image prompt.", tb.ForceReply)
|
||||
return ctx, nil
|
||||
}
|
||||
// write the prompt into the command and call confirm
|
||||
m := ctx.Message()
|
||||
m.Text = GetMemoFromCommand(m.Text, 1)
|
||||
return bot.confirmGenerateImages(ctx)
|
||||
}
|
||||
|
||||
// confirmGenerateImages is called when the user has entered a prompt through /generate <prompt>
|
||||
// or because he answered to the request to enter it in generateImages()
|
||||
// confirmGenerateImages will create an invoice that the user can pay and if they pay
|
||||
// generateDalleImages will fetch the images and send it to the user
|
||||
func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
|
||||
ResetUserState(user, bot)
|
||||
m := ctx.Message()
|
||||
prompt := m.Text
|
||||
if len(prompt) == 0 {
|
||||
return ctx, fmt.Errorf("prompt not given")
|
||||
}
|
||||
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), InvoiceCallbackGenerateDalle, prompt)
|
||||
invoice.Payer = user
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "generateDallePayInvoiceMessage"))
|
||||
|
||||
// invoke internal pay if enough balance
|
||||
if balance >= internal.Configuration.Generate.DallePrice {
|
||||
m.Text = fmt.Sprintf("/pay %s", invoice.PaymentRequest)
|
||||
return bot.payHandler(ctx)
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(invoice.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
msg := bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
invoice.InvoiceMessage = msg
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
var jobChan chan func(workerId int)
|
||||
var workers = internal.Configuration.Generate.Worker
|
||||
|
||||
func init() {
|
||||
if workers == 0 {
|
||||
log.Printf("Dalle is disabled. No worker started.")
|
||||
return
|
||||
}
|
||||
log.Printf("Starting Dalle image generation. Worker: %d, Price: %d sat", workers, internal.Configuration.Generate.DallePrice)
|
||||
jobChan = make(chan func(workerId int), workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
go worker(jobChan, i)
|
||||
}
|
||||
}
|
||||
func worker(linkChan chan func(workerId int), workerId int) {
|
||||
for generatePrompt := range linkChan {
|
||||
generatePrompt(workerId)
|
||||
}
|
||||
}
|
||||
|
||||
// generateDalleImages is called by the invoice event when the user has paid
|
||||
func (bot *TipBot) generateDalleImages(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
user := invoiceEvent.Payer
|
||||
if user == nil || user.Wallet == nil {
|
||||
log.Errorf("[generateDalleImages] invalid user")
|
||||
return
|
||||
}
|
||||
bot.trySendMessage(user.Telegram, "🔄 Your images are being generated. Please wait a few moments.")
|
||||
var job = func(workerId int) {
|
||||
// create the client with the bearer token api key
|
||||
dalleClient, err := dalle.NewHTTPClient(internal.Configuration.Generate.DalleKey)
|
||||
// handle err
|
||||
if err != nil {
|
||||
log.Errorf("[NewHTTPClient-%d] %v", workerId, err.Error())
|
||||
bot.dalleRefundUser(user, "")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*15)
|
||||
defer cancel()
|
||||
// generate a task to create an image with a prompt
|
||||
task, err := dalleClient.Generate(ctx, invoiceEvent.CallbackData)
|
||||
if err != nil {
|
||||
log.Errorf("[Generate-%d] %v", workerId, err.Error())
|
||||
bot.dalleRefundUser(user, "")
|
||||
return
|
||||
}
|
||||
// poll the task.ID until status is succeeded
|
||||
var t *dalle.Task
|
||||
timeout := time.After(10 * time.Minute)
|
||||
ticker := time.Tick(5 * time.Second)
|
||||
// Keep trying until we're timed out or get a result/error
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
bot.dalleRefundUser(user, "")
|
||||
log.Errorf("[DALLE-%d] ctx done. Task %s", workerId, task.ID)
|
||||
return
|
||||
// Got a timeout! fail with a timeout error
|
||||
case <-timeout:
|
||||
bot.dalleRefundUser(user, "Timeout. Please try again later.")
|
||||
log.Errorf("[DALLE-%d] timeout. Task: %s", workerId, task.ID)
|
||||
return
|
||||
// Got a tick, we should check on checkSomething()
|
||||
case <-ticker:
|
||||
t, err = dalleClient.GetTask(ctx, task.ID)
|
||||
// handle err
|
||||
if err != nil {
|
||||
log.Errorf("[GetTask-%d] Task: %s. Error: %v", workerId, task.ID, err.Error())
|
||||
//bot.dalleRefundUser(user, "")
|
||||
continue
|
||||
}
|
||||
if t.Status == dalle.StatusSucceeded {
|
||||
log.Printf("[DALLE-%d] 🎆 task succeeded for user %s", workerId, GetUserStr(user.Telegram))
|
||||
// download the first generated image
|
||||
for _, data := range t.Generations.Data {
|
||||
err = bot.downloadAndSendImages(ctx, dalleClient, data, invoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[downloadAndSendImages-%d] Id: %s. Error: %v", workerId, data.ID, err.Error())
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
} else if t.Status == dalle.StatusRejected {
|
||||
log.Errorf("[DALLE-%d] rejected: %s", workerId, t.ID)
|
||||
bot.dalleRefundUser(user, "Your prompt has been rejected by OpenAI. Do not use celebrity names, sexual expressions, or any other harmful content as prompt.")
|
||||
return
|
||||
}
|
||||
log.Debugf("[DALLE-%d] pending for user %s", workerId, GetUserStr(user.Telegram))
|
||||
}
|
||||
}
|
||||
}
|
||||
jobChan <- job
|
||||
}
|
||||
|
||||
// downloadAndSendImages will download dalle images and send them to the payer.
|
||||
func (bot *TipBot) downloadAndSendImages(ctx context.Context, dalleClient dalle.Client, data dalle.GenerationData, event *InvoiceEvent) error {
|
||||
reader, err := dalleClient.Download(ctx, data.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
image := "data/dalle/" + data.ID + ".png"
|
||||
file, err := os.Create(image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
_, err = io.Copy(file, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(image, 0, os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
bot.trySendMessage(event.Payer.Telegram, &tb.Photo{File: tb.File{FileReader: f}})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
|
||||
if user.Wallet == nil {
|
||||
return fmt.Errorf("user has no wallet")
|
||||
}
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create invioce for user
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(internal.Configuration.Generate.DallePrice),
|
||||
Memo: fmt.Sprintf("Refund DALLE2 %s", GetUserStr(user.Telegram)),
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// pay invoice
|
||||
_, err = me.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return err
|
||||
}
|
||||
log.Warnf("[DALLE] refunding user %s with %d sat", GetUserStr(user.Telegram), internal.Configuration.Generate.DallePrice)
|
||||
|
||||
var err_reason string
|
||||
if len(message) > 0 {
|
||||
err_reason = message
|
||||
} else {
|
||||
err_reason = "Something went wrong."
|
||||
}
|
||||
bot.trySendMessage(user.Telegram, fmt.Sprintf("🚫 %s You have been refunded.", err_reason))
|
||||
return nil
|
||||
}
|
||||
@@ -324,7 +324,7 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
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"), GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
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
|
||||
@@ -366,9 +366,9 @@ 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(i18n.Translate(ticketEvent.LanguageCode, "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(i18n.Translate(ticketEvent.LanguageCode, "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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
|
||||
amount := int64(0) // default amount is zero
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 3); err == nil {
|
||||
amount, err = getAmount(amount_str)
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
return ctx, err
|
||||
|
||||
@@ -99,6 +99,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/generate"},
|
||||
Handler: bot.generateImages,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/tip", "/t", "/honk"},
|
||||
Handler: bot.tipHandler,
|
||||
@@ -172,6 +188,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -261,6 +278,25 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
// previously, this was the send menu but it
|
||||
// was replaced with the webapp
|
||||
// {
|
||||
// Endpoints: []interface{}{&btnWebAppMainMenu},
|
||||
// Handler: bot.keyboardSendHandler,
|
||||
// Interceptor: &Interceptor{
|
||||
|
||||
// Before: []intercept.Func{
|
||||
// bot.localizerInterceptor,
|
||||
// bot.logMessageInterceptor,
|
||||
// bot.requireUserInterceptor,
|
||||
// bot.loadReplyToInterceptor,
|
||||
// bot.lockInterceptor,
|
||||
// },
|
||||
// OnDefer: []intercept.Func{
|
||||
// bot.unlockInterceptor,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
{
|
||||
Endpoints: []interface{}{"/transactions"},
|
||||
Handler: bot.transactionsHandler,
|
||||
@@ -280,6 +316,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -295,6 +332,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -321,7 +359,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/tipjar", "/spendendose"},
|
||||
Handler: bot.tipjarHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -337,7 +374,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/help", &btnHelpMainMenu},
|
||||
Handler: bot.helpHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -385,8 +421,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/advanced"},
|
||||
Handler: bot.advancedHelpHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -401,8 +437,24 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/link"},
|
||||
Handler: bot.lndhubHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/api"},
|
||||
Handler: bot.apiHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -417,8 +469,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/lnurl"},
|
||||
Handler: bot.lnurlHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -434,7 +486,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/group"},
|
||||
Handler: bot.groupHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -471,6 +522,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -548,6 +600,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -563,6 +616,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -578,6 +632,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -593,6 +648,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -608,6 +664,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -623,6 +680,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -638,6 +696,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -653,6 +712,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -669,10 +729,12 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
bot.singletonCallbackInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -684,6 +746,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -699,6 +762,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -714,6 +778,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -729,6 +794,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -744,6 +810,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -759,6 +826,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -774,6 +842,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -789,6 +858,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -803,6 +873,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -817,6 +888,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -831,6 +903,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -845,6 +918,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -859,6 +933,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -874,6 +949,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -889,6 +965,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -904,6 +981,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -919,6 +997,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -934,6 +1013,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -949,6 +1029,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -964,6 +1045,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -979,6 +1061,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -994,6 +1077,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1008,6 +1092,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1022,6 +1107,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1036,6 +1122,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1051,6 +1138,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1065,6 +1153,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1079,6 +1168,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1093,6 +1183,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1107,6 +1198,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1121,6 +1213,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1135,6 +1228,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
@@ -1149,6 +1243,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.answerCallbackInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
|
||||
@@ -59,10 +59,9 @@ func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error
|
||||
}
|
||||
|
||||
// answerCallbackInterceptor will answer the callback with the given text in the context
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
if c != nil {
|
||||
ctxcr := ctx.Value("callback_response")
|
||||
var res []*tb.CallbackResponse
|
||||
if ctxcr != nil {
|
||||
|
||||
@@ -40,6 +40,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +52,7 @@ const (
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
InvoiceCallbackGenerateDalle
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
+19
-21
@@ -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"
|
||||
@@ -19,22 +20,9 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return ctx, fmt.Errorf("invalid configuration")
|
||||
}
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser := LoadUser(ctx)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
// do not respond to banned users
|
||||
if bot.UserIsBanned(fromUser) {
|
||||
log.Warnln("[lndhubHandler] user is banned. not responding.")
|
||||
return ctx, fmt.Errorf("user is banned")
|
||||
}
|
||||
linkmsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
|
||||
|
||||
@@ -47,14 +35,24 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
}
|
||||
|
||||
// send the link to the user
|
||||
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
|
||||
qrmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
// auto delete
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
bot.tryDeleteMessage(qrmsg)
|
||||
bot.tryEditMessage(linkmsg, Translate(ctx, "linkHiddenMessage"), tb.Silent)
|
||||
}()
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) apiHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
fromUser := LoadUser(ctx)
|
||||
apimesg := bot.trySendMessageEditable(m.Sender, fmt.Sprintf(Translate(ctx, "apiConnectMessage"), fromUser.Wallet.Adminkey, fromUser.Wallet.Inkey))
|
||||
// auto delete
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryEditMessage(apimesg, Translate(ctx, "apiHiddenMessage"))
|
||||
}()
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
// statusMsg := bot.trySendMessageEditable(c.Sender,
|
||||
// Translate(ctx, "lnurlResolvingUrlMessage"),
|
||||
// )
|
||||
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlAuthState.Message.Text, ButtonText: Translate(ctx, "lnurlResolvingUrlMessage")})
|
||||
|
||||
// from fiatjaf/go-lnurl
|
||||
p := lnurlAuthState.LNURLAuthParams
|
||||
@@ -107,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
}
|
||||
|
||||
var sentsigres lnurl.LNURLResponse
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
@@ -125,7 +125,11 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
bot.tryEditMessage(c, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
|
||||
return ctx, err
|
||||
}
|
||||
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlSuccessfulLogin"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{
|
||||
Message: lnurlAuthState.Message.Text,
|
||||
ButtonText: Translate(ctx, "lnurlSuccessfulLogin"),
|
||||
URL: fmt.Sprintf("https://%s", lnurlAuthState.LNURLAuthParams.Host),
|
||||
})
|
||||
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
@@ -25,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))
|
||||
@@ -76,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))
|
||||
|
||||
@@ -91,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
|
||||
@@ -99,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
|
||||
@@ -145,7 +154,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
@@ -187,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))
|
||||
|
||||
@@ -42,21 +42,35 @@ 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"`
|
||||
}
|
||||
|
||||
type EditSingleButtonParams struct {
|
||||
Message string
|
||||
ButtonText string
|
||||
Data string
|
||||
URL string
|
||||
}
|
||||
|
||||
// editSingleButton edits a message to display a single button (for something like a progress indicator)
|
||||
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
|
||||
bot.tryEditMessage(
|
||||
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, params EditSingleButtonParams) (*tb.Message, error) {
|
||||
if len(params.URL) > 0 && len(params.Data) > 0 {
|
||||
return &tb.Message{}, fmt.Errorf("URL and Data cannot be set at the same time.")
|
||||
}
|
||||
if len(params.URL) == 0 && len(params.Data) == 0 {
|
||||
params.Data = "placeholder"
|
||||
}
|
||||
return bot.tryEditMessage(
|
||||
m,
|
||||
message,
|
||||
params.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: button}},
|
||||
{tb.InlineButton{Text: params.ButtonText, Data: params.Data, URL: params.URL}},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
|
||||
@@ -232,13 +246,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
ResetUserState(user, bot)
|
||||
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw")})
|
||||
|
||||
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -254,7 +268,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
lnurlWithdrawState.Invoice = invoice
|
||||
@@ -266,25 +280,25 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil || res.StatusCode >= 300 {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -293,12 +307,12 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "OK" {
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess")})
|
||||
|
||||
} else {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed")})
|
||||
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
|
||||
}
|
||||
|
||||
|
||||
+26
-10
@@ -2,6 +2,8 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
@@ -22,7 +24,7 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
@@ -65,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 {
|
||||
@@ -91,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
|
||||
@@ -142,7 +144,7 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
}
|
||||
|
||||
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -151,7 +153,7 @@ func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -176,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
|
||||
|
||||
@@ -207,12 +209,12 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
return "", nil,
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug("[HandleLNURL] rawurl: ", rawurl)
|
||||
parsed, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
@@ -236,7 +238,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -273,6 +275,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
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"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"
|
||||
@@ -195,7 +196,7 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
payData.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
|
||||
{tb.InlineButton{Unique: "attempt_payment", Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -4,11 +4,12 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
|
||||
@@ -250,7 +250,7 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = getAmount(amount_str)
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
@@ -424,7 +424,7 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = getAmount(amount_str)
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
|
||||
if m.Text == "0" {
|
||||
amount = 0
|
||||
} else {
|
||||
amount, err = getAmount(m.Text)
|
||||
amount, err = GetAmount(m.Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterShopItemPriceHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
|
||||
@@ -2,6 +2,8 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -10,7 +12,6 @@ import (
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
@@ -20,5 +20,6 @@ func initializeStateCallbackMessage(bot *TipBot) {
|
||||
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
|
||||
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
|
||||
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
|
||||
lnbits.UserEnterDallePrompt: bot.confirmGenerateImages,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
|
||||
@@ -113,10 +113,10 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
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
|
||||
|
||||
@@ -58,7 +58,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
perUserAmount, err := GetAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
+19
-14
@@ -27,27 +27,28 @@ func ResetUserState(user *lnbits.User, bot *TipBot) {
|
||||
}
|
||||
|
||||
func GetUserStr(user *tb.User) string {
|
||||
if len(user.Username) == 0 {
|
||||
if user.FirstName != "" {
|
||||
return fmt.Sprintf("%s", user.FirstName)
|
||||
} else {
|
||||
return fmt.Sprintf("%d", user.ID)
|
||||
}
|
||||
userStr := fmt.Sprintf("@%s", user.Username)
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && user.FirstName != "" {
|
||||
userStr = fmt.Sprintf("%s", user.FirstName)
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("%d", user.ID)
|
||||
}
|
||||
return fmt.Sprintf("@%s", user.Username)
|
||||
return userStr
|
||||
}
|
||||
|
||||
func GetUserStrMd(user *tb.User) string {
|
||||
userStr := fmt.Sprintf("@%s", user.Username)
|
||||
// if user does not have a username
|
||||
if len(user.Username) == 0 {
|
||||
if user.FirstName != "" {
|
||||
return fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
|
||||
} else {
|
||||
return fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
|
||||
}
|
||||
if len(userStr) < 2 && user.FirstName != "" {
|
||||
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
|
||||
return userStr
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
|
||||
return userStr
|
||||
} else {
|
||||
// escape only if user has a username
|
||||
return str.MarkdownEscape(fmt.Sprintf("@%s", user.Username))
|
||||
return str.MarkdownEscape(userStr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,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())
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetUserStr(t *testing.T) {
|
||||
type args struct {
|
||||
user *tb.User
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "BotUser"},
|
||||
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
|
||||
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "12351241"},
|
||||
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := GetUserStr(tt.args.user); got != tt.want {
|
||||
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGetUserName(b *testing.B) {
|
||||
benchmarkGetUserStr(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
|
||||
}
|
||||
func BenchmarkGetUserStrNoUsername(b *testing.B) {
|
||||
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
|
||||
}
|
||||
|
||||
func BenchmarkGetUserStrNoFirstName(b *testing.B) {
|
||||
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
|
||||
}
|
||||
|
||||
func benchmarkGetUserStr(s *tb.User, b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
GetUserStr(s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserStrMd(t *testing.T) {
|
||||
type args struct {
|
||||
user *tb.User
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "[BotUser](tg://user?id=12351241)"},
|
||||
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
|
||||
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "[12351241](tg://user?id=12351241)"},
|
||||
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := GetUserStrMd(tt.args.user); got != tt.want {
|
||||
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGetUserStrMdName(b *testing.B) {
|
||||
benchmarkGetUserStrMd(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
|
||||
}
|
||||
func BenchmarkGetUserStrMdNoUsername(b *testing.B) {
|
||||
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
|
||||
}
|
||||
|
||||
func BenchmarkGetUserStrMdNoFirstName(b *testing.B) {
|
||||
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
|
||||
}
|
||||
|
||||
func benchmarkGetUserStrMd(s *tb.User, b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
GetUserStrMd(s)
|
||||
}
|
||||
}
|
||||
@@ -54,23 +54,35 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
// append lnurl ctx functions
|
||||
lnUrl := lnurl.New(bot)
|
||||
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
|
||||
|
||||
// userpage server
|
||||
userpage := userpage.New(bot)
|
||||
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
|
||||
s.AppendRoute("/app/@{username}", userpage.UserWebAppHandler, 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/auth`, api.AuthTypeNone, api.AccessKeyTypeNone, bot.DB.Users, hub.Handle)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
|
||||
|
||||
// starting api service
|
||||
apiService := api.Service{Bot: bot}
|
||||
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, api.AccessKeyTypeAdmin, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestream`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStream, http.MethodGet)
|
||||
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.Balance, http.MethodGet)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
internalAdminServer := api.NewServer("0.0.0.0:6060")
|
||||
internalAdminServer := api.NewServer(internal.Configuration.Bot.AdminAPIHost)
|
||||
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
|
||||
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
|
||||
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
|
||||
internalAdminServer.AppendRoute("/admin/unban/{id}", adminService.UnbanUser)
|
||||
internalAdminServer.AppendRoute("/admin/dalle/enable", adminService.EnableDalle)
|
||||
internalAdminServer.AppendRoute("/admin/dalle/disable", adminService.DisableDalle)
|
||||
internalAdminServer.PathPrefix("/debug/pprof/", http.DefaultServeMux)
|
||||
|
||||
}
|
||||
|
||||
+18
-5
@@ -124,12 +124,14 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <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>`"""
|
||||
*/shop* 🛍 Durchsuche Shops: `/shop` oder `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`"""
|
||||
|
||||
# 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
|
||||
|
||||
@@ -259,11 +261,22 @@ lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
|
||||
|
||||
walletConnectMessage = """🔗 *Verbinde dein Wallet*
|
||||
|
||||
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto.
|
||||
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /api für deine API keys.
|
||||
|
||||
- *BlueWallet:* Drücke *New wallet*, *Import wallet*, *Scan or import a file*, und scanne den QR Code.
|
||||
- *Zeus:* Kopiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Konnte dein Wallet nicht verbinden. Bitte versuche es später noch einmal."""
|
||||
linkHiddenMessage = """🔍 Link versteckt. Gebe /link ein um ihn wieder zu sehen."""
|
||||
|
||||
# API
|
||||
|
||||
walletConnectMessage = """🔗 *Deine API Keys*
|
||||
|
||||
⚠️ Teile diese Key mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /link um dein Wallet zu verbinden.
|
||||
|
||||
- *Admin key:* `%s`
|
||||
- *Invoice key:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Keys versteckt. Gebe /api ein um sie wieder zu sehen."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
|
||||
+22
-4
@@ -127,12 +127,15 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
enterAmountMessage = """💯 Enter an amount."""
|
||||
enterUserMessage = """👤 Enter a user."""
|
||||
enterTextMessage = """⌨️ Enter text."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
@@ -264,13 +267,23 @@ lnurlWithdrawSuccess = """✅ Withdrawal requested."""
|
||||
|
||||
walletConnectMessage = """🔗 *Link your wallet*
|
||||
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds. Use /api for your API keys.
|
||||
|
||||
- *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."""
|
||||
|
||||
# API
|
||||
|
||||
apiConnectMessage = """🔗 *Your API keys*
|
||||
|
||||
⚠️ Never share these keys with anyone or they will be able to access your funds. Use /link to link your wallet.
|
||||
|
||||
- *Admin key:* `%s`
|
||||
- *Invoice key:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Keys hidden. Enter /api to see them again."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Create a faucet."""
|
||||
@@ -383,4 +396,9 @@ 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`"""
|
||||
*For users (in private chat):* `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
|
||||
generateDallePayInvoiceMessage = """Pay this invoice to generate four images 👇"""
|
||||
generateDalleGeneratingMessage = """Your images are being generated. Please wait..."""
|
||||
@@ -123,7 +123,8 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
|
||||
@@ -123,7 +123,8 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
|
||||
@@ -123,7 +123,8 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
|
||||
@@ -123,7 +123,8 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
|
||||
@@ -123,7 +123,8 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <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>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
|
||||
Reference in New Issue
Block a user