Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7de4bc901 | ||
|
|
d90d37e8f9 | ||
|
|
e385cb7bcf | ||
|
|
2535fd3248 | ||
|
|
d2922e7cc8 | ||
|
|
bbfa7598a0 | ||
|
|
1303429ca5 | ||
|
|
e82196b6fa | ||
|
|
4f205abbb9 | ||
|
|
5433bcee27 | ||
|
|
587da5d117 | ||
|
|
e731cff689 | ||
|
|
92d687637c | ||
|
|
33674de1b6 | ||
|
|
56f9e7e40b |
@@ -18,7 +18,7 @@ To build the bot from source, clone the repository and compile the source code.
|
||||
git clone https://github.com/LightningTipBot/LightningTipBot.git
|
||||
cd LightningTipBot
|
||||
go build .
|
||||
cp config.yaml.example config.yaml
|
||||
cp config.yaml-example config.yaml
|
||||
```
|
||||
|
||||
After the configuration (see below), start it using the command
|
||||
@@ -136,10 +136,6 @@ To pay a Lightning invoice, you can snap a photo of a QR code and send it direct
|
||||
|
||||
To minimize the clutter all the heavy tipping can cause in a group chat, the bot will remove all failed commands (for example due to a syntax error) from the chat immediately. All successful commands will stay visible for `message_dispose_duration` seconds (default 10s) and then be removed. The tips will sill be visible for everyone in the Live tooltip. This feature only works, if the bot is made admin of the group.
|
||||
|
||||
## Full Guide to Install and run on a VPS
|
||||
|
||||
A complete guide to install and run LightningTipBot + LNBITS (on docker with PostgreSQL) on the same VPS with an external LND funding source has been prepared by Massimo Musumeci (@massmux) and it is available: [LightningTipBot full install](https://www.massmux.com/howto-complete-lightningtipbot-lnbits-setup-vps/)
|
||||
|
||||
## Made with
|
||||
|
||||
- [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package cashu
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cashu-ts/cashu-ts"
|
||||
)
|
||||
|
||||
var (
|
||||
mintUrl = "https://your-cashu-mint-url"
|
||||
wallet = cashuts.NewCashuWallet(cashuts.NewCashuMint(mintUrl))
|
||||
)
|
||||
|
||||
func DecodeToken(token string) (cashuts.Token, error) {
|
||||
decoded, err := wallet.DecodeToken(token)
|
||||
if err != nil {
|
||||
return cashuts.Token{}, errors.New("invalid Cashu token")
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func RedeemToken(token string, userLightningAddress string) (string, error) {
|
||||
proofs, err := wallet.Receive(token)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to receive Cashu token")
|
||||
}
|
||||
invoice, err := wallet.CreateInvoice(proofs.Amount, userLightningAddress)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to create invoice")
|
||||
}
|
||||
result, err := wallet.PayLnInvoiceWithToken(invoice.PaymentRequest, token)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to pay Lightning invoice with Cashu token")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
+3
-6
@@ -6,8 +6,8 @@ bot:
|
||||
tor_proxy:
|
||||
host: 127.0.0.1:9050
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "https://mylnurl.com"
|
||||
lnurl_server: "http://127.0.0.1:5454" # or http://0.0.0.0:5454 depending on your configuration
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
lnurl_image: true
|
||||
admin_api_host: localhost:6060
|
||||
telegram:
|
||||
@@ -26,9 +26,6 @@ database:
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
groupsdb_path: "data/groups.db"
|
||||
generate:
|
||||
open_ai_bearer_token: "token_here"
|
||||
dalle_key: "asd"
|
||||
dalle_price: 1000
|
||||
worker: 2
|
||||
nostr:
|
||||
private_key: "hex private key here"
|
||||
worker: 2
|
||||
@@ -1,45 +1,41 @@
|
||||
module github.com/LightningTipBot/LightningTipBot
|
||||
|
||||
go 1.18
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/PuerkitoBio/goquery v1.8.0
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.2.0
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7
|
||||
github.com/fiatjaf/go-lnurl v1.11.2
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nbd-wtf/go-nostr v0.13.0
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/prometheus/common v0.26.0
|
||||
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
|
||||
github.com/satori/go.uuid v1.2.0
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
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
|
||||
go.elastic.co/ecslogrus v1.0.0
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
|
||||
golang.org/x/text v0.3.7
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 // indirect
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
|
||||
github.com/aead/siphash v1.0.1 // indirect
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // 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
|
||||
@@ -64,7 +60,7 @@ require (
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/go-errors/errors v1.0.1 // indirect
|
||||
github.com/go-redis/redis/v8 v8.8.2 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/google/uuid v1.3.0 // 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
|
||||
@@ -76,6 +72,7 @@ require (
|
||||
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/magefile/mage v1.9.0 // 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
|
||||
@@ -87,19 +84,15 @@ require (
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tidwall/rtred v0.1.2 // indirect
|
||||
github.com/tidwall/tinyqueue v0.1.1 // indirect
|
||||
github.com/valyala/fastjson v1.6.3 // 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/exp v0.0.0-20221106115401-f9659909a136 // indirect
|
||||
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
|
||||
golang.org/x/sys v0.1.0 // 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/alecthomas/kingpin.v2 v2.2.6 // indirect
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 // 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
|
||||
|
||||
@@ -46,8 +46,6 @@ github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0g
|
||||
github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI=
|
||||
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 h1:Xa6tp8DPDhdV+k23uiTC/GrAYOe4IdyJVKtob4KW3GA=
|
||||
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8/go.mod h1:ihkm1viTbO/LOsgdGoFPBSvzqvx7ibvkMzYp3CgtHik=
|
||||
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
|
||||
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
|
||||
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
|
||||
@@ -61,11 +59,9 @@ github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg=
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
|
||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d h1:UQZhZ2O0vMHr2cI+DC1Mbh0TJxzA3RcLoMsFw+aXw7E=
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/allegro/bigcache/v2 v2.2.5 h1:mRc8r6GQjuJsmSKQNPsR5jQVXc8IJ1xsW5YXUYMLfqI=
|
||||
github.com/allegro/bigcache/v2 v2.2.5/go.mod h1:FppZsIO+IZk7gCuj5FiIDHGygD9xvWQcqg1uIPMb6tY=
|
||||
@@ -161,6 +157,7 @@ github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtE
|
||||
github.com/btcsuite/winsvc v1.0.0 h1:J9B4L7e3oqhXOcm+2IuNApwzQec85lE+QaikUcCs+dk=
|
||||
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
|
||||
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
|
||||
@@ -253,8 +250,8 @@ github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGE
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fergusstrange/embedded-postgres v1.10.0 h1:YnwF6xAQYmKLAXXrrRx4rHDLih47YJwVPvg8jeKfdNg=
|
||||
github.com/fergusstrange/embedded-postgres v1.10.0/go.mod h1:a008U8/Rws5FtIOTGYDYa7beVWsT3qVKyqExqYYjL+c=
|
||||
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7 h1:0m0ph1FcZY7p89OpaXOUs8N44GhP7gE/98l+eWCNSkQ=
|
||||
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7/go.mod h1:KJfs14iAY3gCgt/3T6fxfBvPhU67OfIp7PSrBg/v/R8=
|
||||
github.com/fiatjaf/go-lnurl v1.11.2 h1:XyZS6Uuu/2ZbhkZjOm3W+FaFvRzRRTFel3aMoO6eDUE=
|
||||
github.com/fiatjaf/go-lnurl v1.11.2/go.mod h1:9PAgeVpZ5u6olV/dfkoyPSOJs3j4q0JIGLSbBbmMci8=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
|
||||
github.com/form3tech-oss/jwt-go v3.2.3+incompatible h1:7ZaBxOI7TMoYBfyA3cQHErNNyAWIKUMIwqxEtgHOs5c=
|
||||
@@ -265,6 +262,7 @@ github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVB
|
||||
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
|
||||
github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
@@ -365,7 +363,8 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
||||
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
|
||||
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
|
||||
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
@@ -381,6 +380,8 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4
|
||||
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
|
||||
@@ -573,6 +574,7 @@ github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFB
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
@@ -630,6 +632,8 @@ github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1s
|
||||
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
|
||||
github.com/lunixbochs/vtclean v0.0.0-20160125035106-4fbf7632a2c6/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
|
||||
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
|
||||
github.com/magefile/mage v1.9.0 h1:t3AU2wNwehMCW97vuqQLtw6puppWXHO+O2MHo5a50XE=
|
||||
github.com/magefile/mage v1.9.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=
|
||||
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/makiuchi-d/gozxing v0.0.2 h1:TGSCQRXd9QL1ze1G1JE9sZBMEr6/HLx7m5ADlLUgq7E=
|
||||
@@ -691,8 +695,6 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE
|
||||
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/nbd-wtf/go-nostr v0.13.0 h1:3OcUknuSLm8prTk2u/kUvbMQYtaSjLKemADRQ8TBIXk=
|
||||
github.com/nbd-wtf/go-nostr v0.13.0/go.mod h1:qFFTIxh15H5GGN0WsBI/P73DteqsevnhSEW/yk8nEf4=
|
||||
github.com/nbd-wtf/ln-decodepay v1.5.1 h1:i/SMR94AXIL21KxE/CyWLg/1kKUOVfxHD4QJswaNRDc=
|
||||
github.com/nbd-wtf/ln-decodepay v1.5.1/go.mod h1:xzBXPaCj/7oRRaui+iYSIxy5LYUjoPfAyAGq2WCyNKk=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
@@ -753,6 +755,7 @@ github.com/pierrec/lz4/v4 v4.1.8 h1:ieHkV+i2BRzngO4Wd/3HGowuZStgq6QkPsD1eolNAO4=
|
||||
github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18=
|
||||
@@ -802,13 +805,13 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So
|
||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
||||
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
|
||||
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
|
||||
@@ -818,8 +821,9 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
|
||||
@@ -856,6 +860,7 @@ github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRci
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.0/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
@@ -904,8 +909,6 @@ github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijb
|
||||
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/valyala/fastjson v1.6.3 h1:tAKFnnwmeMGPbwJ7IwxcTPCNr3uIzoIj3/Fh90ra4xc=
|
||||
github.com/valyala/fastjson v1.6.3/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
|
||||
@@ -919,6 +922,8 @@ github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1
|
||||
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||
gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec/go.mod h1:BZ1RAoRPbCxum9Grlv5aeksu2H8BiKehBYooU2LFiOQ=
|
||||
go.elastic.co/ecslogrus v1.0.0 h1:o1qvcCNaq+eyH804AuK6OOiUupLIXVDfYjDtSLPwukM=
|
||||
go.elastic.co/ecslogrus v1.0.0/go.mod h1:vMdpljurPbwu+iFmNc/HSWCkn1Fu/dYde1o/adaEczo=
|
||||
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
go.etcd.io/bbolt v1.3.5-0.20200615073812-232d8fc87f50/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
|
||||
@@ -1025,8 +1030,6 @@ golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u0
|
||||
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
|
||||
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
|
||||
golang.org/x/exp v0.0.0-20220426173459-3bcf042a4bf5/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
|
||||
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 h1:Fq7F/w7MAa1KJ5bt2aJ62ihqp9HDcRuyILskkpIAurw=
|
||||
golang.org/x/exp v0.0.0-20221106115401-f9659909a136/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -1196,8 +1199,8 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 h1:fqTvyMIIj+HRzMmnzr9NtpHP6uVpvB5fkHcgPDC4nu8=
|
||||
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
@@ -1382,7 +1385,6 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y=
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI=
|
||||
|
||||
+57
-41
@@ -2,10 +2,11 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
@@ -24,6 +25,7 @@ type ErrorResponse struct {
|
||||
func RespondError(w http.ResponseWriter, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
log.WithFields(log.Fields{"module": "api", "func": "RespondError"}).Error(message)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
|
||||
}
|
||||
|
||||
@@ -38,7 +40,14 @@ func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
|
||||
balanceResponse := BalanceResponse{
|
||||
Balance: balance,
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "PayInvoice",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"amount": balance,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Info("checked balance")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(balanceResponse)
|
||||
@@ -58,7 +67,6 @@ func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
Out: false,
|
||||
DescriptionHash: createInvoiceRequest.DescriptionHash,
|
||||
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
|
||||
Memo: createInvoiceRequest.Memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
s.Bot.Client)
|
||||
if err != nil {
|
||||
@@ -66,6 +74,15 @@ func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "CreateInvoice",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"amount": createInvoiceRequest.Amount,
|
||||
"invoice": invoice.PaymentRequest,
|
||||
"telegram_id": user.Telegram.ID}).Info("created invoice")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(invoice)
|
||||
@@ -90,7 +107,14 @@ func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
// we assume that it's paid since thre was no error earlier
|
||||
payment.Paid = true
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "PayInvoice",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"invoice": invoice.PaymentRequest,
|
||||
"telegram_id": user.Telegram.ID}).Info("payed invoice")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
@@ -104,6 +128,14 @@ func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
|
||||
RespondError(w, "could not get payment")
|
||||
return
|
||||
}
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "PayInvoice",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"status": payment.Paid,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Info("returning payment status")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
@@ -119,6 +151,14 @@ func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
RespondError(w, "could not get invoice")
|
||||
return
|
||||
}
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "PayInvoice",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"status": payment.Paid,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Info("returning invoice status")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
@@ -143,46 +183,22 @@ type InvoiceStream struct {
|
||||
|
||||
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
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.Connection.Transport = &http.Transport{DisableCompression: true}
|
||||
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
|
||||
c := make(chan *sse.Event)
|
||||
err := client.SubscribeChan("", c)
|
||||
if err != nil {
|
||||
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
out:
|
||||
for {
|
||||
select {
|
||||
case msg := <-c:
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
client.Unsubscribe(c)
|
||||
break out
|
||||
default:
|
||||
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
written, err = fmt.Fprint(w, "\n")
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
close(c)
|
||||
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)
|
||||
}
|
||||
|
||||
+11
-13
@@ -9,17 +9,14 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"gorm.io/gorm"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
|
||||
func LoggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
log.Tracef("[%s] %s %s", prefix, r.Method, r.URL.Path)
|
||||
log.Tracef("[%s]\n%s", prefix, dump(r))
|
||||
r.BasicAuth()
|
||||
log.WithFields(log.Fields{"module": "api", "method": r.Method, "path": r.URL.Path, "request": dump(r)}).Info("incoming api request")
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
@@ -52,7 +49,7 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
|
||||
// check if the user is banned
|
||||
if auth == "" {
|
||||
w.WriteHeader(401)
|
||||
log.Warn("[api] no auth")
|
||||
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware"}).Warn("no auth")
|
||||
return
|
||||
}
|
||||
_, password, ok := parseAuth(authType, auth)
|
||||
@@ -63,29 +60,30 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
|
||||
// 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)
|
||||
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password}).Warn("Banned user. Not forwarding request")
|
||||
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 = ? OR wallet_adminkey = ? COLLATE NOCASE", password, password).First(user)
|
||||
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
|
||||
} else {
|
||||
log.Errorf("[api] route without access type")
|
||||
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password, "error": tx.Error}).
|
||||
Warnf("route without access type")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[api] could not load access key: %v", tx.Error)
|
||||
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password, "error": tx.Error}).
|
||||
Warnf("could not load access key")
|
||||
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)
|
||||
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "path": fmt.Sprintf("%s %s%s", r.Method, r.URL.Path, r.URL.RawQuery), "user": user.GetUserStr()}).
|
||||
Debugf("Loaded Api user")
|
||||
r = r.WithContext(context.WithValue(r.Context(), "user", user))
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
@@ -34,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.WithFields(log.Fields{"module": "api"}).Infof("Server started at %s", address)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
@@ -45,20 +45,23 @@ 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)))
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware(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))
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware(handler))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
|
||||
func NotFoundHandler(writer http.ResponseWriter, err error) {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "NotFoundHandler",
|
||||
"error": err.Error()}).Errorln("Returning Http 404")
|
||||
// return 404 on any error
|
||||
http.Error(writer, "404 page not found", http.StatusNotFound)
|
||||
}
|
||||
|
||||
@@ -243,7 +243,7 @@
|
||||
<div class="wrapper">
|
||||
<label class="sr-only" for="inlineFormInputGroup">Username</label>
|
||||
<div class="input-group">
|
||||
<input type="number" class="form-control" min="1" inputmode="decimal" step="any" pattern="\d+(\.\d*)?" id="invoiceAmount" placeholder="amount">
|
||||
<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>
|
||||
|
||||
@@ -71,10 +71,17 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 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)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "UserPageHandler",
|
||||
"user": username}).Infof("rendering page")
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "UserPageHandler",
|
||||
"user": username,
|
||||
"error": err.Error()}).Errorln("[UserPage]", "error encoding lnurl")
|
||||
return
|
||||
}
|
||||
image, err := s.getTelegramUserPictureURL(username)
|
||||
@@ -88,7 +95,11 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
Image string
|
||||
LNURLPay string
|
||||
}{username, image, lnurlEncode}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "api",
|
||||
"func": "UserPageHandler",
|
||||
"user": username,
|
||||
"error": err.Error()}).Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-9
@@ -15,18 +15,12 @@ var Configuration = struct {
|
||||
Database DatabaseConfiguration `yaml:"database"`
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
Generate GenerateConfiguration `yaml:"generate"`
|
||||
Nostr NostrConfiguration `yaml:"nostr"`
|
||||
}{}
|
||||
|
||||
type NostrConfiguration struct {
|
||||
PrivateKey string `yaml:"private_key"`
|
||||
}
|
||||
|
||||
type GenerateConfiguration struct {
|
||||
OpenAiBearerToken string `yaml:"open_ai_bearer_token"`
|
||||
DalleKey string `yaml:"dalle_key"`
|
||||
DallePrice int64 `yaml:"dalle_price"`
|
||||
Worker int `yaml:"worker"`
|
||||
DalleKey string `yaml:"dalle_key"`
|
||||
DallePrice int64 `yaml:"dalle_price"`
|
||||
Worker int `yaml:"worker"`
|
||||
}
|
||||
|
||||
type SocksConfiguration struct {
|
||||
|
||||
@@ -30,7 +30,7 @@ func MigrateAnonIdSha265Hash(db *gorm.DB) error {
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
pw := u.Wallet.ID
|
||||
anon_id := str.AnonIdSha256(&u)
|
||||
anon_id := u.AnonIdSha256()
|
||||
log.Infof("[MigrateAnonIdSha265Hash] %s -> %s", pw, anon_id)
|
||||
u.AnonIDSha256 = anon_id
|
||||
tx := db.Save(u)
|
||||
@@ -48,7 +48,7 @@ func MigrateUUIDSha265Hash(db *gorm.DB) error {
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
pw := u.Wallet.ID
|
||||
uuid := str.UUIDSha256(&u)
|
||||
uuid := u.UUIDSha256()
|
||||
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
|
||||
u.UUID = uuid
|
||||
tx := db.Save(u)
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func FindUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
|
||||
// now check for the user
|
||||
user := &lnbits.User{}
|
||||
// check if "username" is actually the user ID
|
||||
tx := database
|
||||
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
|
||||
// asume it's anon_id
|
||||
tx = database.Where("anon_id = ?", username).First(user)
|
||||
} else if strings.HasPrefix(username, "0x") {
|
||||
// asume it's anon_id_sha256
|
||||
tx = database.Where("anon_id_sha256 = ?", username).First(user)
|
||||
} else if strings.HasPrefix(username, "1x") {
|
||||
// asume it's uuid
|
||||
tx = database.Where("uuid = ?", username).First(user)
|
||||
} else {
|
||||
// assume it's a string @username
|
||||
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
|
||||
}
|
||||
return user, tx
|
||||
}
|
||||
|
||||
func FindUserSettings(user *lnbits.User, settingsTx *gorm.DB) (*lnbits.User, error) {
|
||||
// tx := bot.DB.Users.Preload("Settings").First(user)
|
||||
tx := settingsTx.First(user)
|
||||
if tx.Error != nil {
|
||||
return user, tx.Error
|
||||
}
|
||||
if user.Settings == nil {
|
||||
user.Settings = &lnbits.Settings{ID: user.ID}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package gpt
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
Message struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
User interface{} `json:"user"`
|
||||
CreateTime interface{} `json:"create_time"`
|
||||
UpdateTime interface{} `json:"update_time"`
|
||||
Content struct {
|
||||
ContentType string `json:"content_type"`
|
||||
Parts []string `json:"parts"`
|
||||
} `json:"content"`
|
||||
EndTurn interface{} `json:"end_turn"`
|
||||
Weight float64 `json:"weight"`
|
||||
Metadata struct {
|
||||
} `json:"metadata"`
|
||||
Recipient string `json:"recipient"`
|
||||
} `json:"message"`
|
||||
ConversationID string `json:"conversation_id"`
|
||||
Error interface{} `json:"error"`
|
||||
}
|
||||
type Request struct {
|
||||
Action string `json:"action"`
|
||||
ConversationId string `json:"conversation_id,omitempty"`
|
||||
Messages []Messages `json:"messages"`
|
||||
ParentMessageID string `json:"parent_message_id"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
type Content struct {
|
||||
ContentType string `json:"content_type"`
|
||||
Parts []string `json:"parts"`
|
||||
}
|
||||
type Messages struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
Content Content `json:"content"`
|
||||
}
|
||||
|
||||
var dataPrefix = []byte("data: ")
|
||||
var doneSequence = []byte("[DONE]")
|
||||
|
||||
func GetRawCompletion(ctx intercept.Context, rr Request, cb func(s string)) (*Response, error) {
|
||||
rawClient := http.Client{}
|
||||
r, err := json.Marshal(rr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx.Context, "POST", "https://chat.openai.com/backend-api/conversation", bytes.NewBuffer(r))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", internal.Configuration.Generate.OpenAiBearerToken))
|
||||
req.Header.Set("accept", "text/event-stream")
|
||||
req.Header.Set("authority", "chat.openai.com")
|
||||
req.Header.Set("accept-language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7")
|
||||
req.Header.Set("Content-type", "application/json")
|
||||
req.Header.Set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
|
||||
|
||||
resp, err := rawClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
output := new(Response)
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// make sure there isn't any extra whitespace before or after
|
||||
line = bytes.TrimSpace(line)
|
||||
// the completion API only returns data events
|
||||
if !bytes.HasPrefix(line, dataPrefix) {
|
||||
continue
|
||||
}
|
||||
line = bytes.TrimPrefix(line, dataPrefix)
|
||||
|
||||
// the stream is completed when terminated by [DONE]
|
||||
if bytes.HasPrefix(line, doneSequence) {
|
||||
break
|
||||
}
|
||||
if err := json.Unmarshal(line, output); err != nil {
|
||||
return nil, fmt.Errorf("invalid json stream data: %v", err)
|
||||
}
|
||||
if len(output.Message.Content.Parts) > 0 {
|
||||
cb(output.Message.Content.Parts[len(output.Message.Content.Parts)-1])
|
||||
}
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
@@ -18,15 +18,12 @@ func RegisterLanguages() *i18n.Bundle {
|
||||
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
|
||||
bundle.MustLoadMessageFile("translations/en.toml")
|
||||
bundle.LoadMessageFile("translations/de.toml")
|
||||
bundle.LoadMessageFile("translations/fi.toml")
|
||||
bundle.LoadMessageFile("translations/it.toml")
|
||||
bundle.LoadMessageFile("translations/es.toml")
|
||||
bundle.LoadMessageFile("translations/nl.toml")
|
||||
bundle.LoadMessageFile("translations/pl.toml")
|
||||
bundle.LoadMessageFile("translations/fr.toml")
|
||||
bundle.LoadMessageFile("translations/pt-br.toml")
|
||||
bundle.LoadMessageFile("translations/tr.toml")
|
||||
bundle.LoadMessageFile("translations/cs.toml")
|
||||
bundle.LoadMessageFile("translations/id.toml")
|
||||
bundle.LoadMessageFile("translations/ru.toml")
|
||||
return bundle
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
@@ -38,19 +39,64 @@ type User struct {
|
||||
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
ID string `json:"id" gorm:"primarykey"`
|
||||
Display DisplaySettings `gorm:"embedded;embeddedPrefix:display_"`
|
||||
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
|
||||
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
|
||||
func (u User) Log() map[string]interface{} {
|
||||
logMap := make(map[string]interface{})
|
||||
logMap["user_id"] = u.ID
|
||||
if u.Wallet != nil {
|
||||
logMap["wallet_id"] = u.Wallet.ID
|
||||
}
|
||||
if u.Telegram != nil {
|
||||
logMap["telegram_id"] = u.Telegram.ID
|
||||
logMap["user_name"] = u.GetUserStr()
|
||||
}
|
||||
return logMap
|
||||
}
|
||||
|
||||
type DisplaySettings struct {
|
||||
DisplayCurrency string `json:"displaycurrency"`
|
||||
func (u User) GetUserStr() string {
|
||||
userStr := fmt.Sprintf("@%s", u.Telegram.Username)
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && u.Telegram.FirstName != "" {
|
||||
userStr = fmt.Sprintf("%s", u.Telegram.FirstName)
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("%d", u.Telegram.ID)
|
||||
}
|
||||
return userStr
|
||||
}
|
||||
type NostrSettings struct {
|
||||
PubKey string `json:"pubkey"`
|
||||
|
||||
func (u User) GetUserStrMd() string {
|
||||
userStr := fmt.Sprintf("@%s", u.Telegram.Username)
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && u.Telegram.FirstName != "" {
|
||||
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", u.Telegram.FirstName, u.Telegram.ID)
|
||||
return userStr
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", u.Telegram.ID, u.Telegram.ID)
|
||||
return userStr
|
||||
} else {
|
||||
// escape only if user has a username
|
||||
return str.MarkdownEscape(userStr)
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) AnonIdSha256() string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
func (u User) UUIDSha256() string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
ID string `json:"id" gorm:"primarykey"`
|
||||
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
|
||||
}
|
||||
|
||||
type NodeSettings struct {
|
||||
NodeType string `json:"nodetype"`
|
||||
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
|
||||
|
||||
@@ -32,7 +32,7 @@ type Server struct {
|
||||
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
@@ -48,7 +48,7 @@ type Webhook struct {
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
Addr: "0.0.0.0:5588",
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
@@ -61,7 +61,9 @@ func NewServer(bot *telegram.TipBot) *Server {
|
||||
}
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[Webhook] Server started at %s", internal.Configuration.Lnbits.WebhookServerUrl)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnbits",
|
||||
"func": "NewServer", "host": internal.Configuration.Lnbits.WebhookServerUrl.String()}).Infof("started webhook server")
|
||||
return apiServer
|
||||
}
|
||||
|
||||
@@ -81,23 +83,37 @@ func (w *Server) newRouter() *mux.Router {
|
||||
}
|
||||
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive"}).Debugln("Received request")
|
||||
webhookEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"error": err.Error()}).Errorf("Error decoding request")
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"error": err.Error()}).Errorf("Error getting user")
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
amount := webhookEvent.Amount / 1000
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"user": user.GetUserStr(),
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"amount": amount}).Infoln(fmt.Sprintf("User received invoice"))
|
||||
|
||||
writer.WriteHeader(200)
|
||||
|
||||
@@ -105,12 +121,24 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"user": user.GetUserStr(),
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"error": err.Error(),
|
||||
"amount": amount}).Errorln(err)
|
||||
} else {
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
|
||||
if err := telegram.AssertEventType(txInvoiceEvent, c.Type); err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"user": user.GetUserStr(),
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"error": err.Error(),
|
||||
"amount": amount}).Errorln("invalid event type")
|
||||
return
|
||||
}
|
||||
go c.Function(txInvoiceEvent)
|
||||
@@ -121,6 +149,12 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
// fallback: send a message to the user if there is no callback for this invoice
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "webhook",
|
||||
"func": "receive",
|
||||
"user": user.GetUserStr(),
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"error": err.Error(),
|
||||
"amount": amount}).Errorln("could not send fallback message")
|
||||
}
|
||||
}
|
||||
|
||||
+61
-180
@@ -19,13 +19,11 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"gorm.io/gorm"
|
||||
|
||||
db "github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/nbd-wtf/go-nostr"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -34,19 +32,17 @@ const (
|
||||
Endpoint = ".well-known/lnurlp"
|
||||
MinSendable = 1000 // mSat
|
||||
MaxSendable = 1_000_000_000
|
||||
CommentAllowed = 2000
|
||||
CommentAllowed = 500
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
*telegram.Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
Nip57Receipt nostr.Event `json:"nip57_receipt"`
|
||||
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
}
|
||||
type Lnurl struct {
|
||||
telegram *tb.Bot
|
||||
@@ -56,7 +52,6 @@ type Lnurl struct {
|
||||
buntdb *storage.DB
|
||||
WebhookServer string
|
||||
cache telegram.Cache
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) Lnurl {
|
||||
@@ -68,7 +63,6 @@ func New(bot *telegram.TipBot) Lnurl {
|
||||
buntdb: bot.Bunt,
|
||||
telegram: bot.Telegram,
|
||||
cache: bot.Cache,
|
||||
bot: bot,
|
||||
}
|
||||
}
|
||||
func (lnurlInvoice Invoice) Key() string {
|
||||
@@ -109,43 +103,14 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
// payer data
|
||||
payerdata := request.FormValue("payerdata")
|
||||
var payerData lnurl.PayerDataValues
|
||||
if len(payerdata) > 0 {
|
||||
err = json.Unmarshal([]byte(payerdata), &payerData)
|
||||
if err != nil {
|
||||
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
|
||||
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
|
||||
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
|
||||
}
|
||||
|
||||
err = json.Unmarshal([]byte(payerdata), &payerData)
|
||||
if err != nil {
|
||||
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
|
||||
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
|
||||
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
|
||||
}
|
||||
|
||||
// nostr NIP-57
|
||||
// the "nostr" query param has a zap request which is a nostr event
|
||||
// that specifies which nostr note has been zapped.
|
||||
// here we check wheter its present, the event signature is valid
|
||||
// and whether the event has the necessary tags that we need (p and relays are necessary, e is optional)
|
||||
zapEventQuery := request.FormValue("nostr")
|
||||
var zapEvent nostr.Event
|
||||
if len(zapEventQuery) > 0 {
|
||||
err = json.Unmarshal([]byte(zapEventQuery), &zapEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[handleLnUrl] Couldn't parse nostr event: %v", err)
|
||||
} else {
|
||||
valid, err := zapEvent.CheckSignature()
|
||||
if !valid || err != nil {
|
||||
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event signature invalid: %v", err)
|
||||
return
|
||||
}
|
||||
if len(zapEvent.Tags) == 0 || zapEvent.Tags.GetFirst([]string{"p"}) == nil {
|
||||
// zapEvent.Tags.GetFirst([]string{"e"}) == nil {
|
||||
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event validation error")
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData, zapEvent)
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
@@ -180,7 +145,7 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
|
||||
// load the user profile picture
|
||||
if internal.Configuration.Bot.LNURLSendImage {
|
||||
// get the user from the database
|
||||
user, tx := db.FindUser(w.database, username)
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error == nil && user.Telegram != nil {
|
||||
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
|
||||
}
|
||||
@@ -191,25 +156,9 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
|
||||
return metadata
|
||||
}
|
||||
|
||||
// we have our custom LNURLPayParams response object here because we want to
|
||||
// add nostr nip57 fields to it
|
||||
type LNURLPayParamsCustom struct {
|
||||
lnurl.LNURLResponse
|
||||
Callback string `json:"callback"`
|
||||
Tag string `json:"tag"`
|
||||
MaxSendable int64 `json:"maxSendable"`
|
||||
MinSendable int64 `json:"minSendable"`
|
||||
EncodedMetadata string `json:"metadata"`
|
||||
CommentAllowed int64 `json:"commentAllowed"`
|
||||
PayerData *lnurl.PayerDataSpec `json:"payerData,omitempty"`
|
||||
AllowNostr bool `json:"allowsNostr,omitempty"`
|
||||
NostrPubKey string `json:"nostrPubkey,omitempty"`
|
||||
Metadata lnurl.Metadata `json:"-"`
|
||||
}
|
||||
|
||||
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
|
||||
// to call and the metadata that matches the description hash of the second response
|
||||
func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error) {
|
||||
func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
|
||||
if err != nil {
|
||||
@@ -219,18 +168,7 @@ func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error)
|
||||
// produce the metadata including the image
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
// check if the user has added a nostr key for nip57
|
||||
var allowNostr bool = false
|
||||
var nostrPubkey string = ""
|
||||
// if the bot has a nostr private key
|
||||
if len(internal.Configuration.Nostr.PrivateKey) > 0 {
|
||||
allowNostr = true
|
||||
pk := internal.Configuration.Nostr.PrivateKey
|
||||
pub, _ := nostr.GetPublicKey(pk)
|
||||
nostrPubkey = pub
|
||||
}
|
||||
|
||||
return &LNURLPayParamsCustom{
|
||||
return &lnurl.LNURLPayParams{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
Tag: PayRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
@@ -243,13 +181,11 @@ func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error)
|
||||
LightningAddress: &lnurl.PayerDataItemSpec{},
|
||||
Email: &lnurl.PayerDataItemSpec{},
|
||||
},
|
||||
AllowNostr: allowNostr,
|
||||
NostrPubKey: nostrPubkey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues, zapEvent nostr.Event) (*lnurl.LNURLPayValues, error) {
|
||||
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount_msat < MinSendable || amount_msat > MaxSendable {
|
||||
// amount is not ok
|
||||
@@ -267,11 +203,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
// get rid of LNURL spam
|
||||
if amount_msat < 21_000 {
|
||||
comment = ""
|
||||
}
|
||||
user, tx := db.FindUser(w.database, username)
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
@@ -286,75 +218,28 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
|
||||
}
|
||||
// get user settings
|
||||
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
|
||||
if err != nil {
|
||||
fmt.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
|
||||
} else {
|
||||
user = user2
|
||||
}
|
||||
// user is ok now create invoice
|
||||
// set wallet lnbits client
|
||||
|
||||
var resp *lnurl.LNURLPayValues
|
||||
var descriptionHash string
|
||||
|
||||
// NIP57 ZAPs
|
||||
// TODO: refactor all this into nip57.go
|
||||
var nip57Receipt nostr.Event
|
||||
var zapEventSerializedStr string
|
||||
var nip57ReceiptRelays []string
|
||||
// for nip57 use the nostr event as the descriptionHash
|
||||
if zapEvent.Sig != "" {
|
||||
log.Infof("[LNURL] nostr zap for user %s", username)
|
||||
// we calculate the descriptionHash here, create an invoice with it
|
||||
// and store the invoice in the zap receipt later down the line
|
||||
zapEventSerialized, err := json.Marshal(zapEvent)
|
||||
zapEventSerializedStr = fmt.Sprintf("%s", zapEventSerialized)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: "Couldn't serialize zap event."},
|
||||
}, err
|
||||
}
|
||||
// we extract the relays from the zap request
|
||||
nip57ReceiptRelaysTags := zapEvent.Tags.GetFirst([]string{"relays"})
|
||||
if len(fmt.Sprintf("%s", nip57ReceiptRelaysTags)) > 0 {
|
||||
nip57ReceiptRelays = strings.Split(fmt.Sprintf("%s", nip57ReceiptRelaysTags), " ")
|
||||
// this tirty method returns slice [ "[relays", "wss...", "wss...", "wss...]" ] – we need to clean it up
|
||||
if len(nip57ReceiptRelays) > 1 {
|
||||
// remove the first entry
|
||||
nip57ReceiptRelays = nip57ReceiptRelays[1:]
|
||||
// clean up the last entry
|
||||
len_last_entry := len(nip57ReceiptRelays[len(nip57ReceiptRelays)-1])
|
||||
nip57ReceiptRelays[len(nip57ReceiptRelays)-1] = nip57ReceiptRelays[len(nip57ReceiptRelays)-1][:len_last_entry-1]
|
||||
}
|
||||
// now the relay list is clean!
|
||||
}
|
||||
// calculate description hash from the serialized nostr event
|
||||
descriptionHash = w.Nip57DescriptionHash(zapEventSerializedStr)
|
||||
} else {
|
||||
// calculate normal LNURL descriptionhash
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.getMetaDataCached(username)
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
var payerDataByte []byte
|
||||
var err error
|
||||
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
|
||||
payerDataByte, err = json.Marshal(payerData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err = w.DescriptionHash(metadata, string(payerDataByte))
|
||||
var payerDataByte []byte
|
||||
var err error
|
||||
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
|
||||
payerDataByte, err = json.Marshal(payerData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err := w.DescriptionHash(metadata, string(payerDataByte))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
@@ -378,46 +263,21 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
Amount: amount_msat / 1000,
|
||||
}
|
||||
|
||||
// nip57 - we need to store the newly created invoice in the zap receipt
|
||||
if zapEvent.Sig != "" {
|
||||
pk := internal.Configuration.Nostr.PrivateKey
|
||||
pub, _ := nostr.GetPublicKey(pk)
|
||||
nip57Receipt = nostr.Event{
|
||||
PubKey: pub,
|
||||
CreatedAt: time.Now(),
|
||||
Kind: 9735,
|
||||
Tags: nostr.Tags{
|
||||
*zapEvent.Tags.GetFirst([]string{"p"}),
|
||||
[]string{"bolt11", invoice.PaymentRequest},
|
||||
[]string{"description", zapEventSerializedStr},
|
||||
},
|
||||
}
|
||||
if zapEvent.Tags.GetFirst([]string{"e"}) != nil {
|
||||
nip57Receipt.Tags = nip57Receipt.Tags.AppendUnique(*zapEvent.Tags.GetFirst([]string{"e"}))
|
||||
}
|
||||
nip57Receipt.Sign(pk)
|
||||
}
|
||||
|
||||
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
|
||||
// also holds Nip57 Zap receipt to send to nostr when invoice is paid
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
Invoice{
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Comment: comment,
|
||||
CreatedAt: time.Now(),
|
||||
From: extractSenderFromPayerdata(payerData),
|
||||
Nip57Receipt: nip57Receipt,
|
||||
Nip57ReceiptRelays: nip57ReceiptRelays,
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Comment: comment,
|
||||
CreatedAt: time.Now(),
|
||||
From: extractSenderFromPayerdata(payerData),
|
||||
}))
|
||||
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
telegram.InvoiceEvent{
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Callback: telegram.InvoiceCallbackLNURLPayReceive,
|
||||
UserCurrency: user.Settings.Display.DisplayCurrency,
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Callback: telegram.InvoiceCallbackLNURLPayReceive,
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
@@ -450,7 +310,7 @@ func (w Lnurl) metaData(username string) lnurl.Metadata {
|
||||
// we actually want to find the users username so it looks nicer in the
|
||||
// metadata description
|
||||
if strings.HasPrefix(username, "1x") {
|
||||
user, _ := db.FindUser(w.database, username)
|
||||
user, _ := findUser(w.database, username)
|
||||
if user.Telegram.Username != "" {
|
||||
username = user.Telegram.Username
|
||||
}
|
||||
@@ -491,6 +351,27 @@ func isAnonUsername(username string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
func findUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
|
||||
// now check for the user
|
||||
user := &lnbits.User{}
|
||||
// check if "username" is actually the user ID
|
||||
tx := database
|
||||
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
|
||||
// asume it's anon_id
|
||||
tx = database.Where("anon_id = ?", username).First(user)
|
||||
} else if strings.HasPrefix(username, "0x") {
|
||||
// asume it's anon_id_sha256
|
||||
tx = database.Where("anon_id_sha256 = ?", username).First(user)
|
||||
} else if strings.HasPrefix(username, "1x") {
|
||||
// asume it's uuid
|
||||
tx = database.Where("uuid = ?", username).First(user)
|
||||
} else {
|
||||
// assume it's a string @username
|
||||
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
|
||||
}
|
||||
return user, tx
|
||||
}
|
||||
|
||||
func extractSenderFromPayerdata(payer lnurl.PayerDataValues) string {
|
||||
if payer.LightningAddress != "" {
|
||||
return payer.LightningAddress
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Tag []string
|
||||
|
||||
type Tags []Tag
|
||||
|
||||
type NostrEvent struct {
|
||||
ID string `json:"id"`
|
||||
PubKey string `json:"pubkey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Kind int `json:"kind"`
|
||||
Tags Tags `json:"tags"`
|
||||
Content string `json:"content"`
|
||||
Sig string `json:"sig"`
|
||||
}
|
||||
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) Nip57DescriptionHash(zapEventSerialized string) string {
|
||||
hash := sha256.Sum256([]byte(zapEventSerialized))
|
||||
hashString := hex.EncodeToString(hash[:])
|
||||
return hashString
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"go.elastic.co/ecslogrus"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
log.SetFormatter(customFormatter)
|
||||
rotateFileHook, err := NewRotateFileHook(RotateFileConfig{
|
||||
Filename: "out.log",
|
||||
MaxSize: 1, // megabytes
|
||||
MaxBackups: 3,
|
||||
MaxAge: 28,
|
||||
Compress: true,
|
||||
Level: log.DebugLevel,
|
||||
Formatter: &ecslogrus.Formatter{},
|
||||
})
|
||||
//log.StandardLogger().ReportCaller = true
|
||||
log.SetFormatter(customFormatter)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.AddHook(rotateFileHook)
|
||||
}
|
||||
|
||||
// Logger is printing Text format of log map to stdout. Will also write to file using logrus hook
|
||||
type Logger struct {
|
||||
logger *log.Logger
|
||||
vars map[string]interface{}
|
||||
}
|
||||
|
||||
// Loggable structs provider their own logmap.
|
||||
type Loggable interface {
|
||||
Log() map[string]interface{}
|
||||
}
|
||||
|
||||
func WithObjects(objects ...interface{}) *log.Entry {
|
||||
fields := log.Fields{}
|
||||
for _, object := range objects {
|
||||
switch object.(type) {
|
||||
case intercept.Context:
|
||||
ctx := object.(intercept.Context)
|
||||
if fields["path"] != "" {
|
||||
switch {
|
||||
case ctx.Message() != nil:
|
||||
fields["path"] = "message"
|
||||
case ctx.Query() != nil:
|
||||
fields["path"] = "query"
|
||||
case ctx.Callback() != nil:
|
||||
fields["path"] = "callback"
|
||||
}
|
||||
}
|
||||
// check for context uuid
|
||||
if uuid := ctx.Value("uuid"); uuid != nil {
|
||||
fields["uuid"] = uuid.(string)
|
||||
}
|
||||
// add chat info from context
|
||||
if chat := ctx.Chat(); chat != nil {
|
||||
fields["chat_id"] = ctx.Chat().ID
|
||||
fields["title"] = ctx.Chat().Title
|
||||
}
|
||||
// add text as data if not set yet
|
||||
if fields["data"] == "" {
|
||||
fields["data"] = ctx.Text()
|
||||
}
|
||||
case Loggable:
|
||||
// loggable structs provider their own logmap
|
||||
for key, value := range object.(Loggable).Log() {
|
||||
fields[key] = value
|
||||
}
|
||||
case time.Time:
|
||||
t := object.(time.Time)
|
||||
fields["runtime"] = time.Now().Sub(t).String()
|
||||
case error:
|
||||
err := object.(error)
|
||||
fields["error"] = err.Error()
|
||||
}
|
||||
|
||||
}
|
||||
return log.StandardLogger().WithFields(fields)
|
||||
}
|
||||
|
||||
// RotateFileConfig configuration for logfile rotation.
|
||||
type RotateFileConfig struct {
|
||||
Filename string
|
||||
MaxSize int
|
||||
MaxBackups int
|
||||
MaxAge int
|
||||
Compress bool
|
||||
Level log.Level
|
||||
Formatter log.Formatter
|
||||
}
|
||||
|
||||
// RotateFileHook
|
||||
type RotateFileHook struct {
|
||||
Config RotateFileConfig
|
||||
logWriter io.Writer
|
||||
}
|
||||
|
||||
func NewRotateFileHook(config RotateFileConfig) (log.Hook, error) {
|
||||
hook := RotateFileHook{
|
||||
Config: config,
|
||||
}
|
||||
hook.logWriter = &lumberjack.Logger{
|
||||
Filename: config.Filename,
|
||||
MaxSize: config.MaxSize,
|
||||
MaxBackups: config.MaxBackups,
|
||||
MaxAge: config.MaxAge,
|
||||
Compress: config.Compress,
|
||||
}
|
||||
|
||||
return &hook, nil
|
||||
}
|
||||
|
||||
func (hook *RotateFileHook) Levels() []log.Level {
|
||||
return log.AllLevels[:hook.Config.Level+1]
|
||||
}
|
||||
|
||||
func (hook *RotateFileHook) Fire(entry *log.Entry) (err error) {
|
||||
b, err := hook.Config.Formatter.Format(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hook.logWriter.Write(b)
|
||||
return nil
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
@@ -21,23 +20,6 @@ const (
|
||||
ClientTypeTor = "tor"
|
||||
)
|
||||
|
||||
// checks if strings contains http(s)://*.onion
|
||||
var isOnion = regexp.MustCompile("^https?\\:\\/\\/[\\w\\-\\.]+\\.onion")
|
||||
|
||||
// GetClientForScheme returns correct client for url scheme.
|
||||
// if tld is .onion, function will also return an onion client.
|
||||
func GetClientForScheme(url *url.URL) (*http.Client, error) {
|
||||
if isOnion.FindString(url.String()) != "" {
|
||||
return GetClient(ClientTypeTor)
|
||||
}
|
||||
switch url.Scheme {
|
||||
case "onion":
|
||||
return GetClient(ClientTypeTor)
|
||||
default:
|
||||
return GetClient(ClientTypeClearNet)
|
||||
}
|
||||
}
|
||||
|
||||
func GetClient(clientType ClientType) (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
@@ -54,9 +36,6 @@ func GetClient(clientType ClientType) (*http.Client, error) {
|
||||
if cfg == nil {
|
||||
return &client, nil
|
||||
}
|
||||
if cfg.Host == "" {
|
||||
return &client, nil
|
||||
}
|
||||
proxyURL, _ := url.Parse(cfg.Host)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package nostr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
db "github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/prometheus/common/log"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Nostr struct {
|
||||
database *gorm.DB
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) Nostr {
|
||||
return Nostr{
|
||||
database: bot.DB.Users,
|
||||
bot: bot,
|
||||
}
|
||||
}
|
||||
|
||||
func (n Nostr) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
username := request.FormValue("name")
|
||||
if username == "" {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[NostrNip05] Form value 'name' is not set"))
|
||||
return
|
||||
}
|
||||
user, tx := db.FindUser(n.database, username)
|
||||
if tx.Error == nil && user.Telegram != nil {
|
||||
user, err := db.FindUserSettings(user, n.bot.DB.Users.Preload("Settings"))
|
||||
if err != nil {
|
||||
log.Errorf("[NostrNip05] user settings not found")
|
||||
api.NotFoundHandler(writer, fmt.Errorf("user settings error"))
|
||||
return
|
||||
}
|
||||
if user.Settings.Nostr.PubKey != "" {
|
||||
data := []byte(fmt.Sprintf(`{
|
||||
"names":{
|
||||
"%s":"%s"
|
||||
}
|
||||
}
|
||||
`, username, user.Settings.Nostr.PubKey))
|
||||
_, err = writer.Write(data)
|
||||
if err != nil {
|
||||
log.Errorf("[NostrNip05] Failed responding to user %s", username)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.Errorf("[NostrNip05] user not found")
|
||||
api.NotFoundHandler(writer, fmt.Errorf("user not found"))
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,9 @@ func NewPriceWatcher() *PriceWatcher {
|
||||
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
|
||||
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
|
||||
Price = make(map[string]float64, 0)
|
||||
log.Infof("[PriceWatcher] Watcher started")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "price",
|
||||
"func": "PriceWatcher"}).Infof("Watcher started")
|
||||
P = pricewatcher
|
||||
return pricewatcher
|
||||
}
|
||||
|
||||
@@ -5,127 +5,72 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var functionMap cmap.ConcurrentMap
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
functionMap = cmap.New()
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var DefaultTickerDuration = time.Second * 10
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunction will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunction struct {
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
Timer *time.Timer
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
StopChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
type ResettableFunctionTickerOption func(*ResettableFunction)
|
||||
|
||||
func WithTicker(t *time.Ticker) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunction) {
|
||||
a.Ticker = t
|
||||
}
|
||||
}
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunction) {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func WithTimer(t *time.Timer) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunction) {
|
||||
a.Timer = t
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
functionMap.Remove(name)
|
||||
tickerMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
func Get(name string) (*ResettableFunction, bool) {
|
||||
if t, ok := functionMap.Get(name); ok {
|
||||
return t.(*ResettableFunction), ok
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
func GetFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
|
||||
if t, ok := functionMap.Get(name); ok {
|
||||
return t.(*ResettableFunction)
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
} else {
|
||||
t := NewResettableFunction(name, option...)
|
||||
functionMap.Set(name, t)
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
func NewResettableFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
|
||||
t := &ResettableFunction{
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
StopChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = DefaultTickerDuration
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
// Do will listen for timers and invoke functionCallback on tick.
|
||||
func (t *ResettableFunction) Do(functionCallback func()) {
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
t.Started = true
|
||||
// persist function
|
||||
functionMap.Set(t.name, t)
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
if t.Timer != nil {
|
||||
// timer is set. checking event
|
||||
select {
|
||||
case <-t.Timer.C:
|
||||
functionCallback()
|
||||
return
|
||||
default:
|
||||
}
|
||||
}
|
||||
if t.Ticker != nil {
|
||||
// ticker is set. checking event
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function functionCallback
|
||||
functionCallback()
|
||||
return
|
||||
default:
|
||||
}
|
||||
}
|
||||
// check stop and reset channels
|
||||
select {
|
||||
case <-t.StopChan:
|
||||
if t.Timer != nil {
|
||||
t.Timer.Stop()
|
||||
}
|
||||
if t.Ticker != nil {
|
||||
t.Ticker.Stop()
|
||||
}
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
if t.Ticker != nil {
|
||||
t.Ticker.Reset(t.duration)
|
||||
}
|
||||
if t.Timer != nil {
|
||||
t.Timer.Reset(t.duration)
|
||||
}
|
||||
default:
|
||||
break
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -69,7 +69,11 @@ func LockWithContext(ctx context.Context, s string) {
|
||||
if nLocks == 0 {
|
||||
Lock(s)
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Unlock",
|
||||
"telegram_id": s,
|
||||
}).Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
|
||||
}
|
||||
nLocks++
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
@@ -98,7 +102,11 @@ func UnlockWithContext(ctx context.Context, s string) {
|
||||
Unlock(s)
|
||||
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Unlock",
|
||||
"telegram_id": s,
|
||||
}).Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
|
||||
}
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
@@ -108,7 +116,11 @@ func UnlockWithContext(ctx context.Context, s string) {
|
||||
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
|
||||
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
|
||||
func Lock(s string) {
|
||||
log.Tracef("[Mutex] Attempt Lock %s", s)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Lock",
|
||||
"telegram_id": s,
|
||||
}).Tracef("Locking attempt")
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
m.(*sync.Mutex).Lock()
|
||||
// write into mutex map
|
||||
@@ -123,7 +135,11 @@ func Lock(s string) {
|
||||
mutexMap.Set(s, m)
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
log.Tracef("[Mutex] Locked %s", s)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Lock",
|
||||
"telegram_id": s,
|
||||
}).Tracef("Locked")
|
||||
}
|
||||
|
||||
// Unlock unlocks a mutex in the mutexMap.
|
||||
@@ -132,10 +148,18 @@ func Unlock(s string) {
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
mutexMap.Remove(s)
|
||||
m.(*sync.Mutex).Unlock()
|
||||
log.Tracef("[Mutex] Unlocked %s", s)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Unlock",
|
||||
"telegram_id": s,
|
||||
}).Tracef("Unlocked")
|
||||
} else {
|
||||
// this should never happen. Mutex should have been in the mutexMap.
|
||||
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "mutex",
|
||||
"func": "Unlock",
|
||||
"telegram_id": s,
|
||||
}).Errorf("⚠️⚠️⚠️ Unlock not in mutexMap. Skip.")
|
||||
}
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
|
||||
@@ -5,14 +5,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// todo -- use function.go instead!
|
||||
// var retryMap cmap.ConcurrentMap
|
||||
|
||||
// func init() {
|
||||
// retryMap = cmap.New()
|
||||
// }
|
||||
|
||||
// ResettableFunction will reset the user state as soon as tick is delivered.
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type FunctionRetry struct {
|
||||
Ticker *time.Ticker
|
||||
duration time.Duration
|
||||
@@ -36,14 +35,14 @@ func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOpt
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = DefaultTickerDuration
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
|
||||
functionMap.Set(t.name, t)
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
|
||||
@@ -105,7 +105,6 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
@@ -118,7 +117,10 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[MakeInvoice] LND invoice at %s", backend.Host)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "MakeInvoice",
|
||||
"host": backend.Host}).Debugf("LND invoice")
|
||||
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
@@ -173,7 +175,10 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
return checkInvoiceParams, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[MakeInvoice] LNBits invoice at %s", backend.Host)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "MakeInvoice",
|
||||
"host": backend.Host}).Debug("LNBits invoice")
|
||||
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
|
||||
body, _ = sjson.Set(body, "out", false)
|
||||
|
||||
@@ -241,13 +246,16 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[CheckInvoice] LND invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "CheckInvoice",
|
||||
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
|
||||
"host": backend.Host}).Debugf("[CheckInvoice] LND invoice")
|
||||
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
|
||||
@@ -291,8 +299,16 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
return params, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[CheckInvoice] LNBits invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
log.Debug("Getting ", backend.Host+"/api/v1/payments/"+string(params.Hash))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "CheckInvoice",
|
||||
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
|
||||
"host": backend.Host}).Debugf("LNBits invoice")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "CheckInvoice",
|
||||
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
|
||||
"host": backend.Host + "/api/v1/payments/" + string(params.Hash)}).Debug("Fetching GET")
|
||||
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
|
||||
@@ -2,7 +2,6 @@ package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
@@ -57,7 +56,6 @@ func (db *DB) Get(object Storable) error {
|
||||
}
|
||||
err = json.Unmarshal([]byte(val), object)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
)
|
||||
|
||||
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
@@ -41,17 +38,3 @@ func Int64Hash(s string) uint64 {
|
||||
h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
func AnonIdSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
func UUIDSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -17,16 +18,10 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// amountsMap maps string to int64 amounts
|
||||
var amountsMap = map[string]int64{
|
||||
"🍌": 777,
|
||||
"🥜": 69,
|
||||
}
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", fmt.Errorf("message doesn't contain enough arguments")
|
||||
@@ -37,9 +32,7 @@ func getArgumentFromCommand(input string, which int) (output string, err error)
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
return 0, fmt.Errorf("message doesn't contain any amount")
|
||||
}
|
||||
amount, err = GetAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
@@ -48,14 +41,6 @@ func decodeAmountFromCommand(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) {
|
||||
// replace occurances of comma with dot
|
||||
input = strings.Replace(input, ",", ".", -1)
|
||||
|
||||
// replace strings in amountsMap with their integer values
|
||||
for k, v := range amountsMap {
|
||||
input = strings.Replace(input, k, strconv.FormatInt(v, 10), -1)
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -76,7 +61,6 @@ func GetAmount(input string) (amount int64, err error) {
|
||||
numeric_string = strings.Replace(strings.ToLower(numeric_string), strings.ToLower(currency), "", 1) // for 1USD
|
||||
fmount, err := strconv.ParseFloat(numeric_string, 64)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
@@ -98,14 +82,6 @@ func GetAmount(input string) (amount int64, err error) {
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
}
|
||||
fiat = float64(amount) / 100_000_000 * price.Price[currency]
|
||||
return fiat, nil
|
||||
}
|
||||
|
||||
type EnterAmountStateData struct {
|
||||
ID string `json:"ID"` // holds the ID of the tx object in bunt db
|
||||
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
|
||||
@@ -130,7 +106,9 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "askForAmount"}).Errorln("could not marshal state data")
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
|
||||
@@ -159,24 +137,27 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "enterAmountHandler",
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("could not unmarshal state data")
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
amount, err := GetAmount(ctx.Message().Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Warnf("invalid amount")
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
(amount > EnterAmountStateData.AmountMax/1000 || amount < EnterAmountStateData.AmountMin/1000) { // this line then checks whether the amount is in the range
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{"data": ctx.Message().Text, "amount": amount}).Warnf("amount not in range")
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
@@ -201,7 +182,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(ctx, err, user).WithField("data", ctx.Message().Text).Errorln("error marshaling state data")
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
@@ -212,6 +193,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.WithObjects(ctx, user, err).WithField("data", ctx.Message().Text).Warnf("transaction not found")
|
||||
return ctx, err
|
||||
}
|
||||
LnurlWithdrawState := sn.(*LnurlWithdrawState)
|
||||
@@ -222,7 +204,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(ctx, user, err).WithField("data", ctx.Message().Text).Errorln("could not marshal state data")
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
|
||||
@@ -2,11 +2,12 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
logrus "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
@@ -17,7 +18,7 @@ func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
if len(m.Text) > 0 {
|
||||
bot.anyTextHandler(ctx)
|
||||
}
|
||||
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
@@ -33,15 +34,18 @@ func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
return bot.startHandler(ctx)
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(ctx.Sender())
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
|
||||
log.WithObjects(user, err).WithFields(logFields).Error("Error fetching balance")
|
||||
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "balanceErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
log.WithObjects(user).WithFields(logFields).WithField("amount", balance).Infof("sending balance to user")
|
||||
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -77,7 +77,9 @@ func (bot TipBot) initBotWallet() error {
|
||||
botWalletInitialisation.Do(func() {
|
||||
_, err := bot.initWallet(bot.Telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "initBotWallet"}).Errorln(fmt.Sprintf("Could not initialize bot wallet: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
})
|
||||
@@ -109,7 +111,10 @@ func (bot *TipBot) GracefulShutdown() {
|
||||
|
||||
// Start will initialize the Telegram bot and lnbits.
|
||||
func (bot *TipBot) Start() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "Start",
|
||||
"user": bot.Telegram.Me.Username}).Infof("Authorized on account")
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
@@ -135,7 +140,6 @@ func (bot *TipBot) Start() {
|
||||
// start the telegram bot
|
||||
go bot.Telegram.Start()
|
||||
|
||||
go bot.restartPersistedTickets()
|
||||
// gracefully shutdown
|
||||
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
|
||||
// we need to catch SIGTERM and SIGSTOP
|
||||
|
||||
@@ -13,17 +13,11 @@ import (
|
||||
|
||||
// we can't use space in the label of buttons, because string splitting will mess everything up.
|
||||
const (
|
||||
// MainMenuCommandWebApp = "⤵️ Recv"
|
||||
// MainMenuCommandBalance = "Balance"
|
||||
// MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
// MainMenuCommandHelp = "📖 Help"
|
||||
// MainMenuCommandSend = "⤴️ Send"
|
||||
// SendMenuCommandEnter = "👤 Enter"
|
||||
MainMenuCommandWebApp = "🗳️ App"
|
||||
MainMenuCommandWebApp = "⤵️ Recv"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
MainMenuCommandSend = "⤴️"
|
||||
MainMenuCommandSend = "⤴️ Send"
|
||||
SendMenuCommandEnter = "👤 Enter"
|
||||
)
|
||||
|
||||
@@ -44,8 +38,7 @@ func init() {
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -99,7 +92,13 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
if user.Wallet != nil {
|
||||
amount, err := bot.GetUserBalanceCached(user)
|
||||
if err == nil {
|
||||
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-buttons",
|
||||
"func": "mainMenuBalanceButtonUpdate",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Tracef("user %s balance %d sat", user.GetUserStr(), amount)
|
||||
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
}
|
||||
@@ -107,8 +106,7 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -122,8 +120,14 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
|
||||
user := LoadUser(ctx)
|
||||
// get 5 most recent transactions by from_id with distint to_user
|
||||
// where to_user starts with an @ and is not the user itself
|
||||
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
|
||||
log.Debugf("[makeContactsButtons] found %d records", len(records))
|
||||
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", user.GetUserStr()).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-buttons",
|
||||
"func": "makeContactsButtons",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Debugf("[makeContactsButtons] found %d records", len(records))
|
||||
|
||||
// get all contacts and add them to the buttons
|
||||
for i, r := range records {
|
||||
|
||||
@@ -5,23 +5,23 @@ import (
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/tidwall/buntdb"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -36,29 +36,18 @@ type Databases struct {
|
||||
}
|
||||
|
||||
const (
|
||||
JoinTicketIndex = "join-ticket:*"
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
|
||||
func createBunt(file string) *storage.DB {
|
||||
t1 := time.Now()
|
||||
// create bunt database
|
||||
bunt := storage.NewBunt(file)
|
||||
log.Infof("[blunt] loaded file in %s", time.Since(t1))
|
||||
// create bunt database index for ascending (searching) TipTooltips
|
||||
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
|
||||
log.Infof("[blunt] index 1 created in %s", time.Since(t1))
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = bunt.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString)
|
||||
log.Infof("[blunt] index 2 created in %s", time.Since(t1))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Infof("[blunt] total time: %s", time.Since(t1))
|
||||
return bunt
|
||||
}
|
||||
|
||||
@@ -71,7 +60,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running anon_id database migrations ...")
|
||||
logrus.Info("Running anon_id database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdInt32Hash(db)
|
||||
}
|
||||
@@ -83,7 +72,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running anon_id_sha256 database migrations ...")
|
||||
logrus.Info("Running anon_id_sha256 database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdSha265Hash(db)
|
||||
}
|
||||
@@ -95,7 +84,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running UUID database migrations ...")
|
||||
logrus.Info("Running UUID database migrations ...")
|
||||
// run the migration on uuid
|
||||
err = database.MigrateUUIDSha265Hash(db)
|
||||
}
|
||||
@@ -178,8 +167,7 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
tx := bot.DB.Users.First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
|
||||
user.Telegram = u
|
||||
return user, tx.Error
|
||||
}
|
||||
@@ -191,8 +179,10 @@ func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
tx := bot.DB.Users.Preload("Settings").First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetLnbitsUserWithSettings] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
log.WithObjects(user, tx.Error).WithFields(logrus.Fields{
|
||||
"module": "database",
|
||||
"func": "GetLnbitsUserWithSettings",
|
||||
}).Warnln(fmt.Sprintf("Couldn't preload user settings from Database"))
|
||||
user.Telegram = u
|
||||
return user, tx.Error
|
||||
}
|
||||
@@ -218,7 +208,10 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user.Telegram = u
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
|
||||
log.WithObjects(user, err).WithFields(logrus.Fields{
|
||||
"module": "database",
|
||||
"func": "GetUser",
|
||||
}).Warnln(fmt.Sprintf("UpdateUserRecord failed"))
|
||||
}
|
||||
}
|
||||
return user, err
|
||||
@@ -241,7 +234,7 @@ func debugStack() {
|
||||
hasher.Write(stack)
|
||||
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
|
||||
fo, err := os.Create(fmt.Sprintf("trace_%s.txt", sha))
|
||||
log.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
|
||||
logrus.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -260,36 +253,38 @@ func debugStack() {
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
user.UpdatedAt = time.Now()
|
||||
|
||||
logFields := logrus.Fields{
|
||||
"module": "database",
|
||||
"func": "UpdateUserRecord",
|
||||
}
|
||||
// There is a weird bug that makes the AnonID vanish. This is a workaround.
|
||||
// TODO -- Remove this after empty anon id bug is identified
|
||||
if user.AnonIDSha256 == "" {
|
||||
debugStack()
|
||||
user.AnonIDSha256 = str.AnonIdSha256(user)
|
||||
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonIDSha256)
|
||||
user.AnonIDSha256 = user.AnonIdSha256()
|
||||
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.AnonIDSha256).Errorf("Setting AnonIDSha256")
|
||||
}
|
||||
// TODO -- Remove this after empty anon id bug is identified
|
||||
if user.AnonID == "" {
|
||||
debugStack()
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
log.Errorf("[UpdateUserRecord] AnonID empty! Setting to: %s", user.AnonID)
|
||||
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.AnonID).Errorf("Setting AnonID")
|
||||
}
|
||||
// TODO -- Remove this after empty anon id bug is identified
|
||||
if user.UUID == "" {
|
||||
debugStack()
|
||||
user.UUID = str.UUIDSha256(user)
|
||||
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
|
||||
user.UUID = user.UUIDSha256()
|
||||
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.UUID).Errorf("Setting UUID")
|
||||
}
|
||||
|
||||
tx := bot.DB.Users.Save(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
log.WithObjects(user).WithFields(logFields).Info("Updated records of user")
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
|
||||
+19
-43
@@ -2,14 +2,11 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
@@ -19,7 +16,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
logrus "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -42,6 +39,9 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
|
||||
|
||||
func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "donationHandler"}
|
||||
m := ctx.Message()
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
@@ -55,44 +55,19 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
|
||||
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
amount = amount * 1000
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
// get invoice
|
||||
r, err := http.NewRequest(http.MethodGet, donationEndpoint, nil)
|
||||
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, user.GetUserStr(), GetUserStr(bot.Telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
// Create query parameters
|
||||
params := url.Values{}
|
||||
params.Set("amount", strconv.FormatInt(amount, 10))
|
||||
params.Set("comment", fmt.Sprintf("from %s bot %s", GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
|
||||
// Set the query parameters in the URL
|
||||
r.URL.RawQuery = params.Encode()
|
||||
|
||||
resp, err := http.DefaultClient.Do(r)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(user, err, ctx).WithFields(logFields).Errorln("could not GET donation endpoint")
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
pv := lnurl.LNURLPayValues{}
|
||||
err = json.Unmarshal(body, &pv)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
if pv.Status == "ERROR" || len(pv.PR) < 1 {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(user, err, ctx).WithFields(logFields).Errorln("could not read body")
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -100,11 +75,9 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
|
||||
// send donation invoice
|
||||
// user := LoadUser(ctx)
|
||||
// bot.trySendMessage(user.Telegram, string(body))
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(pv.PR)}, bot.Client)
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
|
||||
if err != nil {
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln("donation failed")
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -118,7 +91,8 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
|
||||
|
||||
func init() {
|
||||
var sb strings.Builder
|
||||
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/.jryy-xabja/yaheyc/YvtugavatGvcObg")})
|
||||
rot := []byte{117, 103, 103, 99, 102, 58, 47, 47, 121, 97, 46, 103, 118, 99, 102, 47, 113, 98, 97, 110, 103, 114, 47, 37, 113, 63, 115, 101, 98, 122, 61, 37, 102, 38, 111, 98, 103, 61, 37, 102}
|
||||
_, err := io.Copy(&sb, rot13Reader{strings.NewReader(string(rot))})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -150,7 +124,9 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
var d = []byte{71, 117, 110, 97, 120, 32, 108, 98, 104, 33, 32, 86, 39, 122, 32, 101, 98, 104, 103, 118, 97, 116, 32, 103, 117, 118, 102, 32, 113, 98, 97, 110, 103, 118, 98, 97, 32, 103, 98, 32, 89, 118, 116, 117, 103, 97, 118, 97, 116, 71, 118, 99, 79, 98, 103, 64, 121, 97, 46, 103, 118, 99, 102, 46}
|
||||
|
||||
func (bot TipBot) parseDonationCommandHandler(ctx intercept.Context) error {
|
||||
m := ctx.Message()
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
@@ -175,7 +151,7 @@ func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader(string(d))})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -183,7 +159,7 @@ func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
|
||||
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(ctx)
|
||||
ctx, err = bot.donationHandler(ctx)
|
||||
// returning nil here will abort the parent ctx (/pay or /tip)
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
+68
-11
@@ -158,7 +158,6 @@ func (bot TipBot) makeQueryFaucet(ctx intercept.Context) (*InlineFaucet, error)
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
@@ -187,16 +186,31 @@ func (bot TipBot) faucetHandler(ctx intercept.Context) (intercept.Context, error
|
||||
ctx.Context = bot.mapFaucetLanguage(ctx, ctx.Text())
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, ctx.Message(), false)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "faucetHandler",
|
||||
"error": err.Error()}).Warnf("could not create faucet from message")
|
||||
return ctx, err
|
||||
}
|
||||
fromUserStr := GetUserStr(ctx.Message().Sender)
|
||||
mFaucet := bot.trySendMessage(ctx.Message().Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "faucetHandler",
|
||||
"user": fromUserStr,
|
||||
"telegram_id": ctx.Message().Sender.ID,
|
||||
"data": fmt.Sprintf("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount),
|
||||
"error": err.Error()}).Infof("created faucet")
|
||||
|
||||
// log faucet link if possible
|
||||
if mFaucet != nil && mFaucet.Chat != nil {
|
||||
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "faucetHandler",
|
||||
"user": fromUserStr,
|
||||
"telegram_id": ctx.Message().Sender.ID,
|
||||
"data": fmt.Sprintf("https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID),
|
||||
"error": err.Error()}).Infof("found faucet link")
|
||||
}
|
||||
return ctx, inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
}
|
||||
@@ -204,7 +218,10 @@ func (bot TipBot) faucetHandler(ctx intercept.Context) (intercept.Context, error
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "handleInlineFaucetQuery",
|
||||
"error": err.Error()}).Errorf("could not create faucet from query")
|
||||
return ctx, err
|
||||
}
|
||||
urls := []string{
|
||||
@@ -248,7 +265,12 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "acceptInlineFaucetHandler",
|
||||
"telegram_id": ctx.Message().Sender.ID,
|
||||
"data": c.Data,
|
||||
"error": err.Error()}).Errorf("could not fetch transaction")
|
||||
return ctx, err
|
||||
}
|
||||
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
|
||||
@@ -263,11 +285,27 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
}
|
||||
// log faucet link if possible
|
||||
if c.Message != nil && c.Message.Chat != nil {
|
||||
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "acceptInlineFaucetHandler",
|
||||
"user": GetUserStr(from.Telegram),
|
||||
"user_id": from.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"data": fmt.Sprintf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID),
|
||||
}).Infof("found faucet link")
|
||||
}
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "acceptInlineFaucetHandler",
|
||||
"user": GetUserStr(from.Telegram),
|
||||
"user_id": from.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"data": inlineFaucet.ID,
|
||||
}).Debugf("cannot drain own faucet")
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
@@ -275,7 +313,17 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
for _, a := range inlineFaucet.To {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "acceptInlineFaucetHandler",
|
||||
"user": GetUserStr(from.Telegram),
|
||||
"to_user_id": to.ID,
|
||||
"to_telegram_id": to.Telegram.ID,
|
||||
"user_id": from.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"data": inlineFaucet.ID,
|
||||
}).Debugf("already took from faucet")
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
@@ -293,8 +341,17 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
if !exists {
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-faucet",
|
||||
"func": "acceptInlineFaucetHandler",
|
||||
"to_user": GetUserStr(to.Telegram),
|
||||
"to_user_id": to.ID,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"user": GetUserStr(from.Telegram),
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"error": err.Error()},
|
||||
).Errorln("Could not create wallet for user")
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
@@ -17,7 +16,7 @@ func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found ctx for this state
|
||||
// now looking for user state reset ticker
|
||||
ticker := runtime.GetFunction(user.ID, runtime.WithTicker(time.NewTicker(runtime.DefaultTickerDuration)))
|
||||
ticker := runtime.GetTicker(user.ID)
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
ResetUserState(user, bot)
|
||||
|
||||
@@ -65,7 +65,7 @@ func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Conte
|
||||
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, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", user.GetUserStr()), InvoiceCallbackGenerateDalle, prompt)
|
||||
invoice.Payer = user
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -175,7 +175,7 @@ func (bot *TipBot) generateDalleImages(event Event) {
|
||||
continue
|
||||
}
|
||||
if t.Status == dalle.StatusSucceeded {
|
||||
log.Printf("[DALLE-%d] 🎆 task succeeded for user %s", workerId, GetUserStr(user.Telegram))
|
||||
log.Printf("[DALLE-%d] task succeeded for user %s", workerId, user.GetUserStr())
|
||||
// download the first generated image
|
||||
for _, data := range t.Generations.Data {
|
||||
err = bot.downloadAndSendImages(ctx, dalleClient, data, invoiceEvent)
|
||||
@@ -190,7 +190,7 @@ func (bot *TipBot) generateDalleImages(event Event) {
|
||||
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))
|
||||
log.Debugf("[DALLE-%d] pending for user %s", workerId, user.GetUserStr())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,7 +237,7 @@ func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(internal.Configuration.Generate.DallePrice),
|
||||
Memo: fmt.Sprintf("Refund DALLE2 %s", GetUserStr(user.Telegram)),
|
||||
Memo: fmt.Sprintf("Refund DALLE2 %s", user.GetUserStr()),
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
@@ -250,7 +250,7 @@ func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
|
||||
log.Errorln(err)
|
||||
return err
|
||||
}
|
||||
log.Warnf("[DALLE] refunding user %s with %d sat", GetUserStr(user.Telegram), internal.Configuration.Generate.DallePrice)
|
||||
log.Warnf("[DALLE] refunding user %s with %d sat", user.GetUserStr(), internal.Configuration.Generate.DallePrice)
|
||||
|
||||
var err_reason string
|
||||
if len(message) > 0 {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/gpt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot *TipBot) gptHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
question := GetMemoFromCommand(ctx.Text(), 1)
|
||||
req := gpt.Request{
|
||||
Action: "next",
|
||||
Model: "text-davinci-002-render",
|
||||
Messages: []gpt.Messages{{
|
||||
ID: uuid.NewV4().String(),
|
||||
Role: "user",
|
||||
Content: gpt.Content{
|
||||
ContentType: "text",
|
||||
Parts: []string{question},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
conversationIdCacheKey := fmt.Sprintf("conversation_%d", ctx.Chat().ID)
|
||||
parentIdCacheKey := fmt.Sprintf("conversation_parent_%d", ctx.Chat().ID)
|
||||
conversationId, _ := bot.Cache.Get(conversationIdCacheKey)
|
||||
|
||||
if parentId, _ := bot.Cache.Get(parentIdCacheKey); parentId != nil {
|
||||
req.ParentMessageID = parentId.(string)
|
||||
}
|
||||
if conversationId != nil {
|
||||
req.ConversationId = conversationId.(string)
|
||||
}
|
||||
cbc := 0
|
||||
var msg *telebot.Message
|
||||
completion, err := gpt.GetRawCompletion(ctx, req, func(s string) {
|
||||
cbc++
|
||||
if ctx.Chat().Type == telebot.ChatPrivate {
|
||||
if cbc == 20 {
|
||||
msg = bot.trySendMessageEditable(ctx.Sender(), s)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if cbc == 20 {
|
||||
msg = bot.tryReplyMessage(ctx.Message(), s)
|
||||
return
|
||||
}
|
||||
}
|
||||
if cbc%20 == 0 {
|
||||
bot.tryEditMessage(msg, s)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not create completion."))
|
||||
return ctx, err
|
||||
}
|
||||
answer := completion.Message.Content.Parts[len(completion.Message.Content.Parts)-1]
|
||||
bot.tryEditMessage(msg, answer)
|
||||
err = bot.Cache.Set(conversationIdCacheKey, completion.ConversationID, nil)
|
||||
if err != nil {
|
||||
log.Errorf("[/gpt] error setting conversation id %s: %v", conversationIdCacheKey, err)
|
||||
}
|
||||
err = bot.Cache.Set(parentIdCacheKey, completion.Message.ID, nil)
|
||||
if err != nil {
|
||||
log.Errorf("[/gpt] error setting parent message id %s: %v", parentIdCacheKey, err)
|
||||
}
|
||||
log.Infof("[/gpt] \"%s\" => \"%s\"", question, answer)
|
||||
return ctx, nil
|
||||
}
|
||||
+24
-157
@@ -5,9 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
@@ -24,30 +22,6 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type JoinTicket struct {
|
||||
Sender *tb.User `json:"sender"`
|
||||
Message *tb.Message `json:"message"`
|
||||
CreatedTimestamp time.Time `json:"created_timestamp"`
|
||||
Ticket *Ticket `json:"ticket"`
|
||||
}
|
||||
|
||||
func (jt JoinTicket) Key() string {
|
||||
return fmt.Sprintf("join-ticket:%d_%d", jt.Message.Chat.ID, jt.Sender.ID)
|
||||
}
|
||||
|
||||
func (jt JoinTicket) Type() EventType {
|
||||
return EventTypeTicketInvoice
|
||||
}
|
||||
|
||||
func (bot *TipBot) loadGroup(groupName string) (*Group, error) {
|
||||
group := &Group{}
|
||||
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return group, nil
|
||||
}
|
||||
|
||||
type Ticket struct {
|
||||
Price int64 `json:"price"`
|
||||
Memo string `json:"memo"`
|
||||
@@ -109,9 +83,8 @@ var (
|
||||
btnPayTicket = paymentConfirmationMenu.Data("✅ Pay", "pay_ticket")
|
||||
)
|
||||
|
||||
const (
|
||||
groupInvoiceMemo = "🎟 Ticket for group %s"
|
||||
groupInvoiceCommissionMemo = "🎟 Commission for group %s"
|
||||
var (
|
||||
groupInvoiceMemo = "🎟 Ticket for group %s"
|
||||
)
|
||||
|
||||
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
|
||||
@@ -119,18 +92,15 @@ const (
|
||||
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
// user := LoadUser(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if len(splits) == 1 {
|
||||
// command: /group
|
||||
if ctx.Message().Private() {
|
||||
// /group help message
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "groupHelpMessage"), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me)))
|
||||
} else {
|
||||
if bot.isOwner(ctx.Message().Chat, user.Telegram) {
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
|
||||
}
|
||||
}
|
||||
// else {
|
||||
// if bot.isOwner(ctx.Message().Chat, user.Telegram) {
|
||||
// bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
|
||||
// }
|
||||
// }
|
||||
return ctx, nil
|
||||
} else if len(splits) > 1 {
|
||||
if splits[1] == "join" {
|
||||
@@ -139,9 +109,6 @@ func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if splits[1] == "add" {
|
||||
return bot.addGroupHandler(ctx)
|
||||
}
|
||||
if splits[1] == "ticket" {
|
||||
return bot.handleJoinTicketPayWall(ctx)
|
||||
}
|
||||
if splits[1] == "remove" {
|
||||
// todo -- implement this
|
||||
// return bot.addGroupHandler(ctx, m)
|
||||
@@ -246,11 +213,6 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
|
||||
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
|
||||
// pay button is sent to the user.
|
||||
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
|
||||
confirmText, confirmationMenu := bot.getSendPayButton(ctx, ticket)
|
||||
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, confirmationMenu)
|
||||
return ctx, nil
|
||||
}
|
||||
func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (string, *tb.ReplyMarkup) {
|
||||
// object that holds all information about the send payment
|
||||
// // // create inline buttons
|
||||
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
|
||||
@@ -259,10 +221,11 @@ func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (
|
||||
btnPayTicket),
|
||||
)
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), ticket.Group.Ticket.Price)
|
||||
// if len(ticket.Group.Ticket.Memo) > 0 {
|
||||
// confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
|
||||
// }
|
||||
return confirmText, ticketPayConfirmationMenu
|
||||
if len(ticket.Group.Ticket.Memo) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
|
||||
}
|
||||
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, ticketPayConfirmationMenu)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
|
||||
@@ -297,23 +260,19 @@ func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercep
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", GetUserStr(user.Telegram), ticketEvent.ID, ticketEvent.Group.Ticket.Price)
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", user.GetUserStr(), ticketEvent.ID, ticketEvent.Group.Ticket.Price)
|
||||
// // pay invoice
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: ticketEvent.Invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", user.GetUserStr(), err)
|
||||
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
if ticketEvent.Callback != InvoiceCallbackPayJoinTicket {
|
||||
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
}
|
||||
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
// if this was a join-ticket, we want to delete the invoice message
|
||||
|
||||
// update the message and remove the button
|
||||
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -369,12 +328,19 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
|
||||
// take a commission
|
||||
ticketSat := ticketEvent.Group.Ticket.Price
|
||||
if commissionSat := getTicketCommission(ticketEvent.Group.Ticket); commissionSat > 0 {
|
||||
if ticketEvent.Group.Ticket.Price > 20 {
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[groupGetInviteLinkHandler] Could not get bot user from DB: %s", err.Error())
|
||||
return
|
||||
}
|
||||
// 2% cut + 100 sat base fee
|
||||
commissionSat := ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.Cut/100 + ticketEvent.Group.Ticket.BaseFee
|
||||
if ticketEvent.Group.Ticket.Price <= 1000 {
|
||||
// if < 1000, then 10% cut + 10 sat base fee
|
||||
commissionSat = ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.CutCheap/100 + ticketEvent.Group.Ticket.BaseFeeCheap
|
||||
}
|
||||
|
||||
ticketSat = ticketEvent.Group.Ticket.Price - commissionSat
|
||||
invoice, err := me.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
@@ -406,105 +372,6 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) handleJoinTicketPayWall(ctx intercept.Context) (intercept.Context, error) {
|
||||
var err error
|
||||
var cmd string
|
||||
if cmd, err = getArgumentFromCommand(ctx.Message().Text, 2); err == nil {
|
||||
switch strings.TrimSpace(strings.ToLower(cmd)) {
|
||||
case "del":
|
||||
fallthrough
|
||||
case "delete":
|
||||
fallthrough
|
||||
case "remove":
|
||||
return bot.removeJoinTicketPayWallHandler(ctx)
|
||||
default:
|
||||
return bot.addJoinTicketPayWallHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
func (bot TipBot) removeJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).Delete(&Group{})
|
||||
if tx.Error != nil {
|
||||
return ctx, tx.Error
|
||||
}
|
||||
bot.trySendMessage(ctx.Message().Chat, "🎟 Ticket removed.")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// addJoinTicketPayWallHandler is invoked if the user calls the "/group ticket" command
|
||||
func (bot TipBot) addJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type == tb.ChatPrivate {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, fmt.Errorf("not in group")
|
||||
}
|
||||
// parse command "/group ticket <grou_name> [<amount>]"
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) < 3 || len(m.Text) > 100 {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
// check if the user is the owner of the group
|
||||
if !bot.isOwner(m.Chat, user.Telegram) {
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
|
||||
if !bot.isAdminAndCanInviteUsers(m.Chat, bot.Telegram.Me) {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupBotIsNotAdminMessage"))
|
||||
return ctx, fmt.Errorf("bot is not admin")
|
||||
}
|
||||
|
||||
// check if the group with this name is already in db
|
||||
// only if a group with this name is owned by this user, it can be overwritten
|
||||
group := &Group{}
|
||||
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error == nil {
|
||||
// if it is already added, check if this user is the admin
|
||||
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
}
|
||||
|
||||
amount := int64(0) // default amount is zero
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
ticket := &Ticket{
|
||||
Price: amount,
|
||||
Memo: "Ticket for group " + groupName,
|
||||
Creator: user,
|
||||
Cut: 2,
|
||||
BaseFee: 100,
|
||||
CutCheap: 10,
|
||||
BaseFeeCheap: 10,
|
||||
}
|
||||
|
||||
group = &Group{
|
||||
Name: groupName,
|
||||
Title: m.Chat.Title,
|
||||
ID: m.Chat.ID,
|
||||
Owner: user.Telegram,
|
||||
Ticket: ticket,
|
||||
}
|
||||
|
||||
bot.DB.Groups.Save(group)
|
||||
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddedMessagePublic"))
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// addGroupHandler is invoked if the user calls the "/group add" command
|
||||
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
@@ -572,7 +439,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
|
||||
bot.DB.Groups.Save(group)
|
||||
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
|
||||
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessagePrivate"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+411
-164
File diff suppressed because it is too large
Load Diff
@@ -274,7 +274,7 @@ func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *In
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), "", InvoiceCallbackInlineReceive, inlineReceive.ID)
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
|
||||
@@ -72,12 +72,17 @@ func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Contex
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "handleInlineSendQuery"}).Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
log.Errorf("Balance of user %s too low", fromUserStr)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "handleInlineSendQuery",
|
||||
"user": fromUserStr}).Errorf("Balance too low")
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
@@ -158,7 +163,13 @@ func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Contex
|
||||
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "handleInlineSendQuery",
|
||||
"user": fromUserStr,
|
||||
"user_id": fromUser.ID,
|
||||
"wallet_id": fromUser.Wallet.ID,
|
||||
"telegram_id": fromUser.Telegram.ID}).Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
@@ -180,8 +191,13 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
|
||||
fromUser := inlineSend.From
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
err = errors.Create(errors.NotActiveError)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"error": err.Error()},
|
||||
).Errorf("inline send not active anymore")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
@@ -212,11 +228,26 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
log.Infof("[sendInline] User %s has no wallet.", toUserStr)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"user": fromUserStr,
|
||||
"user_id": fromUser.ID,
|
||||
"wallet_id": fromUser.Wallet.ID},
|
||||
).Infof("User has no wallet.")
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"to_user": toUserStr,
|
||||
"user": fromUserStr,
|
||||
"user_id": fromUser.ID,
|
||||
"wallet_id": fromUser.Wallet.ID,
|
||||
"error": err.Error()},
|
||||
).Errorln("Could not create wallet for user")
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
@@ -228,14 +259,41 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
if err != nil {
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"user": fromUserStr,
|
||||
"user_id": fromUser.ID,
|
||||
"wallet_id": fromUser.Wallet.ID,
|
||||
"amount": amount,
|
||||
"error": err.Error()},
|
||||
).Errorln("inline send failed")
|
||||
}
|
||||
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
if !success {
|
||||
err = errors.Create(errors.UnknownError)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"error": err.Error()},
|
||||
).Errorln("transaction failed")
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, err
|
||||
}
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "acceptInlineSendHandler",
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"user": fromUserStr,
|
||||
"user_id": fromUser.ID,
|
||||
"wallet_id": fromUser.Wallet.ID,
|
||||
"amount": amount},
|
||||
).Infof("Success")
|
||||
|
||||
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineSend.Memo
|
||||
@@ -249,10 +307,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -264,7 +319,11 @@ func (bot *TipBot) cancelInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "inline_send",
|
||||
"func": "cancelInlineSendHandler",
|
||||
"error": err.Error()},
|
||||
).Errorf("could not cancel")
|
||||
return ctx, err
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
@@ -2,78 +2,108 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// Context bundles tb.Context and context.Context
|
||||
type Context struct {
|
||||
context.Context
|
||||
TeleContext
|
||||
}
|
||||
|
||||
// TeleContext is a proxy struct for tb.Context
|
||||
type TeleContext struct {
|
||||
tb.Context
|
||||
}
|
||||
|
||||
// Func is the custom intercept handler func type. This will accept and return the bundled context
|
||||
type Func func(ctx Context) (Context, error)
|
||||
|
||||
type handlerInterceptor struct {
|
||||
// handlerWithInterceptor is the custom handler func containing a Chain of intercept's
|
||||
type handlerWithInterceptor struct {
|
||||
handler Func
|
||||
before Chain
|
||||
after Chain
|
||||
onDefer Chain
|
||||
fields log.Fields
|
||||
}
|
||||
|
||||
// Chain are multiple custom intercept Func
|
||||
type Chain []Func
|
||||
type Option func(*handlerInterceptor)
|
||||
|
||||
// Option for building custom intercept Chain
|
||||
type Option func(*handlerWithInterceptor)
|
||||
|
||||
func WithBefore(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
return func(a *handlerWithInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfter(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
return func(a *handlerWithInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDefer(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
return func(a *handlerWithInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func intercept(h Context, hm Chain) (Context, error) {
|
||||
func WithDefaultLogFields(f log.Fields) Option {
|
||||
return func(a *handlerWithInterceptor) {
|
||||
a.fields = f
|
||||
}
|
||||
}
|
||||
|
||||
if hm != nil {
|
||||
// intercept is where all intercept's from single Chain are executed
|
||||
func intercept(ctx Context, chain Chain) (Context, error) {
|
||||
if chain != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
h, err = m(h)
|
||||
for _, m := range chain {
|
||||
ctx, err = m(ctx)
|
||||
if err != nil {
|
||||
return h, err
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return h, nil
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// WithHandler returns a tb.HandlerFunc and which will proxy the real handler.
|
||||
func WithHandler(handler Func, option ...Option) tb.HandlerFunc {
|
||||
hm := &handlerInterceptor{handler: handler}
|
||||
// create handlerWithInterceptor
|
||||
hm := &handlerWithInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
// return proxy handler
|
||||
return func(c tb.Context) error {
|
||||
h := Context{TeleContext: TeleContext{Context: c}, Context: context.Background()}
|
||||
// add default log fields from handler to context
|
||||
if len(hm.fields) > 0 {
|
||||
h.Context = context.WithValue(h.Context, "fields", hm.fields)
|
||||
}
|
||||
// add uuid for log tracing to context
|
||||
h.Context = context.WithValue(h.Context, "uuid", uuid.New().String())
|
||||
// run all before intercepts
|
||||
h, err := intercept(h, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return err
|
||||
}
|
||||
// make sure to run onDefer intercepts
|
||||
defer intercept(h, hm.onDefer)
|
||||
// run the real handler
|
||||
h, err = hm.handler(h)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return err
|
||||
}
|
||||
// run all after intercepts
|
||||
_, err = intercept(h, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
|
||||
@@ -3,6 +3,7 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"strconv"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
@@ -15,11 +16,12 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
logrus "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Interceptor struct {
|
||||
Fields logrus.Fields
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
OnDefer []intercept.Func
|
||||
@@ -53,6 +55,8 @@ func (bot TipBot) unlockInterceptor(ctx intercept.Context) (intercept.Context, e
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// idInterceptor wraps random uid into context
|
||||
func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx.Context = context.WithValue(ctx, "uid", RandStringRunes(64))
|
||||
return ctx, nil
|
||||
@@ -123,6 +127,8 @@ func (bot TipBot) startUserInterceptor(ctx intercept.Context) (intercept.Context
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// loadUserInterceptor will try to wrap user into context. Returns error if user is banned
|
||||
func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx)
|
||||
// if user is banned, also loadUserInterceptor will return an error
|
||||
@@ -131,10 +137,6 @@ func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context,
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
func (bot TipBot) tryLoadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
@@ -153,6 +155,7 @@ func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Conte
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// localizerInterceptor will wrap localizer into context, based on user settings.
|
||||
func (bot TipBot) localizerInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
var userLocalizer *i18n2.Localizer
|
||||
var publicLocalizer *i18n2.Localizer
|
||||
@@ -187,33 +190,37 @@ func (bot TipBot) localizerInterceptor(ctx intercept.Context) (intercept.Context
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// requirePrivateChatInterceptor will ensure, that handler was invoked in private chat.
|
||||
func (bot TipBot) requirePrivateChatInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Message() != nil {
|
||||
if ctx.Message().Chat.Type != tb.ChatPrivate {
|
||||
return ctx, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
|
||||
}
|
||||
return ctx, nil
|
||||
if ctx.Chat().Type != tb.ChatPrivate {
|
||||
return ctx, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
const photoTag = "<Photo>"
|
||||
|
||||
// logMessageInterceptor will log incoming handler requests.
|
||||
func (bot TipBot) logMessageInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user == nil {
|
||||
user = &lnbits.User{Telegram: ctx.Sender()}
|
||||
}
|
||||
if ctx.Message() != nil {
|
||||
|
||||
// log incoming messages
|
||||
if ctx.Message().Text != "" {
|
||||
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", ctx.Message().Chat.Title, ctx.Message().Chat.ID, GetUserStr(ctx.Message().Sender), ctx.Message().Sender.ID, ctx.Message().Text)
|
||||
if ctx.Message().IsReply() {
|
||||
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(ctx.Message().ReplyTo.Sender))
|
||||
}
|
||||
log.Infof(log_string)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "logMessageInterceptor"}).Infof("intercepting message")
|
||||
} else if ctx.Message().Photo != nil {
|
||||
log.Infof("[%s:%d %s:%d] %s", ctx.Message().Chat.Title, ctx.Message().Chat.ID, GetUserStr(ctx.Message().Sender), ctx.Message().Sender.ID, photoTag)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "logMessageInterceptor"}).Infof("intercepting photo message")
|
||||
}
|
||||
return ctx, nil
|
||||
} else if ctx.Callback() != nil {
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(ctx.Callback().Sender), ctx.Callback().Sender.ID, ctx.Callback().Data)
|
||||
// log incoming callbacks
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "logMessageInterceptor"}).Infof("intercepting callback")
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
@@ -4,18 +4,18 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/nbd-wtf/go-nostr"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
@@ -42,7 +42,6 @@ func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
|
||||
InvoiceCallbackPayJoinTicket: EventHandler{Function: bot.stopJoinTicketTimer, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +54,6 @@ const (
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
InvoiceCallbackGenerateDalle
|
||||
InvoiceCallbackPayJoinTicket
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -89,7 +87,6 @@ type InvoiceEvent struct {
|
||||
CallbackData string `json:"callbackdata"` // add some data for the callback
|
||||
Chat *tb.Chat `json:"chat,omitempty"` // if invoice is supposed to be sent to a particular chat
|
||||
Payer *lnbits.User `json:"payer,omitempty"` // if a particular user is supposed to pay this
|
||||
UserCurrency string `json:"usercurrency,omitempty"` // the currency a user selected
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Type() EventType {
|
||||
@@ -117,12 +114,15 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
// load user settings
|
||||
user, err := GetLnbitsUserWithSettings(user.Telegram, *bot)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
|
||||
logfields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "invoiceHandler",
|
||||
"path": "/invoice"}
|
||||
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
@@ -149,27 +149,21 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
}
|
||||
|
||||
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
|
||||
currency := user.Settings.Display.DisplayCurrency
|
||||
if currency == "" {
|
||||
currency = "BTC"
|
||||
}
|
||||
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, currency, InvoiceCallbackGeneric, "")
|
||||
logfields["amount"] = amount
|
||||
log.WithObjects(ctx, user).WithFields(logfields).Debugf("Creating invoice")
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logfields).Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
logfields["invoice"] = invoice.PaymentRequest
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logfields).Errorln("Failed to create QR code for invoice")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -178,21 +172,22 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
log.WithObjects(ctx, user).WithFields(logfields).Printf("Incvoice created.")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, currency string, callback int, callbackData string) (InvoiceEvent, error) {
|
||||
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(amount),
|
||||
Amount: amount,
|
||||
Memo: memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "createInvoiceWithEvent"}).Errorln("Could not create an invoice")
|
||||
return InvoiceEvent{}, err
|
||||
}
|
||||
invoiceEvent := InvoiceEvent{
|
||||
@@ -204,7 +199,6 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
UserCurrency: currency,
|
||||
}
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
|
||||
@@ -217,33 +211,20 @@ func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
|
||||
_, err := bot.GetUserBalance(invoiceEvent.User)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(invoiceEvent.User, err).WithFields(logrus.Fields{"module": "telegram", "func": "notifyInvoiceReceivedEvent"}).Error(errmsg)
|
||||
}
|
||||
|
||||
if invoiceEvent.UserCurrency == "" || strings.ToLower(invoiceEvent.UserCurrency) == "btc" {
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
|
||||
} else {
|
||||
fiatAmount, err := SatoshisToFiat(invoiceEvent.Amount, strings.ToUpper(invoiceEvent.UserCurrency))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// fallback to satoshis
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
|
||||
return
|
||||
}
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedCurrencyMessage"), invoiceEvent.Amount, fiatAmount, strings.ToUpper(invoiceEvent.UserCurrency)))
|
||||
}
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
|
||||
}
|
||||
|
||||
type LNURLInvoice struct {
|
||||
*Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
Nip57Receipt nostr.Event `json:"nip57_receipt"`
|
||||
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
}
|
||||
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
@@ -252,40 +233,20 @@ func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
|
||||
func (bot *TipBot) lnurlReceiveEvent(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
|
||||
err := bot.Bunt.Get(tx)
|
||||
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
log.WithObjects(tx.User, err).WithFields(logrus.Fields{"module": "lnurl", "func": "lnurlReceiveEvent", "amount": tx.Amount}).Debugf("Received invoice")
|
||||
if err == nil {
|
||||
// filter: if tx.Comment includes a URL, return if tx.Amount is less than 100 sat
|
||||
if len(tx.Comment) > 0 && tx.Amount < 100 {
|
||||
if strings.Contains(tx.Comment, "http") {
|
||||
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if tx.Amount < 21 {
|
||||
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
// notify user with LNURL comment and sender Information
|
||||
if len(tx.Comment) > 0 {
|
||||
if len(tx.From) == 0 {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)), tb.NoPreview)
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)))
|
||||
} else {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)), tb.NoPreview)
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)))
|
||||
}
|
||||
} else if len(tx.From) > 0 {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)), tb.NoPreview)
|
||||
}
|
||||
// send out NIP57 zap receipt
|
||||
if len(tx.Nip57Receipt.Sig) > 0 {
|
||||
// zapEventSerialized, _ := json.Marshal(tx.Nip57Receipt)
|
||||
bot.trySendMessage(tx.User.Telegram, "💜 This was a zap on nostr.")
|
||||
go bot.publishNostrEvent(tx.Nip57Receipt, tx.Nip57ReceiptRelays)
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
}
|
||||
|
||||
var sentsigres lnurl.LNURLResponse
|
||||
client, err := network.GetClientForScheme(p.CallbackURL)
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ type LnurlPayState struct {
|
||||
}
|
||||
|
||||
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hasn't necessarily entered an amount yet
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
@@ -75,7 +75,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
(int64(amount) > (payParams.LNURLPayParams.MaxSendable/1000) || int64(amount) < (payParams.LNURLPayParams.MinSendable/1000)) &&
|
||||
(payParams.LNURLPayParams.MaxSendable != 0 && payParams.LNURLPayParams.MinSendable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Warnf("%s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
@@ -106,7 +111,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
paramsJson, err := json.Marshal(payParams)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
@@ -127,7 +137,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorln("state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
}
|
||||
@@ -136,7 +151,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf("Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -146,7 +166,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -154,15 +179,25 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
client, err := network.GetClientForScheme(callbackUrl)
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -178,13 +213,23 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -196,20 +241,39 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"error": error_reason}).Error("Error in LNURLPayValues")
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), 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))
|
||||
bot.Telegram.Delete(statusMsg)
|
||||
|
||||
// store success action in context for printing after the payHandler
|
||||
ctx.Context = context.WithValue(ctx, "SuccessAction", lnurlPayState.LNURLPayValues.SuccessAction)
|
||||
|
||||
m.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
return bot.payHandler(ctx)
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := network.GetClientForScheme(callbackUrl)
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
|
||||
@@ -37,8 +37,15 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Infof("%s", m.Text)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
@@ -60,7 +67,14 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
lnurlSplit = split[1]
|
||||
} else {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
|
||||
log.Warnln("[/lnurl] Could not parse command.")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Warnln("Could not parse command.")
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
@@ -73,20 +87,41 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Error(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLAuthParams:
|
||||
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
|
||||
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl-auth",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Info(authParams.LNURLAuthParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams)
|
||||
return ctx, err
|
||||
|
||||
case lnurl.LNURLPayParams:
|
||||
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl-p",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Infof(payParams.LNURLPayParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
|
||||
// display the metadata image from the first LNURL-p response
|
||||
@@ -104,14 +139,28 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl-w",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Info(withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlWithdrawHandler(ctx, withdrawParams)
|
||||
default:
|
||||
if err == nil {
|
||||
err = fmt.Errorf("invalid LNURL type")
|
||||
}
|
||||
log.Warnln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "lnurl",
|
||||
"func": "lnurlHandler",
|
||||
"path": "/lnurl",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID}).Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
@@ -209,7 +258,12 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
return "", nil,
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// rerun LNURLDecode to convert lnurlp/keyauth schemes to https://
|
||||
rawurl, err = lnurl.LNURLDecode(rawurl)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -238,7 +292,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
|
||||
client, err := network.GetClientForScheme(parsed)
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/nbd-wtf/go-nostr"
|
||||
"github.com/nbd-wtf/go-nostr/nip19"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
nosterRegisterMessage = "📖 Add your nostr pubkey for zap receipts"
|
||||
nostrInfoMessage = "💜 *Your nostr information*\n\nYour pubkey: `%s`"
|
||||
nostrInfoLNAddrMessage = "Your Lightning address: `%s`"
|
||||
nostrHelpMessage = "⚙️ *Nostr commands:*\n`/nostr add <pubkey>` ✅ Add your nostr pubkey.\n`/nostr help` 📖 Show help."
|
||||
nostrAddedMessage = "✅ *Nostr pubkey added.*"
|
||||
nostrPrivateKeyErrorMessage = "🚫 This is not your public key but your private key! Very dangerous! Try again with your npub..."
|
||||
nostrPublicKeyErrorMessage = "🚫 There was an error decoding your public key."
|
||||
)
|
||||
|
||||
func uniqueSlice(slice []string) []string {
|
||||
keys := make(map[string]bool)
|
||||
list := []string{}
|
||||
for _, entry := range slice {
|
||||
if _, value := keys[entry]; !value {
|
||||
keys[entry] = true
|
||||
list = append(list, entry)
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func cleanUrls(slice []string) []string {
|
||||
list := []string{}
|
||||
for _, entry := range slice {
|
||||
if strings.HasSuffix(entry, "/") {
|
||||
entry = entry[:len(entry)-1]
|
||||
}
|
||||
list = append(list, entry)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func (bot *TipBot) publishNostrEvent(ev nostr.Event, relays []string) {
|
||||
pk := internal.Configuration.Nostr.PrivateKey
|
||||
|
||||
// // BEGIN: testing
|
||||
// pub, _ := nostr.GetPublicKey(pk)
|
||||
// ev = nostr.Event{
|
||||
// PubKey: pub,
|
||||
// CreatedAt: time.Now(),
|
||||
// Kind: 1,
|
||||
// Tags: nil,
|
||||
// Content: "Hello World!",
|
||||
// }
|
||||
// // END: testing
|
||||
|
||||
// calling Sign sets the event ID field and the event Sig field
|
||||
ev.Sign(pk)
|
||||
log.Debugf("[NOSTR] 🟣 publishing nostr event %s", ev.ID)
|
||||
|
||||
// more relays
|
||||
relays = append(relays, "wss://relay.nostr.ch", "wss://eden.nostr.land", "wss://nostr.btcmp.com", "wss://nostr.relayer.se", "wss://relay.current.fyi", "wss://nos.lol", "wss://nostr.mom", "wss://relay.nostr.info", "wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net", "wss://relay.snort.social/", "wss://relay.damus.io/", "wss://nostr.oxtr.dev/", "wss://nostr.fmt.wiz.biz/", "wss://brb.io")
|
||||
|
||||
// remove trailing /
|
||||
relays = cleanUrls(relays)
|
||||
|
||||
// unique relays
|
||||
relays = uniqueSlice(relays)
|
||||
|
||||
// crop relays
|
||||
var max_relays int = 50
|
||||
if len(relays) > max_relays {
|
||||
relays = relays[:max_relays]
|
||||
}
|
||||
|
||||
// publish the event to relays
|
||||
for _, url := range relays {
|
||||
go func(url string) {
|
||||
// remove trailing /
|
||||
relay, e := nostr.RelayConnect(context.Background(), url)
|
||||
if e != nil {
|
||||
log.Errorf(e.Error())
|
||||
return
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
status := relay.Publish(context.Background(), ev)
|
||||
log.Debugf("[NOSTR] published to %s: %s", url, status)
|
||||
|
||||
time.Sleep(3 * time.Second)
|
||||
relay.Close()
|
||||
}(url)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) nostrHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) == 1 {
|
||||
return bot.getNostrHandler(ctx)
|
||||
} else if len(splits) > 1 {
|
||||
switch strings.ToLower(splits[1]) {
|
||||
case "add":
|
||||
return bot.addNostrPubkeyHandler(ctx)
|
||||
case "help":
|
||||
return bot.nostrHelpHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) addNostrPubkeyHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
splitlen := len(splits)
|
||||
if splitlen < 3 {
|
||||
return ctx, fmt.Errorf("not enough arguments")
|
||||
}
|
||||
nostrKeyInput := splits[2]
|
||||
|
||||
// parse input
|
||||
if strings.HasPrefix(nostrKeyInput, "nsec") {
|
||||
bot.trySendMessage(ctx.Message().Sender, nostrPrivateKeyErrorMessage)
|
||||
return ctx, fmt.Errorf("user entered nostr private key")
|
||||
}
|
||||
// conver to hex
|
||||
if strings.HasPrefix(nostrKeyInput, "npub") {
|
||||
prefix, pubkey, err := nip19.Decode(nostrKeyInput)
|
||||
if err != nil {
|
||||
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
|
||||
return ctx, fmt.Errorf("shouldn't error: %s", err)
|
||||
}
|
||||
if prefix != "npub" {
|
||||
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
|
||||
return ctx, fmt.Errorf("returned invalid prefix")
|
||||
}
|
||||
nostrKeyInput = pubkey.(string)
|
||||
}
|
||||
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
// save node in db
|
||||
user.Settings.Nostr.PubKey = nostrKeyInput
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(ctx.Message().Sender, nostrAddedMessage)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nostrHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.trySendMessage(ctx.Message().Sender, nosterRegisterMessage+"\n\n"+nostrHelpMessage)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) getNostrHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
|
||||
return ctx, err
|
||||
}
|
||||
var dynamicHelpMessage string
|
||||
dynamicHelpMessage += nostrHelpMessage
|
||||
if user.Settings.Nostr.PubKey == "" {
|
||||
bot.trySendMessage(m.Sender, dynamicHelpMessage)
|
||||
return ctx, fmt.Errorf("no nostr pubkey registered")
|
||||
} else if len(user.Settings.Nostr.PubKey) > 0 {
|
||||
|
||||
pubkeyBech32, err := nip19.EncodePublicKey(user.Settings.Nostr.PubKey)
|
||||
if err != nil {
|
||||
log.Infof("Could not decode user nostr pubkey %s", GetUserStr(user.Telegram))
|
||||
return ctx, err
|
||||
}
|
||||
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoMessage, pubkeyBech32)
|
||||
if lnaddr, _ := bot.UserGetLightningAddress(user); len(lnaddr) > 0 {
|
||||
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoLNAddrMessage, lnaddr)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
+32
-33
@@ -17,7 +17,6 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -39,16 +38,15 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
|
||||
type PayData struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
Proof string `json:"proof"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
Amount int64 `json:"amount"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
SuccessAction *lnurl.SuccessAction `json:"successAction"`
|
||||
TelegramMessage *tb.Message `json:"telegrammessage"`
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
Proof string `json:"proof"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
Amount int64 `json:"amount"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
TelegramMessage *tb.Message `json:"telegrammessage"`
|
||||
}
|
||||
|
||||
// payHandler invoked on "/pay lnbc..." command
|
||||
@@ -134,12 +132,6 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
|
||||
// read successaction
|
||||
sa, ok := ctx.Value("SuccessAction").(*lnurl.SuccessAction)
|
||||
if !ok {
|
||||
sa = &lnurl.SuccessAction{}
|
||||
}
|
||||
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
@@ -148,7 +140,6 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
Memo: bolt11.Description,
|
||||
Message: confirmText,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
SuccessAction: sa,
|
||||
TelegramMessage: payMessage,
|
||||
}
|
||||
// add result to persistent struct
|
||||
@@ -192,6 +183,8 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
invoiceString := payData.Invoice
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
@@ -208,9 +201,18 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
},
|
||||
)
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "confirmPayHandler",
|
||||
"user": userStr,
|
||||
"user_id": user.ID,
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"path": "/pay",
|
||||
"data": payData.ID,
|
||||
"amount": payData.Amount,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Attempting invoice payment")
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payData.Invoice}, bot.Client)
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
|
||||
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
@@ -243,19 +245,16 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
|
||||
// display LNURL success action if present
|
||||
sa := payData.SuccessAction
|
||||
if sa.Tag == "message" && len(sa.Message) > 0 {
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: `%s`", sa.Message))
|
||||
} else if sa.Tag == "url" && len(sa.URL) > 0 {
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("🔗: %s", str.MarkdownEscape(sa.URL)), tb.NoPreview)
|
||||
if len(sa.Description) > 0 {
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: %s", sa.Description))
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "confirmPayHandler",
|
||||
"user": userStr,
|
||||
"user_id": user.ID,
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"path": "⚡️ pay",
|
||||
"data": payData.ID,
|
||||
"amount": payData.Amount,
|
||||
"wallet_id": user.Wallet.ID}).Infof("User paid invoice")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
|
||||
+197
-30
@@ -126,7 +126,12 @@ func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, err
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "getNodeHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Could not get user settings for user")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -137,7 +142,12 @@ func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, err
|
||||
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "getNodeHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Could not get node info for user")
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
@@ -193,7 +203,15 @@ func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "registerNodeHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType,
|
||||
"error": err.Error(),
|
||||
"status": getInvoiceParams.Status}).Errorf("Could not add user %s's %s node: %s", user.GetUserStr(), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
@@ -211,7 +229,7 @@ func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", user.GetUserStr(), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
@@ -222,18 +240,29 @@ func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context
|
||||
}
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", user.GetUserStr(), err)
|
||||
return ctx, err
|
||||
}
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "registerNodeHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Could not get node info for user")
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
|
||||
|
||||
log.Infof("[node:add] Added node of user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "registerNodeHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType}).Infof("Added node")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -245,7 +274,7 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.NodeType == "" {
|
||||
bot.trySendMessage(m.Sender, "You did not register a node yet.")
|
||||
return ctx, fmt.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return ctx, fmt.Errorf("node of user %s not registered", user.GetUserStr())
|
||||
}
|
||||
|
||||
var amount int64
|
||||
@@ -256,7 +285,12 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("[node:invoice] Getting invoice for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "invHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Getting invoice with backend %s", user.Settings.Node.NodeType)
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
@@ -311,7 +345,12 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
log.Infof("[node:invoice] Invoice created for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "invHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID}).Infof("Invoice created with backend %s", user.Settings.Node.NodeType)
|
||||
|
||||
// check if invoice settles
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
@@ -325,10 +364,24 @@ func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept
|
||||
}
|
||||
|
||||
// get the getInvoiceParams from cache
|
||||
log.Debugf("[Cache] Getting key: %s", fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
|
||||
).Debugf("Getting key")
|
||||
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
|
||||
).Errorf(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
|
||||
@@ -345,7 +398,14 @@ func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept
|
||||
check_message = check_message_interface.(*tb.Message)
|
||||
check_message, err = bot.tryEditMessage(check_message, checkingInvoiceMessage)
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
|
||||
).Errorf(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,14 +415,37 @@ func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept
|
||||
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
|
||||
runtime.NewRetryTicker(deadLineCtx, "node_invoice_check", runtime.WithRetryDuration(5*time.Second)).Do(func() {
|
||||
// get invoice from user's node
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Checking invoice: %s", getInvoiceParams.Hash)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
|
||||
"invoice": getInvoiceParams.Hash},
|
||||
).Debugf("Checking invoice")
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
|
||||
).Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
if getInvoiceParams.Status == "SETTLED" {
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice settled: %s", getInvoiceParams.Hash)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
|
||||
"invoice": getInvoiceParams.Hash},
|
||||
).Debugf("Invoice settled")
|
||||
bot.tryEditMessage(check_message, invoiceSettledMessage)
|
||||
cancel()
|
||||
}
|
||||
@@ -372,7 +455,15 @@ func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept
|
||||
},
|
||||
func() {
|
||||
// deadline
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice check expired: %s", getInvoiceParams.Hash)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressCheckInvoiceHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
|
||||
"invoice": getInvoiceParams.Hash},
|
||||
).Debugf("Invoice check expired")
|
||||
bot.tryEditMessage(check_message, invoiceNotSettledMessage,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
@@ -418,8 +509,14 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return ctx, fmt.Errorf("no node settings.")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID},
|
||||
).Errorf("node of user %s not registered", user.GetUserStr())
|
||||
return ctx, fmt.Errorf("no node settings")
|
||||
}
|
||||
|
||||
var amount int64
|
||||
@@ -431,11 +528,17 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
|
||||
}
|
||||
|
||||
memo := "🔀 Payment proxy in."
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, "", InvoiceCallbackSatdressProxy, "")
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID},
|
||||
).Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -444,12 +547,26 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
|
||||
log.Infof("[node] Proxy payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Infof("Proxy payment done")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -458,11 +575,24 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
user := invoiceEvent.User
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID},
|
||||
).Errorf("node not registered")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[node:proxy] Relaying payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Infof("Relaying payment", user.GetUserStr(), user.Settings.Node.NodeType)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
|
||||
@@ -499,14 +629,28 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
log.Infof("[node:proxy] Retrieved invoice for payment of user %s backend %s. Paying...", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Infof("Retrieved invoice for payment. Paying...")
|
||||
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
|
||||
@@ -519,7 +663,14 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType},
|
||||
).Errorln(errmsg)
|
||||
bot.tryEditMessage(check_message, payingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
@@ -544,12 +695,28 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType,
|
||||
"invoice": invoice.PaymentRequest},
|
||||
).Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(check_message, invoiceRoutedMessage)
|
||||
|
||||
log.Infof("[node:proxy] Proxy paid for user %s backend %s.", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "satdress",
|
||||
"func": "satdressProxyRelayPaymentHandler",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"backend": user.Settings.Node.NodeType,
|
||||
"invoice": invoice.PaymentRequest},
|
||||
).Infof("Proxy paid invoice")
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
return
|
||||
|
||||
+59
-32
@@ -4,7 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
@@ -20,7 +21,6 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -59,6 +59,7 @@ type SendData struct {
|
||||
|
||||
// sendHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
@@ -76,40 +77,35 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
|
||||
}
|
||||
|
||||
if ok, errstr := bot.SendCheckSyntax(ctx, ctx.Message()); !ok {
|
||||
bot.trySendMessage(ctx.Message().Sender, helpSendUsage(ctx, errstr))
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
// NewMessage(m, WithDuration(0, bot))
|
||||
// return
|
||||
// }
|
||||
|
||||
// get send amount, returns 0 if no amount is given
|
||||
amount, err := decodeAmountFromCommand(ctx.Text())
|
||||
// info: /send 10 <user> DEMANDS an amount, while /send <ln@address.com> also works without
|
||||
// todo: /send <user> should also invoke amount input dialog if no amount is given
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// CHECK whether first or second argument is a LIGHTNING ADDRESS
|
||||
arg := ""
|
||||
space := regexp.MustCompile(`\s+`)
|
||||
ctx.Message().Text = space.ReplaceAllString(ctx.Message().Text, " ")
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "sendHandler",
|
||||
"path": "/send",
|
||||
}
|
||||
if len(strings.Split(ctx.Message().Text, " ")) > 2 {
|
||||
arg, err = getArgumentFromCommand(ctx.Message().Text, 2)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
} else if len(strings.Split(ctx.Message().Text, " ")) == 2 {
|
||||
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
if lightning.IsLightningAddress(arg) {
|
||||
// lightning address, send to that address
|
||||
ctx, err = bot.sendToLightningAddress(ctx, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, err
|
||||
@@ -133,7 +129,7 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Warnln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Warnln(errmsg)
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
@@ -154,14 +150,14 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
} else {
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(ctx.Message().Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
err = bot.parseDonationCommandHandler(ctx)
|
||||
if err == nil {
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
@@ -205,7 +201,7 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
sendDataJson, err := json.Marshal(sendData)
|
||||
if err != nil {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error marshaling sendData")
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -235,6 +231,7 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// then, the flow is handled as if the user entered /send (then ask for contacts from keyboard or entry,
|
||||
// then ask for an amount).
|
||||
func (bot *TipBot) keyboardSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
@@ -244,10 +241,15 @@ func (bot *TipBot) keyboardSendHandler(ctx intercept.Context) (intercept.Context
|
||||
Type: "CreateSendState",
|
||||
OiringalCommand: "/send",
|
||||
}
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "keyboardSendHandler",
|
||||
"path": "/send",
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
|
||||
@@ -265,7 +267,7 @@ func (bot *TipBot) keyboardSendHandler(ctx intercept.Context) (intercept.Context
|
||||
// this is suboptimal because Telegram.Send is not rate limited etc. but it's the only way to send a custom keyboard for now
|
||||
_, err = bot.Telegram.Send(user.Telegram, Translate(ctx, "enterUserMessage"), sendToMenu)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -275,9 +277,17 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
tx := &SendData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "confirmSendHandler",
|
||||
"path": "button",
|
||||
}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, tx.From).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_telegram_id": tx.ToTelegramId,
|
||||
"to_user": tx.ToTelegramUser},
|
||||
).Errorf("could not find transaction")
|
||||
return ctx, err
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
@@ -286,7 +296,10 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
log.WithObjects(ctx, tx.From).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user": sendData.ToTelegramUser,
|
||||
"to_telegram_id": sendData.ToTelegramId},
|
||||
).Errorf("send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
@@ -305,11 +318,14 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
toUserStrWithoutAt := sendData.ToTelegramUser
|
||||
amount := sendData.Amount
|
||||
sendMemo := sendData.Memo
|
||||
|
||||
// we can now get the wallets of both users
|
||||
to, err := GetLnbitsUser(&tb.User{ID: toId, Username: toUserStrWithoutAt}, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithObjects(ctx, from, err).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user_id": to.ID,
|
||||
"to_user": sendData.ToTelegramUser,
|
||||
"to_telegram_id": sendData.ToTelegramId},
|
||||
).Errorln("erro fetching lnbits user")
|
||||
bot.tryDeleteMessage(ctx.Callback().Message)
|
||||
return ctx, err
|
||||
}
|
||||
@@ -326,13 +342,21 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
if !success || err != nil {
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, from, err).WithFields(logrus.Fields{
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"to_telegram_id": to.Telegram.ID},
|
||||
).Errorln(errmsg)
|
||||
bot.tryEditMessage(ctx.Callback().Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
|
||||
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.WithObjects(ctx, from, err).WithFields(logrus.Fields{
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"to_telegram_id": to.Telegram.ID,
|
||||
"amount": amount}).Infof("Send confirmation received")
|
||||
|
||||
// notify to user
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
@@ -367,7 +391,10 @@ func (bot *TipBot) cancelSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "cancelSendHandler"},
|
||||
).Errorf(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
settingsHelpMessage = "📖 Change user settings\n\n`/set unit <BTC|USD|EUR|GBP>` 💶 Change your default currency."
|
||||
)
|
||||
|
||||
func (bot *TipBot) settingHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) == 1 {
|
||||
bot.trySendMessage(m.Sender, settingsHelpMessage)
|
||||
} else if len(splits) > 1 {
|
||||
switch strings.ToLower(splits[1]) {
|
||||
case "unit":
|
||||
return bot.addFiatCurrency(ctx)
|
||||
case "help":
|
||||
return bot.nostrHelpHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) addFiatCurrency(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
splits := strings.Split(m.Text, " ")
|
||||
splitlen := len(splits)
|
||||
if splitlen < 3 {
|
||||
// display users current fiat currency
|
||||
currentCurrency := strings.ToUpper(user.Settings.Display.DisplayCurrency)
|
||||
if currentCurrency == "" {
|
||||
currentCurrency = "BTC"
|
||||
}
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf("🌍 Your current default currency is `%s`", currentCurrency))
|
||||
return ctx, nil
|
||||
}
|
||||
currencyInput := splits[2]
|
||||
// convert to lowercase and check if in [usd, eur, gbp, btc, sat]
|
||||
currencyInput = strings.ToLower(currencyInput)
|
||||
if currencyInput != "usd" && currencyInput != "eur" && currencyInput != "gbp" && currencyInput != "btc" && currencyInput != "sat" {
|
||||
bot.trySendMessage(ctx.Message().Sender, "🚫 Invalid currency. Please use one of the following: `BTC`, `USD`, `EUR`")
|
||||
return ctx, fmt.Errorf("invalid currency")
|
||||
}
|
||||
if currencyInput == "sat" {
|
||||
currencyInput = "BTC"
|
||||
}
|
||||
// save node in db
|
||||
user.Settings.Display.DisplayCurrency = currencyInput
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(ctx.Message().Sender, "✅ Your default currency has been updated.")
|
||||
return ctx, nil
|
||||
}
|
||||
+133
-90
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -17,7 +19,6 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -117,7 +118,7 @@ var (
|
||||
// shopItemPriceHandler is invoked when the user presses the item settings button to set a price
|
||||
func (bot *TipBot) shopItemPriceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopItemPriceHandler] %s", c.Data)
|
||||
log.WithObjects(ctx).Debugf("[shopItemPriceHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
@@ -130,7 +131,7 @@ func (bot *TipBot) shopItemPriceHandler(ctx intercept.Context) (intercept.Contex
|
||||
item := shop.Items[shop.ItemIds[shopView.Page]]
|
||||
// sanity check
|
||||
if item.ID != c.Data {
|
||||
log.Error("[shopItemPriceHandler] item id mismatch")
|
||||
log.WithObjects(ctx).Error("[shopItemPriceHandler] item id mismatch")
|
||||
return ctx, errors.Create(errors.ItemIdMismatchError)
|
||||
}
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
@@ -142,8 +143,8 @@ func (bot *TipBot) shopItemPriceHandler(ctx intercept.Context) (intercept.Contex
|
||||
// enterShopItemPriceHandler is invoked when the user enters a price amount
|
||||
func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[enterShopItemPriceHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[enterShopItemPriceHandler] %s", m.Text)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -158,7 +159,7 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
|
||||
item := shop.Items[shop.ItemIds[shopView.Page]]
|
||||
// sanity check
|
||||
if item.ID != user.StateData {
|
||||
log.Error("[shopItemPriceHandler] item id mismatch")
|
||||
log.WithObjects(ctx, user).Error("[shopItemPriceHandler] item id mismatch")
|
||||
return ctx, fmt.Errorf("item id mismatch")
|
||||
}
|
||||
|
||||
@@ -168,13 +169,17 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
|
||||
} else {
|
||||
amount, err = GetAmount(m.Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterShopItemPriceHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user).Warnf("[enterShopItemPriceHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
if amount > 2000 {
|
||||
bot.sendStatusMessageAndDelete(ctx, m.Sender, "ℹ️ During testing, price can be max 2000 sat.")
|
||||
amount = 2000
|
||||
}
|
||||
item.Price = amount
|
||||
shop.Items[item.ID] = item
|
||||
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
|
||||
@@ -192,8 +197,8 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
|
||||
// shopItemPriceHandler is invoked when the user presses the item settings button to set a item title
|
||||
func (bot *TipBot) shopItemTitleHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopItemTitleHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopItemTitleHandler] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -205,7 +210,7 @@ func (bot *TipBot) shopItemTitleHandler(ctx intercept.Context) (intercept.Contex
|
||||
item := shop.Items[shop.ItemIds[shopView.Page]]
|
||||
// sanity check
|
||||
if item.ID != c.Data {
|
||||
log.Error("[shopItemTitleHandler] item id mismatch")
|
||||
log.WithObjects(ctx, user).Error("[shopItemTitleHandler] item id mismatch")
|
||||
return ctx, errors.Create(errors.ItemIdMismatchError)
|
||||
}
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
@@ -217,8 +222,8 @@ func (bot *TipBot) shopItemTitleHandler(ctx intercept.Context) (intercept.Contex
|
||||
// enterShopItemTitleHandler is invoked when the user enters a title of the item
|
||||
func (bot *TipBot) enterShopItemTitleHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[enterShopItemTitleHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[enterShopItemTitleHandler] %s", m.Text)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -233,7 +238,7 @@ func (bot *TipBot) enterShopItemTitleHandler(ctx intercept.Context) (intercept.C
|
||||
item := shop.Items[shop.ItemIds[shopView.Page]]
|
||||
// sanity check
|
||||
if item.ID != user.StateData {
|
||||
log.Error("[enterShopItemTitleHandler] item id mismatch")
|
||||
log.WithObjects(ctx, user).Error("[enterShopItemTitleHandler] item id mismatch")
|
||||
return ctx, errors.Create(errors.ItemIdMismatchError)
|
||||
}
|
||||
if len(m.Text) == 0 {
|
||||
@@ -267,8 +272,8 @@ func (bot *TipBot) enterShopItemTitleHandler(ctx intercept.Context) (intercept.C
|
||||
// shopItemSettingsHandler is invoked when the user presses the item settings button
|
||||
func (bot *TipBot) shopItemSettingsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopItemSettingsHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopItemSettingsHandler] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -277,7 +282,7 @@ func (bot *TipBot) shopItemSettingsHandler(ctx intercept.Context) (intercept.Con
|
||||
item := shop.Items[shop.ItemIds[shopView.Page]]
|
||||
// sanity check
|
||||
if item.ID != c.Data {
|
||||
log.Error("[shopItemSettingsHandler] item id mismatch")
|
||||
log.WithObjects(ctx, user).Error("[shopItemSettingsHandler] item id mismatch")
|
||||
return ctx, errors.Create(errors.ItemIdMismatchError)
|
||||
}
|
||||
if item.TbPhoto != nil {
|
||||
@@ -290,8 +295,8 @@ func (bot *TipBot) shopItemSettingsHandler(ctx intercept.Context) (intercept.Con
|
||||
// shopItemPriceHandler is invoked when the user presses the item settings button to set a item title
|
||||
func (bot *TipBot) shopItemDeleteHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopItemDeleteHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopItemDeleteHandler] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -340,8 +345,8 @@ func (bot *TipBot) shopItemDeleteHandler(ctx intercept.Context) (intercept.Conte
|
||||
// displayShopItemHandler is invoked when the user presses the back button in the item settings
|
||||
func (bot *TipBot) displayShopItemHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[displayShopItemHandler] c.Data: %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[displayShopItemHandler] c.Data: %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -363,8 +368,8 @@ func (bot *TipBot) displayShopItemHandler(ctx intercept.Context) (intercept.Cont
|
||||
// shopNextItemHandler is invoked when the user presses the next item button
|
||||
func (bot *TipBot) shopNextItemButtonHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopNextItemButtonHandler] c.Data: %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopNextItemButtonHandler] c.Data: %s", c.Data)
|
||||
// shopView, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
@@ -386,8 +391,8 @@ func (bot *TipBot) shopNextItemButtonHandler(ctx intercept.Context) (intercept.C
|
||||
// shopPrevItemButtonHandler is invoked when the user presses the previous item button
|
||||
func (bot *TipBot) shopPrevItemButtonHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopPrevItemButtonHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopPrevItemButtonHandler] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -429,10 +434,10 @@ func (bot *TipBot) getItemTitle(ctx context.Context, item *ShopItem) string {
|
||||
// m is the message that will be edited
|
||||
func (bot *TipBot) displayShopItem(ctx intercept.Context, m *tb.Message, shop *Shop) *tb.Message {
|
||||
user := LoadUser(ctx)
|
||||
log.Debugf("[displayShopItem] User: %s shop: %s", GetUserStr(user.Telegram), shop.ID)
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[displayShopItem] %s", err.Error())
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Errorf("[displayShopItem] %s", err.Error())
|
||||
return nil
|
||||
}
|
||||
// failsafe: if the page is out of bounds, reset it
|
||||
@@ -441,8 +446,10 @@ func (bot *TipBot) displayShopItem(ctx intercept.Context, m *tb.Message, shop *S
|
||||
} else if len(shop.Items) == 0 {
|
||||
shopView.Page = 0
|
||||
}
|
||||
|
||||
log.Debugf("[displayShopItem] shop: %s page: %d items: %d", shop.ID, shopView.Page, len(shop.Items))
|
||||
logFields["shop"] = shop.ID
|
||||
logFields["page"] = shopView.Page
|
||||
logFields["items"] = len(shop.Items)
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debug("displaying shop items")
|
||||
if len(shop.Items) == 0 {
|
||||
no_items_message := "There are no items in this shop yet."
|
||||
if shopView.Message != nil && len(shopView.Message.Text) > 0 {
|
||||
@@ -495,12 +502,15 @@ func (bot *TipBot) displayShopItem(ctx intercept.Context, m *tb.Message, shop *S
|
||||
// shopHandler is invoked when the user enters /shop
|
||||
func (bot *TipBot) shopHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[shopHandler] %s", m.Text)
|
||||
if !m.Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
shopOwner := user
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
|
||||
logFields["text"] = m.Text
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debug("displaying shop items")
|
||||
|
||||
// when no argument is given, i.e. command is only /shop, load /shops
|
||||
shop := &Shop{}
|
||||
@@ -512,7 +522,7 @@ func (bot *TipBot) shopHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
var err error
|
||||
shop, err = bot.getShop(ctx, shopID)
|
||||
if err != nil {
|
||||
log.Errorf("[shopHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error fetching shop")
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
@@ -541,11 +551,14 @@ func (bot *TipBot) shopHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// shopNewItemHandler is invoked when the user presses the new item button
|
||||
func (bot *TipBot) shopNewItemHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopNewItemHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debug("creating new item")
|
||||
|
||||
shop, err := bot.getShop(ctx, c.Data)
|
||||
if err != nil {
|
||||
log.Errorf("[shopNewItemHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error fetching shop")
|
||||
return ctx, err
|
||||
}
|
||||
if shop.Owner.Telegram.ID != c.Sender.ID {
|
||||
@@ -559,7 +572,7 @@ func (bot *TipBot) shopNewItemHandler(ctx intercept.Context) (intercept.Context,
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
paramsJson, err := json.Marshal(shop)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error marshaling shop")
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
@@ -570,13 +583,15 @@ func (bot *TipBot) shopNewItemHandler(ctx intercept.Context) (intercept.Context,
|
||||
|
||||
// addShopItem is a helper function for creating a shop item in the database
|
||||
func (bot *TipBot) addShopItem(ctx intercept.Context, shopId string) (*Shop, ShopItem, error) {
|
||||
log.Debugf("[addShopItem] shopId: %s", shopId)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{"shop": shopId}).Debug("adding shop item")
|
||||
|
||||
shop, err := bot.getShop(ctx, shopId)
|
||||
if err != nil {
|
||||
log.Errorf("[addShopItem] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{"shop": shopId}).Error("error fetching shop")
|
||||
return shop, ShopItem{}, err
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
// onnly the correct user can press
|
||||
if shop.Owner.Telegram.ID != user.Telegram.ID {
|
||||
return shop, ShopItem{}, fmt.Errorf("not owner")
|
||||
@@ -602,8 +617,9 @@ func (bot *TipBot) addShopItem(ctx intercept.Context, shopId string) (*Shop, Sho
|
||||
// addShopItemPhoto is invoked when the users sends a photo as a new item
|
||||
func (bot *TipBot) addShopItemPhoto(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[addShopItemPhoto] <Photo>")
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram"}).Debug("adding shop item photo")
|
||||
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
@@ -612,7 +628,7 @@ func (bot *TipBot) addShopItemPhoto(ctx intercept.Context) (intercept.Context, e
|
||||
var state_shop Shop
|
||||
err := json.Unmarshal([]byte(user.StateData), &state_shop)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram"}).Errorf("error unmarshaling state")
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"), Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -646,7 +662,8 @@ func (bot *TipBot) addShopItemPhoto(ctx intercept.Context) (intercept.Context, e
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
bot.displayShopItem(ctx, shopView.Message, shop)
|
||||
|
||||
log.Infof("[🛍 shop] %s added an item %s:%s.", GetUserStr(user.Telegram), shop.ID, item.ID)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram", "shop": shop.ID, "item": item.ID}).
|
||||
Infof("[🛍 shop] added new item")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -654,20 +671,22 @@ func (bot *TipBot) addShopItemPhoto(ctx intercept.Context) (intercept.Context, e
|
||||
// shopItemAddItemHandler is invoked when the user presses the new item button
|
||||
func (bot *TipBot) shopItemAddItemHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopItemAddItemHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
logFields["data"] = c.Data
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debugf("new item")
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopItemAddItemHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("error fetching shop view")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
shop, err := bot.getShop(ctx, shopView.ShopID)
|
||||
if err != nil {
|
||||
log.Errorf("[shopItemAddItemHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("error fetching shop ")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -687,23 +706,23 @@ func (bot *TipBot) shopItemAddItemHandler(ctx intercept.Context) (intercept.Cont
|
||||
// addItemFileHandler is invoked when the users sends a new file for the item
|
||||
func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[addItemFileHandler] <File>")
|
||||
user := LoadUser(ctx)
|
||||
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[addItemFileHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("error fetching shop view")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
shop, err := bot.getShop(ctx, shopView.ShopID)
|
||||
if err != nil {
|
||||
log.Errorf("[shopNewItemHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("error fetching shop")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addItemFileHandler", "module": "telegram", "shop": shop.ID}).Debugf("adding new file")
|
||||
itemID := user.StateData
|
||||
|
||||
item := shop.Items[itemID]
|
||||
@@ -730,8 +749,9 @@ func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context,
|
||||
item.FileIDs = append(item.FileIDs, m.Sticker.FileID)
|
||||
item.FileTypes = append(item.FileTypes, "sticker")
|
||||
} else {
|
||||
log.Errorf("[addItemFileHandler] no file found")
|
||||
return ctx, errors.Create(errors.NoFileFoundError)
|
||||
err = errors.Create(errors.NoFileFoundError)
|
||||
log.WithObjects(ctx, user, err).Errorf("no file found")
|
||||
return ctx, err
|
||||
}
|
||||
shop.Items[item.ID] = item
|
||||
|
||||
@@ -753,7 +773,7 @@ func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context,
|
||||
// // start a ticker to check if the user has sent more files
|
||||
// if t, ok := fileStateResetTicker.Get(shop.ID); ok {
|
||||
// // state reset ticker found. resetting ticker.
|
||||
// t.(*runtime.ResettableFunction).ResetChan <- struct{}{}
|
||||
// t.(*runtime.ResettableFunctionTicker).ResetChan <- struct{}{}
|
||||
// } else {
|
||||
// // state reset ticker not found. creating new one.
|
||||
// ticker := runtime.NewResettableFunctionTicker(runtime.WithDuration(time.Second * 5))
|
||||
@@ -775,25 +795,28 @@ func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context,
|
||||
// bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
// }()
|
||||
bot.displayShopItem(ctx, shopView.Message, shop)
|
||||
log.Infof("[🛍 shop] %s added a file to shop:item %s:%s.", GetUserStr(user.Telegram), shop.ID, item.ID)
|
||||
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addItemFileHandler", "module": "telegram", "shop": shop.ID, "item": item.ID}).Infof("[🛍 shop] added file")
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) shopGetItemFilesHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopGetItemFilesHandler] %s", c.Data)
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
logFields["data"] = c.Data
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debugf("buy item button clicked")
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[addItemFileHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop view")
|
||||
return ctx, err
|
||||
}
|
||||
shop, err := bot.getShop(ctx, shopView.ShopID)
|
||||
if err != nil {
|
||||
log.Errorf("[shopGetItemFilesHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error feching shop")
|
||||
return ctx, err
|
||||
}
|
||||
itemID := c.Data
|
||||
@@ -814,33 +837,39 @@ func (bot *TipBot) shopGetItemFilesHandler(ctx intercept.Context) (intercept.Con
|
||||
// for i, fileID := range item.FileIDs {
|
||||
// bot.sendFileByID(ctx, c.Sender, fileID, item.FileTypes[i])
|
||||
// }
|
||||
// log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", GetUserStr(user.Telegram), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
|
||||
// log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", user.GetUserStr(), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// shopConfirmBuyHandler is invoked when the user has confirmed to pay for an item
|
||||
func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopConfirmBuyHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
logFields := ctx.Context.Value("fields").(logrus.Fields)
|
||||
logFields["data"] = c.Data
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debugf("user confirmed to pay item")
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopConfirmBuyHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop view")
|
||||
return ctx, err
|
||||
}
|
||||
shop, err := bot.getShop(ctx, shopView.ShopID)
|
||||
if err != nil {
|
||||
log.Errorf("[shopConfirmBuyHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop")
|
||||
return ctx, err
|
||||
}
|
||||
logFields["shop_title"] = shop.Title
|
||||
logFields["shop"] = shop.ID
|
||||
itemID := c.Data
|
||||
item := shop.Items[itemID]
|
||||
logFields["item"] = item.ID
|
||||
if item.Owner.ID != shop.Owner.ID {
|
||||
log.Errorf("[shopConfirmBuyHandler] Owners do not match.")
|
||||
return ctx, errors.Create(errors.NotShopOwnerError)
|
||||
err = errors.Create(errors.NotShopOwnerError)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("Owners do not match.")
|
||||
return ctx, err
|
||||
}
|
||||
from := user
|
||||
to := shop.Owner
|
||||
@@ -850,9 +879,11 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Conte
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
amount := item.Price
|
||||
logFields["amount"] = amount
|
||||
if amount <= 0 {
|
||||
log.Errorf("[shopConfirmBuyHandler] item has no price.")
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
err = errors.Create(errors.InvalidAmountError)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("item has no price")
|
||||
return ctx, err
|
||||
}
|
||||
transactionMemo := fmt.Sprintf("🛍 Shop from %s.", toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("shop"))
|
||||
@@ -862,7 +893,7 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Conte
|
||||
if !success || err != nil {
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[shop] Error: Transaction failed. %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(errmsg)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", i18n.Translate(user.Telegram.LanguageCode, "sendErrorMessage"))
|
||||
// bot.trySendMessage(user.Telegram, i18n.Translate(user.Telegram.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
@@ -872,29 +903,33 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Conte
|
||||
if len(item.Title) > 0 {
|
||||
shopItemTitle = fmt.Sprintf("%s", item.Title)
|
||||
}
|
||||
logFields["item_title"] = shopItemTitle
|
||||
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", "🛍 Purchase successful.")
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("🛍 Someone bought `%s` from your shop `%s` for `%d sat`.", str.MarkdownEscape(shopItemTitle), str.MarkdownEscape(shop.Title), amount))
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf("🛍 You bought `%s` from %s's shop `%s` for `%d sat`.", str.MarkdownEscape(shopItemTitle), toUserStrMd, str.MarkdownEscape(shop.Title), amount))
|
||||
log.Infof("[🛍 shop] %s bought from %s shop: %s item: %s for %d sat.", toUserStr, GetUserStr(to.Telegram), shop.Title, shopItemTitle, amount)
|
||||
logFields["to_user"] = GetUserStr(to.Telegram)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Infof("[🛍 shop] sold item")
|
||||
bot.shopSendItemFilesToUser(ctx, user, itemID)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// shopSendItemFilesToUser is a handler function to send itemID's files to the user
|
||||
func (bot *TipBot) shopSendItemFilesToUser(ctx intercept.Context, toUser *lnbits.User, itemID string) {
|
||||
log.Debugf("[shopSendItemFilesToUser] %s -> %s", GetUserStr(toUser.Telegram), itemID)
|
||||
user := LoadUser(ctx)
|
||||
logFields := logrus.Fields{"to_user": GetUserStr(toUser.Telegram), "item": itemID}
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Debugf("sending files to user")
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopGetItemFilesHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("[shopGetItemFilesHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
shop, err := bot.getShop(ctx, shopView.ShopID)
|
||||
if err != nil {
|
||||
log.Errorf("[addItemFileHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("[addItemFileHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
item := shop.Items[itemID]
|
||||
@@ -904,7 +939,11 @@ func (bot *TipBot) shopSendItemFilesToUser(ctx intercept.Context, toUser *lnbits
|
||||
for i, fileID := range item.FileIDs {
|
||||
bot.sendFileByID(ctx, toUser.Telegram, fileID, item.FileTypes[i])
|
||||
}
|
||||
log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", GetUserStr(user.Telegram), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
|
||||
logFields["amount"] = len(item.FileIDs)
|
||||
logFields["from_user"] = GetUserStr(shop.Owner.Telegram)
|
||||
logFields["item"] = item.ID
|
||||
logFields["price"] = item.Price
|
||||
log.WithObjects(ctx, user).WithFields(logFields).Infof("[🛍 shop] files sent to user")
|
||||
|
||||
// delete old shop and show again below the files
|
||||
if shopView.Message != nil {
|
||||
@@ -947,6 +986,7 @@ func (bot *TipBot) sendFileByID(ctx context.Context, to tb.Recipient, fileId str
|
||||
var ShopsText = ""
|
||||
var ShopsTextWelcome = "*You are browsing %s shop.*"
|
||||
var ShopsTextShopCount = "*Browse %d shops:*"
|
||||
var ShopsTextHelp = "⚠️ Shops are still in beta. Expect bugs."
|
||||
var ShopsNoShopsText = "*There are no shops here yet.*"
|
||||
|
||||
// shopsHandlerCallback is a warpper for shopsHandler for callbacks
|
||||
@@ -957,11 +997,11 @@ func (bot *TipBot) shopsHandlerCallback(ctx intercept.Context) (intercept.Contex
|
||||
// shopsHandler is invoked when the user enters /shops
|
||||
func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[shopsHandler] %s", GetUserStr(m.Sender))
|
||||
if !m.Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("invoked shops hanler")
|
||||
shopOwner := user
|
||||
|
||||
// if the user in the command, i.e. /shops @user
|
||||
@@ -977,7 +1017,7 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
|
||||
var err error
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorln("error reading args from command")
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
@@ -1005,14 +1045,15 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
|
||||
}
|
||||
|
||||
if shopOwner == nil {
|
||||
log.Error("[shopsHandler] shopOwner is nil")
|
||||
return ctx, errors.Create(errors.ShopNoOwnerError)
|
||||
err := errors.Create(errors.ShopNoOwnerError)
|
||||
log.WithObjects(ctx, user, err).Error("[shopsHandler] shopOwner is nil")
|
||||
return ctx, err
|
||||
}
|
||||
shops, err := bot.getUserShops(ctx, shopOwner)
|
||||
if err != nil && user.Telegram.ID == shopOwner.Telegram.ID {
|
||||
shops, err = bot.initUserShops(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopsHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("failed initializing user shops")
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
@@ -1027,7 +1068,7 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
|
||||
for _, shopId := range shops.Shops {
|
||||
shop, err := bot.getShop(ctx, shopId)
|
||||
if err != nil {
|
||||
log.Errorf("[shopsHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("error fetching shop")
|
||||
return ctx, err
|
||||
}
|
||||
shopTitles += fmt.Sprintf("\n· %s (%d items)", str.MarkdownEscape(shop.Title), len(shop.Items))
|
||||
@@ -1056,6 +1097,7 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
|
||||
if len(shops.Shops) > 0 {
|
||||
ShopsText += fmt.Sprintf("%s\n", shopTitles)
|
||||
}
|
||||
ShopsText += fmt.Sprintf("\n%s", ShopsTextHelp)
|
||||
|
||||
// fmt.Sprintf(ShopsText, shopOwnerText, len(shops.Shops), shopTitles)
|
||||
|
||||
@@ -1098,8 +1140,8 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
|
||||
// shopsDeleteShopBrowser is invoked when the user clicks on "delete shops" and makes a list of all shops
|
||||
func (bot *TipBot) shopsDeleteShopBrowser(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsDeleteShopBrowser] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsDeleteShopBrowser] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1122,7 +1164,7 @@ func (bot *TipBot) shopsDeleteShopBrowser(ctx intercept.Context) (intercept.Cont
|
||||
|
||||
func (bot *TipBot) shopsAskDeleteAllShopsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsAskDeleteAllShopsHandler] %s", c.Data)
|
||||
log.WithObjects(ctx).Debugf("[shopsAskDeleteAllShopsHandler] %s", c.Data)
|
||||
shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", c.Data)
|
||||
buttons := []tb.Row{
|
||||
shopKeyboard.Row(shopResetShopButton),
|
||||
@@ -1138,8 +1180,8 @@ func (bot *TipBot) shopsAskDeleteAllShopsHandler(ctx intercept.Context) (interce
|
||||
// shopsLinkShopBrowser is invoked when the user clicks on "shop links" and makes a list of all shops
|
||||
func (bot *TipBot) shopsLinkShopBrowser(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsLinkShopBrowser] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsLinkShopBrowser] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1161,7 +1203,7 @@ func (bot *TipBot) shopsLinkShopBrowser(ctx intercept.Context) (intercept.Contex
|
||||
// shopSelectLink is invoked when the user has chosen a shop to get the link of
|
||||
func (bot *TipBot) shopSelectLink(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopSelectLink] %s", c.Data)
|
||||
log.WithObjects(ctx).Debugf("[shopSelectLink] %s", c.Data)
|
||||
shop, _ := bot.getShop(ctx, c.Data)
|
||||
if shop.Owner.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
@@ -1173,8 +1215,8 @@ func (bot *TipBot) shopSelectLink(ctx intercept.Context) (intercept.Context, err
|
||||
// shopsLinkShopBrowser is invoked when the user clicks on "shop links" and makes a list of all shops
|
||||
func (bot *TipBot) shopsRenameShopBrowser(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsRenameShopBrowser] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsRenameShopBrowser] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1196,8 +1238,8 @@ func (bot *TipBot) shopsRenameShopBrowser(ctx intercept.Context) (intercept.Cont
|
||||
// shopSelectLink is invoked when the user has chosen a shop to get the link of
|
||||
func (bot *TipBot) shopSelectRename(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopSelectRename] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopSelectRename] %s", c.Data)
|
||||
shop, _ := bot.getShop(ctx, c.Data)
|
||||
if shop.Owner.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
@@ -1211,11 +1253,11 @@ func (bot *TipBot) shopSelectRename(ctx intercept.Context) (intercept.Context, e
|
||||
// shopsDescriptionHandler is invoked when the user clicks on "description" to set a shop description
|
||||
func (bot *TipBot) shopsDescriptionHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsDescriptionHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsDescriptionHandler] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopsDescriptionHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("[shopsDescriptionHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterShopsDescription, shops.ID)
|
||||
@@ -1226,11 +1268,11 @@ func (bot *TipBot) shopsDescriptionHandler(ctx intercept.Context) (intercept.Con
|
||||
// enterShopsDescriptionHandler is invoked when the user enters the shop title
|
||||
func (bot *TipBot) enterShopsDescriptionHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[enterShopsDescriptionHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[enterShopsDescriptionHandler] %s", m.Text)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[enterShopsDescriptionHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("[enterShopsDescriptionHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
if shops.Owner.Telegram.ID != m.Sender.ID {
|
||||
@@ -1266,11 +1308,11 @@ func (bot *TipBot) enterShopsDescriptionHandler(ctx intercept.Context) (intercep
|
||||
// shopsResetHandler is invoked when the user clicks button to reset shops completely
|
||||
func (bot *TipBot) shopsResetHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsResetHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsResetHandler] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopsResetHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("[shopsResetHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
if shops.Owner.Telegram.ID != c.Sender.ID {
|
||||
@@ -1288,9 +1330,9 @@ func (bot *TipBot) shopsResetHandler(ctx intercept.Context) (intercept.Context,
|
||||
// shopSelect is invoked when the user has selected a shop to browse
|
||||
func (bot *TipBot) shopSelect(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopSelect] %s", c.Data)
|
||||
shop, _ := bot.getShop(ctx, c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopSelect] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
shopView = ShopView{
|
||||
@@ -1312,7 +1354,7 @@ func (bot *TipBot) shopSelect(ctx intercept.Context) (intercept.Context, error)
|
||||
// shopMessage = bot.tryEditMessage(c.Message, "There are no items in this shop yet.", bot.shopMenu(ctx, shop, &ShopItem{}))
|
||||
// }
|
||||
shopView.Message = shopMessage
|
||||
log.Infof("[🛍 shop] %s erntering shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
log.WithObjects(ctx, user, err).Infof("[🛍 shop] %s erntering shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", fmt.Sprintf("🛍 You are browsing %s", shop.Title))
|
||||
return ctx, bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
}
|
||||
@@ -1320,9 +1362,9 @@ func (bot *TipBot) shopSelect(ctx intercept.Context) (intercept.Context, error)
|
||||
// shopSelectDelete is invoked when the user has chosen a shop to delete
|
||||
func (bot *TipBot) shopSelectDelete(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopSelectDelete] %s", c.Data)
|
||||
shop, _ := bot.getShop(ctx, c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopSelectDelete] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1343,7 +1385,7 @@ func (bot *TipBot) shopSelectDelete(ctx intercept.Context) (intercept.Context, e
|
||||
// then, delete shop
|
||||
runtime.IgnoreError(shop.Delete(shop, bot.ShopBunt))
|
||||
|
||||
log.Infof("[🛍 shop] %s deleted shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
log.WithObjects(ctx, user).Infof("[🛍 shop] %s deleted shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
// then update buttons
|
||||
return bot.shopsDeleteShopBrowser(ctx)
|
||||
}
|
||||
@@ -1351,8 +1393,8 @@ func (bot *TipBot) shopSelectDelete(ctx intercept.Context) (intercept.Context, e
|
||||
// shopsBrowser makes a button list of all shops the user can browse
|
||||
func (bot *TipBot) shopsBrowser(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopsBrowser] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopsBrowser] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1381,8 +1423,8 @@ func (bot *TipBot) shopsBrowser(ctx intercept.Context) (intercept.Context, error
|
||||
// shopItemSettingsHandler is invoked when the user presses the shop settings button
|
||||
func (bot *TipBot) shopSettingsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopSettingsHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopSettingsHandler] %s", c.Data)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
@@ -1392,8 +1434,9 @@ func (bot *TipBot) shopSettingsHandler(ctx intercept.Context) (intercept.Context
|
||||
return ctx, err
|
||||
}
|
||||
if shops.ID != c.Data || shops.Owner.Telegram.ID != user.Telegram.ID {
|
||||
log.Error("[shopSettingsHandler] item id mismatch")
|
||||
return ctx, errors.Create(errors.ItemIdMismatchError)
|
||||
err = errors.Create(errors.ItemIdMismatchError)
|
||||
log.WithObjects(ctx, user, err).Error("[shopSettingsHandler] item id mismatch")
|
||||
return ctx, err
|
||||
}
|
||||
_, err = bot.tryEditMessage(shopView.Message, shopView.Message.Text, bot.shopsSettingsMenu(ctx, shops))
|
||||
return ctx, err
|
||||
@@ -1402,11 +1445,11 @@ func (bot *TipBot) shopSettingsHandler(ctx intercept.Context) (intercept.Context
|
||||
// shopNewShopHandler is invoked when the user presses the new shop button
|
||||
func (bot *TipBot) shopNewShopHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
log.Debugf("[shopNewShopHandler] %s", c.Data)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[shopNewShopHandler] %s", c.Data)
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
log.Errorf("[shopNewShopHandler] %s", err.Error())
|
||||
log.WithObjects(ctx, user, err).Errorf("[shopNewShopHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
if len(shops.Shops) >= shops.MaxShops {
|
||||
@@ -1423,8 +1466,8 @@ func (bot *TipBot) shopNewShopHandler(ctx intercept.Context) (intercept.Context,
|
||||
// enterShopTitleHandler is invoked when the user enters the shop title
|
||||
func (bot *TipBot) enterShopTitleHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
log.Debugf("[enterShopTitleHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
log.WithObjects(ctx, user).Debugf("[enterShopTitleHandler] %s", m.Text)
|
||||
// read item from user.StateData
|
||||
shop, err := bot.getShop(ctx, user.StateData)
|
||||
if err != nil {
|
||||
@@ -1457,9 +1500,9 @@ func (bot *TipBot) enterShopTitleHandler(ctx intercept.Context) (intercept.Conte
|
||||
// }()
|
||||
ctx, err = bot.shopsHandler(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[shop] failed shopshandler")
|
||||
log.WithObjects(ctx, user, err).Errorf("[shop] failed shopshandler")
|
||||
}
|
||||
bot.tryDeleteMessage(m)
|
||||
log.Infof("[🛍 shop] %s added new shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
log.WithObjects(ctx, user).Infof("[🛍 shop] %s added new shop %s.", GetUserStr(user.Telegram), shop.ID)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recip
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
|
||||
// kick off ticker to remove all messages
|
||||
ticker := runtime.GetFunction(id, runtime.WithTicker(time.NewTicker(5*time.Second)), runtime.WithDuration(5*time.Second))
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
@@ -237,7 +237,7 @@ func (bot *TipBot) getUserShops(ctx intercept.Context, user *lnbits.User) (*Shop
|
||||
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
|
||||
log.Errorf("[getUserShops] User: %s (%d): %s", user.GetUserStr(), user.Telegram.ID, err)
|
||||
return &Shops{}, err
|
||||
}
|
||||
shops := sn.(*Shops)
|
||||
|
||||
+18
-15
@@ -28,11 +28,23 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(ctx.Sender()), ctx.Sender().ID)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "startHandler",
|
||||
"path": "/start",
|
||||
"user": GetUserStr(ctx.Sender()),
|
||||
"user_id": ctx.Sender().ID,
|
||||
}).Printf(" New user")
|
||||
walletCreationMsg := bot.trySendMessageEditable(ctx.Sender(), Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(ctx.Sender())
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "startHandler",
|
||||
"path": "/start",
|
||||
"user": GetUserStr(ctx.Sender()),
|
||||
"user_id": ctx.Sender().ID,
|
||||
}).Errorln(fmt.Sprintf("Error with initWallet: %s", err.Error()))
|
||||
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
@@ -62,7 +74,6 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
}
|
||||
} else if !user.Initialized {
|
||||
@@ -71,28 +82,24 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
}
|
||||
} else if user.Initialized {
|
||||
// wallet is already initialized
|
||||
return user, nil
|
||||
} else {
|
||||
err = fmt.Errorf("could not initialize wallet")
|
||||
return user, err
|
||||
return user, fmt.Errorf("could not initialize wallet")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
UserStr := user.GetUserStr()
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
@@ -100,22 +107,18 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
user.AnonIDSha256 = str.AnonIdSha256(user)
|
||||
user.UUID = str.UUIDSha256(user)
|
||||
user.AnonIDSha256 = user.AnonIdSha256()
|
||||
user.UUID = user.UUIDSha256()
|
||||
|
||||
user.Initialized = false
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -2,12 +2,14 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -25,12 +27,18 @@ func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options .
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tryForwardMessage",
|
||||
"user": to.Recipient()}).Errorf("error converting message recipient to int64")
|
||||
return
|
||||
}
|
||||
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tryForwardMessage",
|
||||
"user": to.Recipient()}).Warnln("error forwarding message")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -39,13 +47,23 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "trySendMessage",
|
||||
"user": to.Recipient()}).Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
log.Tracef("[trySendMessage] chatId: %d", chatId)
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "trySendMessage",
|
||||
"chat_id": chatId,
|
||||
"user": to.Recipient()}).Tracef("trying to send something")
|
||||
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "trySendMessage",
|
||||
"user": to.Recipient()}).Warnln("error sending message")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -54,7 +72,10 @@ func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, opti
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Send(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "trySendMessageEditable",
|
||||
"user": to.Recipient()}).Warnln("error sending editable")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -63,7 +84,9 @@ func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...i
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err, &lnbits.User{Telegram: to.Sender}).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "trySendMessageEditable"}).Warnln("error reply message")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -77,10 +100,15 @@ func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...in
|
||||
rate.CheckLimit(sig)
|
||||
|
||||
_, chatId := to.MessageSig()
|
||||
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tryEditMessage",
|
||||
"chat_id": chatId}).Tracef("trying to send something")
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tryEditMessage"}).Warnln("error edit message")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -92,7 +120,9 @@ func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
rate.CheckLimit(msg)
|
||||
err := bot.Telegram.Delete(msg)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tryDeleteMessage"}).Warnln("error delete message")
|
||||
}
|
||||
return
|
||||
|
||||
@@ -114,7 +144,9 @@ func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(member
|
||||
if err != nil {
|
||||
admins, err = bot.Telegram.AdminsOf(message.Chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "allowedToPerformAction"}).Warnln("error fetching admins")
|
||||
return false
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
|
||||
@@ -142,7 +174,10 @@ func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
func (bot *TipBot) isOwner(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "isOwner",
|
||||
"chat_id": chat.ID}).Warnln("error checking bot admin status")
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
@@ -157,7 +192,10 @@ func (bot *TipBot) isOwner(chat *tb.Chat, me *tb.User) bool {
|
||||
func (bot *TipBot) isAdmin(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "isAdmin",
|
||||
"chat_id": chat.ID}).Warnln("error checking bot admin status")
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
@@ -172,7 +210,10 @@ func (bot *TipBot) isAdmin(chat *tb.Chat, me *tb.User) bool {
|
||||
func (bot *TipBot) isAdminAndCanInviteUsers(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
log.WithObjects(err).WithFields(logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "isAdminAndCanInviteUsers",
|
||||
"chat_id": chat.ID}).Warnln("error checking bot admin status")
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
|
||||
@@ -106,7 +106,14 @@ func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, e
|
||||
var EnterUserStateData EnterUserStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "lnurlPayHandlerSend",
|
||||
"user": user.GetUserStr(),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"error": err}).Errorf("error unmarshaling state data")
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
"github.com/tidwall/buntdb"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var defaultTicketDuration = time.Minute * 15
|
||||
|
||||
// handleTelegramNewMember is invoked when users join groups.
|
||||
// handler will create a new invoice and send it to the group chat.
|
||||
// a ticket callback timer function is stored in the blunt db.
|
||||
func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Context, error) {
|
||||
id := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
group, err := bot.loadGroup(id)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if !bot.isAdmin(ctx.Chat(), bot.Telegram.Me) {
|
||||
log.Traceln("[TICKET] I am not an admin of this group")
|
||||
return ctx, fmt.Errorf("no admin rights")
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
// if the user does not have an account we put his Telegram user here
|
||||
// because we will need it after the invoice callback has been triggered in stopJoinTicketTimer
|
||||
if user == nil {
|
||||
user = &lnbits.User{
|
||||
ID: "",
|
||||
Telegram: ctx.Message().Sender,
|
||||
}
|
||||
}
|
||||
|
||||
ownerUser, err := GetUser(group.Owner, *bot)
|
||||
if err != nil {
|
||||
log.Errorln("[TICKET] Error: no owner found")
|
||||
return ctx, err
|
||||
}
|
||||
ticket := JoinTicket{
|
||||
Sender: ctx.Sender(),
|
||||
Ticket: group.Ticket,
|
||||
}
|
||||
// group owner creates invoice
|
||||
invoice, err := ownerUser.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: ticket.Ticket.Price,
|
||||
Memo: ticket.Ticket.Memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[handleTelegramNewMember] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send the owner invoice to chat
|
||||
// TicketEvent is used for callback button (if user has balance)
|
||||
ticketEvent := TicketEvent{
|
||||
// invoice event is used for invoice callbacks (do not kick if invoice is paid)
|
||||
InvoiceEvent: &InvoiceEvent{
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", id))),
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: ticket.Ticket.Price,
|
||||
Memo: ticket.Ticket.Memo},
|
||||
Payer: user,
|
||||
Chat: ctx.Chat(),
|
||||
Callback: InvoiceCallbackPayJoinTicket,
|
||||
CallbackData: "",
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
},
|
||||
Group: group,
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", id))),
|
||||
}
|
||||
captionText := fmt.Sprintf("⚠️ %s, this group requires you to pay *%d sat* to join. You have 15 minutes to pay or you will be kicked for one day.", GetUserStrMd(ctx.Message().Sender), ticket.Ticket.Price)
|
||||
|
||||
var balance int64 = 0
|
||||
if user.ID != "" {
|
||||
// if the user has an account
|
||||
// // if the user has enough balance, we send him a payment button
|
||||
balance, err = bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/group] Error: Could not get user balance: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
} else {
|
||||
balance = 0
|
||||
}
|
||||
|
||||
var msg *tb.Message
|
||||
if balance >= group.Ticket.Price {
|
||||
_, menu := bot.getSendPayButton(ctx, ticketEvent)
|
||||
msg = bot.trySendMessageEditable(ctx.Chat(), captionText, menu)
|
||||
} else {
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
entryMessage := &tb.Photo{
|
||||
File: tb.File{FileReader: bytes.NewReader(qr)},
|
||||
Caption: captionText}
|
||||
entryMessage.Caption = fmt.Sprintf("%s\n\n`%s`", entryMessage.Caption, invoice.PaymentRequest)
|
||||
msg = bot.trySendMessageEditable(ctx.Chat(), entryMessage)
|
||||
}
|
||||
ticketEvent.Message = msg
|
||||
ticket.Message = msg
|
||||
ticket.CreatedTimestamp = time.Now()
|
||||
err = bot.Bunt.Set(&ticket)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
// save invoice struct for later use
|
||||
err = ticketEvent.Set(&ticketEvent, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
err = ticketEvent.InvoiceEvent.Set(ticketEvent.InvoiceEvent, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
bot.startTicketCallbackFunctionTimer(ticket)
|
||||
fmt.Println(ctx.Message())
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// stopTicketTimer will load the timer function based on the event.
|
||||
// should stop the ticker timer function and remove ticket from bluntDB.
|
||||
func (bot *TipBot) stopJoinTicketTimer(event Event) {
|
||||
ev := event.(*InvoiceEvent)
|
||||
ticket := JoinTicket{Sender: ev.Payer.Telegram, Message: ev.Message}
|
||||
err := bot.Bunt.Get(&ticket)
|
||||
if err != nil {
|
||||
log.Errorf("[stopJoinTicketTimer] %v", err)
|
||||
return
|
||||
}
|
||||
if commission := getTicketCommission(ticket.Ticket); commission > 0 {
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[stopJoinTicketTimer] %v", err)
|
||||
return
|
||||
}
|
||||
invoice, err := me.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: commission,
|
||||
Memo: fmt.Sprintf("Ticket %d", ticket.Message.Chat.ID)},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
log.Errorf("[stopJoinTicketTimer] %v", err)
|
||||
return
|
||||
}
|
||||
_, err = ticket.Ticket.Creator.Wallet.Pay(lnbits.PaymentParams{Bolt11: invoice.PaymentRequest, Out: true}, bot.Client)
|
||||
if err != nil {
|
||||
log.Errorf("[stopJoinTicketTimer] %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
d := time.Until(time.Now().Add(defaultTicketDuration))
|
||||
bot.tryDeleteMessage(ev.Message)
|
||||
t := runtime.GetFunction(ticket.Key(), runtime.WithDuration(d))
|
||||
t.StopChan <- struct{}{}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorf("[stopJoinTicketTimer] %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
|
||||
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
|
||||
// check if ticket is already expired
|
||||
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
|
||||
return
|
||||
}
|
||||
// ticket is valid. create duration until kick
|
||||
ticketDuration := time.Until(ticket.CreatedTimestamp.Add(defaultTicketDuration))
|
||||
// create function timer
|
||||
t := runtime.NewResettableFunction(ticket.Key(),
|
||||
runtime.WithTimer(time.NewTimer(ticketDuration)))
|
||||
// run the ticket callback function
|
||||
t.Do(func() {
|
||||
// ticket expired
|
||||
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
|
||||
if err != nil {
|
||||
log.Errorln("🧨 could not fetch / ban chat member")
|
||||
return
|
||||
}
|
||||
// ban user
|
||||
err = bot.Telegram.Ban(ticket.Message.Chat, member)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
bot.tryDeleteMessage(ticket.Message)
|
||||
})
|
||||
}
|
||||
|
||||
// restartPersistedTickets kicks of all ticket timers
|
||||
func (bot *TipBot) restartPersistedTickets() {
|
||||
bot.Bunt.View(func(tx *buntdb.Tx) error {
|
||||
err := tx.Ascend("join-ticket", func(key, value string) bool {
|
||||
ticket := JoinTicket{}
|
||||
err := json.Unmarshal([]byte(value), &ticket)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
bot.startTicketCallbackFunctionTimer(ticket)
|
||||
return true // continue iteration
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
func getTicketCommission(ticket *Ticket) int64 {
|
||||
if ticket.Price < 20 {
|
||||
return 0
|
||||
}
|
||||
// 2% cut + 100 sat base fee
|
||||
commissionSat := ticket.Price*ticket.Cut/100 + ticket.BaseFee
|
||||
if ticket.Price <= 1000 {
|
||||
// if < 1000, then 10% cut + 10 sat base fee
|
||||
commissionSat = ticket.Price*ticket.CutCheap/100 + ticket.BaseFeeCheap
|
||||
}
|
||||
return commissionSat
|
||||
}
|
||||
+29
-14
@@ -3,6 +3,7 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -13,7 +14,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
logrus "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
@@ -55,21 +56,26 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
logFields := logrus.Fields{
|
||||
"module": "telegram",
|
||||
"func": "tipHandler",
|
||||
"path": "/tip",
|
||||
}
|
||||
// get tip amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
err = fmt.Errorf("%v: %v", errors.Create(errors.InvalidAmountError), err)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).Warnln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
err = bot.parseDonationCommandHandler(ctx)
|
||||
if err == nil {
|
||||
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).WithField("amount", amount).Warnln("failed parsing donation command")
|
||||
return ctx, err
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
@@ -87,12 +93,17 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
if _, exists := bot.UserExists(to.Telegram); !exists {
|
||||
log.Infof("[/tip] User %s has no wallet.", toUserStr)
|
||||
log.WithObjects(ctx, user).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID}).Infof("User has no wallet.")
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user": GetUserStr(to.Telegram),
|
||||
"to_user_id": to.ID,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
}).Errorln("Could not create wallet for user")
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,15 +125,19 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
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)
|
||||
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
}).Warnf("Transaction failed")
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
|
||||
|
||||
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.WithObjects(ctx, user).WithFields(logFields).WithFields(logrus.Fields{
|
||||
"to_user": toUserStr,
|
||||
"amount": amount}).Info("created Tip")
|
||||
|
||||
// notify users
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
|
||||
@@ -153,7 +153,6 @@ func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error)
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
@@ -220,7 +219,16 @@ func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Cont
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
|
||||
bot.Cache.Set(inlineTipjar.ID, inlineTipjar, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-tipjar",
|
||||
"func": "handleInlineTipjarQuery",
|
||||
"to_user": GetUserStr(inlineTipjar.To.Telegram),
|
||||
"to_user_id": inlineTipjar.To.ID,
|
||||
"to_telegram_id": inlineTipjar.To.Telegram.ID,
|
||||
"to_wallet_id": inlineTipjar.To.Wallet.ID,
|
||||
"amount": inlineTipjar.PerUserAmount,
|
||||
"data": fmt.Sprintf("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)}).
|
||||
Infof("created tipjar")
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -229,7 +237,9 @@ func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Cont
|
||||
IsPersonal: true,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram-tipjar",
|
||||
"func": "handleInlineTipjarQuery"}).Errorln("could not answer query")
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
@@ -252,7 +262,14 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "acceptInlineTipjarHandler",
|
||||
"to_user_id": to.ID,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"amount": inlineTipjar.PerUserAmount,
|
||||
"telegram_id": from.Telegram.ID}).Errorf(fmt.Sprintf("tipjar %s inactive.", inlineTipjar.ID))
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
@@ -291,7 +308,16 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "acceptInlineTipjarHandler",
|
||||
"user": fromUserStr,
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"amount": inlineTipjar.PerUserAmount,
|
||||
"telegram_id": from.Telegram.ID}).Infof("Draining tipjar")
|
||||
inlineTipjar.NGiven += 1
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
@@ -300,7 +326,16 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "acceptInlineTipjarHandler",
|
||||
"user": fromUserStr,
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"amount": inlineTipjar.PerUserAmount,
|
||||
"telegram_id": from.Telegram.ID}).Warnln(errmsg)
|
||||
}
|
||||
|
||||
// build tipjar message
|
||||
@@ -318,7 +353,16 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineTipjar.Message)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "acceptInlineTipjarHandler",
|
||||
"user": fromUserStr,
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"amount": inlineTipjar.PerUserAmount,
|
||||
"telegram_id": from.Telegram.ID}).Infoln(inlineTipjar.Message)
|
||||
bot.tryEditMessage(c, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
}
|
||||
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
|
||||
|
||||
@@ -78,8 +78,17 @@ func (t *Transaction) Send() (success bool, err error) {
|
||||
// save transaction to db
|
||||
tx := t.Bot.DB.Transactions.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"user": t.FromUser,
|
||||
"user_id": t.From.ID,
|
||||
"wallet_id": t.From.Wallet.ID,
|
||||
"telegram_id": t.From.Telegram.ID,
|
||||
"to_user": t.ToUser,
|
||||
"to_wallet_id": t.To.Wallet.ID,
|
||||
"to_user_id": t.To.ID,
|
||||
"error": tx.Error}).Errorln("could not log transaction")
|
||||
}
|
||||
return success, err
|
||||
}
|
||||
@@ -94,14 +103,30 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"to_user": toUserStr,
|
||||
"to_user_id": to.ID,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"user": fromUserStr,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"amount": amount},
|
||||
).Errorln("error checking balance")
|
||||
return false, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
errmsg := fmt.Sprintf("balance too low.")
|
||||
log.Warnf("Balance of user %s too low", fromUserStr)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"to_user": to.ID,
|
||||
"user": fromUserStr,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"telegram_id": from.Telegram.ID}).Warn("balance of too low")
|
||||
return false, fmt.Errorf(errmsg)
|
||||
}
|
||||
|
||||
@@ -116,30 +141,63 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
Memo: memo},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"user": toUserStr,
|
||||
"user_id": to.ID,
|
||||
"wallet_id": to.Wallet.ID,
|
||||
"telegram_id": to.Telegram.ID,
|
||||
"error": err.Error()}).Errorln("could not create invoice")
|
||||
return false, err
|
||||
}
|
||||
t.Invoice = invoice
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
|
||||
log.Warnf(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"user": fromUserStr,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"to_user": toUserStr,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"to_user_id": to.ID,
|
||||
"error": err.Error()}).Warnf("Payment failed")
|
||||
return false, err
|
||||
}
|
||||
|
||||
// check if fromUser has balance
|
||||
_, err = bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"user": fromUserStr,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"to_user": toUserStr,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"to_user_id": to.ID,
|
||||
"error": err.Error()}).Errorln("could not get sender balance")
|
||||
return false, err
|
||||
}
|
||||
_, err = bot.GetUserBalance(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "SendTransaction",
|
||||
"user": fromUserStr,
|
||||
"user_id": from.ID,
|
||||
"wallet_id": from.Wallet.ID,
|
||||
"telegram_id": from.Telegram.ID,
|
||||
"to_user": toUserStr,
|
||||
"to_wallet_id": to.Wallet.ID,
|
||||
"to_user_id": to.ID,
|
||||
"error": err.Error()}).Errorln("could not get receiver balance")
|
||||
return false, err
|
||||
}
|
||||
|
||||
|
||||
@@ -133,7 +133,10 @@ func (bot *TipBot) transactionsScrollLeftHandler(ctx intercept.Context) (interce
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "transactionsScrollLeftHandler",
|
||||
}).Info("Transactions not in cache anymore")
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
@@ -155,7 +158,9 @@ func (bot *TipBot) transactionsScrollRightHandler(ctx intercept.Context) (interc
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "transactionsScrollRightHandler"}).Info("Transactions not in cache anymore")
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
+20
-30
@@ -7,7 +7,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -25,33 +24,13 @@ func ResetUserState(user *lnbits.User, bot *TipBot) {
|
||||
user.ResetState()
|
||||
UpdateUserRecord(user, *bot)
|
||||
}
|
||||
|
||||
func GetUserStr(user *tb.User) string {
|
||||
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 userStr
|
||||
return lnbits.User{Telegram: user}.GetUserStr()
|
||||
}
|
||||
|
||||
func GetUserStrMd(user *tb.User) string {
|
||||
userStr := fmt.Sprintf("@%s", user.Username)
|
||||
// if user does not have a username
|
||||
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(userStr)
|
||||
}
|
||||
return lnbits.User{Telegram: user}.GetUserStrMd()
|
||||
}
|
||||
|
||||
func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
for _, ele := range slice {
|
||||
if ele.ID == i.ID {
|
||||
@@ -77,8 +56,6 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
user.Wallet.Balance = wallet.Balance
|
||||
@@ -88,7 +65,15 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
}
|
||||
// msat to sat
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "GetUserBalance",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"telegram_id": user.Telegram.ID,
|
||||
"amount": amount},
|
||||
).Debugf("updated user balance")
|
||||
|
||||
// update user balance in cache
|
||||
bot.Cache.Set(
|
||||
@@ -96,7 +81,7 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
amount,
|
||||
&store.Options{Expiration: 1 * time.Hour},
|
||||
)
|
||||
return
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
|
||||
@@ -109,8 +94,6 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
|
||||
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
|
||||
err := bot.createWallet(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
return user, err
|
||||
}
|
||||
// todo: remove this. we're doing this already in bot.createWallet().
|
||||
@@ -118,7 +101,14 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
|
||||
log.WithFields(log.Fields{
|
||||
"module": "telegram",
|
||||
"func": "CreateWalletForTelegramUser",
|
||||
"user": GetUserStr(user.Telegram),
|
||||
"user_id": user.ID,
|
||||
"wallet_id": user.Wallet.ID,
|
||||
"error": err.Error()},
|
||||
).Printf("Wallet created")
|
||||
return user, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api/userpage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/nostr"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
|
||||
_ "net/http/pprof"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -24,17 +22,8 @@ import (
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
log.SetFormatter(customFormatter)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
|
||||
defer withRecovery()
|
||||
price.NewPriceWatcher().Start()
|
||||
@@ -60,10 +49,6 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
|
||||
s.AppendRoute("/app/@{username}", userpage.UserWebAppHandler, http.MethodGet)
|
||||
|
||||
// nostr nip05 identifier
|
||||
nostr := nostr.New(bot)
|
||||
s.AppendRoute("/.well-known/nostr.json", nostr.Handle, http.MethodGet)
|
||||
|
||||
// append lndhub ctx functions
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext/auth`, api.AuthTypeNone, api.AccessKeyTypeNone, bot.DB.Users, hub.Handle)
|
||||
|
||||
@@ -1,405 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """pomoc"""
|
||||
basicsCommandStr = """základy"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """zůstatek"""
|
||||
sendCommandStr = """poslat"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """zaplatit"""
|
||||
donateCommandStr = """podpořit"""
|
||||
advancedCommandStr = """pokročilé"""
|
||||
transactionsCommandStr = """transakce"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """list"""
|
||||
|
||||
linkCommandStr = """odkaz"""
|
||||
lnurlCommandStr = """LNURL"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """přijmout"""
|
||||
hideCommandStr = """skrýt"""
|
||||
volcanoCommandStr = """sopka"""
|
||||
showCommandStr = """ukázat"""
|
||||
optionsCommandStr = """možnosti"""
|
||||
settingsCommandStr = """nastavení"""
|
||||
saveCommandStr = """uložit"""
|
||||
deleteCommandStr = """smazat"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """To nelze udělat."""
|
||||
cantClickMessage = """Toto tlačítko nejde zmáčkout."""
|
||||
balanceTooLowMessage = """Tvůj zůstatek je příliš malý."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Odeslat"""
|
||||
payButtonMessage = """✅ Zaplatit"""
|
||||
payReceiveButtonMessage = """💸 Zaplatit"""
|
||||
receiveButtonMessage = """✅ Přijmout"""
|
||||
withdrawButtonMessage = """✅ Vybrat"""
|
||||
cancelButtonMessage = """🚫 Zrušit"""
|
||||
collectButtonMessage = """✅ Vybrat"""
|
||||
nextButtonMessage = """Dále"""
|
||||
backButtonMessage = """Zpět"""
|
||||
acceptButtonMessage = """Potvrdit"""
|
||||
denyButtonMessage = """Odmítnout"""
|
||||
tipButtonMessage = """Platba"""
|
||||
revealButtonMessage = """Odhalit"""
|
||||
showButtonMessage = """Ukázat"""
|
||||
hideButtonMessage = """Skrýt"""
|
||||
joinButtonMessage = """Připojit se"""
|
||||
optionsButtonMessage = """Možnosti"""
|
||||
settingsButtonMessage = """Nastavení"""
|
||||
saveButtonMessage = """Uložit"""
|
||||
deleteButtonMessage = """Smazat"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Peněženka*
|
||||
_Tento bot je bitcoinová lightning peněženka, která umožňuje posílat platby na Telegramu. Pro použití přidejte bota do chatu. Základní jednotkou je 1 sat. 100 000 000 sats = 1 bitcoin. Napiš 📚 /basics pro víc info._
|
||||
|
||||
❤️ *Podpořit*
|
||||
_Tento bot si neúčtuje žádné poplatky, ale jeho provoz stojí nějaké sats. Pokud se Ti líbí, zvaž prosím podporu tohoto projektu. Pro podporu napiš_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Příkazy*
|
||||
*/tip* 🏅 Odpověz na zprávu, abys poslal tip: `/tip <částka> [<zpráva>]`
|
||||
*/balance* 👑 Zkontroluj svůj zůstatek: `/balance`
|
||||
*/send* 💸 Poslat platbu uživateli: `/send <částka> @uživatel nebo uživatel@ln.tips [<zpráva>]`
|
||||
*/invoice* ⚡️ Vytvořit lightning (invoice): `/invoice <částka> [<zpráva>]`
|
||||
*/pay* ⚡️ Zaplatit lightning invoice: `/pay <invoice>`
|
||||
*/donate* ❤️ Podpořit projekt: `/donate 1000`
|
||||
*/advanced* 🤖 Pokročilé funkce.
|
||||
*/help* 📖 Tato nápověda."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Tvoje lightning adresa je `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin jsou internetové peníze. Jsou decentralizované, k jejich použití nepotřebuješ povolení a nemají žádnou centrální autoritu, která by je řídila. Bitcoin jsou zdravé peníze, které jsou na rozdíl od starého finančního systému rychlejší, bezpečnější a pro každého._
|
||||
|
||||
🧮 *Ekonomnika*
|
||||
_Nejmenší jednotkou bitcoinu je 1 sat. 100 000 000 sats = 1 bitcoin. Nikdy nebude existovat víc než 21 milionů bitcoinů. Kurz bitcoinu vůči státním měnám se může často a náhle měnit. Nicméně, pokud žijete na bitcoinovém standardu, 1 sat se bude pořád rovnat 1 satu._
|
||||
|
||||
⚡️ *Lightning Network*
|
||||
_Lightningová síť je platební protokol který umožňuje rychlé a levné bitcoinové platby nevyžadující téměř žádnou energii. Tato síť škáluje bitcoin pro miliardy lidí na celém světě._
|
||||
|
||||
📲 *Lightning peněženky*
|
||||
_Tvoje prostředky z této lightning peněženky můžeš poslat na jakoukoliv jinou a naopak. Doporučené lightning peněženky pro mobil jsou_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (držíte své klíče), nebo_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(jednoduchá, ale klíče od sats nedržíte)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Tento bot je volný a otevřený_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. Můžeš ho běžet na vlastním počítači a používat jej ve vlastní komunitě._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Přidej tohoto bota do své skupiny na Telegramu a můžeš posílat /tip za zprávy. Pokud uděláš bota adminem skupiny, bude odstraňovat příkazy, aby zůstal chat přehlednější._
|
||||
|
||||
🏛 *Podmínky*
|
||||
_Nejsme správci Tvých prostředků. Budeme konat v Tvém nejlepším zájmu, ale také jsme si vědomi nejisté situace bez KYC, dokud nepřijdeme na něco jiného. Jakákoli částka, kterou si pošleš do peněženky, je proto považována za příspěvek podpory. Neposílej nám všechny svoje peníze. Vezmi v potaz, že bot je v beta fázi vývoje. Používáš ho na vlastní riziko._
|
||||
|
||||
❤️ *Podpora*
|
||||
_Tento bot si neúčtuje žádné poplatky, ale jeho provoz stojí nějaké sats. Pokud se Ti líbí, zvaž prosím podporu tohoto projektu. Pro podporu napiš_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Prosím, nastav si uživatelské jméno na Telegramu."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline příkazy*
|
||||
*send* 💸 Poslat sats do chatu: `%s send <částka> [<uživatel>] [<zpráva>]`
|
||||
*receive* 🏅 Vyžádat platbu: `... receive <částka> [<uživatel>] [<zpráva>]`
|
||||
*faucet* 🚰 Vytvořit faucet: `... faucet <kapacita> <částka_na_uživatele> [<zpráva>]`
|
||||
*tipjar* 🍯 Vytvořit tipjar: `... tipjar <kapacita> <částka_na_uživatele> [<zpráva>]`
|
||||
|
||||
📖 V každém chatu můžeš používat inline příkazy, dokonce i v soukromých konverzacích. Po zadání inline příkazu chvilku vyčkej a *klikni* na výsledek, nemačkej enter.
|
||||
|
||||
⚙️ *Pokročilé příkazy*
|
||||
*/transactions* 📊 Seznam transakcí
|
||||
*/link* 🔗 Propojit peněženku s [BlueWallet](https://bluewallet.io/) nebo [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ LNURL obdržet nebo zaplatit: `/lnurl` nebo `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/faucet* 🚰 Vytvořit faucet: `/faucet <kapacita> <částka_na_uživatele>`
|
||||
*/tipjar* 🍯 Vytvořit tipjar: `/tipjar <kapacita> <částka_na_uživatele>`
|
||||
*/group* 🎟 Vytvořit vstupenky do skupiny: `/group add <název_skupiny> [<cena_vstupenky>]`
|
||||
*/shop* 🛍 Prohlížet obchody: `/shop` nebo `/shop <uživatel/id_obchodu>`
|
||||
*/generate* 🎆 Vytvořit obrázky od DALLE 2: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Zadej částku mezi %d a %d sats."""
|
||||
enterAmountMessage = """💯 Zadej částku."""
|
||||
enterUserMessage = """👤 Zadej uživatele."""
|
||||
enterTextMessage = """⌨️ Zadej text."""
|
||||
errorReasonMessage = """🚫 Chyba: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Nastavování peněženky..."""
|
||||
startWalletCreatedMessage = """🧮 Peněženka vytvořena."""
|
||||
startWalletReadyMessage = """✅ *Tvá peněženka je připravena.*"""
|
||||
startWalletErrorMessage = """🚫 Chyba při vytváření peněženky. Zkus to později znovu."""
|
||||
startNoUsernameMessage = """☝️ Vypadá to, že na Telegramu nemáš ještě uživatelské jméno (@username). Nevadí, pro používání tohoto bota ho nepotřebuješ. Nicméně, pro snazší používání peněženky si nastav uživatelské jméno v nastavení Telegramu. Poté zadej příkaz /balance a bot si zaktualizuje své záznamy."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Tvůj zůstatek:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Nepodařilo se získat info o zůstatku. Zkus to později znovu."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Odpověděl jsi na zprávu kvůli platbě? Pro odpověď na jakoukoli zprávu na PC klikni pravým myšítkem a vyber ´Odpovědět´ nebo na mobilu přes zprávu přejeď do strany. Pokud chceš poslat platbu jinému uživateli přímo, použij příkaz /send"""
|
||||
tipInviteGroupMessage = """ℹ️ Tohoto bota můžeš přizvat do jakékoli skupiny a posílat v ní platby."""
|
||||
tipEnterAmountMessage = """Zadal jsi částku?"""
|
||||
tipValidAmountMessage = """Zadal jsi platnou částku?"""
|
||||
tipYourselfMessage = """📖 Nemůžeš poslat platbu sobě."""
|
||||
tipSentMessage = """💸 %d sats posláno pro %s."""
|
||||
tipReceivedMessage = """🏅 %s ti poslal %d sats."""
|
||||
tipErrorMessage = """🚫 Platba selhala."""
|
||||
tipUndefinedErrorMsg = """Prosím, zkus to později znovu."""
|
||||
tipHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/tip <částka> [<zpráva>]`
|
||||
*Příklad:* `/tip 1000 Díky moc!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Zadal jsi platnou částku?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Uživatel %s si ještě nevytvořil peněženku."""
|
||||
sendSentMessage = """💸 %d sats posláno uživateli %s."""
|
||||
sendPublicSentMessage = """💸 %d sats posláno od %s uživateli %s."""
|
||||
sendReceivedMessage = """🏅 %s ti poslal %d sats."""
|
||||
sendErrorMessage = """🚫 Odeslání selhalo."""
|
||||
confirmSendMessage = """Chceš zaplatit uživateli %s?\n\n💸 Částka: %d sats"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Odeslání zrušeno."""
|
||||
errorTryLaterMessage = """🚫 Chyba. Prosím, zkus to později znovu."""
|
||||
sendSyntaxErrorMessage = """Zadal jsi částku a příjemce? Můžeš použít příkaz /send k poslání platby buď uživateli Telegramu jako %s nebo na lightning adresu jako LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/send <částka> <uživatel> [<zpráva>]`
|
||||
*Příklad:* `/send 1000 @LightningTipBot Všichni jsme Satoshi ❤️`
|
||||
*Příklad:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Obdržel jsi %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Obdržel jsi %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Zadal jsi částku?"""
|
||||
invoiceValidAmountMessage = """Zadal jsi platnou částku?"""
|
||||
invoiceHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/invoice <částka> [<zpráva>]`
|
||||
*Příklad:* `/invoice 1000 Děkuji!`"""
|
||||
invoicePaidText = """✅ Invoice zaplacena."""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Platba zrušena."""
|
||||
invoicePaidMessage = """⚡️ Platba odeslána."""
|
||||
invoicePublicPaidMessage = """⚡️ Platba od %s odeslána."""
|
||||
invalidInvoiceHelpMessage = """Máš platnou lightning invoice? Zkus příkaz /send k poslání platby uživateli Telegramu nebo na lightning adresu."""
|
||||
invoiceNoAmountMessage = """🚫 Nemůžu zaplatit invoice bez částky."""
|
||||
insufficientFundsMessage = """🚫 Nedostatek prostředků. Máš %d sats, ale potřebuješ alespoň %d sats."""
|
||||
feeReserveMessage = """⚠️ Odeslání celého zůstatku se nemusí zdařit kvůli poplatkům v síti. Nechej rezervu aspoň 1% na poplatky."""
|
||||
invoicePaymentFailedMessage = """🚫 Platba selhala: %s"""
|
||||
invoiceUndefinedErrorMessage = """Nemohl jsem zaplatit invoice."""
|
||||
confirmPayInvoiceMessage = """Chceš poslat tuto platbu?\n\n💸 Částka: %d sats"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/pay <invoice>`
|
||||
*Příklad:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Díky za tvůj příspěvek."""
|
||||
donationErrorMessage = """🚫 Ale ne, odeslání přspěvku selhalo."""
|
||||
donationProgressMessage = """🧮 Příprava odeslání příspěvku..."""
|
||||
donationFailedMessage = """🚫 Příspěvek selhal: %s"""
|
||||
donateEnterAmountMessage = """Zadal jsi částku?"""
|
||||
donateValidAmountMessage = """Zadal jsi platnou částku?"""
|
||||
donateHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/donate <částka>`
|
||||
*Příklad:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Lightning invoice nebo LNURL nešlo rozpoznat. Pokus se QR kód vycentrovat, oříznout, nebo ho více přiblížit."""
|
||||
photoQrRecognizedMessage = """✅ QR kód:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Pro příjem plateb můžeš používat tuto statickou LNURL."""
|
||||
lnurlResolvingUrlMessage = """🧮 Zpracovávám adresu..."""
|
||||
lnurlGettingUserMessage = """🧮 Připravuji platbu..."""
|
||||
lnurlPaymentFailed = """🚫 Platba selhala: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Neplatná částka."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Částka musí být mezi %d a %d sats."""
|
||||
lnurlNoUsernameMessage = """🚫 Pro příjem plateb pomocí LNURL potřebuješ na Telegramu uživatelské jméno."""
|
||||
lnurlHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/lnurl [částka] <lnurl>`
|
||||
*Příklad:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Chceš se přihlásit do %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Přihlášení úspěšné."""
|
||||
loginButtonMessage = """✅ Přihlásit"""
|
||||
loginCancelledMessage = """🚫 Přihlášení zrušeno."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Chceš provést tento výběr?\n\n💸 Částka: %d sats"""
|
||||
lnurlPreparingWithdraw = """🧮 Příprava výběru..."""
|
||||
lnurlWithdrawFailed = """🚫 Výběr selhal."""
|
||||
lnurlWithdrawCancelled = """🚫 Výběr zrušen."""
|
||||
lnurlWithdrawSuccess = """✅ Výběr vyžádán."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Propojit vlastní peněženku*
|
||||
|
||||
⚠️ Nikdy s nikým nesdílej URL nebo QR kód, jinak bude mít přístup k tvým prostředkům. Použij příkaz /api pro své API klíče.
|
||||
|
||||
- *BlueWallet:* Vyber *Nová peněženka*, *Importovat peněženku*, *Scanovat nebo importovat ze souboru* a nascanuj QR kód.
|
||||
- *Zeus:* Zkopíruj URL níže, vyber *Add a new node/Přidat novou nodu*, zvol *LNDHub* jako Node interface/Rozhraní nody, vlož URL a ulož nastavení *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Propojení s peněženkou se nezdařilo. Prosím, zkus to později znovu."""
|
||||
linkHiddenMessage = """🔍 Propojení je skryto. Abys ho znovu viděl, zadej /link příkaz."""
|
||||
|
||||
# API
|
||||
|
||||
apiConnectMessage = """🔗 *Tvé API klíče*
|
||||
|
||||
⚠️ Nikdy s nikým tyto klíče nesdílej, jinak bude mít přístup k tvým prostředkům. Použij příkaz /link k propojení své peněženky.
|
||||
|
||||
- *Admin klíč:* `%s`
|
||||
- *Invoice klíč:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Klíče jsou skryty. Abys je znovu viděl, zadej /api příkaz."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Vytvořit faucet."""
|
||||
inlineQueryFaucetDescription = """Použití: @%s faucet <kapacita> <částka_na_uživatele>"""
|
||||
inlineResultFaucetTitle = """🚰 Vytvořit faucet s %d sats."""
|
||||
inlineResultFaucetDescription = """👉 Klikni zde pro vytvoření faucetu v tomto chatu."""
|
||||
|
||||
inlineFaucetMessage = """Zmáčkni ✅ pro výběr %d sats z faucetu od %s.
|
||||
|
||||
🚰 Zbývá: %d/%d sats (rozdáno %d/%d uživatelům)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Faucet je prázdný 🍺\n\n🏅 %d sats rozdáno %d uživatelům."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Komunikuj s %s 👈 pro správu své peněženky."""
|
||||
inlineFaucetCancelledMessage = """🚫 Faucet zrušen."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Částka na uživatele musí dělit kapacitu faucetu beze zbytku nebo je příliš malá (min 5 sats)."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Neplatná částka."""
|
||||
inlineFaucetSentMessage = """🚰 %d sats posláno %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s ti poslal %d sats."""
|
||||
inlineFaucetHelpFaucetInGroup = """Vytvoř faucet ve skupině s botem nebo použij 👉 inline příkaz (napiš /advanced pro víc info)."""
|
||||
inlineFaucetAlreadyTookMessage = """🚫 Z tohoto faucetu už jsi čerpal."""
|
||||
inlineFaucetHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/faucet <kapacita> <částka_na_uživatele>`
|
||||
*Příklad:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Poslat platbu do chatu."""
|
||||
inlineQuerySendDescription = """Použití: @%s send <částka> [<uživatel>] [<zpráva>]"""
|
||||
inlineResultSendTitle = """💸 Poslat %d sats."""
|
||||
inlineResultSendDescription = """👉 Klikni pro poslání %d sats do tohoto chatu."""
|
||||
|
||||
inlineSendMessage = """Zmáčkni ✅ pro obdržení platby od %s.\n\n💸 Částka: %d sats"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sats posláno od %s uživateli %s."""
|
||||
inlineSendCreateWalletMessage = """Chatuj s %s 👈 pro správu své peněženky."""
|
||||
sendYourselfMessage = """📖 Nemůžeš platit sám sobě."""
|
||||
inlineSendFailedMessage = """🚫 Platba selhala."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Částka musí být větší než 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Tvůj zůstatek je příliš malý."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Vyžádat platbu v chatu."""
|
||||
inlineQueryReceiveDescription = """Použití: @%s receive <částka> [<uživatel>] [<zpráva>]"""
|
||||
inlineResultReceiveTitle = """🏅 Dostat %d sats."""
|
||||
inlineResultReceiveDescription = """👉 Klikni pro vyžádání platby %d sats."""
|
||||
|
||||
inlineReceiveMessage = """Zmáčkni 💸 pro zaplacení uživateli %s.\n\n💸 Částka: %d sats"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sats posláno od %s uživateli %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chatuj s %s 👈 pro správu své peněženky."""
|
||||
inlineReceiveYourselfMessage = """📖 Nemůžeš platit sám sobě."""
|
||||
inlineReceiveFailedMessage = """🚫 Platba selhala."""
|
||||
inlineReceiveCancelledMessage = """🚫 Platba zrušena."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Vytvořit tipjar."""
|
||||
inlineQueryTipjarDescription = """Použití: @%s tipjar <kapacita> <částka_od_uživatele>"""
|
||||
inlineResultTipjarTitle = """🍯 Vytvořit tipjar na %d sats."""
|
||||
inlineResultTipjarDescription = """👉 Klikni zde pro vytvoření tipjar v tomto chatu."""
|
||||
|
||||
inlineTipjarMessage = """Zmáčkni 💸 pro *platbu %d sats* do tohoto tipjar od %s.
|
||||
|
||||
🙏 Věnováno: *%d*/%d sats (od %d uživatelů)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 Tipjar od %s je plný ⭐️\n\n🏅 Věnováno %d sats od %d uživatelů."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Tipjar zrušen."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Částka od jednoho uživatele musí dělit kapacitu tipjar beze zbytku."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Neplatná částka."""
|
||||
inlineTipjarSentMessage = """🍯 %d sats posláno pro %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s ti poslal %d sats."""
|
||||
inlineTipjarHelpTipjarInGroup = """Vytvoř tipjar ve skupině s botem nebo použij 👉 inline příkaz (/advanced pro víc info)."""
|
||||
inlineTipjarHelpText = """📖 Ou, tohle se nezdařilo. %s
|
||||
|
||||
*Použití:* `/tipjar <kapacita> <částka_od_uživatele>`
|
||||
*Příklad:* `/tipjar 210 21`"""
|
||||
|
||||
# GROUP TICKETS
|
||||
groupAddGroupHelpMessage = """📖 Ou, tohle se nezdařilo. Tento příkaz funguje pouze ve skupinovém chatu. Mohou ho použít pouze vlastníci skupin.\nPoužití: `/group add <název_skupiny> [<částka>]`\nPříklad: `/group add NejvícHustáSkupina 1000`"""
|
||||
groupJoinGroupHelpMessage = """📖 Ou, tohle se nezdařilo. Prosím, zkus to znovu.\nPoužití: `/join <název_skupiny>`\nPříklad: `/join NejvícHustáSkupina`"""
|
||||
groupClickToJoinMessage = """🎟 [Klikni zde](%s) 👈 pro připojení `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 Uživatel %s obdržel vstupenku do této skupiny."""
|
||||
groupPayInvoiceMessage = """🎟 Pro připojení se ke skupině %s, zaplať výše uvedenou invoice."""
|
||||
groupBotIsNotAdminMessage = """🚫 Ou, tohle se nezdařilo. Musíš mě jmenovat adminem a dát mi práva zvát uživatele."""
|
||||
groupNameExists = """🚫 Skupina s tímto názvem už existuje. Prosím, vyber jiný název."""
|
||||
groupAddedMessage = """🎟 Vstupenky pro skupinu `%s` přidány.\nAlias: `%s` Cena: %d sats\n\nPro vyžádání vstupenky do této skupiny začni soukromý chat s %s a napiš `/join %s`."""
|
||||
groupNotFoundMessage = """🚫 Skupinu s tímto názvem se nepodařilo najít."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 Obdržel jsi *%d sats* (bez provize %d sats) za vstupenku do skupiny `%s` od uživatele %s."""
|
||||
groupReceiveTicketInvoice = """🎟 Obdržel jsi *%d sats* za vstupenku do skupiny `%s` od uživatele %s."""
|
||||
commandPrivateMessage = """Prosím, použij tento příkaz v soukromém chatu s %s."""
|
||||
groupHelpMessage = """🎟 Vstupenky do soukromých skupin 🎟
|
||||
|
||||
Prodej vstupenky do své _soukromé skupiny_ a zbavíš se spam botů.
|
||||
|
||||
*Pokyny pro skupinové adminy:*
|
||||
|
||||
1) Pozvi %s do své skupiny a udělej ho adminem.
|
||||
2) Skupinu změň na soukromou.
|
||||
3) Ve své skupině, jako její majitel, napiš `/group add <název_skupiny> [<cena_vstupenky>]`.
|
||||
|
||||
_Poplatky: Bot si bere provizi 10%% +10 sats za levné vstupenky. Je-li cena vstupenky >= 1000 sats, je provize 2%% + 100 sats._
|
||||
|
||||
*Pokyny pro členy skupin:*
|
||||
|
||||
Pro připojení ke skupině si promluv s %s a v soukromé zprávě napiš `/join <název_skupiny>`.
|
||||
|
||||
📖 *Použití:*
|
||||
*Pro adminy (ve skupinovém chatu):* `/group add <název_skupiny> [<cena_vstupenky>]`\nPříklad: `/group add NejvícHustáSkupina 1000`
|
||||
*Pro uživatele (v soukromém chatu):* `/join <název_skupiny>`\nPříklad: `/join NejvícHustáSkupina`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Vytvořit obrázky pomocí OpenAI DALLE 2.\nPoužití: `/generate <prompt>`\nCena: 1000 sat"""
|
||||
generateDallePayInvoiceMessage = """Zaplať tuto invoice pro vytvoření 4 obrázků 👇"""
|
||||
generateDalleGeneratingMessage = """Tvé obrázky se generují. Chvilku strpení..."""
|
||||
@@ -120,14 +120,12 @@ advancedMessage = """%s
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/transactions* 📊 Liste der Transaktionen
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Verbinde Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
|
||||
*/group* 🎟 Gruppenchat Funktionen: `/group`
|
||||
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
|
||||
*/shop* 🛍 Durchsuche Shops: `/shop` oder `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`
|
||||
*/chat* 💬 Chatte mit GPT: `/chat <nachricht>`"""
|
||||
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Gebe Betrag zwuschen %d und %d sat ein."""
|
||||
@@ -186,7 +184,6 @@ sendHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Du hast %d sat erhalten."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Du hast %d sat (%.2f %s) erhalten."""
|
||||
invoiceEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
|
||||
invoiceValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
|
||||
invoiceHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
+8
-16
@@ -123,14 +123,14 @@ advancedMessage = """%s
|
||||
⚙️ *Advanced commands*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Group chat features: `/group`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/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."""
|
||||
@@ -189,7 +189,6 @@ sendHelpText = """📖 Oops, that didn't work. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ You received %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ You received %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Did you enter an amount?"""
|
||||
invoiceValidAmountMessage = """Did you enter a valid amount?"""
|
||||
invoiceHelpText = """📖 Oops, that didn't work. %s
|
||||
@@ -372,21 +371,14 @@ groupJoinGroupHelpMessage = """📖 Oops, that didn't work. Please try
|
||||
groupClickToJoinMessage = """🎟 [Click here](%s) 👈 to join `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 User %s has received a ticket for this group."""
|
||||
groupPayInvoiceMessage = """🎟 To join the group %s, pay the invoice above."""
|
||||
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite and ban users."""
|
||||
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite users."""
|
||||
groupNameExists = """🚫 A group with this name already exists. Please choose a different name."""
|
||||
groupAddedMessagePrivate = """🎟 Tickets for group `%s` added.\n\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
|
||||
groupAddedMessagePublic = """🎟 Tickets enabled."""
|
||||
groupAddedMessage = """🎟 Tickets for group `%s` added.\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
|
||||
groupNotFoundMessage = """🚫 Could not find a group with this name."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 You received *%d sat* (excl. %d sat commission) for a ticket for group `%s` paid by user %s."""
|
||||
groupReceiveTicketInvoice = """🎟 You received *%d sat* for a ticket for group `%s` paid by user %s."""
|
||||
commandPrivateMessage = """Please use this command in a private chat with %s."""
|
||||
groupHelpMessage = """👥 *Group commands*
|
||||
|
||||
🎟 *Public tickets*
|
||||
|
||||
For admins (in group chat): `/group ticket <ticket_price>`\nExample: `/group ticket 1000`
|
||||
|
||||
🎟 *Private tickets*
|
||||
groupHelpMessage = """🎟 Private group tickets 🎟
|
||||
|
||||
Sell tickets for your _private Group_ and get rid of spam bots.
|
||||
|
||||
@@ -403,8 +395,8 @@ _Fees: The bot takes a 10%% +10 sat commission for cheap tickets. If the ticket
|
||||
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 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`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
|
||||
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Comandos avanzados*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Conectar a Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -184,7 +183,6 @@ sendHelpText = """📖 Oops, eso no funcionó. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Recibiste %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Recibiste %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """¿Ingresaste un monto?"""
|
||||
invoiceValidAmountMessage = """¿Ingresaste un monto válido?"""
|
||||
invoiceHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
@@ -1,412 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """ohje"""
|
||||
basicsCommandStr = """peruskomennot"""
|
||||
tipCommandStr = """tippi"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """lähetä"""
|
||||
invoiceCommandStr = """laskuta"""
|
||||
payCommandStr = """maksa"""
|
||||
donateCommandStr = """lahjoita"""
|
||||
advancedCommandStr = """lisäkomennot"""
|
||||
transactionsCommandStr = """tapahtumat"""
|
||||
logCommandStr = """loki"""
|
||||
listCommandStr = """lista"""
|
||||
|
||||
linkCommandStr = """linkki"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """hana"""
|
||||
|
||||
tipjarCommandStr = """tippikulho"""
|
||||
receiveCommandStr = """vastaanota"""
|
||||
hideCommandStr = """piilota"""
|
||||
volcanoCommandStr = """tulivuori"""
|
||||
showCommandStr = """näytä"""
|
||||
optionsCommandStr = """valinnat"""
|
||||
settingsCommandStr = """asetukset"""
|
||||
saveCommandStr = """tallenna"""
|
||||
deleteCommandStr = """poista"""
|
||||
infoCommandStr = """tiedot"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Et voi tehdä tuota."""
|
||||
cantClickMessage = """Et voi painaa tätä nappia."""
|
||||
balanceTooLowMessage = """Saldosi on liian pieni."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Lähetä"""
|
||||
payButtonMessage = """✅ Maksa"""
|
||||
payReceiveButtonMessage = """💸 Maksa"""
|
||||
receiveButtonMessage = """✅ Vastaanota"""
|
||||
withdrawButtonMessage = """✅ Nosta"""
|
||||
cancelButtonMessage = """🚫 Peruuta"""
|
||||
collectButtonMessage = """✅ Kerää"""
|
||||
nextButtonMessage = """Seuraava"""
|
||||
backButtonMessage = """Edellinen"""
|
||||
acceptButtonMessage = """Hyväksy"""
|
||||
denyButtonMessage = """Hylkää"""
|
||||
tipButtonMessage = """Tippi"""
|
||||
revealButtonMessage = """Paljasta"""
|
||||
showButtonMessage = """Näytä"""
|
||||
hideButtonMessage = """Piilota"""
|
||||
joinButtonMessage = """Liity"""
|
||||
optionsButtonMessage = """Valinnat"""
|
||||
settingsButtonMessage = """Asetukset"""
|
||||
saveButtonMessage = """Tallenna"""
|
||||
deleteButtonMessage = """Poista"""
|
||||
infoButtonMessage = """Tiedot"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Lompakko*
|
||||
_Tämä botti on Bitcoin Lightning -lompakko ja sitä käytetään Telegram:in sisällä tippien lähettämiseen. Botti on lisättävä jäseneksi ryhmäkeskusteluun, jotta se voi toimia. Tippien rahayksikkö on satoshi (sat). 100,000,000 sat = 1 Bitcoin. Kirjoita 📚 /basics lukeaksesi lisää._
|
||||
|
||||
❤️ *Lahjoitus*
|
||||
_Tämä botti ei veloita kuluja, mutta sen ylläpidosta aiheutuu kuluja. Jos tykkäät botista, niin harkitsethan lahjoituksen tekemistä projektille. Lahjoituksen voit tehdä komennolla_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Komennot*
|
||||
*/tip* 🏅 Lähetä tippi liittämällä vastausviestiin: `/tip <amount> [<memo>]`
|
||||
*/balance* 👑 Tarkista saldosi: `/balance`
|
||||
*/send* 💸 Lähetä varoja käyttäjälle: `/send <amount> @user or user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Vastaanota Lightning-maksu: `/invoice <amount> [<memo>]`
|
||||
*/pay* ⚡️ Lähetä Lightning-maksu: `/pay <invoice>`
|
||||
*/donate* ❤️ Lahjoitus LightningTipBot-tiimille: `/donate 1000`
|
||||
*/advanced* 🤖 Lisäasetukset.
|
||||
*/help* 📖 Lue tämä ohje."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Tiedot*"""
|
||||
infoYourLightningAddress = """Lightning Address -osoitteesi on `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin on internetin raha. Se on hajautettu ja vapaa, eikä sillä ole johtajia tai hallinnoijia. Bitcoin on kovaa rahaa. Se on myös nopeampi, turvallisempi ja laajemmin toimiva kuin perinteiset pankkijärjestelmät tai valuutat._
|
||||
|
||||
🧮 *Ekonomia*
|
||||
_Bitcoinin pienin yksikkö on satoshi (sat) ja 100.000.000 sat = 1 Bitcoin. Bitcoineja tulee kostkaan olemaan enintään 21 miljoonaa kappaletta. Bitcoinin päivittäinen valuuttavaihtokurssi vaihtelee päivittän, mutta jos elät Bitcoin standardin mukaisesti on kuitenkin 1 sat aina 1 sat._
|
||||
|
||||
⚡️ *Lightning-verkko*
|
||||
_Lightning-verkko on maksuprotokolla, joka mahdollistaa nopeat ja edulliset bitcoin-siirrot, eikä se juurikaan kuluta energiaa. Sen avulla miljardit ihmiset ympäri maailmaa pystyvät käyttämään Bitcoinia._
|
||||
|
||||
📲 *Lightning-lompakot*
|
||||
_Tämän botin lompakosta voit lähettää, tai vastaanottaa siihen, varoja kenen tahansa omistaman Lightning-lompakon välillä. Suositeltuja muita lompakkoja mobiililaitteisiin ovat_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), tai_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(helppo)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Tämä bottiohjelmisto on vapaa ja_ [open source](https://github.com/LightningTipBot/LightningTipBot) _ohjelmisto. Voit ajaa bottia omassa tietokoneessasi ja käyttää sitä yhdessä lähipiirisi kanssa._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Lisää tämä botti Telegram-ryhmäkeskusteluun, ja /tip -komennolla voit tipata kuita keskustelijoita. Kun määrität botin ryhmän pääkäyttäjäksi (admin), niin se myös siivoaa myös bottikomennot pois keskustelusta ja ryhmäsi sisältö pysyy siistinä._
|
||||
|
||||
🏛 *Ehdot*
|
||||
_Me emme pidä varojasi hallussa. Toimimme sinun parhaaksesi ja tiedämme KYC-henkilötunnistautumisen vaatimukset. Ne ovat aika mutkikkaita, kunnes keksimme asiaan ratkaisun. Käsittelemme kaikkia lompakossasi olevia varoja lahjoituksina. Älä siis lahjoita meille kaikkia varojasi. Huomioi myös että tämä botti on ns beta-kehitysvaiheessa ja huomioit riskit botin mahdollisesti tekemistä virheistä._
|
||||
|
||||
❤️ *Lahjoitus*
|
||||
_Tämä botti ei veloita kuluja, mutta sen ylläpidosta aiheutuu kuluja. Jos tykkäät botista, niin harkitsethan lahjoituksen tekemistä projektille. Lahjoituksen voit tehdä komennolla_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Ole hyvä ja määritä Telegram-käyttäjänimesi."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Keskustelun komennot*
|
||||
*send* 💸 Lähetä satteja keskusteluun: `%s send <amount> [<user>] [<memo>]`
|
||||
*receive* 🏅 Pyydä maksua: `... receive <amount> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Luo hana: `... faucet <capacity> <per_user> [<memo>]`
|
||||
*tipjar* 🍯 Luo tippikulho: `... tipjar <capacity> <per_user> [<memo>]`
|
||||
|
||||
📖 Keskustelu komennot ovat käytettävissä kaikissa keskusteluissa, jopa kahdenkeskisissä. Kun olet kirjoittanut keskustelussa komennon, niin odota hetkinen vaihtoehtoja - älä paina Enteriä.
|
||||
|
||||
⚙️ *Edistyneemmät komennot*
|
||||
*/transactions* 📊 Maksutapahtumien listaus
|
||||
*/link* 🔗 Linkitä lompakkosi [BlueWallet](https://bluewallet.io/) tai [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Vastaanota tai maksa Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Yhdistä nostr: `/nostr`
|
||||
*/faucet* 🚰 Luo hana: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Luo tippikulho: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Ryhmäkeskustelun toiminnot: `/group`
|
||||
*/shop* 🛍 Selaa kauppoja: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Luo DALLE-2 kuvia: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Syötä määrä %d ja %d sat väliltä."""
|
||||
enterAmountMessage = """💯 Syötä määrä."""
|
||||
enterUserMessage = """👤 Syötä käyttäjä."""
|
||||
enterTextMessage = """⌨️ Syötä teksti."""
|
||||
errorReasonMessage = """🚫 Virhe: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Lompakkoasi määritetään..."""
|
||||
startWalletCreatedMessage = """🧮 Lompakkosi on luotu."""
|
||||
startWalletReadyMessage = """✅ *Lompakkosi on valmis.*"""
|
||||
startWalletErrorMessage = """🚫 Lompakon määritys tai avaus epäonnistui. Yritä myöhemmin uudelleen."""
|
||||
startNoUsernameMessage = """☝️ Näyttäisi että sinulla ei ole vielä Telegram @username -käyttäjätunnusta. Se ei haittaa, voit kuitenkin käyttää tätä bottia. Saat kuitenkin botin käytöstä enemmän irti, kun asetat itsellesi käyttäjänimen Telegram-asetuksista. Sen tehtyäsi syötä komento /balance ja botti päivittää tietosi."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Saldosi on:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Saldosi hakeminen epäonnistui. Yritä myöhemmin uudelleen."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Lähetitkö vastauksen siihen viestiin, mitä halusit tipata? Vastaa mihintahansa viestiin tietokoneella klikkaamalla oikealla hiiren napilla viestiä, ja valitse Vastaa tai Reply, mobiililaitteella voit pyyhkäistä viestiä. Jos haluat lähettää suoraan varoja toiselle käyttäjälle, niin se onnistuu /send -komennolla."""
|
||||
tipInviteGroupMessage = """ℹ️ Muuten, voit kutsua tämän botin mihin tahansa ryhmään ja käyttää bottia siellä tippien lähettämiseen."""
|
||||
tipEnterAmountMessage = """Syötithän määrän?"""
|
||||
tipValidAmountMessage = """Syötithän määrän oikein?"""
|
||||
tipYourselfMessage = """📖 Et voi lähettää tippiä itsellesi."""
|
||||
tipSentMessage = """💸 %d sat läheteettiin %s:lle."""
|
||||
tipReceivedMessage = """🏅 %s lähetti sinulle %d sat tipin."""
|
||||
tipErrorMessage = """🚫 Tippi epäonnistui."""
|
||||
tipUndefinedErrorMsg = """yritä myöhemmin uudelleen."""
|
||||
tipHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/tip <amount> [<memo>]`
|
||||
*Esimerkki:* `/tip 1000 Kiitti meemistä!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Syötithän määrän oikein?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Käyttäjällä %s ei ole lompakkoa."""
|
||||
sendSentMessage = """💸 %d sat lähetettiin %s:lle."""
|
||||
sendPublicSentMessage = """💸 %d sat lähetettiin %s:ltä to %s:lle."""
|
||||
sendReceivedMessage = """🏅 %s lähetti sinulle %d sat."""
|
||||
sendErrorMessage = """🚫 Lähetys epäonnistu."""
|
||||
confirmSendMessage = """Haluatko lähettää vastaanottajalle %s?\n\n💸 Määrä: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Lähetys peruutettu."""
|
||||
errorTryLaterMessage = """🚫 Virhe. Yritä myöhemmin uudelleen."""
|
||||
sendSyntaxErrorMessage = """Annoithan määrän ja vastaanottajan? Lähetä /send komennolla joko Telegram-käyttäjänimelle (kuten %s) tai Lightning Address -osoitteeseen muotoa LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/send <amount> <user> [<memo>]`
|
||||
*Esimerkki:* `/send 1000 @LightningTipBot Rakastan bottia ❤️`
|
||||
*Esimerkki:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Vastaanotit %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Vastaanotit %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Syötithän määrän?"""
|
||||
invoiceValidAmountMessage = """Syötithän määrän oikein?"""
|
||||
invoiceHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/invoice <amount> [<memo>]`
|
||||
*Esimerkki:* `/invoice 1000 Kiitos!`"""
|
||||
invoicePaidText = """✅ Lasku maksettu."""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Maksu peruutettu."""
|
||||
invoicePaidMessage = """⚡️ Maksu lähetettiin."""
|
||||
invoicePublicPaidMessage = """⚡️ Maksun lähetti %s."""
|
||||
invalidInvoiceHelpMessage = """Syötithän Lightning-laskun oikein? Käytä /send -komentoa jos haluat lähettää Telegram-käyttäjälle tai Lightning Address -osoitteeseen."""
|
||||
invoiceNoAmountMessage = """🚫 Laskua ei voi maksaa ilman määrää."""
|
||||
insufficientFundsMessage = """🚫 Varat eivät riitä. Sinulla on %d sat mutta tarvitset vähintään %d sat."""
|
||||
feeReserveMessage = """⚠️ Koko saldosi lähettäminen ei todennäköisesti onnistu, koska maksun käsittelystä menee kuluja. Varaa vähintään 1% kuluihin."""
|
||||
invoicePaymentFailedMessage = """🚫 Maksu epäonnistui: %s"""
|
||||
invoiceUndefinedErrorMessage = """Laskun maksu epäonnistui."""
|
||||
confirmPayInvoiceMessage = """Vahvista maksun lähetys?\n\n💸 Määrä: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/pay <invoice>`
|
||||
*Esimerkki:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Kiitoksia lahjoituksesta."""
|
||||
donationErrorMessage = """🚫 Oi ei! Lahjoitus epäonnistui."""
|
||||
donationProgressMessage = """🧮 Valmistellaan lahjoitusta..."""
|
||||
donationFailedMessage = """🚫 Lahjoitus epäonnistui: %s"""
|
||||
donateEnterAmountMessage = """Syötithän määrän?"""
|
||||
donateValidAmountMessage = """Syötithän määrän oikein?"""
|
||||
donateHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/donate <amount>`
|
||||
*Esimerkki:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Lightning- tai LNURL -laskun tunnistus epäonnistui. Koeta keskittää QR-koodi, leikkaa kuvaa tai zoomaa tarkemmaksi."""
|
||||
photoQrRecognizedMessage = """✅ QR-koodi:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Voit ottaa maksuja vastaan tämän kiinteän LNURL:in avulla."""
|
||||
lnurlResolvingUrlMessage = """🧮 Selvitetään osoitetta..."""
|
||||
lnurlGettingUserMessage = """🧮 Valmistellaan maksua..."""
|
||||
lnurlPaymentFailed = """🚫 Maksu epäonnistui: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Virheellinen määrä."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Määrän tulee olla %d ja %d sat väliltä."""
|
||||
lnurlNoUsernameMessage = """🚫 LNURL:in avulla maksujen vastaanotto edellyttää että, sinulla on Telegram-käyttäjätunnus määriteltynä."""
|
||||
lnurlHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/lnurl [amount] <lnurl>`
|
||||
*Esimerkki:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Haluatko kirjautua %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Kirjautuminen onnistui."""
|
||||
loginButtonMessage = """✅ Kirjautuminen"""
|
||||
loginCancelledMessage = """🚫 Kirjautuminen peruutettiin."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Haluatko toteuttaa noston?\n\n💸 Määrä: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Valmistellaan nostoa..."""
|
||||
lnurlWithdrawFailed = """🚫 Nosto epäonnistui."""
|
||||
lnurlWithdrawCancelled = """🚫 Nosto peruutettiin."""
|
||||
lnurlWithdrawSuccess = """✅ Nosto käsitelty."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Linkitä lompakkosi*
|
||||
|
||||
⚠️ Älä koskaan paljasta seuraavia URL-osoitetta tai QR-koodia kenellekään. Niiden avulla pääsee käsiksi botissa oleviin varoihisi. jos tarvitse API-avaimia, käytä /api -komentoa.
|
||||
|
||||
- *BlueWallet:* Paina *New wallet*, *Import wallet*, *Scan or import a file*, ja lue QR-koodi.
|
||||
- *Zeus:* Kopioi alla oleva URL, valitse *Add a new node* ja Node interface kohdasta *LNDHub*, syötä URL ja paina *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Lompakon linkitys epäonnistui. Yritä myöhemmin uudelleen."""
|
||||
linkHiddenMessage = """🔍 Linkki on piilotettu. Käytä /link -komentoa nähdäksesi sen uudelleen."""
|
||||
|
||||
# API
|
||||
|
||||
apiConnectMessage = """🔗 *Sinun API avaimet*
|
||||
|
||||
⚠️ Älä koskaan paljasta API-avaimia kenellekään. Niiden avulla pääsee käsiksi botissa oleviin varoihisi. Käytä /link -komentoa yhdistääksesi ulkoiseen lompakkoon.
|
||||
|
||||
- *Admin key:* `%s`
|
||||
- *Invoice key:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Avaimet on piilotettu. Käytä /api -komentoa nähdäksesi ne uudelleen."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Luo hana."""
|
||||
inlineQueryFaucetDescription = """Muoto: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Luo hana %d sat kapasiteetilla."""
|
||||
inlineResultFaucetDescription = """👉 Paina tästä luodaksesi hanan tähän keskusteluun."""
|
||||
|
||||
inlineFaucetMessage = """Painamalla ✅ nostat %d sat %s:n tekemästä hanasta.
|
||||
|
||||
🚰 Jäljellä: %d/%d sat (nostettu %d/%d käyttäjälle)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Hana on tyhjä 🍺\n\n🏅 %d sat annettiin %d käyttäjälle."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Hallinnoi lompakkoasti viestillä %s:lle 👈 ."""
|
||||
inlineFaucetCancelledMessage = """🚫 Hana suljettu."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Hanan käyttäjäkohtainen kapasiteetti ei jakaudu tasan tai se on liian pieni (min 5 sat)."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Virheellinen määrä."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat lähetetty %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s lähetti sinulle %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Luo botin avulla ryhmäkeskusteluun hana tai käytä 👉 keskustelun komentoja (/advanced lisätoimintoja)."""
|
||||
inlineFaucetAlreadyTookMessage = """🚫 Olet jo nostanut varoja tästä hanasta."""
|
||||
inlineFaucetHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/faucet <capacity> <per_user>`
|
||||
*Esimerkki:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Lähetä maksu keskusteluun."""
|
||||
inlineQuerySendDescription = """Muoto: @%s send <amount> [<user>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Lähetä %d sat."""
|
||||
inlineResultSendDescription = """👉 Paina tästä lähettääksesi %d sat tähän keskusteluun."""
|
||||
|
||||
inlineSendMessage = """Paina ✅ vastaanottaaksesi maksun %s:ltä.\n\n💸 Määrä: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat lähetty %s:ltä %s:lle."""
|
||||
inlineSendCreateWalletMessage = """Avaa keskustelu %s :lle 👈 ja hallinnoi lompakkoasi."""
|
||||
sendYourselfMessage = """📖 Et voi maksaa itsellesi."""
|
||||
inlineSendFailedMessage = """🚫 Lähetys epäonnistui."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Määrän pitää olla nollaa suurempi."""
|
||||
inlineSendBalanceLowMessage = """🚫 Saldosi on liian pieni."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Pyydä maksua keskustelussa."""
|
||||
inlineQueryReceiveDescription = """Muoto: @%s receive <amount> [<user>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Vastaanota %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Paina tästä vastaanottaaksesi %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Paina 💸 maksaaksesi %s:lle.\n\n💸 Määrä: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat lähetetty %s:ltä %s:lle."""
|
||||
inlineReceiveCreateWalletMessage = """Avaa keskustelu %s :lle 👈 ja hallinnoi lompakkoasi."""
|
||||
inlineReceiveYourselfMessage = """📖 Et voi maksaa itsellesi."""
|
||||
inlineReceiveFailedMessage = """🚫 Vastaanotto epäonnistui."""
|
||||
inlineReceiveCancelledMessage = """🚫 Vastaanotto peruutettu."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Luo tippikulho."""
|
||||
inlineQueryTipjarDescription = """Muoto: @%s tipjar <capacity> <per_user>"""
|
||||
inlineResultTipjarTitle = """🍯 Luo %d sat tippikulho."""
|
||||
inlineResultTipjarDescription = """👉 Paina tästä luodaksesi tippikulhon tähän keskusteluun."""
|
||||
|
||||
inlineTipjarMessage = """Paina 💸 *maksaaksesi %d sat* %s:n luomaan tippikulhoon.
|
||||
|
||||
🙏 Tippikulhossa: *%d*/%d sat (%d käyttäjältä)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s:n tippikulho on täynnä⭐️\n\n🏅 %d sat saatin %d käyttäjältä."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Tippikulho poistettu."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Käyttäjäkohtainen määrä ei ole jaollinen kapasiteetilla."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Virheellinen määrä."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat lähetty %s:lle."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s lähetti sinulle %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Luo tippikulho ryhmään, jossa botti on jäsenenä tai käytä 👉 keskustelun komentoa (/advanced lisätoimintoja)."""
|
||||
inlineTipjarHelpText = """📖 Hups, sepä ei toiminutkaan. %s
|
||||
|
||||
*Muoto:* `/tipjar <capacity> <per_user>`
|
||||
*Esimerkki:* `/tipjar 210 21`"""
|
||||
|
||||
# GROUP TICKETS
|
||||
groupAddGroupHelpMessage = """📖 Hups, sepä ei toiminutkaan. Tämä toiminto on käytettävissä vain ryhmäkeskusteluissa ja sitä voi käyttää ainoastaan ryhmän omistaja.\nMuoto: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"""
|
||||
groupJoinGroupHelpMessage = """📖 Hups, sepä ei toiminutkaan. Yritä uudelleen.\nMuoto: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
groupClickToJoinMessage = """🎟 [Paina tästä](%s) 👈 liittyäksesi `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 Käyttäjä %s on saanut pääsyn tähän ryhmään."""
|
||||
groupPayInvoiceMessage = """🎟 Maksa yllä oleva lasku, jotta voit liittyä ryhmään %s."""
|
||||
groupBotIsNotAdminMessage = """🚫 Hups, sepä ei toiminutkaan. Sinun pitää lisätä minut ryhmän pääkäyttäjäksi ja antaa minulle oikeudet lisätä ja bannata käyttäjiä."""
|
||||
groupNameExists = """🚫 Tämän niminen ryhmä on jo olemassa. Valitse ryhmälle uusi nimi."""
|
||||
groupAddedMessagePrivate = """🎟 Ryhmään `%s` on lisätty pääsymaksut.\n\nAlias: `%s` Hinta: %d sat\n\nKun haluat pääsyn tähän ryhmään, aloita keskustelu %s:n kanssa ja anna komento `/join %s`."""
|
||||
groupAddedMessagePublic = """🎟 Pääsymaksut otettu käyttöön."""
|
||||
groupNotFoundMessage = """🚫 Tämän nimistä ryhmää ei löydy."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 Vastaanotit *%d sat* (mistä on vähennetty %d sat komissio) käyttäjän %s pääsymaksuna ryhmään `%s` ."""
|
||||
groupReceiveTicketInvoice = """🎟 Vastaanotit *%d sat* käyttäjän %s pääsymaksuna ryhmään `%s`."""
|
||||
commandPrivateMessage = """Käytä tätä komentoa %s:n kanssa kahdenkeskisessä keskustelussa."""
|
||||
groupHelpMessage = """👥 *Ryhmäkomennot*
|
||||
|
||||
🎟 *Julkiset pääsymaksut*
|
||||
|
||||
Pääkäyttäjille (ryhmäkeskustelussa): `/group ticket <ticket_price>`\nExample: `/group ticket 1000`
|
||||
|
||||
🎟 *Yksityiset pääsymaksut*
|
||||
|
||||
Veloita pääsymaksuja sinun _yksityiseen ryhmään_ ja pidät spammibotit poissa.
|
||||
|
||||
*Ohjeet ryhmän pääkäyttäjille:*
|
||||
|
||||
1) Kutsu ryhmääsi jäseneksi %s ja anna sille pääkäyttäjä (admin) oikeudet.
|
||||
2) Muuta ryhmäsi yksityiseksi (private).
|
||||
3) Ryhmässä, sinun (ryhmän omistaja) pitää antaa komento `/group add <mygroup> [<ticket_price>]`.
|
||||
|
||||
_Kulut: botti veloittaa 10%% +10 sat komission edullisista pääsymaksuista. Jos pääsymaksu on >= 1000 sat, niin komissio on 2%% + 100 sat._
|
||||
|
||||
*Ohjeet ryhmän jäsenille:*
|
||||
|
||||
Liittyäksesi ryhmään, aloita keskustelu %s:n kanssa ja kirjoita kahdenkeskiseen keskusteluun viesti `/join <mygroup>`.
|
||||
|
||||
📖 *Muoto:*
|
||||
Pääkäyttäjille (ryhmissä): `/group add <group_name> [<ticket_price>]`\nEsimerkki: `/group add TheBestBitcoinGroup 1000`
|
||||
Käyttäjille (yksityskeskusteluissa): `/join <group_name>`\nEsimerkki: `/join TheBestBitcoinGroup`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Luo OpenAI DALLE 2. -kuvia\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
|
||||
generateDallePayInvoiceMessage = """Maksa tämä lasku ja neljä kuvaa luotaan 👇"""
|
||||
generateDalleGeneratingMessage = """Kuvia luodaan. Odota hetkinen..."""
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Commandes avancées*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -184,7 +183,6 @@ sendHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Vous avez reçu %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Vous avez reçu %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Avez-vous choisi un montant ?"""
|
||||
invoiceValidAmountMessage = """Avez-vous choisi un montant correct ?"""
|
||||
invoiceHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
@@ -231,7 +229,7 @@ photoQrRecognizedMessage = """✅ QR code:
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Vous pouvez utiliser cet LNURL pour recevoir des paiements."""
|
||||
lnurlReceiveInfoText = """👇 Vous ne pouvez pas utiliser cet LNURL pour recevoir des paiements."""
|
||||
lnurlResolvingUrlMessage = """🧮 Recherche de l'adresse..."""
|
||||
lnurlGettingUserMessage = """🧮 Préparation du paiement..."""
|
||||
lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
|
||||
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -184,7 +183,6 @@ sendHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Kamu menerima %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Kamu menerima %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
|
||||
invoiceValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
|
||||
invoiceHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Comandi avanzati*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -184,7 +183,6 @@ sendHelpText = """📖 Ops, non ha funzionato. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Hai ricevuto %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
|
||||
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
|
||||
invoiceHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Geavanceerde opdrachten*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -184,7 +183,6 @@ sendHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Je hebt %d sat ontvangen ."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Je hebt %d sat (%.2f %s) ontvangen."""
|
||||
invoiceEnterAmountMessage = """Heb je een bedrag ingevoerd?"""
|
||||
invoiceValidAmountMessage = """Heeft u een geldig bedrag ingevoerd?"""
|
||||
invoiceHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
@@ -1,406 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """pomoc"""
|
||||
basicsCommandStr = """podstawy"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """wyślij"""
|
||||
invoiceCommandStr = """faktura"""
|
||||
payCommandStr = """pay"""
|
||||
donateCommandStr = """donate"""
|
||||
advancedCommandStr = """advanced"""
|
||||
transactionsCommandStr = """transactions"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """list"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """receive"""
|
||||
hideCommandStr = """hide"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """show"""
|
||||
optionsCommandStr = """options"""
|
||||
settingsCommandStr = """settings"""
|
||||
saveCommandStr = """save"""
|
||||
deleteCommandStr = """delete"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Nie możesz tego zrobić."""
|
||||
cantClickMessage = """Nie możesz kliknąć tego przycisku."""
|
||||
balanceTooLowMessage = """Twoje saldo jest za niskie."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Wyślij"""
|
||||
payButtonMessage = """✅ Zapłać"""
|
||||
payReceiveButtonMessage = """💸 Zapłać"""
|
||||
receiveButtonMessage = """✅ Otrzymaj"""
|
||||
withdrawButtonMessage = """✅ Wypłać"""
|
||||
cancelButtonMessage = """🚫 Anuluj"""
|
||||
collectButtonMessage = """✅ Odbierz"""
|
||||
nextButtonMessage = """Dalej"""
|
||||
backButtonMessage = """Cofnij"""
|
||||
acceptButtonMessage = """Potwierdź"""
|
||||
denyButtonMessage = """Odmów"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Ujawnij"""
|
||||
showButtonMessage = """Pokaż"""
|
||||
hideButtonMessage = """Ukryj"""
|
||||
joinButtonMessage = """Dołącz"""
|
||||
optionsButtonMessage = """Opcje"""
|
||||
settingsButtonMessage = """Ustawienia"""
|
||||
saveButtonMessage = """Zapisz"""
|
||||
deleteButtonMessage = """Skasuj"""
|
||||
infoButtonMessage = """Informacje"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Portfel*
|
||||
_Ten bot jest portfelem Bitcoin Lightning, który potrafi wysyłać napiwki na Telegramie. Aby zacząć dodaj tego bota do chatu grupowego. Podstawową jednostką dla napiwków są Satoshi (sat). 100 000 000 sat = 1 Bitcoin. Napisz 📚 /basics aby uzyskać więcej informacji._
|
||||
|
||||
❤️ *Wsparcie*
|
||||
_Ten bot nie pobiera opłat, ale jego funkcjonowanie kosztuje. Jeśli podoba Ci się, rozważ proszę wsparcie tego projektu darowizną. Aby to zrobić użyj_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Komendy*
|
||||
*/tip* 🏅 Odpowiedz na wiadomość aby dać napiwek: `/tip <kwota> [<notatka>]`
|
||||
*/balance* 👑 Sprawdź swoje saldo: `/balance`
|
||||
*/send* 💸 Wyślij środki do użytkownika: `/send <kwota> @użytkownik lub użytkownik@ln.tips [<notatka>]`
|
||||
*/invoice* ⚡️ Otrzymaj przy pomocy Lightning: `/invoice <kwota> [<notatka>]`
|
||||
*/pay* ⚡️ Zapłać przy pomocy Lightning: `/pay <faktura>`
|
||||
*/donate* ❤️ Wesprzyj projekt darowizną: `/donate 1000`
|
||||
*/advanced* 🤖 Funkcje zaawansowane.
|
||||
*/help* 📖 Przeczytaj tę stronę o pomocy."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Informacje*"""
|
||||
infoYourLightningAddress = """Twój adres Lightning to `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin jest walutą internetu. Nie wymaga pozwolenia, jest zdecentralizowany i nie ma władców ani kontrolujących go instytucji. Bitcoin jest twardym pieniądzem, który jest szybszy, bezpieczniejszy i inkluzywny niż dotychczasowy system finansowy._
|
||||
|
||||
🧮 *Ekonomia*
|
||||
_Najmniejszą jednostką Bitcoina są Satoshi (sat) a 100 00 00 sat = 1 Bitcoin. Zawsze będzie tylko 21 milionów Bitcoinów. Ich cena w walucie fiducjarnego może zmieniać się codziennie. Jednak jeśli żyjesz na standardziej Bitcoina 1 sat zawsze będzie równy 1 sat._
|
||||
|
||||
⚡️ *Sieć Lightning*
|
||||
_Sieć Lightning jest protokołem, który umożliwia szybkie i tanie płatności w Bitcoinie, nie potrzebujące do tego prawie żadnej energii. Dzięki temu umożliwia dotarcie do miliardów ludzi na całym świecie._
|
||||
|
||||
📲 *Portfele Lightning*
|
||||
_Twoje środki na tym bocie mogą być wysłane na inne portfele Lightning i vice versa. Rekomendowane portfele dla Twojego telefonu to_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (niepowierniczy), lub_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(łatwy)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Ten bot to wolne oprogramowanie [open source](https://github.com/LightningTipBot/LightningTipBot)_. Możesz go uruchomić na własnym komputerze i używać we własnej społeczności._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Dodaj tego bota do swojego chatu grupowego na Telegramie aby dawać napiwki za wiadomości. Jeśli uczynisz bota adminem grupy będzie czyścił komendy aby chat był uporządkowany._
|
||||
|
||||
🏛 *Warunki*
|
||||
_Nie jesteśmy powiernikiem Twoich środków. Będziemy działać w Twoim najlepszym interesie ale jesteśmy świadomi tego, że sytuacja bez KYC jest trudna dopóki czegoś nie wymyślimy.
|
||||
Jakakolwiek kwota, którą załadujesz na portfel będzie traktowana jako darowizna. Nie dawaj nam wszystkich swoich pieniędzy. Wiedz, że ten bota jest w fazie rozwoju beta. Używaj go na własne ryzko._
|
||||
|
||||
❤️ *Wesprzyj darowizną*
|
||||
_Ten bot nie pobiera opłat, ale jego funkcjonowanie kosztuje. Jeśli podoba Ci się, rozważ proszę wsparcie tego projektu darowizną. Aby to zrobić użyj `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Podaj proszę nazwę swojego użytkownika w Telegramie."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Komendy inline*
|
||||
*send* 💸 Wysyła sats na chat: `%s send <kwota> [<użytkownik>] [<notatka>]`
|
||||
*receive* 🏅 Prosi o płatność: `... receive <kwota> [<użytkownik>] [<notatka>]`
|
||||
*faucet* 🚰 Tworzy kranik (_faucet_): `... faucet <pojemność> <na_użytkownika> [<notatka>]`
|
||||
*tipjar* 🍯 Tworzy słoik na napiwki (_tipjar_): `... tipjar <pojemność> <na_użytkownika> [<notatka>]`
|
||||
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Komendy zaawansowane*
|
||||
*/transactions* 📊 Lista transakcji
|
||||
*/link* 🔗 Połączenie Twojego portfela z [BlueWallet](https://bluewallet.io/) lub [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Przyjmij płatność lub zapłać za pomocą Lnurl: `/lnurl` lub `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/faucet* 🚰 Stwórz kranik (_faucet_): `/faucet <pojemność> <na_użytkownika>`
|
||||
*/tipjar* 🍯 Stwórz słoik na napiwki (_tipjar_): `/tipjar <pojemność> <na_użytkownika>`
|
||||
*/group* 🎟 Stwórz bilety na wejście do grupy: `/group add <mojagrupa> [<cena_biletu>]`
|
||||
*/shop* 🛍 Przeglądaj sklepy: `/shop` lub `/shop <użytkownik/id_sklepu>`
|
||||
*/generate* 🎆 Generuj obrazy przy użyciu DALLE-2: `/generate <podpowiedź>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Wprowadź kwotę między %d a %d sat."""
|
||||
enterAmountMessage = """💯 Wprowadź kwotę."""
|
||||
enterUserMessage = """👤 Podaj użytkownika."""
|
||||
enterTextMessage = """⌨️ Wprowadź tekst."""
|
||||
errorReasonMessage = """🚫 Błąd: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Tworzę Twój portfel..."""
|
||||
startWalletCreatedMessage = """🧮 Portfel utworzony."""
|
||||
startWalletReadyMessage = """✅ *Twój portfel jest gotowy.*"""
|
||||
startWalletErrorMessage = """🚫 Błąd przy inicjowaniu Twojego portfela. Spróbuj ponownie później."""
|
||||
startNoUsernameMessage = """☝️ Wygląda na to, że nie masz jeszcze nazwy @użytkownika w Telegramie. Nic nie szkodzi, nie potrzebujesz jej by używać tego bota. Jednak aby lepiej go wykorzystać, ustaw nazwę w ustawieniach aplikacji Telegram. Następnie napisz /balance aby bot mógł zaktualizować swoje dane o Tobie."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Twoje saldo:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Pobranie Twojego salda nie powiodło się. Spróbuj ponownie później."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Czy odpowiadasz na wiadomość aby dać napiwek? Aby odpowiedzieć na jakąkolwiek wiadomość na komputerze, naciśnij prawy przycisk myszy i wybierz Odpowiedz, a na telefonie przesuń palcem. Jeśli chcesz wysłać bezpośrednio do innego użytkownika użyj komendy /send."""
|
||||
tipInviteGroupMessage = """ℹ️ Przy okazji, możesz zaprosić tego bota do dowolnej grupy aby zacząć dawać napiwki tam."""
|
||||
tipEnterAmountMessage = """Czy wprowadzono kwotę?"""
|
||||
tipValidAmountMessage = """Czy wprowadzono poprawną kwotę?"""
|
||||
tipYourselfMessage = """📖 Nie możesz dać sobie napiwku."""
|
||||
tipSentMessage = """💸 %d sat wysłano do %s."""
|
||||
tipReceivedMessage = """🏅 %s daje Ci napiwek w wysokości %d sat."""
|
||||
tipErrorMessage = """🚫 Napiwek się nie powiódł."""
|
||||
tipUndefinedErrorMsg = """spróbuj proszę później."""
|
||||
tipHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/tip <kwota> [<notatka>]`
|
||||
*Przykład:* `/tip 1000 pojechany mem!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Czy podano poprawną kwotę?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Użytkownik %s jeszcze nie utworzył portfela."""
|
||||
sendSentMessage = """💸 %d sat wysłano do %s."""
|
||||
sendPublicSentMessage = """💸 %d sat wysłano od %s do %s."""
|
||||
sendReceivedMessage = """🏅 %s przysyła Ci %d sat."""
|
||||
sendErrorMessage = """🚫 Wysłanie nie powiodło się."""
|
||||
confirmSendMessage = """Czy chcesz zapłacić %s?\n\n💸 Kwota: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Wysłanie anulowane."""
|
||||
errorTryLaterMessage = """🚫 Błąd. Spróbuj ponownie później."""
|
||||
sendSyntaxErrorMessage = """Czy wpropwadzono kwotę i odbiorcę? Możesz użyć komendy /send albo żeby wysłać do użytkownika takiego jak %s lub pod adres Lightning taki jak LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/send <kwota> <użytkownik> [<notatka>]`
|
||||
*Przykład:* `/send 1000 @LightningTipBot Po prostu lubię tego bota ❤️`
|
||||
*Przykład:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Otrzymujesz %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Otrzymujesz %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Czy wprowadzono kwotę?"""
|
||||
invoiceValidAmountMessage = """Czy wprowadzono poprawną kwotę?"""
|
||||
invoiceHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/invoice <kwota> [<notatka>]`
|
||||
*Przykład:* `/invoice 1000 Dziękuję!`"""
|
||||
invoicePaidText = """✅ Faktura załacona."""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Płatność anulowana."""
|
||||
invoicePaidMessage = """⚡️ Płatność wysłana."""
|
||||
invoicePublicPaidMessage = """⚡️ Płatność wysłana przez %s."""
|
||||
invalidInvoiceHelpMessage = """Czy podajesz poprawną fakturę Lightning? Spróbuj /send jeśli chcesz wysłać do użytkownika na Telegramie lub pod adres Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Nie można opłacić faktury bez kwoty."""
|
||||
insufficientFundsMessage = """🚫 Niewystarczające środki. Masz %d sat a potrzebujesz conajmniej %d sat."""
|
||||
feeReserveMessage = """⚠️ Wysyłanie swojego całkowitego salda może się nie powieść z powodu opłat sieciowych. Zarezerwuj conajmniej 1% na opłaty."""
|
||||
invoicePaymentFailedMessage = """🚫 Płatność nie powiodła się: %s"""
|
||||
invoiceUndefinedErrorMessage = """Nie można było zapłacić faktury."""
|
||||
confirmPayInvoiceMessage = """Czy chcesz wysłać tę płatność?\n\n💸 Kwota: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/pay <faktura>`
|
||||
*Przykład:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Dziękuję za twoją darowiznę."""
|
||||
donationErrorMessage = """🚫 O nie! Darowizna nie powiodła się."""
|
||||
donationProgressMessage = """🧮 Przygotowuję Twoją darowiznę..."""
|
||||
donationFailedMessage = """🚫 Darowizna nie powiodła się: %s"""
|
||||
donateEnterAmountMessage = """Czy podano kwotę?"""
|
||||
donateValidAmountMessage = """Czy podano poprawną kwotę?"""
|
||||
donateHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/donate <kwota>`
|
||||
*Przykład:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Nie udało się rozpoznać faktury Lightning ani LNURL. Wypośrodkuj kod QR, przytnij zdjęcie lub powiększ."""
|
||||
photoQrRecognizedMessage = """✅ Kod QR:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Możesz użyć teego statycznego kodu LNRUL aby otrzymywać płatności."""
|
||||
lnurlResolvingUrlMessage = """🧮 Rozwiązuje adres..."""
|
||||
lnurlGettingUserMessage = """🧮 Przygotowuję płatność..."""
|
||||
lnurlPaymentFailed = """🚫 Płatność się nie powiodła: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Kwota musi być między %d a %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Musisz ustawić nazwę użytkownika na Telegramie aby otrzymywać płatności poprzez LNURL."""
|
||||
lnurlHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/lnurl [kwota] <lnurl>`
|
||||
*Przykład:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Czy chcesz się zalogować do %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Logowanie udało się."""
|
||||
loginButtonMessage = """✅ Zaloguj się"""
|
||||
loginCancelledMessage = """🚫 Logowanie anulowane."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Czy chcesz dokonąć tej wypłaty?\n\n💸 Kwota: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Przygotowywanie wypłaty..."""
|
||||
lnurlWithdrawFailed = """🚫 Wypłata nie powiodła się."""
|
||||
lnurlWithdrawCancelled = """🚫 Wypłata anulowana."""
|
||||
lnurlWithdrawSuccess = """✅ Zażądano wypłaty."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Połącz swój portfel*
|
||||
|
||||
⚠️ Nigdy nie ujawniaj adresu URL lub kodu QR nikomu, gdyż będą w stanie uzyskać dostęp do Twoich środków. Użyj /api aby uzyskać dostęp do swoich kluczy API.
|
||||
|
||||
- *BlueWallet:* Naciśnij *Dodaj porfel*, *Import portfela*, *Skanuj lub importuj plik*, i przeskanuj kod QR.
|
||||
- *Zeus:* Skopiuj poniższy adres URL, naciśnij *Dodaj nowy węzeł*, wybierz *LNDHub* jako interfejs węzła, wprowadź adres URL, *Zapisz konfigurację węzła*."""
|
||||
couldNotLinkMessage = """🚫 Nie udało się połączyć Twojego portfela. Spróbuj ponownie później."""
|
||||
linkHiddenMessage = """🔍 Połączenie ukryto. Napisz /link aby zobaczyć je ponownie."""
|
||||
|
||||
# API
|
||||
|
||||
apiConnectMessage = """🔗 *Twoje klucze API*
|
||||
|
||||
⚠️ Nigdy nie ujawniaj tych kluczy nikomu, gdyż będą w stanie uzyskać dostęp do Twoich środków. Użyj /link aby połączyć swój portfel.
|
||||
|
||||
- *Klucz Admin:* `%s`
|
||||
- *Klucz Invoice:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Klucze ukryte. Napisz /api aby zobaczyć je ponownie."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Utwórz kranik (_faucet_)."""
|
||||
inlineQueryFaucetDescription = """Użycie: @%s faucet <pojemność> <na_użytkownika>"""
|
||||
inlineResultFaucetTitle = """🚰 Tworzenie kranika o pojemności %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Kliknij tu aby utworzyć kranik w tym chacie."""
|
||||
|
||||
inlineFaucetMessage = """Naciśnij ✅ aby zebrać %d sat z kranika %s.
|
||||
|
||||
🚰 Pozostało: %d/%d sat (rozdanych %d użytkownikom z %d)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Kranik pusty 🍺\n\n🏅 %d sat rozdano do %d użytkowników."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
|
||||
inlineFaucetCancelledMessage = """🚫 Kranik anulowany."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Wartość na_użytkownika nie jest dzielnikiem pojemności lub jest za mała (min 5 sat)."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat wysłano do %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s wysyła Ci %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Utwórz w grupie z botem kranik (_facuet_) lub użyj 👉 komendy inline (zobacz /advanced aby uzyskać więcej informacji)."""
|
||||
inlineFaucetAlreadyTookMessage = """🚫 Już brałeś z tego kranika."""
|
||||
inlineFaucetHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/faucet <pojemność> <na_użytkownika>`
|
||||
*Przykład:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Wyślij płatność do tego chatu."""
|
||||
inlineQuerySendDescription = """Użycie: @%s send <kwota> [<użytkownik>] [<notatka>]"""
|
||||
inlineResultSendTitle = """💸 Wysłano %d sat."""
|
||||
inlineResultSendDescription = """👉 Kliknij aby wysłać %d sat do tego chatu."""
|
||||
|
||||
inlineSendMessage = """Naciśnij ✅ aby otrzymać płatność od %s.\n\n💸 Kwota: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat wysłano od %s do %s."""
|
||||
inlineSendCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
|
||||
sendYourselfMessage = """📖 Nie możesz zapłacić sobie."""
|
||||
inlineSendFailedMessage = """🚫 Wysłanie nie powiodło się."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Kwota musi być większa niż 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Twoje saldo jest za niskie."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Poproś o płatność na chacie."""
|
||||
inlineQueryReceiveDescription = """Użycie: @%s receive <kwota> [<użytkownik>] [<notatka>]"""
|
||||
inlineResultReceiveTitle = """🏅 Otrzymaj %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Kliknij aby poprosić o płatność %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Naciśnij 💸 aby zapłacić %s.\n\n💸 Kwota: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat wysłano od %s do %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
|
||||
inlineReceiveYourselfMessage = """📖 Nie możesz zapłacić sobie."""
|
||||
inlineReceiveFailedMessage = """🚫 Przyjmowanie środków nie powiodło się."""
|
||||
inlineReceiveCancelledMessage = """🚫 Przyjmowanie środków anulowane."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Utwórz słoik na napiwki (_tipjar_)."""
|
||||
inlineQueryTipjarDescription = """Użycie: @%s tipjar <pojemność> <na_użytkownika>"""
|
||||
inlineResultTipjarTitle = """🍯 Tworzenie słoika na napiwki (_tipjar_) o pojemności %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Kliknij tu aby utworzyć w tym chacie słoik na napiwki (_tipjar_)."""
|
||||
|
||||
inlineTipjarMessage = """Naciśnij 💸 aby *wpłacić %d sat* do tego słoika na napiwki (_tipjar_) przez %s.
|
||||
|
||||
🙏 Przekazano: *%d*/%d sat (przez %d użytkowników)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 Słoik na napiwki %s jest pełen ⭐️\n\n🏅 %d sat przekazanych przez %d użytkowników."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Słoik na napiwki anulowany."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Kwota na_użytkownika nie jest dzielnikiem pojemności."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat wysłano do %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s wysyła Ci %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Stwórz w grupie z tym botem słoik na napiwki (_tipjar_) lub użyj 👉 komendy inline (zobacz /advanced aby uzyskać więcej informacji)."""
|
||||
inlineTipjarHelpText = """📖 Ojej, to nie zadziałało. %s
|
||||
|
||||
*Użycie:* `/tipjar <capacity> <na_użytkownika>`
|
||||
*Przykład:* `/tipjar 210 21`"""
|
||||
|
||||
# GROUP TICKETS
|
||||
groupAddGroupHelpMessage = """📖 Ojej, to nie zadziałało. Ta komenda działa tylko w chacie grupowym. Tylko właściciele grupy mogą użyć tej komendy.\nUżycie: `/group add <nazwa_grupy> [<kwota>]`\nPrzykład: `/group add NajlepszaGrupaBitcoinowa 1000`"""
|
||||
groupJoinGroupHelpMessage = """📖 Ojej, to nie zadziałało. Spróbuj ponownie później.\nUżycie: `/join <nazwa_grupy>`\nPrzykład: `/join NajlepszaGrupaBitcoinowa`"""
|
||||
groupClickToJoinMessage = """🎟 [Kliknij tu](%s) 👈 aby dołączyć do `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 Użytkownik %s otrzymuje bilet do tej grupy."""
|
||||
groupPayInvoiceMessage = """🎟 Aby dołączyć do grupy %s, opłać powyższą fakturę."""
|
||||
groupBotIsNotAdminMessage = """🚫 Ojej, to nie zadziałało. Musisz uczynić mnie administratorem i nadać prawo do zapraszania użytkowników."""
|
||||
groupNameExists = """🚫 Grupa o tej nazwie już istnieje. Wybierz inną nazwę."""
|
||||
groupAddedMessage = """🎟 Bilety dla grupy `%s` dodane.\nAlias: `%s` Cena: %d sat\n\nAby poprosić o bilet na tę grupę, rozpocznij prywatny czat z %s i napisz `/join %s`."""
|
||||
groupNotFoundMessage = """🚫 Nie znaleziono grupy o tej nazwie."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 Otrzymujesz *%d sat* (wyłączając. %d sat prowizji) za bilet na grupę `%s` zapłacony przez %s."""
|
||||
groupReceiveTicketInvoice = """🎟 Otrzymujesz *%d sat* za bilet na grupę `%s` zapłacony przez %s."""
|
||||
commandPrivateMessage = """Użyj proszę tej komendy na czacie prywatnym z %s."""
|
||||
groupHelpMessage = """🎟 Bilety na prywatne grupy 🎟
|
||||
|
||||
Sprzedawaj bilety na swoją _prywatną grupę_ i pozbądź się spamujących botów.
|
||||
|
||||
*Instrukcje dla administratorów grup:*
|
||||
|
||||
1) Zaproś %s do swojej grupy i nadaj uprawnienia administratora.
|
||||
2) Uczyń swoją grupę prywatną.
|
||||
3) W grupie, napisz (będąc właścicielem grupy) napisz `/group add <mojagrupa> [<cena_biletu>]`.
|
||||
|
||||
_Opłaty: Bot bierze prowizję w wysokości 10%% + 10 sat za tanie bilety. Jeśli cena bilety >= 1000 sat, prowizja wynosi 2%% + 100 sat._
|
||||
|
||||
*Instrukcje dla członków grupy:*
|
||||
|
||||
Aby dołączyć do grupy, napisz do %s i napisz w prywatnej wiadomości `/join <mojagrupa>`.
|
||||
|
||||
📖 *Użycie:*
|
||||
*Dla adminów (w czacie grupowym):* `/group add <nazwa_grupy> [<cena_biletu>]`\nPrzykład: `/group add NajlepszaGrupaBitcoinowa 1000`
|
||||
*Dla użytkowników (w czacie prywatnym):* `/join <nazwa_grupy>`\nPrzykład: `/join NajlepszaGrupaBitcoinowa`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Generuj obrazy przy użyciu OpenAI DALLE 2.\nUżycie: `/generate <podpowiedź>`\nCena: 1000 sat"""
|
||||
generateDallePayInvoiceMessage = """Opłać tę fakturę by wygenerować 4 obrazy 👇"""
|
||||
generateDalleGeneratingMessage = """Twoje obrazy są generowane. Proszę czekaj..."""
|
||||
@@ -119,13 +119,11 @@ advancedMessage = """%s
|
||||
⚙️ *Comandos avançados*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
@@ -184,7 +182,6 @@ sendHelpText = """📖 Opa, isso não funcionou. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Recebeu %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Recebeu %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Você inseriu uma quantia?"""
|
||||
invoiceValidAmountMessage = """Você inseriu uma quantia válida?"""
|
||||
invoiceHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
@@ -123,8 +123,7 @@ advancedMessage = """%s
|
||||
⚙️ *Продвинутые команды*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -187,7 +186,6 @@ sendHelpText = """📖 Упс, это не сработало. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ Вы получили %d sat (%.2f %s)."""
|
||||
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
invoiceHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
@@ -119,8 +119,7 @@ advancedMessage = """%s
|
||||
⚙️ *Gelişmiş komutlar*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl> [memo]`
|
||||
*/nostr* 💜 Connect to Nostr: `/nostr`
|
||||
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
@@ -183,7 +182,6 @@ sendHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ %d sat sana geldi."""
|
||||
invoiceReceivedCurrencyMessage = """⚡️ %d sat (%.2f %s) sana geldi."""
|
||||
invoiceEnterAmountMessage = """Miktar girdin mi?"""
|
||||
invoiceValidAmountMessage = """Geçerli bir miktar girdin mi?"""
|
||||
invoiceHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
Reference in New Issue
Block a user