Compare commits
394
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23ebc4e65e | ||
|
|
01f4cff348 | ||
|
|
a67ec62054 | ||
|
|
895fd06a14 | ||
|
|
ed5ceeb095 | ||
|
|
bc8c8f952a | ||
|
|
64055db1a5 | ||
|
|
ec679d5e6b | ||
|
|
9e8958ece2 | ||
|
|
7a2aba59ff | ||
|
|
62d7dd965e | ||
|
|
32a5863b25 | ||
|
|
45931c087a | ||
|
|
c561ae24d3 | ||
|
|
d5ff4867c0 | ||
|
|
1f5a6a5a31 | ||
|
|
e8f24d99ee | ||
|
|
b9bf071de9 | ||
|
|
ced9446287 | ||
|
|
94ed7d4692 | ||
|
|
d3c2fe7117 | ||
|
|
5c950ef1be | ||
|
|
51ac159072 | ||
|
|
857649150d | ||
|
|
842a037029 | ||
|
|
5aa76f86da | ||
|
|
e170394eb8 | ||
|
|
65842b056d | ||
|
|
979d3c58a2 | ||
|
|
b4cb695e33 | ||
|
|
89552a73b7 | ||
|
|
d5f18a0d3a | ||
|
|
e24490b05c | ||
|
|
f288bb05f6 | ||
|
|
3055f6d317 | ||
|
|
f19a6dd6cc | ||
|
|
cd55ee075b | ||
|
|
9d3f856d02 | ||
|
|
f2b59140fa | ||
|
|
c21d42d1e8 | ||
|
|
2dd2dde231 | ||
|
|
5e3432fe32 | ||
|
|
c6df59e51b | ||
|
|
b4081df2fa | ||
|
|
9b9ceb8793 | ||
|
|
3069126971 | ||
|
|
b56f5e73b0 | ||
|
|
42efc918c1 | ||
|
|
8c75f2f947 | ||
|
|
7d9c0d0c8a | ||
|
|
b77f92c9b2 | ||
|
|
ec2de611e4 | ||
|
|
1b69313fc5 | ||
|
|
55fc5eaa54 | ||
|
|
6bc6ef215a | ||
|
|
52ac3bfc13 | ||
|
|
fea7281e29 | ||
|
|
d992d5858f | ||
|
|
2569f0d12e | ||
|
|
6bdd24e4a3 | ||
|
|
3c862d59ff | ||
|
|
2c4d499cd9 | ||
|
|
2e4a793c20 | ||
|
|
890448ce81 | ||
|
|
08d6a0e369 | ||
|
|
069029fbb3 | ||
|
|
92f9ba1550 | ||
|
|
98bc70fc7c | ||
|
|
1ee38a2989 | ||
|
|
3353bedc7a | ||
|
|
30c1e3231d | ||
|
|
a3ed8ab931 | ||
|
|
3772f056a8 | ||
|
|
65d933a6d5 | ||
|
|
4038a03184 | ||
|
|
2c8a653c3a | ||
|
|
03509adcd1 | ||
|
|
74655219f3 | ||
|
|
74c057ce8e | ||
|
|
0aeec7e488 | ||
|
|
921395d283 | ||
|
|
9b2c23cab5 | ||
|
|
3c45a80627 | ||
|
|
62c2cbab5f | ||
|
|
ab82b49ff5 | ||
|
|
025261d595 | ||
|
|
ed6ea4d33c | ||
|
|
69559f8aff | ||
|
|
00406553e4 | ||
|
|
c237e55a29 | ||
|
|
24b2c2413c | ||
|
|
cb19e7375a | ||
|
|
55ba146592 | ||
|
|
52230d486e | ||
|
|
c8e45de27d | ||
|
|
6a01936c2e | ||
|
|
48374ad2a1 | ||
|
|
5b5f0ef6a2 | ||
|
|
b618b1aa41 | ||
|
|
c5f106187f | ||
|
|
f35473b010 | ||
|
|
359ae13057 | ||
|
|
8d0bf2cce7 | ||
|
|
f5c3d9fb55 | ||
|
|
56c391b24e | ||
|
|
cbdc8638bd | ||
|
|
046baab3e1 | ||
|
|
f0f3a7c5d0 | ||
|
|
43eb4966bc | ||
|
|
0d112e19de | ||
|
|
649be03c29 | ||
|
|
5e4c045312 | ||
|
|
44f397e2de | ||
|
|
9451032552 | ||
|
|
8180d3cfae | ||
|
|
f11ac3d807 | ||
|
|
cb02fd557f | ||
|
|
ac3ac51d7b | ||
|
|
ac9cc644eb | ||
|
|
545898dbbe | ||
|
|
d98aa26db9 | ||
|
|
13c0f3b70a | ||
|
|
3a4f99314d | ||
|
|
a0f7cf09e6 | ||
|
|
0ff0d889ff | ||
|
|
7009d3dedc | ||
|
|
a87eac37b8 | ||
|
|
250c036c47 | ||
|
|
df303ae186 | ||
|
|
d0d844fd4f | ||
|
|
dbe94b9494 | ||
|
|
d9f373cebb | ||
|
|
d066fa9e27 | ||
|
|
127f95b8de | ||
|
|
98401546fa | ||
|
|
fbc47c0fb9 | ||
|
|
0c29fec19f | ||
|
|
4bcbd2fefe | ||
|
|
a669ea86ac | ||
|
|
b396219792 | ||
|
|
4871b42f22 | ||
|
|
6ff264ab18 | ||
|
|
fff933e413 | ||
|
|
36d94ecff8 | ||
|
|
aaba02020b | ||
|
|
02bbc8e5a3 | ||
|
|
61fb20e132 | ||
|
|
7707fbf4a5 | ||
|
|
dfcf576dce | ||
|
|
796abe7f96 | ||
|
|
52e1fc043a | ||
|
|
3f64ceb6c1 | ||
|
|
30e0ba9cdf | ||
|
|
f474988606 | ||
|
|
865592b0a6 | ||
|
|
41a4946071 | ||
|
|
d7dc6f71aa | ||
|
|
d9f2f87739 | ||
|
|
29f03807f2 | ||
|
|
042ccaf8ef | ||
|
|
4ecc65fb27 | ||
|
|
f73e027e9c | ||
|
|
b4e8721e3e | ||
|
|
dd87d4f6f8 | ||
|
|
8033d05f7e | ||
|
|
c27de372a5 | ||
|
|
bc849c5b03 | ||
|
|
6f2a95609e | ||
|
|
d6e9f49cd1 | ||
|
|
d2a63c07a3 | ||
|
|
8729011aaf | ||
|
|
5199e4c8c6 | ||
|
|
e5928defd0 | ||
|
|
1167392140 | ||
|
|
cf68245012 | ||
|
|
6c06a4972e | ||
|
|
e7fa555506 | ||
|
|
666eecf207 | ||
|
|
0eaf96749f | ||
|
|
672402616e | ||
|
|
cfde78e639 | ||
|
|
fce4fb9ecc | ||
|
|
1946a0e873 | ||
|
|
fd531e6719 | ||
|
|
94ff302d15 | ||
|
|
631c314b31 | ||
|
|
307967b61a | ||
|
|
a53f8e307a | ||
|
|
6f14fab93b | ||
|
|
99a866854b | ||
|
|
21f5abbb25 | ||
|
|
158990f46d | ||
|
|
c00196e9d6 | ||
|
|
410f56aaf5 | ||
|
|
0631fd53eb | ||
|
|
afcd530d06 | ||
|
|
5aaf9452b5 | ||
|
|
b07053172b | ||
|
|
6ebb5688fd | ||
|
|
2e3a1fe087 | ||
|
|
997faa2c45 | ||
|
|
048141908e | ||
|
|
900ce09aa6 | ||
|
|
bd41dd078b | ||
|
|
bf643f103d | ||
|
|
23db317c0d | ||
|
|
7085b4dbf6 | ||
|
|
9895498237 | ||
|
|
4a93019428 | ||
|
|
71d8aa202c | ||
|
|
a9f6539eaf | ||
|
|
1179800a4b | ||
|
|
a5d8c5d7e5 | ||
|
|
0dcf4bd845 | ||
|
|
afcbca28f2 | ||
|
|
205e75d2d6 | ||
|
|
6e7886e029 | ||
|
|
00b07998e6 | ||
|
|
373b4a9752 | ||
|
|
fa46f06f2e | ||
|
|
24e321e5ed | ||
|
|
725af545ab | ||
|
|
2b09fc95dd | ||
|
|
54beceba32 | ||
|
|
70ecf335f2 | ||
|
|
d786dc58e0 | ||
|
|
c72111dfb7 | ||
|
|
902928f794 | ||
|
|
96292604c7 | ||
|
|
9522418272 | ||
|
|
a112c1b25d | ||
|
|
72e13e841d | ||
|
|
83eb185634 | ||
|
|
dedc959f94 | ||
|
|
33776f2616 | ||
|
|
545d20d043 | ||
|
|
9d876cf5d5 | ||
|
|
c6087021b7 | ||
|
|
7c95daabfd | ||
|
|
95a22401b2 | ||
|
|
a7b9506a9f | ||
|
|
c1fb07fcda | ||
|
|
5a25f07bfb | ||
|
|
b6d1ed97f1 | ||
|
|
4e812f7897 | ||
|
|
192930a289 | ||
|
|
7ed34f656b | ||
|
|
31250273b0 | ||
|
|
e70344892f | ||
|
|
39c727d3c4 | ||
|
|
02eb0716aa | ||
|
|
c706ed7aaf | ||
|
|
8c41fba277 | ||
|
|
53c384834a | ||
|
|
1e66dd6a68 | ||
|
|
b42a9ae8b4 | ||
|
|
88143b9a66 | ||
|
|
8f60cb82f3 | ||
|
|
e275b8760a | ||
|
|
01710f3385 | ||
|
|
ec319cc691 | ||
|
|
c6a064b332 | ||
|
|
615b90ab63 | ||
|
|
a7cf6f957e | ||
|
|
e9da937c75 | ||
|
|
d0da1560fa | ||
|
|
113fc02b28 | ||
|
|
1459fcb68e | ||
|
|
3d3d7ab2f6 | ||
|
|
fdb58a7f2b | ||
|
|
a9fecc1e8f | ||
|
|
d65d6aad28 | ||
|
|
95c733459d | ||
|
|
9fe0d776c7 | ||
|
|
25dc9d7b34 | ||
|
|
01423827b7 | ||
|
|
f1df1e6377 | ||
|
|
1e5f7b1169 | ||
|
|
9c6062f317 | ||
|
|
fc7247c72a | ||
|
|
c23d69e8f1 | ||
|
|
35d5ed8d8e | ||
|
|
07ccc6cc28 | ||
|
|
2ef798e56a | ||
|
|
24e4212a93 | ||
|
|
6851badfab | ||
|
|
cbedc5c147 | ||
|
|
373ee844da | ||
|
|
151ed39b04 | ||
|
|
24108f6a1f | ||
|
|
737ab115bd | ||
|
|
13957342df | ||
|
|
fe1a921440 | ||
|
|
39ff25beca | ||
|
|
ec15f26c13 | ||
|
|
0218191793 | ||
|
|
5065f5af86 | ||
|
|
6aca41835d | ||
|
|
6b746447e5 | ||
|
|
ca60b271fd | ||
|
|
1b720b498c | ||
|
|
2066470cba | ||
|
|
73ada1f25b | ||
|
|
43a77fd1b2 | ||
|
|
f968310902 | ||
|
|
32a5a7c264 | ||
|
|
776de88041 | ||
|
|
192a100f8d | ||
|
|
b796db1979 | ||
|
|
eb07cdf117 | ||
|
|
9f1ce26d6e | ||
|
|
0ce42e8f1f | ||
|
|
46d77de38e | ||
|
|
09d3af411e | ||
|
|
5414c82339 | ||
|
|
2edc2953dc | ||
|
|
2bc9555b53 | ||
|
|
47ef5baee3 | ||
|
|
78eadf1a0e | ||
|
|
6aa05c8faa | ||
|
|
8f8644a1d2 | ||
|
|
f9aed70869 | ||
|
|
036ac12f41 | ||
|
|
67cff58c63 | ||
|
|
4730c94c84 | ||
|
|
e53ef94306 | ||
|
|
a9f2728c93 | ||
|
|
657fc7af1d | ||
|
|
1b24072020 | ||
|
|
d912541391 | ||
|
|
72381d0071 | ||
|
|
a644c465cd | ||
|
|
bc0d3df897 | ||
|
|
fa234d4073 | ||
|
|
dd88c93474 | ||
|
|
2469898f9f | ||
|
|
ee656dc5f0 | ||
|
|
3eba0de851 | ||
|
|
f8fadb1729 | ||
|
|
6b5e30dbe4 | ||
|
|
72ef490538 | ||
|
|
7e2404eaf5 | ||
|
|
64f9492af2 | ||
|
|
f85ec34bcc | ||
|
|
8b40253169 | ||
|
|
91d38b5bb4 | ||
|
|
a59a7c226d | ||
|
|
4b620186f1 | ||
|
|
f313b5cdbe | ||
|
|
179d40178c | ||
|
|
15d711a6fd | ||
|
|
a4f5b21f1d | ||
|
|
307d9cd873 | ||
|
|
0f6c37a40c | ||
|
|
9e4b612c26 | ||
|
|
1815bcfaf9 | ||
|
|
6299adf633 | ||
|
|
5b93d43bc5 | ||
|
|
0cfb693619 | ||
|
|
1ea9268698 | ||
|
|
f50e6ced71 | ||
|
|
1b922c03a9 | ||
|
|
f6768b72ea | ||
|
|
236b095bbe | ||
|
|
a0799b1b32 | ||
|
|
38251600f9 | ||
|
|
aaa8a3cc19 | ||
|
|
25d9b8af3b | ||
|
|
ba6bf0a317 | ||
|
|
0abe56dfba | ||
|
|
7c8ba7895d | ||
|
|
eeb9d5224e | ||
|
|
79112717cf | ||
|
|
4a9a77d5f1 | ||
|
|
4ba892908b | ||
|
|
3891c70344 | ||
|
|
6e6c9e02a4 | ||
|
|
488fab7f9f | ||
|
|
8f569ed4c3 | ||
|
|
3f26f0b44f | ||
|
|
1f25cc6ded | ||
|
|
69b0dd5a4a | ||
|
|
e1d858752f | ||
|
|
88bbd4d2cf | ||
|
|
8c4adb4dd4 | ||
|
|
9290f55fa4 | ||
|
|
0653498e0f | ||
|
|
dd57247266 | ||
|
|
051174bd1c | ||
|
|
5eaf380e91 | ||
|
|
fb73c1fe08 | ||
|
|
4a03724540 | ||
|
|
5725a0c9c0 | ||
|
|
d8a98ad433 |
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img alt="logo" src="resources/logo_round.png" >
|
||||
<img alt="logo" width="150" src="resources/logo_round.png" >
|
||||
</p>
|
||||
|
||||
# @LightningTipBot 🏅
|
||||
@@ -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
|
||||
@@ -58,7 +58,7 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
|
||||
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
|
||||
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
|
||||
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
|
||||
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zeus support, optional).
|
||||
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
|
||||
|
||||
## Features
|
||||
@@ -116,7 +116,7 @@ Users can send and receive via . For this to work, you need to set the `lnurl_pu
|
||||
|
||||
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
|
||||
|
||||
### Link to BlueWallet or Zap
|
||||
### Link to BlueWallet or Zeus
|
||||
|
||||
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
|
||||
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
|
||||
help - Read the help.
|
||||
balance - Check balance.
|
||||
transactions - List transactions
|
||||
tip - Reply to a message to tip: /tip 50
|
||||
send - Send funds to a user: /send 100 @LightningTipBot
|
||||
invoice - Receive with Lightning: /invoice 1000
|
||||
pay - Pay with Lightning: /pay lnbc10n1ps...
|
||||
donate - Donate: /donate 1000
|
||||
faucet - Create a faucet: /faucet 2100 21
|
||||
tipjar - Create a tipjar: /tipjar 100 10
|
||||
advanced - Advanced help
|
||||
+15
-1
@@ -1,7 +1,15 @@
|
||||
bot:
|
||||
socks_proxy:
|
||||
host: 127.0.0.1:9996
|
||||
username: test
|
||||
password: username
|
||||
tor_proxy:
|
||||
host: 127.0.0.1:9050
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
lnurl_image: true
|
||||
admin_api_host: localhost:6060
|
||||
telegram:
|
||||
message_dispose_duration: 10
|
||||
api_key: "1234"
|
||||
@@ -14,4 +22,10 @@ lnbits:
|
||||
database:
|
||||
db_path: "data/bot.db"
|
||||
buntdb_path: "data/bunt.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
groupsdb_path: "data/groups.db"
|
||||
generate:
|
||||
dalle_key: "asd"
|
||||
dalle_price: 1000
|
||||
worker: 2
|
||||
@@ -0,0 +1 @@
|
||||
this is where dalle images are stored
|
||||
@@ -1,24 +1,98 @@
|
||||
module github.com/LightningTipBot/LightningTipBot
|
||||
|
||||
go 1.15
|
||||
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.4.0
|
||||
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
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/sirupsen/logrus v1.6.0
|
||||
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
golang.org/x/text v0.3.5
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
github.com/tidwall/gjson v1.12.1
|
||||
github.com/tidwall/sjson v1.2.4
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
|
||||
golang.org/x/text v0.3.7
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
|
||||
github.com/aead/siphash v1.0.1 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.1 // indirect
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
|
||||
github.com/btcsuite/btcd v0.23.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil v1.1.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
|
||||
github.com/btcsuite/btcwallet v0.15.1 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
|
||||
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
|
||||
github.com/decred/dcrd/lru v1.0.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dillonstreator/dalle v0.0.0-20220826164958-b15c236ceadc // indirect
|
||||
github.com/go-errors/errors v1.0.1 // indirect
|
||||
github.com/go-redis/redis/v8 v8.8.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.2 // indirect
|
||||
github.com/kkdai/bstream v1.0.0 // indirect
|
||||
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
|
||||
github.com/lightninglabs/neutrino v0.14.2 // indirect
|
||||
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
|
||||
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
|
||||
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.5 // indirect
|
||||
github.com/miekg/dns v1.1.43 // indirect
|
||||
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
|
||||
github.com/pegasus-kv/thrift v0.13.0 // indirect
|
||||
github.com/spf13/cast v1.5.0 // indirect
|
||||
github.com/tidwall/btree v0.6.1 // indirect
|
||||
github.com/tidwall/grect v0.1.3 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tidwall/rtred v0.1.2 // indirect
|
||||
github.com/tidwall/tinyqueue v0.1.1 // indirect
|
||||
go.opentelemetry.io/otel v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
|
||||
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 // indirect
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(b *telegram.TipBot) Service {
|
||||
return Service{
|
||||
bot: b,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.getUserByTelegramId(r)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not ban user: %v", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !user.Banned && !strings.HasPrefix(user.Wallet.Adminkey, "banned_") {
|
||||
log.Infof("[ADMIN] user is not banned. Aborting.")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user.Banned = false
|
||||
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
|
||||
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
|
||||
err = telegram.UpdateUserRecord(user, *s.bot)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not update user: %v", err)
|
||||
return
|
||||
}
|
||||
log.Infof("[ADMIN] Unbanned user (%s)", user.ID)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) BanUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.getUserByTelegramId(r)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not ban user: %v", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if user.Banned {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
log.Infof("[ADMIN] user is already banned. Aborting.")
|
||||
return
|
||||
}
|
||||
user.Banned = true
|
||||
if reason := r.URL.Query().Get("reason"); reason != "" {
|
||||
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", reason, user.Wallet.Adminkey)
|
||||
}
|
||||
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", "banned", user.Wallet.Adminkey)
|
||||
err = telegram.UpdateUserRecord(user, *s.bot)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not update user: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[ADMIN] Banned user (%s)", user.ID)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
|
||||
user := &lnbits.User{}
|
||||
v := mux.Vars(r)
|
||||
if v["id"] == "" {
|
||||
return nil, fmt.Errorf("invalid id")
|
||||
}
|
||||
tx := s.bot.DB.Users.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (s Service) DisableDalle(w http.ResponseWriter, r *http.Request) {
|
||||
dalle.Enabled = false
|
||||
}
|
||||
|
||||
func (s Service) EnableDalle(w http.ResponseWriter, r *http.Request) {
|
||||
dalle.Enabled = true
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package api
|
||||
|
||||
type BalanceResponse struct {
|
||||
Balance int64 `json:"balance"`
|
||||
}
|
||||
|
||||
type InvoiceStatusResponse struct {
|
||||
State string `json:"state,omitempty"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Preimage int64 `json:"preimage"`
|
||||
}
|
||||
|
||||
type CreateInvoiceResponse struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PayRequest string `json:"pay_request"`
|
||||
Preimage string `json:"preimage,omitempty"`
|
||||
}
|
||||
type CreateInvoiceRequest struct {
|
||||
Memo string `json:"memo"`
|
||||
Amount int64 `json:"amount"`
|
||||
DescriptionHash string `json:"description_hash"`
|
||||
UnhashedDescription string `json:"unhashed_description"`
|
||||
}
|
||||
|
||||
type PayInvoiceRequest struct {
|
||||
PayRequest string `json:"pay_req"`
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/r3labs/sse"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Bot *telegram.TipBot
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Message string `json:"error"`
|
||||
}
|
||||
|
||||
func RespondError(w http.ResponseWriter, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
|
||||
}
|
||||
|
||||
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
balance, err := s.Bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
RespondError(w, "balance check failed")
|
||||
return
|
||||
}
|
||||
|
||||
balanceResponse := BalanceResponse{
|
||||
Balance: balance,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(balanceResponse)
|
||||
}
|
||||
|
||||
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var createInvoiceRequest CreateInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: createInvoiceRequest.Amount,
|
||||
Out: false,
|
||||
DescriptionHash: createInvoiceRequest.DescriptionHash,
|
||||
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not create invoice")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(invoice)
|
||||
}
|
||||
|
||||
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var payInvoiceRequest PayInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not pay invoice: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
|
||||
if err != nil {
|
||||
// we assume that it's paid since thre was no error earlier
|
||||
payment.Paid = true
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get payment")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
// InvoiceStatus
|
||||
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get invoice")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
type InvoiceStream struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
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)
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"gorm.io/gorm"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func LoggingMiddleware(prefix string, 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()
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
type AuthType struct {
|
||||
Type string
|
||||
Decoder func(s string) ([]byte, error)
|
||||
}
|
||||
|
||||
var AuthTypeBasic = AuthType{Type: "Basic"}
|
||||
var AuthTypeBearerBase64 = AuthType{Type: "Bearer", Decoder: base64.StdEncoding.DecodeString}
|
||||
var AuthTypeNone = AuthType{}
|
||||
|
||||
// invoice key or admin key requirement
|
||||
type AccessKeyType struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
|
||||
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
|
||||
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
|
||||
|
||||
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if accessType.Type == "none" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
auth := r.Header.Get("Authorization")
|
||||
// check if the user is banned
|
||||
if auth == "" {
|
||||
w.WriteHeader(401)
|
||||
log.Warn("[api] no auth")
|
||||
return
|
||||
}
|
||||
_, password, ok := parseAuth(authType, auth)
|
||||
if !ok {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
w.WriteHeader(401)
|
||||
log.Warnf("[api] Banned user %s. Not forwarding request", password)
|
||||
return
|
||||
}
|
||||
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
|
||||
|
||||
user := &lnbits.User{}
|
||||
var tx *gorm.DB
|
||||
if accessType.Type == "admin" {
|
||||
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
} else if accessType.Type == "invoice" {
|
||||
tx = database.Where("wallet_inkey = ? OR wallet_adminkey = ? COLLATE NOCASE", password, password).First(user)
|
||||
} else {
|
||||
log.Errorf("[api] route without access type")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[api] could not load access key: %v", tx.Error)
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
|
||||
r = r.WithContext(context.WithValue(r.Context(), "user", user))
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// parseAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
|
||||
parse := func(prefix string) (username, password string, ok bool) {
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
if authType.Decoder != nil {
|
||||
c, err := authType.Decoder(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
return auth[len(prefix):], auth[len(prefix):], true
|
||||
|
||||
}
|
||||
return parse(fmt.Sprintf("%s ", authType.Type))
|
||||
|
||||
}
|
||||
|
||||
func dump(r *http.Request) string {
|
||||
x, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(x)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
|
||||
|
||||
client := &http.Client{Timeout: time.Second * 30}
|
||||
|
||||
//http: Request.RequestURI can't be set in client requests.
|
||||
//http://golang.org/src/pkg/net/http/client.go
|
||||
req.RequestURI = ""
|
||||
|
||||
u, err := url.Parse(rawUrl)
|
||||
if err != nil {
|
||||
http.Error(wr, "Server Error", http.StatusInternalServerError)
|
||||
log.Println("ServeHTTP:", err)
|
||||
return err
|
||||
}
|
||||
req.URL.Host = u.Host
|
||||
req.URL.Scheme = u.Scheme
|
||||
req.Host = req.URL.Host
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
http.Error(wr, "Server Error", http.StatusInternalServerError)
|
||||
log.Println("ServeHTTP:", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
log.Tracef("[Proxy] Proxy request status: %s", resp.Status)
|
||||
if resp.StatusCode > 300 {
|
||||
return fmt.Errorf("invalid response")
|
||||
}
|
||||
delHopHeaders(resp.Header)
|
||||
copyHeader(wr.Header(), resp.Header)
|
||||
wr.WriteHeader(resp.StatusCode)
|
||||
_, err = io.Copy(wr, resp.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
// Hop-by-hop headers. These are removed when sent to the backend.
|
||||
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
|
||||
var hopHeaders = []string{
|
||||
"Connection",
|
||||
"Keep-Alive",
|
||||
"Proxy-Authenticate",
|
||||
"Proxy-Authorization",
|
||||
"Te", // canonicalized version of "TE"
|
||||
"Trailers",
|
||||
"Transfer-Encoding",
|
||||
"Upgrade",
|
||||
}
|
||||
|
||||
func copyHeader(dst, src http.Header) {
|
||||
for k, vv := range src {
|
||||
for _, v := range vv {
|
||||
dst.Add(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func delHopHeaders(header http.Header) {
|
||||
for _, h := range hopHeaders {
|
||||
header.Del(h)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
router *mux.Router
|
||||
}
|
||||
|
||||
const (
|
||||
StatusError = "ERROR"
|
||||
StatusOk = "OK"
|
||||
)
|
||||
|
||||
func NewServer(address string) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: address,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 90 * time.Second,
|
||||
ReadTimeout: 90 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
httpServer: srv,
|
||||
}
|
||||
apiServer.router = mux.NewRouter()
|
||||
apiServer.httpServer.Handler = apiServer.router
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[api] Server started at %s", address)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) ListenAndServe() {
|
||||
go w.httpServer.ListenAndServe()
|
||||
}
|
||||
func (w *Server) PathPrefix(path string, handler http.Handler) {
|
||||
w.router.PathPrefix(path).Handler(handler)
|
||||
}
|
||||
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, accessType, handler)))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
|
||||
func NotFoundHandler(writer http.ResponseWriter, err error) {
|
||||
log.Errorln(err)
|
||||
// return 404 on any error
|
||||
http.Error(writer, "404 page not found", http.StatusNotFound)
|
||||
}
|
||||
|
||||
func WriteResponse(writer http.ResponseWriter, response interface{}) error {
|
||||
jsonResponse, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(jsonResponse)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<!-- @format -->
|
||||
|
||||
{{define "userpage"}}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8" />
|
||||
<meta property="og:title" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta property="og:site_name" content="{{.Username}}@ln.tips">
|
||||
<meta property="og:description" content="Send bitcoin to {{.Username}} over Lightning. Get your own Lightning address at https://ln.tips 👈">
|
||||
<meta property="og:type" content="article" />
|
||||
<meta property="og:image" content="{{.Image}}">
|
||||
<meta property="og:url" content="https://ln.tips/@{{.Username}}">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:image:alt" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta name="lightning" content="lnurlp:{{.Username}}@ln.tips"/>
|
||||
|
||||
<title>{{.Username}}@ln.tips</title>
|
||||
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: rgb(36,71,247);
|
||||
background: radial-gradient(circle, rgba(36,71,247,1) 0%, rgba(249,42,84,1) 100%);
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
font-family: monospace;
|
||||
width: 600px;
|
||||
color: #f3f3f3c5 !important;
|
||||
}
|
||||
.image-cropper {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 50%;
|
||||
}
|
||||
#photo {
|
||||
margin-top: 50px;
|
||||
width: 100px;
|
||||
}
|
||||
.white {
|
||||
color: #f3f3f3c5;
|
||||
}
|
||||
.sm {
|
||||
color: #f3f3f3c5;
|
||||
font-size: 1rem;
|
||||
}
|
||||
#qr {
|
||||
display: block;
|
||||
margin-top: 50px;
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
#invoice {
|
||||
margin: 10px;
|
||||
padding-bottom: 10px;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
word-break: break-all;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<a href="https://t.me/{{.Username}}"><img id="photo" class="image-cropper" src="{{.Image}}"/></a>
|
||||
<h1>Pay to <a class="white" href="https://t.me/{{.Username}}">{{.Username}}@ln.tips</a></h1>
|
||||
|
||||
<div><a href="lightning:{{.LNURLPay}}" id="qr"></a></div>
|
||||
<div class="white" id="invoice">{{.LNURLPay}}</div>
|
||||
<div class="sm">Get your own Lightning address here: <a class="sm" href="https://ln.tips">ln.tips</a></div>
|
||||
<script>
|
||||
qr.appendChild(
|
||||
kjua({
|
||||
text: invoice.innerHTML,
|
||||
rounded: 50,
|
||||
size: 500,
|
||||
render: 'canvas',
|
||||
})
|
||||
)
|
||||
</script>
|
||||
|
||||
{{end}}
|
||||
@@ -0,0 +1,387 @@
|
||||
<!-- @format -->
|
||||
|
||||
{{define "webapp"}}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="MobileOptimized" content="176" />
|
||||
<meta name="HandheldFriendly" content="True" />
|
||||
<meta name="robots" content="noindex,nofollow" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
|
||||
|
||||
<title>@LightningTipBot</title>
|
||||
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
|
||||
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
|
||||
<script>
|
||||
function setThemeClass() {
|
||||
document.documentElement.className = Telegram.WebApp.colorScheme;
|
||||
}
|
||||
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
|
||||
setThemeClass();
|
||||
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
background-color: var(--tg-theme-bg-color, #ffffff);
|
||||
color: var(--tg-theme-text-color, #222222);
|
||||
font-size: 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color-scheme: var(--tg-color-scheme);
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--tg-theme-link-color, #2678b6);
|
||||
}
|
||||
|
||||
button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
border: none;
|
||||
background-color: var(--tg-theme-button-color, #50a8eb);
|
||||
color: var(--tg-theme-button-text-color, #ffffff);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--tg-theme-button-color, #50a8eb);
|
||||
color: var(--tg-theme-button-text-color, #ffffff);
|
||||
}
|
||||
|
||||
button[disabled] {
|
||||
opacity: 0.6;
|
||||
cursor: auto;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
input {
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
border: none;
|
||||
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
|
||||
color: var(--tg-theme-text-color, #1a1a1a) !important;
|
||||
}
|
||||
|
||||
.input-group-text {
|
||||
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
|
||||
color: var(--tg-theme-text-color, #1a1a1a) !important;
|
||||
}
|
||||
|
||||
section {
|
||||
padding: 5px 5px 65px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 40px 0 15px;
|
||||
}
|
||||
|
||||
ul {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
li {
|
||||
color: var(--tg-theme-hint-color, #a8a8a8);
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 7px;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: rgba(0, 0, 0, .07);
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
margin: 7px 0;
|
||||
word-break: break-all;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dark pre {
|
||||
background: rgba(255, 255, 255, .15);
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: .8em;
|
||||
color: var(--tg-theme-hint-color, #a8a8a8);
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: green;
|
||||
}
|
||||
|
||||
.err {
|
||||
color: red;
|
||||
}
|
||||
|
||||
#fixed_wrap {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
transform: translateY(100vh);
|
||||
}
|
||||
|
||||
.viewport_border,
|
||||
.viewport_stable_border {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
height: var(--tg-viewport-height, 100vh);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.viewport_stable_border {
|
||||
height: var(--tg-viewport-stable-height, 100vh);
|
||||
}
|
||||
|
||||
.viewport_border:before,
|
||||
.viewport_stable_border:before {
|
||||
content: attr(text);
|
||||
display: inline-block;
|
||||
position: absolute;
|
||||
background: gray;
|
||||
right: 0;
|
||||
top: 0;
|
||||
font-size: 7px;
|
||||
padding: 2px 4px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.viewport_stable_border:before {
|
||||
background: green;
|
||||
left: 0;
|
||||
right: auto;
|
||||
}
|
||||
|
||||
.viewport_border:after,
|
||||
.viewport_stable_border:after {
|
||||
content: '';
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
border: 2px dashed gray;
|
||||
}
|
||||
|
||||
.viewport_stable_border:after {
|
||||
border-color: green;
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 120%;
|
||||
word-wrap: break-word;
|
||||
margin: 0.5em;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.qr {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 0px;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
}
|
||||
|
||||
.qr > canvas {
|
||||
max-height: 800px;
|
||||
max-width: 800px;
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
display: grid;
|
||||
grid-template-columns: 3fr 2fr;
|
||||
padding: 12px 20px;
|
||||
column-gap: 10px;
|
||||
row-gap: 1em;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<section>
|
||||
<h1 id="greeting"></h1>
|
||||
|
||||
<div class="qr-container">
|
||||
<div class="qr" id="qr">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="buttons">
|
||||
<!-- <button onclick="webviewClose();">Close</button> -->
|
||||
<div class="wrapper">
|
||||
<label class="sr-only" for="inlineFormInputGroup">Username</label>
|
||||
<div class="input-group">
|
||||
<input type="number" class="form-control" min="1" inputmode="numeric" pattern="[0-9]*" id="invoiceAmount" placeholder="amount">
|
||||
<div class="input-group-append">
|
||||
<div class="input-group-text" id="inputCurrency"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn btn-primary" onclick="invoiceButtonClick();" style="display: inline;" id="requestInvoice">Invoice</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script type="application/javascript">
|
||||
Telegram.WebApp.ready();
|
||||
|
||||
// render the LNURL pay QR code
|
||||
var s = "{{.LNURLPay}}";
|
||||
const currencies = ["sat", "USD", "EUR"];
|
||||
var currency_idx = 0;
|
||||
document.getElementById("inputCurrency").innerHTML = currencies[0];
|
||||
|
||||
renderQr(s);
|
||||
|
||||
// data passed form telegram server
|
||||
const initData = Telegram.WebApp.initData || '';
|
||||
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
|
||||
|
||||
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
|
||||
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
|
||||
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
|
||||
|
||||
// react to theme changes
|
||||
try {
|
||||
document.querySelector('#themeData').html(JSON.stringify(Telegram.WebApp.themeParams, null, 2));
|
||||
Telegram.WebApp.onEvent('themeChanged', function() {
|
||||
document.querySelector('#themeData').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
|
||||
// listen for enter in input field
|
||||
var el = document.getElementById("invoiceAmount");
|
||||
el.addEventListener("keydown", function(event) {
|
||||
if (event.key === "Enter") {
|
||||
document.getElementById("requestInvoice").click();
|
||||
}
|
||||
document.getElementById("requestInvoice").innerHTML = "Invoice"
|
||||
// revert color of button
|
||||
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
|
||||
});
|
||||
|
||||
var el = document.getElementById("inputCurrency");
|
||||
el.addEventListener("click", function(event) {
|
||||
currency_idx += 1;
|
||||
$(this).html(currencies[currency_idx%(currencies.length)]);
|
||||
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
|
||||
});
|
||||
|
||||
// ------------------ functions ------------------
|
||||
|
||||
function invoiceButtonClick() {
|
||||
var c = "{{.Callback}}";
|
||||
getInvoice(this, c);
|
||||
// hide keyboard and scroll up
|
||||
document.getElementById("invoiceAmount").blur();
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
function invoiceButtonDisplayError(message) {
|
||||
btn = document.getElementById("requestInvoice")
|
||||
btn.innerHTML = message
|
||||
// update color of button
|
||||
$('#requestInvoice').removeClass('btn-primary').addClass('btn-danger');
|
||||
}
|
||||
|
||||
function webviewClose() {
|
||||
Telegram.WebApp.close();
|
||||
}
|
||||
|
||||
function renderQr(payload) {
|
||||
const qr = document.getElementById('qr');
|
||||
qr.innerHTML = '';
|
||||
if ( qr ) {
|
||||
const qrGfx = kjua({
|
||||
text: payload,
|
||||
rounded: 50,
|
||||
size: 500,
|
||||
render: 'canvas',
|
||||
});
|
||||
qr.appendChild( qrGfx );
|
||||
// var href_link = "lightning:" + payload;
|
||||
// qr.setAttribute('href', "javascript:window.open('"+ href_link+ "');" );
|
||||
}
|
||||
}
|
||||
|
||||
function getInvoice(el, callback) {
|
||||
curr_idx = currency_idx%currencies.length
|
||||
var invoiceAmount = Number(document.getElementById("invoiceAmount").value);
|
||||
if ((currencies[curr_idx] == "sat" && !Number.isInteger(invoiceAmount)) || invoiceAmount < 1) {
|
||||
invoiceButtonDisplayError("Invalid")
|
||||
return false;
|
||||
}
|
||||
var amountQueryParam;
|
||||
if (currencies[curr_idx] == "sat") {
|
||||
amountQueryParam = invoiceAmount * 1000 // sat to msat
|
||||
} else {
|
||||
amountQueryParam = invoiceAmount + currencies[curr_idx]
|
||||
}
|
||||
fetch(callback)
|
||||
.then(data => {
|
||||
return data.json();
|
||||
})
|
||||
.then(r => {
|
||||
console.log(r);
|
||||
console.log("requesting invoice with amount " + amountQueryParam);
|
||||
fetch(r.callback + '?amount='+ amountQueryParam).then(data => {
|
||||
return data.json();
|
||||
})
|
||||
.then(r => {
|
||||
console.log(r);
|
||||
if (r.status == "OK"){
|
||||
// update qr code
|
||||
renderQr(r.pr);
|
||||
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
|
||||
} else {
|
||||
invoiceButtonDisplayError("Error")
|
||||
return false;
|
||||
}
|
||||
|
||||
})
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
{{end}}
|
||||
@@ -0,0 +1,112 @@
|
||||
package userpage
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(b *telegram.TipBot) Service {
|
||||
return Service{
|
||||
bot: b,
|
||||
}
|
||||
}
|
||||
|
||||
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
//go:embed static
|
||||
var templates embed.FS
|
||||
var userpage_tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
|
||||
var qr_tmpl = template.Must(template.ParseFS(templates, "static/webapp.html"))
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// thank you fiatjaf for this code
|
||||
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
// with proxy:
|
||||
// client, err := s.network.GetHttpClient()
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
client := http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
resp, err := client.Get("https://t.me/" + username)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
url, ok := doc.Find(`meta[property="og:image"]`).First().Attr("content")
|
||||
if !ok {
|
||||
return "", errors.New("no image available for this user")
|
||||
}
|
||||
|
||||
return url, nil
|
||||
}
|
||||
|
||||
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/@<username>
|
||||
username := strings.ToLower(mux.Vars(r)["username"])
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
|
||||
log.Infof("[UserPage] rendering page of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
return
|
||||
}
|
||||
image, err := s.getTelegramUserPictureURL(username)
|
||||
if err != nil || image == "https://telegram.org/img/t_logo.png" {
|
||||
// replace the default image
|
||||
image = botImage
|
||||
}
|
||||
|
||||
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
Username string
|
||||
Image string
|
||||
LNURLPay string
|
||||
}{username, image, lnurlEncode}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/app/<username>
|
||||
username := strings.ToLower(mux.Vars(r)["username"])
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
|
||||
log.Infof("[UserPage] rendering webapp of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
return
|
||||
}
|
||||
if err := qr_tmpl.ExecuteTemplate(w, "webapp", struct {
|
||||
Username string
|
||||
LNURLPay string
|
||||
Callback string
|
||||
}{username, lnurlEncode, callback}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
+23
-5
@@ -14,14 +14,30 @@ var Configuration = struct {
|
||||
Telegram TelegramConfiguration `yaml:"telegram"`
|
||||
Database DatabaseConfiguration `yaml:"database"`
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
Generate GenerateConfiguration `yaml:"generate"`
|
||||
}{}
|
||||
|
||||
type GenerateConfiguration struct {
|
||||
DalleKey string `yaml:"dalle_key"`
|
||||
DallePrice int64 `yaml:"dalle_price"`
|
||||
Worker int `yaml:"worker"`
|
||||
}
|
||||
|
||||
type SocksConfiguration struct {
|
||||
Host string `yaml:"host"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
type BotConfiguration struct {
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
|
||||
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
AdminAPIHost string `yaml:"admin_api_host"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
@@ -30,8 +46,10 @@ type TelegramConfiguration struct {
|
||||
}
|
||||
type DatabaseConfiguration struct {
|
||||
DbPath string `yaml:"db_path"`
|
||||
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
|
||||
BuntDbPath string `yaml:"buntdb_path"`
|
||||
TransactionsPath string `yaml:"transactions_path"`
|
||||
GroupsDbPath string `yaml:"groupsdb_path"`
|
||||
}
|
||||
|
||||
type LnbitsConfiguration struct {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package dalle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"io"
|
||||
)
|
||||
|
||||
var Enabled bool
|
||||
|
||||
func init() {
|
||||
if internal.Configuration.Generate.DalleKey != "" {
|
||||
Enabled = true
|
||||
}
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
Generate(ctx context.Context, prompt string) (*Task, error)
|
||||
ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error)
|
||||
GetTask(ctx context.Context, taskID string) (*Task, error)
|
||||
Download(ctx context.Context, generationID string) (io.ReadCloser, error)
|
||||
Share(ctx context.Context, generationID string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dalle
|
||||
|
||||
const (
|
||||
StatusPending = "pending"
|
||||
StatusRejected = "rejected"
|
||||
StatusSucceeded = "succeeded"
|
||||
|
||||
TaskTypeText2Im = "text2im"
|
||||
|
||||
defaultBatchSize = 4
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
package dalle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
libraryVersion = "1.0.0"
|
||||
defaultUserAgent = "dalle/" + libraryVersion
|
||||
baseURL = "https://labs.openai.com/api/labs"
|
||||
|
||||
defaultHTTPClientTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type option func(*HTTPClient) error
|
||||
|
||||
func WithHTTPClient(httpClient *http.Client) option {
|
||||
return func(c *HTTPClient) error {
|
||||
c.httpClient = httpClient
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithUserAgent(userAgent string) option {
|
||||
return func(c *HTTPClient) error {
|
||||
c.userAgent = userAgent
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type HTTPClient struct {
|
||||
httpClient *http.Client
|
||||
userAgent string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
var _ Client = (*HTTPClient)(nil)
|
||||
|
||||
func NewHTTPClient(apiKey string, opts ...option) (*HTTPClient, error) {
|
||||
c := &HTTPClient{
|
||||
httpClient: &http.Client{Timeout: defaultHTTPClientTimeout},
|
||||
userAgent: defaultUserAgent,
|
||||
apiKey: apiKey,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
if err := opt(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
Object string `json:"object"`
|
||||
ID string `json:"id"`
|
||||
Created int64 `json:"created"`
|
||||
TaskType string `json:"task_type"`
|
||||
Status string `json:"status"`
|
||||
PromptID string `json:"prompt_id"`
|
||||
Prompt Prompt `json:"prompt"`
|
||||
Generations Generations `json:"generations"`
|
||||
}
|
||||
type Generations struct {
|
||||
Data []GenerationData `json:"data"`
|
||||
Object string `json:"object"`
|
||||
}
|
||||
type GenerationData struct {
|
||||
Created int64 `json:"created"`
|
||||
Generation Generation `json:"generation"`
|
||||
GenerationType string `json:"generation_type"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
type Generation struct {
|
||||
ImagePath string `json:"image_path"`
|
||||
}
|
||||
|
||||
type Prompt struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
PromptType string `json:"prompt_type"`
|
||||
Prompt struct {
|
||||
Caption string `json:"caption"`
|
||||
} `json:"prompt"`
|
||||
ParentGenerationID string `json:"parent_generation_id"`
|
||||
}
|
||||
|
||||
type GenerateRequest struct {
|
||||
Prompt GenerateRequestPrompt `json:"prompt"`
|
||||
TaskType string `json:"task_type"`
|
||||
}
|
||||
type GenerateRequestPrompt struct {
|
||||
BatchSize int32 `json:"batch_size"`
|
||||
Caption string `json:"caption"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Generate(ctx context.Context, caption string) (*Task, error) {
|
||||
task := &Task{}
|
||||
req := &GenerateRequest{
|
||||
Prompt: GenerateRequestPrompt{
|
||||
BatchSize: defaultBatchSize,
|
||||
Caption: caption,
|
||||
},
|
||||
TaskType: TaskTypeText2Im,
|
||||
}
|
||||
return task, c.request(ctx, "POST", "/tasks", nil, req, task)
|
||||
}
|
||||
|
||||
type ListTasksResponse struct {
|
||||
Object string `json:"object"`
|
||||
Data []Task `json:"data"`
|
||||
}
|
||||
|
||||
type ListTasksRequest struct {
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
|
||||
res := &ListTasksResponse{}
|
||||
url := "/tasks"
|
||||
if req != nil {
|
||||
if req.Limit != 0 {
|
||||
url += fmt.Sprintf("?limit=%d", req.Limit)
|
||||
}
|
||||
}
|
||||
|
||||
return res, c.request(ctx, "GET", url, nil, nil, res)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetTask(ctx context.Context, taskID string) (*Task, error) {
|
||||
task := &Task{}
|
||||
return task, c.request(ctx, "GET", "/tasks/"+taskID, nil, nil, task)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Download(ctx context.Context, generationID string) (io.ReadCloser, error) {
|
||||
req, err := c.createRequest(ctx, "/generations/"+generationID+"/download", "GET", nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("performing request: %w", err)
|
||||
}
|
||||
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// Share makes the generation public and returns the public url
|
||||
func (c *HTTPClient) Share(ctx context.Context, generationID string) (string, error) {
|
||||
res := &GenerationData{}
|
||||
|
||||
err := c.request(ctx, "POST", "/generations/"+generationID+"/share", nil, nil, res)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return res.Generation.ImagePath, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) createRequest(ctx context.Context, path, method string, values *url.Values, data interface{}) (*http.Request, error) {
|
||||
url := baseURL + path
|
||||
|
||||
if values != nil {
|
||||
url += "?" + values.Encode()
|
||||
}
|
||||
|
||||
var body io.Reader
|
||||
if data != nil {
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing request data: %w", err)
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, url, body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("building request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Add("Authorization", "Bearer "+c.apiKey)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) request(ctx context.Context, method, path string, values *url.Values, body interface{}, result interface{}) error {
|
||||
req, err := c.createRequest(ctx, path, method, values, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("performing request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
|
||||
// TODO: improve error handling...
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return Error{
|
||||
Message: "unexpected non 200 status code",
|
||||
StatusCode: resp.StatusCode,
|
||||
Details: string(respBody),
|
||||
}
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(respBody, result); err != nil {
|
||||
return Error{
|
||||
Message: err.Error(),
|
||||
StatusCode: resp.StatusCode,
|
||||
Details: string(respBody),
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Message string
|
||||
StatusCode int
|
||||
Details string
|
||||
}
|
||||
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("dalle: %s (status: %d, details: %s)", e.Message, e.StatusCode, e.Details)
|
||||
}
|
||||
@@ -9,15 +9,51 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func MigrateAnonIdHash(db *gorm.DB) error {
|
||||
func MigrateAnonIdInt32Hash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
log.Info(u.ID, str.Int32Hash(u.ID))
|
||||
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
|
||||
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
|
||||
tx := db.Save(u)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdInt32Hash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MigrateAnonIdSha265Hash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
pw := u.Wallet.ID
|
||||
anon_id := str.AnonIdSha256(&u)
|
||||
log.Infof("[MigrateAnonIdSha265Hash] %s -> %s", pw, anon_id)
|
||||
u.AnonIDSha256 = anon_id
|
||||
tx := db.Save(u)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MigrateUUIDSha265Hash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
pw := u.Wallet.ID
|
||||
uuid := str.UUIDSha256(&u)
|
||||
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
|
||||
u.UUID = uuid
|
||||
tx := db.Save(u)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[MigrateUUIDSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
package errors
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
DecodeAmountError TipBotErrorType = 1000 + iota
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
GetBalanceError
|
||||
BalanceToLowError
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
func Create(code TipBotErrorType) TipBotError {
|
||||
return errMap[code]
|
||||
}
|
||||
func New(code TipBotErrorType, err error) TipBotError {
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
if err != nil {
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
}
|
||||
return Create(code)
|
||||
}
|
||||
|
||||
type TipBotError struct {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package errors
|
||||
|
||||
import "fmt"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
UnknownError TipBotErrorType = iota
|
||||
NoReplyMessageError
|
||||
InvalidSyntaxError
|
||||
MaxReachedError
|
||||
NoPhotoError
|
||||
NoFileFoundError
|
||||
NotActiveError
|
||||
InvalidTypeError
|
||||
)
|
||||
|
||||
const (
|
||||
UserNoWalletError TipBotErrorType = 2000 + iota
|
||||
BalanceToLowError
|
||||
SelfPaymentError
|
||||
NoPrivateChatError
|
||||
GetBalanceError
|
||||
DecodeAmountError
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
)
|
||||
|
||||
const (
|
||||
NoShopError TipBotErrorType = 3000 + iota
|
||||
NotShopOwnerError
|
||||
ShopNoOwnerError
|
||||
ItemIdMismatchError
|
||||
)
|
||||
|
||||
var errMap = map[TipBotErrorType]TipBotError{
|
||||
UserNoWalletError: userNoWallet,
|
||||
NoReplyMessageError: noReplyMessage,
|
||||
InvalidSyntaxError: invalidSyntax,
|
||||
InvalidAmountPerUserError: invalidAmount,
|
||||
InvalidAmountError: invalidAmountPerUser,
|
||||
NoPrivateChatError: noPrivateChat,
|
||||
ShopNoOwnerError: shopNoOwner,
|
||||
NotShopOwnerError: notShopOwner,
|
||||
MaxReachedError: maxReached,
|
||||
NoShopError: noShop,
|
||||
SelfPaymentError: selfPayment,
|
||||
NoPhotoError: noPhoto,
|
||||
ItemIdMismatchError: itemIdMismatch,
|
||||
NoFileFoundError: noFileFound,
|
||||
UnknownError: unknown,
|
||||
NotActiveError: notActive,
|
||||
InvalidTypeError: invalidType,
|
||||
}
|
||||
|
||||
var (
|
||||
userNoWallet = TipBotError{Err: fmt.Errorf("user has no wallet")}
|
||||
noReplyMessage = TipBotError{Err: fmt.Errorf("no reply message")}
|
||||
invalidSyntax = TipBotError{Err: fmt.Errorf("invalid syntax")}
|
||||
invalidAmount = TipBotError{Err: fmt.Errorf("invalid amount")}
|
||||
invalidAmountPerUser = TipBotError{Err: fmt.Errorf("invalid amount per user")}
|
||||
noPrivateChat = TipBotError{Err: fmt.Errorf("no private chat")}
|
||||
shopNoOwner = TipBotError{Err: fmt.Errorf("shop has no owner")}
|
||||
notShopOwner = TipBotError{Err: fmt.Errorf("user is not shop owner")}
|
||||
maxReached = TipBotError{Err: fmt.Errorf("maximum reached")}
|
||||
noShop = TipBotError{Err: fmt.Errorf("user has no shop")}
|
||||
selfPayment = TipBotError{Err: fmt.Errorf("can't pay yourself")}
|
||||
noPhoto = TipBotError{Err: fmt.Errorf("no photo in message")}
|
||||
itemIdMismatch = TipBotError{Err: fmt.Errorf("item id mismatch")}
|
||||
noFileFound = TipBotError{Err: fmt.Errorf("no file found")}
|
||||
unknown = TipBotError{Err: fmt.Errorf("unknown error")}
|
||||
notActive = TipBotError{Err: fmt.Errorf("element not active")}
|
||||
invalidType = TipBotError{Err: fmt.Errorf("invalid type")}
|
||||
)
|
||||
@@ -21,10 +21,13 @@ func RegisterLanguages() *i18n.Bundle {
|
||||
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
|
||||
}
|
||||
func Translate(languageCode string, MessgeID string) string {
|
||||
|
||||
+56
-27
@@ -1,6 +1,9 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
)
|
||||
|
||||
@@ -82,7 +85,7 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
|
||||
}
|
||||
|
||||
// Invoice creates an invoice associated with this wallet.
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
@@ -105,30 +108,6 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err e
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/payments", invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
// custom header with invoice key
|
||||
@@ -153,6 +132,54 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Payments returns wallet payments
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/payments?limit=60", invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
// Payment state of a payment
|
||||
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&payment)
|
||||
return
|
||||
}
|
||||
|
||||
// Wallets returns all wallets belonging to an user
|
||||
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
|
||||
@@ -172,14 +199,16 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
|
||||
// custom header with admin key
|
||||
adminHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Adminkey,
|
||||
}
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
r := req.New()
|
||||
r.SetTimeout(time.Hour * 24)
|
||||
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
+103
-37
@@ -1,10 +1,17 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/btcsuite/btcd/btcec/v2"
|
||||
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -15,16 +22,31 @@ type Client struct {
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" gorm:"primaryKey"`
|
||||
Initialized bool `json:"initialized"`
|
||||
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
|
||||
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
|
||||
StateKey UserStateKey `json:"stateKey"`
|
||||
StateData string `json:"stateData"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
AnonID string `jsin:"anonid"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" gorm:"primaryKey"`
|
||||
Initialized bool `json:"initialized"`
|
||||
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
|
||||
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
|
||||
StateKey UserStateKey `json:"stateKey"`
|
||||
StateData string `json:"stateData"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
AnonID string `json:"anon_id"`
|
||||
AnonIDSha256 string `json:"anon_id_sha256"`
|
||||
UUID string `json:"uuid"`
|
||||
Banned bool `json:"banned"`
|
||||
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
ID string `json:"id" gorm:"primarykey"`
|
||||
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
|
||||
}
|
||||
|
||||
type NodeSettings struct {
|
||||
NodeType string `json:"nodetype"`
|
||||
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
|
||||
LNbitsParams *satdress.LNBitsParams `gorm:"embedded;embeddedPrefix:lnbitsparams_"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -34,6 +56,16 @@ const (
|
||||
UserStateConfirmLNURLPay
|
||||
UserEnterAmount
|
||||
UserHasEnteredAmount
|
||||
UserEnterUser
|
||||
UserHasEnteredUser
|
||||
UserEnterShopTitle
|
||||
UserStateShopItemSendPhoto
|
||||
UserStateShopItemSendTitle
|
||||
UserStateShopItemSendDescription
|
||||
UserStateShopItemSendPrice
|
||||
UserStateShopItemSendItemFile
|
||||
UserEnterShopsDescription
|
||||
UserEnterDallePrompt
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
@@ -44,11 +76,12 @@ func (u *User) ResetState() {
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in MilliSatoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in Satoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
@@ -70,14 +103,11 @@ type TransferParams struct {
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Name string `json:"name"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Status int `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
func (err Error) Error() string {
|
||||
return err.Message
|
||||
return err.Detail
|
||||
}
|
||||
|
||||
type Wallet struct {
|
||||
@@ -88,24 +118,60 @@ type Wallet struct {
|
||||
Name string `json:"name"`
|
||||
User string `json:"user"`
|
||||
}
|
||||
type BitInvoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
|
||||
type Payments []struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
type Payment struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct{} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook interface{} `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
type LNbitsPayment struct {
|
||||
Paid bool `json:"paid"`
|
||||
Preimage string `json:"preimage"`
|
||||
Details Payment `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
type Payments []Payment
|
||||
|
||||
type Invoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
|
||||
// from fiatjaf/lnurl-go
|
||||
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
|
||||
seedHash := sha256.Sum256([]byte(
|
||||
fmt.Sprintf("lnurlkeyseed:%s:%s",
|
||||
domain, u.ID)))
|
||||
return btcec.PrivKeyFromBytes(seedHash[:])
|
||||
}
|
||||
|
||||
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
|
||||
// lnurl-auth: create a key based on the user id and sign with it
|
||||
sk, pk := u.LinkingKey(domain)
|
||||
|
||||
k1, err := hex.DecodeString(k1hex)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
|
||||
}
|
||||
|
||||
signature := ecdsa.Sign(sk, k1)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("error signing k1: %w", err)
|
||||
}
|
||||
|
||||
sig = hex.EncodeToString(signature.Serialize())
|
||||
key = hex.EncodeToString(pk.SerializeCompressed())
|
||||
|
||||
return key, sig, nil
|
||||
}
|
||||
|
||||
@@ -3,29 +3,25 @@ package webhook
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
|
||||
const (
|
||||
// invoiceReceivedMessage = "⚡️ You received %d sat."
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
@@ -35,17 +31,16 @@ type Server struct {
|
||||
}
|
||||
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int64 `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct{} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
@@ -53,14 +48,13 @@ type Webhook struct {
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
database: bot.DB.Users,
|
||||
bot: bot.Telegram,
|
||||
httpServer: srv,
|
||||
buntdb: bot.Bunt,
|
||||
@@ -86,38 +80,47 @@ func (w *Server) newRouter() *mux.Router {
|
||||
return router
|
||||
}
|
||||
|
||||
func (w Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
depositEvent := Webhook{}
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
webhookEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&depositEvent)
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(depositEvent.WalletID)
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
|
||||
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
|
||||
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
|
||||
err = w.buntdb.Get(tx)
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// trigger invoice events
|
||||
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
} else {
|
||||
if len(tx.Comment) > 0 {
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
if err != nil {
|
||||
// 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)
|
||||
return
|
||||
}
|
||||
go c.Function(txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// fallback: send a message to the user if there is no callback for this invoice
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package lndhub
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LndHub struct {
|
||||
database *gorm.DB
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) LndHub {
|
||||
return LndHub{database: bot.DB.Users}
|
||||
}
|
||||
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
|
||||
}
|
||||
+258
-88
@@ -8,31 +8,68 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
PayRequestTag = "payRequest"
|
||||
Endpoint = ".well-known/lnurlp"
|
||||
MinSendable = 1000 // mSat
|
||||
MaxSendable = 1_000_000_000
|
||||
CommentAllowed = 500
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
ToUser *lnbits.User `json:"to_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
*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"`
|
||||
}
|
||||
type Lnurl struct {
|
||||
telegram *tb.Bot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
callbackHostname *url.URL
|
||||
buntdb *storage.DB
|
||||
WebhookServer string
|
||||
cache telegram.Cache
|
||||
}
|
||||
|
||||
func (msg Invoice) Key() string {
|
||||
return fmt.Sprintf("payment-hash:%s", msg.PaymentHash)
|
||||
func New(bot *telegram.TipBot) Lnurl {
|
||||
return Lnurl{
|
||||
c: bot.Client,
|
||||
database: bot.DB.Users,
|
||||
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
|
||||
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
|
||||
buntdb: bot.Bunt,
|
||||
telegram: bot.Telegram,
|
||||
cache: bot.Cache,
|
||||
}
|
||||
}
|
||||
func (lnurlInvoice Invoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
var err error
|
||||
var response interface{}
|
||||
username := mux.Vars(request)["username"]
|
||||
@@ -41,176 +78,309 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
} else {
|
||||
stringAmount := request.FormValue("amount")
|
||||
if stringAmount == "" {
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Form value 'amount' is not set"))
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
|
||||
var amount int64
|
||||
if amount, err = strconv.ParseInt(stringAmount, 10, 64); err != nil {
|
||||
// if the value wasn't a clean msat denomination, parse it
|
||||
amount, err = telegram.GetAmount(stringAmount)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int: %v", err))
|
||||
return
|
||||
}
|
||||
// GetAmount returns sat, we need msat
|
||||
amount *= 1000
|
||||
}
|
||||
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Comment is too long"))
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
return
|
||||
}
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
|
||||
|
||||
// payer data
|
||||
payerdata := request.FormValue("payerdata")
|
||||
var payerData lnurl.PayerDataValues
|
||||
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)
|
||||
}
|
||||
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
// log the error
|
||||
log.Errorf("[LNURL] %v", err)
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = writeResponse(writer, response)
|
||||
err = api.WriteResponse(writer, response)
|
||||
if err != nil {
|
||||
NotFoundHandler(writer, err)
|
||||
api.NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// no error from first or second handler
|
||||
err = writeResponse(writer, response)
|
||||
err = api.WriteResponse(writer, response)
|
||||
if err != nil {
|
||||
NotFoundHandler(writer, err)
|
||||
api.NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
|
||||
key := fmt.Sprintf("lnurl_metadata_%s", username)
|
||||
|
||||
// load metadata from cache
|
||||
if m, err := w.cache.Get(key); err == nil {
|
||||
return m.(lnurl.Metadata)
|
||||
}
|
||||
|
||||
// otherwise, create new metadata
|
||||
metadata := w.metaData(username)
|
||||
|
||||
// load the user profile picture
|
||||
if internal.Configuration.Bot.LNURLSendImage {
|
||||
// get the user from the database
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error == nil && user.Telegram != nil {
|
||||
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
|
||||
}
|
||||
}
|
||||
|
||||
// save into cache
|
||||
runtime.IgnoreError(w.cache.Set(key, metadata, &store.Options{Expiration: 30 * time.Minute}))
|
||||
return metadata
|
||||
}
|
||||
|
||||
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
|
||||
// to call and the metadata that matches the description hash of the second response
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayResponse1, 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(), lnurlEndpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata := w.metaData(username)
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &lnurl.LNURLPayResponse1{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
Tag: payRequestTag,
|
||||
// produce the metadata including the image
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
return &lnurl.LNURLPayParams{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
Tag: PayRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
CallbackURL: callbackURL, // probably no need to set this here
|
||||
MinSendable: minSendable,
|
||||
MinSendable: MinSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: string(jsonMeta),
|
||||
EncodedMetadata: metadata.Encode(),
|
||||
CommentAllowed: CommentAllowed,
|
||||
PayerData: &lnurl.PayerDataSpec{
|
||||
FreeName: &lnurl.PayerDataItemSpec{},
|
||||
LightningAddress: &lnurl.PayerDataItemSpec{},
|
||||
Email: &lnurl.PayerDataItemSpec{},
|
||||
},
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Server) serveLNURLpSecond(username string, amount int64, comment string) (*lnurl.LNURLPayResponse2, 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 < minSendable || amount > MaxSendable {
|
||||
if amount_msat < MinSendable || amount_msat > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d sat, max: %d sat).", MinSendable/1000, MaxSendable/1000)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
|
||||
// now check for the user
|
||||
user := &lnbits.User{}
|
||||
// check if "username" is actually the user ID
|
||||
tx := w.database
|
||||
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
|
||||
// asume it's a user ID
|
||||
tx = w.database.Where("anon_id = ?", username).First(user)
|
||||
} else {
|
||||
// assume it's a string @username
|
||||
tx = w.database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
|
||||
}
|
||||
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
|
||||
}
|
||||
// user is ok now create invoice
|
||||
// set wallet lnbits client
|
||||
|
||||
var resp *lnurl.LNURLPayResponse2
|
||||
var resp *lnurl.LNURLPayValues
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.metaData(username)
|
||||
descriptionHash, err := w.descriptionHash(metadata)
|
||||
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))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount / 1000,
|
||||
Amount: amount_msat / 1000,
|
||||
Out: false,
|
||||
DescriptionHash: descriptionHash,
|
||||
Webhook: w.WebhookServer},
|
||||
w.c)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
|
||||
resp = &lnurl.LNURLPayResponse2{
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Status: api.StatusError,
|
||||
Reason: "Couldn't create invoice."},
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
// save invoice struct for later use
|
||||
invoiceStruct := &telegram.Invoice{
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
Amount: amount_msat / 1000,
|
||||
}
|
||||
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
Invoice{
|
||||
ToUser: user,
|
||||
Amount: amount,
|
||||
Comment: comment,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
CreatedAt: time.Now(),
|
||||
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,
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([][]lnurl.RouteInfo, 0),
|
||||
Routes: make([]struct{}, 0),
|
||||
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return "", err
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
} else {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
}
|
||||
hash := sha256.Sum256([]byte(string(jsonMeta)))
|
||||
hashString := hex.EncodeToString(hash[:])
|
||||
return hashString, nil
|
||||
}
|
||||
|
||||
// metaData returns the metadata that is sent in the first response
|
||||
// and is used again in the second response to verify the description hash
|
||||
func (w Server) metaData(username string) lnurl.Metadata {
|
||||
func (w Lnurl) metaData(username string) lnurl.Metadata {
|
||||
// this is a bit stupid but if the address is a UUID starting with 1x...
|
||||
// we actually want to find the users username so it looks nicer in the
|
||||
// metadata description
|
||||
if strings.HasPrefix(username, "1x") {
|
||||
user, _ := findUser(w.database, username)
|
||||
if user.Telegram.Username != "" {
|
||||
username = user.Telegram.Username
|
||||
}
|
||||
}
|
||||
|
||||
return lnurl.Metadata{
|
||||
{"text/identifier", fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname())},
|
||||
{"text/plain", fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname())}}
|
||||
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
|
||||
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
|
||||
}
|
||||
}
|
||||
|
||||
// addImageMetaData add images an image to the LNURL metadata
|
||||
func addImageToMetaData(tb *tb.Bot, metadata *lnurl.Metadata, username string, user *tb.User) {
|
||||
metadata.Image.Ext = "jpeg"
|
||||
|
||||
// if the username is anonymous, add the bot's picture
|
||||
if isAnonUsername(username) {
|
||||
metadata.Image.Bytes = telegram.BotProfilePicture
|
||||
return
|
||||
}
|
||||
|
||||
// if the user has a profile picture, add it
|
||||
picture, err := telegram.DownloadProfilePicture(tb, user)
|
||||
if err != nil {
|
||||
log.Debugf("[LNURL] Couldn't download user %s's profile picture: %v", username, err)
|
||||
// in case the user has no image, use bot's picture
|
||||
metadata.Image.Bytes = telegram.BotProfilePicture
|
||||
return
|
||||
}
|
||||
metadata.Image.Bytes = picture
|
||||
}
|
||||
|
||||
func isAnonUsername(username string) bool {
|
||||
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
|
||||
return true
|
||||
} else {
|
||||
return strings.HasPrefix(username, "0x")
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if payer.Email != "" {
|
||||
return payer.Email
|
||||
}
|
||||
if payer.FreeName != "" {
|
||||
return payer.FreeName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *telegram.TipBot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
callbackHostname *url.URL
|
||||
buntdb *storage.DB
|
||||
WebhookServer string
|
||||
}
|
||||
|
||||
const (
|
||||
statusError = "ERROR"
|
||||
statusOk = "OK"
|
||||
payRequestTag = "payRequest"
|
||||
lnurlEndpoint = ".well-known/lnurlp"
|
||||
minSendable = 1000 // mSat
|
||||
MaxSendable = 1_000_000_000
|
||||
CommentAllowed = 500
|
||||
)
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Bot.LNURLServerUrl.Host,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
bot: bot,
|
||||
httpServer: srv,
|
||||
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
|
||||
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
|
||||
buntdb: bot.Bunt,
|
||||
}
|
||||
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/.well-known/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
return router
|
||||
}
|
||||
|
||||
func NotFoundHandler(writer http.ResponseWriter, err error) {
|
||||
log.Errorln(err)
|
||||
// return 404 on any error
|
||||
http.Error(writer, "404 page not found", http.StatusNotFound)
|
||||
}
|
||||
|
||||
func writeResponse(writer http.ResponseWriter, response interface{}) error {
|
||||
jsonResponse, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(jsonResponse)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type ClientType string
|
||||
|
||||
const (
|
||||
ClientTypeClearNet = "clearnet"
|
||||
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,
|
||||
}
|
||||
var cfg *internal.SocksConfiguration
|
||||
switch clientType {
|
||||
case ClientTypeClearNet:
|
||||
cfg = internal.Configuration.Bot.SocksProxy
|
||||
case ClientTypeTor:
|
||||
cfg = internal.Configuration.Bot.TorProxy
|
||||
default:
|
||||
return nil, fmt.Errorf("[GetClient] invalid clientType")
|
||||
}
|
||||
if cfg == nil {
|
||||
return &client, nil
|
||||
}
|
||||
proxyURL, _ := url.Parse(cfg.Host)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
var auth *proxy.Auth
|
||||
if cfg.Username != "" && cfg.Password != "" {
|
||||
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
|
||||
}
|
||||
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return &client, nil
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
client.Transport = specialTransport
|
||||
return &client, nil
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package price
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -63,7 +62,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
for currency, _ := range p.Currencies {
|
||||
avg_price := 0.0
|
||||
n_responses := 0
|
||||
for exchange, getPrice := range p.Exchanges {
|
||||
for _, getPrice := range p.Exchanges {
|
||||
fprice, err := getPrice(currency)
|
||||
if err != nil {
|
||||
// log.Debug(err)
|
||||
@@ -72,11 +71,11 @@ func (p *PriceWatcher) Watch() error {
|
||||
}
|
||||
n_responses++
|
||||
avg_price += fprice
|
||||
log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
time.Sleep(time.Second * time.Duration(2))
|
||||
}
|
||||
Price[currency] = avg_price / float64(n_responses)
|
||||
log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
}
|
||||
time.Sleep(p.UpdateInterval)
|
||||
}
|
||||
@@ -85,7 +84,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
|
||||
coinbaseEndpoint, err := url.Parse(fmt.Sprintf("https://api.coinbase.com/v2/prices/spot?currency=%s", currency))
|
||||
response, err := p.client.Get(coinbaseEndpoint.String())
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
@@ -111,7 +110,7 @@ func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
|
||||
pair := bitfinexCurrencyToPair[currency]
|
||||
bitfinexEndpoint, err := url.Parse(fmt.Sprintf("https://api.bitfinex.com/v1/pubticker/%s", pair))
|
||||
response, err := p.client.Get(bitfinexEndpoint.String())
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// Limiter
|
||||
type Limiter struct {
|
||||
keys map[string]*rate.Limiter
|
||||
mu *sync.RWMutex
|
||||
r rate.Limit
|
||||
b int
|
||||
}
|
||||
|
||||
var idLimiter *Limiter
|
||||
var globalLimiter *rate.Limiter
|
||||
|
||||
// NewLimiter creates both chat and global rate limiters.
|
||||
func Start() {
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
|
||||
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
|
||||
}
|
||||
|
||||
// NewRateLimiter .
|
||||
func newIdRateLimiter(r rate.Limit, b int) *Limiter {
|
||||
i := &Limiter{
|
||||
keys: make(map[string]*rate.Limiter),
|
||||
mu: &sync.RWMutex{},
|
||||
r: r,
|
||||
b: b,
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func CheckLimit(to interface{}) {
|
||||
globalLimiter.Wait(context.Background())
|
||||
var id string
|
||||
switch to.(type) {
|
||||
case string:
|
||||
id = to.(string)
|
||||
case *tb.Chat:
|
||||
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
|
||||
case *tb.User:
|
||||
id = strconv.FormatInt(to.(*tb.User).ID, 10)
|
||||
case tb.Recipient:
|
||||
id = to.(tb.Recipient).Recipient()
|
||||
case *tb.Message:
|
||||
if to.(*tb.Message).Chat != nil {
|
||||
id = strconv.FormatInt(to.(*tb.Message).Chat.ID, 10)
|
||||
}
|
||||
}
|
||||
if len(id) > 0 {
|
||||
log.Tracef("[Check Limit] limiter for %+v", id)
|
||||
idLimiter.GetLimiter(id).Wait(context.Background())
|
||||
return
|
||||
}
|
||||
log.Tracef("[Check Limit] skipping id limiter for %+v", to)
|
||||
}
|
||||
|
||||
// Add creates a new rate limiter and adds it to the keys map,
|
||||
// using the key
|
||||
func (i *Limiter) Add(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
|
||||
limiter := rate.NewLimiter(i.r, i.b)
|
||||
|
||||
i.keys[key] = limiter
|
||||
|
||||
return limiter
|
||||
}
|
||||
|
||||
// GetLimiter returns the rate limiter for the provided key if it exists.
|
||||
// Otherwise, calls Add to add key address to the map
|
||||
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
limiter, exists := i.keys[key]
|
||||
|
||||
if !exists {
|
||||
i.mu.Unlock()
|
||||
return i.Add(key)
|
||||
}
|
||||
|
||||
i.mu.Unlock()
|
||||
|
||||
return limiter
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
tickerMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
} else {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
t.Started = true
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package mutex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var mutexMap cmap.ConcurrentMap
|
||||
var mutexMapSync sync.Mutex
|
||||
|
||||
func init() {
|
||||
mutexMap = cmap.New()
|
||||
mutexMapSync = sync.Mutex{}
|
||||
}
|
||||
func IsEmpty() bool {
|
||||
return mutexMap.Count() == 0
|
||||
}
|
||||
|
||||
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock/{id} endpoint to mutex", len(mutexMap.Keys()), mutexMap.Keys())))
|
||||
}
|
||||
|
||||
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
if m, ok := mutexMap.Get(vars["id"]); ok {
|
||||
m.(*sync.Mutex).Unlock()
|
||||
w.Write([]byte(fmt.Sprintf("Unlocked mutex %s.\nCurrent number of locks: %d\nLocks: %+v",
|
||||
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(fmt.Sprintf("Mutex %s not found!", vars["id"])))
|
||||
}
|
||||
|
||||
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
|
||||
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
|
||||
// This happens if multiple handlers call each other and try to lock/unlock multiple times
|
||||
// the same mutex.
|
||||
func checkSoftLock(s string) int {
|
||||
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
|
||||
return v.(int)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
|
||||
// LockWithContext should be used to lock objects like faucets etc.
|
||||
// The context carries a uid that is unique the each request (message, button press, etc.).
|
||||
// If the uid has a lock already *for a certain object*, it increments the
|
||||
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
|
||||
func LockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
if len(uid) == 0 {
|
||||
log.Error("[Mutex] LockWithContext: uid is empty!")
|
||||
}
|
||||
if len(s) == 0 {
|
||||
log.Error("[Mutex] LockWithContext: s is empty!")
|
||||
}
|
||||
// sync mutex to sync checkSoftLock with the increment of nLocks
|
||||
// same user can't lock the same object multiple times
|
||||
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
var nLocks = checkSoftLock(uid)
|
||||
if nLocks == 0 {
|
||||
Lock(s)
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
|
||||
}
|
||||
nLocks++
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
}
|
||||
|
||||
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
|
||||
// If it has been locked more than once
|
||||
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
|
||||
// nLocks == 1
|
||||
func UnlockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
if len(uid) == 0 {
|
||||
log.Error("[Mutex] UnlockWithContext: uid is empty!")
|
||||
return
|
||||
}
|
||||
if len(s) == 0 {
|
||||
log.Error("[Mutex] UnlockWithContext: s is empty!")
|
||||
return
|
||||
}
|
||||
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
var nLocks = checkSoftLock(uid)
|
||||
nLocks--
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
if nLocks == 0 {
|
||||
Unlock(s)
|
||||
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
|
||||
}
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
}
|
||||
|
||||
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
|
||||
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
|
||||
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
|
||||
func Lock(s string) {
|
||||
log.Tracef("[Mutex] Attempt Lock %s", s)
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
m.(*sync.Mutex).Lock()
|
||||
// write into mutex map
|
||||
mutexMapSync.Lock()
|
||||
mutexMap.Set(s, m)
|
||||
mutexMapSync.Unlock()
|
||||
} else {
|
||||
m := &sync.Mutex{}
|
||||
m.Lock()
|
||||
// write into mutex map
|
||||
mutexMapSync.Lock()
|
||||
mutexMap.Set(s, m)
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
log.Tracef("[Mutex] Locked %s", s)
|
||||
}
|
||||
|
||||
// Unlock unlocks a mutex in the mutexMap.
|
||||
func Unlock(s string) {
|
||||
mutexMapSync.Lock()
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
mutexMap.Remove(s)
|
||||
m.(*sync.Mutex).Unlock()
|
||||
log.Tracef("[Mutex] Unlocked %s", s)
|
||||
} else {
|
||||
// this should never happen. Mutex should have been in the mutexMap.
|
||||
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
|
||||
}
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package once
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var onceMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
onceMap = cmap.New()
|
||||
}
|
||||
|
||||
func New(objectKey string) {
|
||||
onceMap.Set(objectKey, cmap.New())
|
||||
}
|
||||
|
||||
// Once creates a map of keys k1 with a map of keys k2.
|
||||
// The idea is that an object with ID k1 can create a list of users k2
|
||||
// that have already interacted with the object. If the user k2 is in the list,
|
||||
// the object is not allowed to accessed again.
|
||||
func Once(k1, k2 string) error {
|
||||
i, ok := onceMap.Get(k1)
|
||||
if ok {
|
||||
return setOrReturn(i.(cmap.ConcurrentMap), k2)
|
||||
}
|
||||
userMap := cmap.New()
|
||||
onceMap.Set(k1, userMap)
|
||||
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
return setOrReturn(userMap, k2)
|
||||
}
|
||||
|
||||
// setOrReturn sets the key k2 in the map i if it is not already set.
|
||||
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
|
||||
if _, ok := objectMap.Get(k2); ok {
|
||||
return fmt.Errorf("[Once] %s already consumed object", k2)
|
||||
}
|
||||
objectMap.Set(k2, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes the key k1 from the map. Should be called after Once was called and
|
||||
// the object k1 finished.
|
||||
func Remove(k1 string) {
|
||||
onceMap.Remove(k1)
|
||||
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// var retryMap cmap.ConcurrentMap
|
||||
|
||||
// func init() {
|
||||
// retryMap = cmap.New()
|
||||
// }
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type FunctionRetry struct {
|
||||
Ticker *time.Ticker
|
||||
duration time.Duration
|
||||
ctx context.Context
|
||||
name string
|
||||
}
|
||||
|
||||
type FunctionRetryOption func(*FunctionRetry)
|
||||
|
||||
func WithRetryDuration(d time.Duration) FunctionRetryOption {
|
||||
return func(a *FunctionRetry) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOption) *FunctionRetry {
|
||||
t := &FunctionRetry{
|
||||
name: name,
|
||||
ctx: ctx,
|
||||
}
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
case <-t.ctx.Done():
|
||||
if t.ctx.Err() == context.DeadlineExceeded {
|
||||
deadline_f()
|
||||
}
|
||||
if t.ctx.Err() == context.Canceled {
|
||||
cancel_f()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package satdress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Much of this is from github.com/fiatjaf/makeinvoice
|
||||
// but with added "checkInvoice" and http proxy support
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" gorm:"-"`
|
||||
CertString string `json:"certstring"`
|
||||
Host string `json:"host"`
|
||||
Macaroon string `json:"macaroon"`
|
||||
}
|
||||
|
||||
func (l LNDParams) getCert() []byte { return l.Cert }
|
||||
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
|
||||
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
|
||||
|
||||
type LNBitsParams struct {
|
||||
Cert string `json:"certstring"`
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
|
||||
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
|
||||
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
|
||||
|
||||
type BackendParams interface {
|
||||
getCert() []byte
|
||||
isTor() bool
|
||||
isLocal() bool
|
||||
}
|
||||
|
||||
type Params struct {
|
||||
Backend BackendParams
|
||||
Msatoshi int64
|
||||
Description string
|
||||
DescriptionHash []byte
|
||||
|
||||
Label string // only used for c-lightning
|
||||
}
|
||||
|
||||
type CheckInvoiceParams struct {
|
||||
Backend BackendParams
|
||||
PR string
|
||||
Hash []byte
|
||||
Status string
|
||||
}
|
||||
|
||||
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
|
||||
var client *http.Client
|
||||
if !useProxy {
|
||||
client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
client, err = network.GetClient(network.ClientTypeTor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
}
|
||||
// use a cert or skip TLS verification?
|
||||
if len(cert) > 0 {
|
||||
caCertPool := x509.NewCertPool()
|
||||
ok := caCertPool.AppendCertsFromPEM(cert)
|
||||
if !ok {
|
||||
return client, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// description hash?
|
||||
var hexh, b64h string
|
||||
if params.DescriptionHash != nil {
|
||||
hexh = hex.EncodeToString(params.DescriptionHash)
|
||||
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[MakeInvoice] LND invoice at %s", backend.Host)
|
||||
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
body, _ = sjson.Set(body, "memo", params.Description)
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "description_hash", b64h)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST",
|
||||
backend.Host+"/v1/invoices",
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// macaroon must be hex, so if it is on base64 we adjust that
|
||||
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
|
||||
backend.Macaroon = hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
checkInvoiceParams := CheckInvoiceParams{
|
||||
Backend: params.Backend,
|
||||
PR: gjson.ParseBytes(b).Get("payment_request").String(),
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[MakeInvoice] LNBits invoice at %s", backend.Host)
|
||||
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
|
||||
body, _ = sjson.Set(body, "out", false)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
if params.Description == "" {
|
||||
body, _ = sjson.Set(body, "memo", "invoice")
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "memo", params.Description)
|
||||
}
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "description_hash", hexh)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST",
|
||||
backend.Host+"/api/v1/payments",
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
checkInvoiceParams := CheckInvoiceParams{
|
||||
Backend: params.Backend,
|
||||
PR: gjson.ParseBytes(b).Get("payment_request").String(),
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("wrong backend type")
|
||||
}
|
||||
}
|
||||
|
||||
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[CheckInvoice] LND invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
|
||||
}
|
||||
hexHash := hex.EncodeToString(p)
|
||||
requestUrl, err := url.Parse(fmt.Sprintf("%s/v1/invoice/%s?r_hash=%s", backend.Host, hexHash, base64.StdEncoding.EncodeToString(params.Hash)))
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
requestUrl.Scheme = "https"
|
||||
req, err := http.NewRequest("GET",
|
||||
requestUrl.String(), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
// macaroon must be hex, so if it is on base64 we adjust that
|
||||
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
|
||||
backend.Macaroon = hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
params.Status = gjson.ParseBytes(b).Get("state").String()
|
||||
return params, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[CheckInvoice] LNBits invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
log.Debug("Getting ", backend.Host+"/api/v1/payments/"+string(params.Hash))
|
||||
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
text := string(body)
|
||||
if len(text) > 300 {
|
||||
text = text[:300]
|
||||
}
|
||||
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
status := strings.ToLower(gjson.ParseBytes(b).Get("paid").String())
|
||||
if status == "true" {
|
||||
params.Status = "SETTLED"
|
||||
} else {
|
||||
params.Status = "OPEN"
|
||||
}
|
||||
return params, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
Canceled bool `json:"canceled"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s Storable, db *DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt Inactivate] %s", tx.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
|
||||
cacheTx, err := transactionCache.Get(s.Key())
|
||||
if err != nil {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
log.Tracef("[Bunt] get object %s", s.Key())
|
||||
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
log.Tracef("[Bunt Cache] get object %s", s.Key())
|
||||
return cacheTx.(Storable), err
|
||||
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s Storable, db *DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
err := db.Set(s)
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt] could not set object: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt] set object %s", s.Key())
|
||||
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
|
||||
}
|
||||
log.Tracef("[Bunt Cache] set object: %s", s.Key())
|
||||
return err
|
||||
}
|
||||
|
||||
func (tx *Base) Delete(s Storable, db *DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
runtime.IgnoreError(transactionCache.Delete(s.Key()))
|
||||
return db.Delete(s.Key(), s)
|
||||
}
|
||||
+23
-15
@@ -2,7 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
)
|
||||
@@ -78,23 +78,31 @@ func (db *DB) Set(object Storable) error {
|
||||
}
|
||||
|
||||
// Delete a storable item.
|
||||
// todo -- not ascend users index
|
||||
func (db *DB) Delete(index string, object Storable) error {
|
||||
return db.Update(func(tx *buntdb.Tx) error {
|
||||
var delkeys []string
|
||||
runtime.IgnoreError(
|
||||
tx.Ascend(index, func(key, value string) bool {
|
||||
if key == object.Key() {
|
||||
delkeys = append(delkeys, key)
|
||||
}
|
||||
return true
|
||||
}),
|
||||
)
|
||||
for _, k := range delkeys {
|
||||
if _, err := tx.Delete(k); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Get(object.Key())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Delete(object.Key()); err != nil {
|
||||
return err
|
||||
}
|
||||
// OLD: from gohumble:
|
||||
// todo -- not ascend users index
|
||||
// var delkeys []string
|
||||
// runtime.IgnoreError(
|
||||
// tx.Ascend(index, func(key, value string) bool {
|
||||
// if key == object.Key() {
|
||||
// delkeys = append(delkeys, key)
|
||||
// }
|
||||
// return true
|
||||
// }),
|
||||
// )
|
||||
// for _, k := range delkeys {
|
||||
// if _, err := tx.Delete(k); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
package transaction
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
InTransaction bool `json:"intransaction"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
MessageID string `json:"messageid"`
|
||||
ChatID string `json:"chatid"`
|
||||
MessageURL string `json:"messageurl"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
InTransaction: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = true
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
// to avoid race conditions, we block the call if there is
|
||||
// already an active transaction by loop until InTransaction is false
|
||||
ticker := time.NewTicker(time.Second * 10)
|
||||
for tx.InTransaction {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
return nil, fmt.Errorf("transaction timeout")
|
||||
default:
|
||||
time.Sleep(time.Duration(500) * time.Millisecond)
|
||||
err = db.Get(s)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not get transaction")
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
return db.Set(s)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
)
|
||||
|
||||
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
@@ -38,3 +41,17 @@ 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
|
||||
}
|
||||
|
||||
@@ -3,45 +3,52 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", errors.New("message doesn't contain enough arguments")
|
||||
return "", fmt.Errorf("message doesn't contain enough arguments")
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int, err error) {
|
||||
func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, errors.New(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
}
|
||||
amount, err = getAmount(strings.Split(input, " ")[1])
|
||||
amount, err = GetAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int, err error) {
|
||||
// GetAmount parses an amount from a string like 1.2k or 3.50€
|
||||
// and returns the value in satoshis
|
||||
func GetAmount(input string) (amount int64, err error) {
|
||||
// convert something like 1.2k into 1200
|
||||
if strings.HasSuffix(strings.ToLower(input), "k") {
|
||||
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = int(fmount * 1000)
|
||||
amount = int64(fmount * 1000)
|
||||
return amount, err
|
||||
}
|
||||
|
||||
@@ -59,20 +66,20 @@ func getAmount(input string) (amount int, err error) {
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, errors.New("price is zero")
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
}
|
||||
amount = int(fmount / price.Price[currency] * float64(100_000_000))
|
||||
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
|
||||
return amount, nil
|
||||
}
|
||||
}
|
||||
|
||||
// use plain integer as satoshis
|
||||
amount, err = strconv.Atoi(input)
|
||||
amount, err = strconv.ParseInt(input, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if amount <= 0 {
|
||||
return 0, errors.New("amount must be greater than 0")
|
||||
return 0, fmt.Errorf("amount must be greater than 0")
|
||||
}
|
||||
return amount, err
|
||||
}
|
||||
@@ -98,16 +105,16 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
|
||||
AmountMax: amountMax,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayResponse1 in the state of the user
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
|
||||
askAmountText := Translate(ctx, "lnurlEnterAmountMessage")
|
||||
askAmountText := Translate(ctx, "enterAmountMessage")
|
||||
if amountMin > 0 && amountMax >= amountMin {
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "lnurlEnterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
}
|
||||
// Let the user enter an amount and return
|
||||
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
|
||||
@@ -117,15 +124,15 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
|
||||
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
|
||||
// the amount is then stored as an entry in the user's stateKey in the user database
|
||||
// any other handler that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterAmount) {
|
||||
ResetUserState(user, bot)
|
||||
return // errors.New("user state does not match"), 0
|
||||
return ctx, fmt.Errorf("invalid statekey")
|
||||
}
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
@@ -133,34 +140,36 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
amount, err := getAmount(m.Text)
|
||||
amount, err := GetAmount(ctx.Message().Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return //err, 0
|
||||
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 > int(EnterAmountStateData.AmountMax/1000) || amount < int(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterAmountStateData.Type {
|
||||
case "LnurlPayState":
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
LnurlPayState := sn.(*LnurlPayState)
|
||||
LnurlPayState.Amount = amount * 1000 // mSat
|
||||
@@ -171,35 +180,49 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
return bot.lnurlPayHandlerSend(ctx)
|
||||
case "LnurlWithdrawState":
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
LnurlWithdrawState := sn.(*LnurlWithdrawState)
|
||||
LnurlWithdrawState.Amount = amount * 1000 // mSat
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
return bot.lnurlWithdrawHandlerWithdraw(ctx)
|
||||
case "CreateInvoiceState":
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
ctx.Message().Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.invoiceHandler(ctx, m)
|
||||
return
|
||||
return bot.invoiceHandler(ctx)
|
||||
case "CreateDonationState":
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
ctx.Message().Text = fmt.Sprintf("/donate %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.donationHandler(ctx, m)
|
||||
return
|
||||
return bot.donationHandler(ctx)
|
||||
case "CreateSendState":
|
||||
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
|
||||
if len(splits) > 1 {
|
||||
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
ctx.Message().Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
return bot.sendHandler(ctx)
|
||||
}
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
// // reset database entry
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if len(m.Text) > 0 {
|
||||
bot.anyTextHandler(ctx)
|
||||
}
|
||||
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
@@ -20,23 +26,22 @@ func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
// first check whether the user is initialized
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
if !user.Initialized {
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
return bot.startHandler(ctx)
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
usrStr := GetUserStr(ctx.Sender())
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "balanceErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+70
-13
@@ -2,26 +2,33 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/eko/gocache/store"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
|
||||
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
DB *Databases
|
||||
Bunt *storage.DB
|
||||
logger *gorm.DB
|
||||
Telegram *telebot.Bot
|
||||
ShopBunt *storage.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
}
|
||||
type Cache struct {
|
||||
@@ -38,12 +45,13 @@ func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger := AutoMigration()
|
||||
dbs := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
Database: db,
|
||||
DB: dbs,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
logger: txLogger,
|
||||
Bunt: createBunt(),
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
}
|
||||
@@ -55,6 +63,7 @@ func newTelegramBot() *tb.Bot {
|
||||
Token: internal.Configuration.Telegram.ApiKey,
|
||||
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
|
||||
ParseMode: tb.ModeMarkdown,
|
||||
Verbose: false,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -75,14 +84,62 @@ func (bot TipBot) initBotWallet() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GracefulShutdown will gracefully shutdown the bot
|
||||
// It will wait for all mutex locks to unlock before shutdown.
|
||||
func (bot *TipBot) GracefulShutdown() {
|
||||
t := time.NewTicker(time.Second * 10)
|
||||
log.Infof("[shutdown] Graceful shutdown (timeout=10s).")
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
// timer expired
|
||||
log.Infof("[shutdown] Graceful shutdown timeout reached. Forcing shutdown.")
|
||||
return
|
||||
default:
|
||||
// check if all mutex locks are unlocked
|
||||
if mutex.IsEmpty() {
|
||||
log.Infof("[shutdown] Graceful shutdown successful.")
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
log.Tracef("[shutdown] Trying graceful shutdown...")
|
||||
}
|
||||
}
|
||||
|
||||
// Start will initialize the Telegram bot and lnbits.
|
||||
func (bot TipBot) Start() {
|
||||
func (bot *TipBot) Start() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
}
|
||||
|
||||
// register telegram handlers
|
||||
bot.registerTelegramHandlers()
|
||||
bot.Telegram.Start()
|
||||
|
||||
// download bot avatar once
|
||||
bot.downloadMyProfilePicture()
|
||||
|
||||
// edit worker collects messages to edit and
|
||||
// periodically edits them
|
||||
bot.startEditWorker()
|
||||
|
||||
// register callbacks for invoices
|
||||
initInvoiceEventCallbacks(bot)
|
||||
|
||||
// register callbacks for user state changes
|
||||
initializeStateCallbackMessage(bot)
|
||||
|
||||
// start the telegram bot
|
||||
go bot.Telegram.Start()
|
||||
|
||||
// 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
|
||||
signal.Notify(exit, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP)
|
||||
<-exit
|
||||
// gracefully shutdown
|
||||
bot.GracefulShutdown()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// 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 = "⤵️"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
MainMenuCommandSend = "⤴️"
|
||||
SendMenuCommandEnter = "👤 Enter"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
|
||||
btnWebAppMainMenu = mainMenu.Text(MainMenuCommandWebApp)
|
||||
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
|
||||
|
||||
sendToMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
sendToButtons = []tb.Btn{}
|
||||
btnSendMenuEnter = mainMenu.Text(SendMenuCommandEnter)
|
||||
)
|
||||
|
||||
func init() {
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
// buttonWrapper wrap buttons slice in rows of length i
|
||||
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
|
||||
buttonLength := len(buttons)
|
||||
rows := make([]tb.Row, 0)
|
||||
|
||||
if buttonLength > length {
|
||||
for i := 0; i < buttonLength; i = i + length {
|
||||
buttonRow := make([]tb.Btn, length)
|
||||
if i+length < buttonLength {
|
||||
buttonRow = buttons[i : i+length]
|
||||
} else {
|
||||
buttonRow = buttons[i:]
|
||||
}
|
||||
rows = append(rows, markup.Row(buttonRow...))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
rows = append(rows, markup.Row(buttons...))
|
||||
return rows
|
||||
}
|
||||
|
||||
// appendWebAppLinkToButton adds a WebApp object to a Button with the user's webapp page
|
||||
func (bot *TipBot) appendWebAppLinkToButton(btn *tb.Btn, user *lnbits.User) {
|
||||
var url string
|
||||
if len(user.Telegram.Username) > 0 {
|
||||
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.Telegram.Username)
|
||||
} else {
|
||||
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
|
||||
}
|
||||
if strings.HasPrefix(url, "https://") {
|
||||
// prevent adding a link if not https is used, otherwise
|
||||
// Telegram returns an error and does not show the keyboard
|
||||
btn.WebApp = &tb.WebAppInfo{Url: url}
|
||||
}
|
||||
}
|
||||
|
||||
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
|
||||
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
if user, err = getCachedUser(&tb.User{ID: to}, *bot); err != nil {
|
||||
user, err = GetLnbitsUser(&tb.User{ID: to}, *bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
updateCachedUser(user, *bot)
|
||||
}
|
||||
if user.Wallet != nil {
|
||||
amount, err := bot.GetUserBalanceCached(user)
|
||||
if err == nil {
|
||||
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
|
||||
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
}
|
||||
|
||||
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// makeContactsButtons will create a slice of buttons for the send menu
|
||||
// it will show the 5 most recently interacted contacts and one button to use a custom contact
|
||||
func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
|
||||
var records []Transaction
|
||||
|
||||
sendToButtons = []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))
|
||||
|
||||
// get all contacts and add them to the buttons
|
||||
for i, r := range records {
|
||||
log.Tracef("[makeContactsButtons] toNames[%d] = %s (id=%d)", i, r.ToUser, r.ID)
|
||||
sendToButtons = append(sendToButtons, tb.Btn{Text: r.ToUser})
|
||||
}
|
||||
|
||||
// add the "enter a username" button to the end
|
||||
sendToButtons = append(sendToButtons, tb.Btn{Text: SendMenuCommandEnter})
|
||||
sendToMenu.Reply(buttonWrapper(sendToButtons, sendToMenu, 3)...)
|
||||
return sendToButtons
|
||||
}
|
||||
|
||||
// appendMainMenu will check if to (recipient) ID is from private or group chat.
|
||||
// appendMainMenu is called in telegram.go every time a user receives a PM from the bot.
|
||||
// this function will only add a keyboard if this is a private chat and no force reply.
|
||||
func (bot *TipBot) appendMainMenu(to int64, recipient interface{}, options []interface{}) []interface{} {
|
||||
|
||||
// update the balance button
|
||||
if to > 0 {
|
||||
bot.mainMenuBalanceButtonUpdate(to)
|
||||
}
|
||||
|
||||
appendKeyboard := true
|
||||
for _, option := range options {
|
||||
if option == tb.ForceReply {
|
||||
appendKeyboard = false
|
||||
}
|
||||
switch option.(type) {
|
||||
case *tb.ReplyMarkup:
|
||||
appendKeyboard = false
|
||||
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
|
||||
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
|
||||
// options = append(options[:i], options[i+1:]...)
|
||||
//}
|
||||
}
|
||||
}
|
||||
// to > 0 is private chats
|
||||
if to > 0 && appendKeyboard {
|
||||
options = append(options, mainMenu)
|
||||
}
|
||||
return options
|
||||
}
|
||||
+134
-15
@@ -1,12 +1,20 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"github.com/eko/gocache/store"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
@@ -15,19 +23,25 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Databases struct {
|
||||
Users *gorm.DB
|
||||
Transactions *gorm.DB
|
||||
Groups *gorm.DB
|
||||
}
|
||||
|
||||
const (
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
|
||||
func createBunt() *storage.DB {
|
||||
func createBunt(file string) *storage.DB {
|
||||
// create bunt database
|
||||
bunt := storage.NewBunt(internal.Configuration.Database.BuntDbPath)
|
||||
bunt := storage.NewBunt(file)
|
||||
// create bunt database index for ascending (searching) TipTooltips
|
||||
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
|
||||
if err != nil {
|
||||
@@ -38,21 +52,47 @@ func createBunt() *storage.DB {
|
||||
|
||||
func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
var err error
|
||||
// anon_id migration (2021-11-01)
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id") {
|
||||
// first we need to auto migrate the user. This will create anon_id column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running ano_id database migrations ...")
|
||||
log.Info("Running anon_id database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdHash(db)
|
||||
err = database.MigrateAnonIdInt32Hash(db)
|
||||
}
|
||||
|
||||
// anon_id_sha256 migration (2022-01-01)
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id_sha256") {
|
||||
// first we need to auto migrate the user. This will create anon_id column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running anon_id_sha256 database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdSha265Hash(db)
|
||||
}
|
||||
|
||||
// uuid migration (2022-02-11)
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "uuid") {
|
||||
// first we need to auto migrate the user. This will create uuid column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running UUID database migrations ...")
|
||||
// run the migration on uuid
|
||||
err = database.MigrateUUIDSha265Hash(db)
|
||||
}
|
||||
|
||||
// todo -- add more database field migrations here in the future
|
||||
return err
|
||||
}
|
||||
|
||||
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
func AutoMigration() *Databases {
|
||||
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
@@ -66,7 +106,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
@@ -74,12 +114,30 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return orm, txLogger
|
||||
|
||||
groupsDb, err := gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
err = groupsDb.AutoMigrate(&Group{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return &Databases{
|
||||
Users: orm,
|
||||
Transactions: txLogger,
|
||||
Groups: groupsDb,
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
toUserDb := &lnbits.User{}
|
||||
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
// return error if username is too long
|
||||
if len(toUserStrWithoutAt) > 100 {
|
||||
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
|
||||
}
|
||||
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil {
|
||||
err := tx.Error
|
||||
if toUserDb.Wallet == nil {
|
||||
@@ -90,7 +148,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
|
||||
return toUserDb, nil
|
||||
}
|
||||
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
if us, err := bot.Cache.Get(user.Name); err == nil {
|
||||
return us.(*lnbits.User), nil
|
||||
}
|
||||
@@ -105,8 +163,8 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
// &tb.User{ID: toId, Username: username}
|
||||
// without updating the user in storage.
|
||||
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
tx := bot.Database.First(user)
|
||||
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)
|
||||
@@ -117,6 +175,21 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
tx := bot.DB.Users.Preload("Settings").First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetLnbitsUserWithSettings] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
user.Telegram = u
|
||||
return user, tx.Error
|
||||
}
|
||||
if user.Settings == nil {
|
||||
user.Settings = &lnbits.Settings{ID: user.ID}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetUser from Telegram user. Update the user if user information changed.
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
var user *lnbits.User
|
||||
@@ -149,16 +222,62 @@ func telegramUserChanged(apiUser, stateUser *tb.User) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
func debugStack() {
|
||||
stack := debug.Stack()
|
||||
go func() {
|
||||
hasher := sha1.New()
|
||||
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))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := fo.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
w := bufio.NewWriter(fo)
|
||||
if _, err := w.Write(stack); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = w.Flush(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
user.UpdatedAt = time.Now()
|
||||
tx := bot.Database.Save(user)
|
||||
|
||||
// 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)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
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.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
|
||||
+25
-15
@@ -8,11 +8,15 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
@@ -32,35 +36,36 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
m := ctx.Message()
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return
|
||||
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessage(user.Telegram, Translate(ctx, "donationProgressMessage"))
|
||||
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
@@ -72,10 +77,14 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
|
||||
// hotfix because the edit doesn't work!
|
||||
// todo: fix edit
|
||||
// bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
bot.tryDeleteMessage(msg)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "donationSuccess"))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -112,7 +121,8 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
m := ctx.Message()
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
arg, _ = getArgumentFromCommand(m.Text, 2)
|
||||
@@ -144,7 +154,7 @@ func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
|
||||
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(ctx, m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
bot.donationHandler(ctx)
|
||||
// returning nil here will abort the parent ctx (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var editStack cmap.ConcurrentMap
|
||||
|
||||
type edit struct {
|
||||
to tb.Editable
|
||||
key string
|
||||
what interface{}
|
||||
options []interface{}
|
||||
lastEdit time.Time
|
||||
edited bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
editStack = cmap.New()
|
||||
}
|
||||
|
||||
const resultTrueError = "telebot: result is True"
|
||||
const editSameStringError = "specified new message content and reply markup are exactly the same as a current content and reply markup of the message"
|
||||
const retryAfterError = "retry after"
|
||||
|
||||
// startEditWorker will loop through the editStack and run tryEditMessage on not edited messages.
|
||||
// if editFromStack is older than 5 seconds, editFromStack will be removed.
|
||||
func (bot TipBot) startEditWorker() {
|
||||
go func() {
|
||||
for {
|
||||
for _, k := range editStack.Keys() {
|
||||
if e, ok := editStack.Get(k); ok {
|
||||
editFromStack := e.(edit)
|
||||
if !editFromStack.edited {
|
||||
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
|
||||
if err != nil && strings.Contains(err.Error(), retryAfterError) {
|
||||
// ignore any other error than retry after
|
||||
log.Errorf("[startEditWorker] Edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
|
||||
|
||||
} else {
|
||||
if err != nil {
|
||||
log.Errorf("[startEditWorker] Ignoring edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
|
||||
}
|
||||
log.Tracef("[startEditWorker] message from stack edited %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
|
||||
editFromStack.lastEdit = time.Now()
|
||||
editFromStack.edited = true
|
||||
editStack.Set(k, editFromStack)
|
||||
}
|
||||
} else {
|
||||
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
|
||||
log.Tracef("[startEditWorker] removing message edit from stack %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
|
||||
editStack.Remove(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Millisecond * 1000)
|
||||
}
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
// tryEditStack will add the editable to the edit stack, if what (message) changed.
|
||||
func (bot TipBot) tryEditStack(to tb.Editable, key string, what interface{}, options ...interface{}) {
|
||||
sig, chat := to.MessageSig()
|
||||
log.Tracef("[tryEditStack] sig=%s, chat=%d, key=%s, what=%+v, options=%+v", sig, chat, key, what, options)
|
||||
// var sig = fmt.Sprintf("%s-%d", msgSig, chat)
|
||||
if e, ok := editStack.Get(key); ok {
|
||||
editFromStack := e.(edit)
|
||||
if editFromStack.what == what.(string) {
|
||||
log.Tracef("[tryEditStack] Message already in edit stack. Skipping")
|
||||
return
|
||||
}
|
||||
}
|
||||
e := edit{options: options, key: key, what: what, to: to}
|
||||
|
||||
editStack.Set(key, e)
|
||||
log.Tracef("[tryEditStack] Added message %s to edit stack. len(editStack)=%d", key, len(editStack.Keys()))
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineFaucetMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
|
||||
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
|
||||
)
|
||||
|
||||
type InlineFaucet struct {
|
||||
*storage.Base
|
||||
Message string `json:"inline_faucet_message"`
|
||||
Amount int64 `json:"inline_faucet_amount"`
|
||||
RemainingAmount int64 `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int64 `json:"inline_faucet_peruseramount"`
|
||||
From *lnbits.User `json:"inline_faucet_from"`
|
||||
To []*lnbits.User `json:"inline_faucet_to"`
|
||||
Memo string `json:"inline_faucet_memo"`
|
||||
NTotal int `json:"inline_faucet_ntotal"`
|
||||
NTaken int `json:"inline_faucet_ntaken"`
|
||||
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context.Context {
|
||||
if len(strings.Split(command, " ")) > 1 {
|
||||
c := strings.Split(command, " ")[0][1:] // cut the /
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
|
||||
amount, err := decodeAmountFromCommand(text)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodeAmountError, err)
|
||||
}
|
||||
peruserStr, err := getArgumentFromCommand(text, 2)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := GetAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 5 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := int(amount / perUserAmount)
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low", fromUserStr))
|
||||
}
|
||||
// // check for memo in command
|
||||
memo := GetMemoFromCommand(text, 3)
|
||||
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, GetUserStrMd(sender), amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("faucet:%s:%d", RandStringRunes(10), amount)
|
||||
|
||||
return &InlineFaucet{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
From: fromUser,
|
||||
Memo: memo,
|
||||
PerUserAmount: perUserAmount,
|
||||
NTotal: nTotal,
|
||||
NTaken: 0,
|
||||
RemainingAmount: amount,
|
||||
UserNeedsWallet: false,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}, nil
|
||||
|
||||
}
|
||||
func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, m.Text, m.Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
// log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
// log.Errorf(err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryFaucet(ctx intercept.Context) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, ctx.Query().Text, ctx.Query().Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
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
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
inlineFaucetMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline", id)
|
||||
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline", id)
|
||||
inlineFaucetMenu.Inline(
|
||||
inlineFaucetMenu.Row(
|
||||
acceptInlineFaucetButton,
|
||||
cancelInlineFaucetButton),
|
||||
)
|
||||
return inlineFaucetMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) faucetHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.anyTextHandler(ctx)
|
||||
if ctx.Message().Private() {
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
ctx.Context = bot.mapFaucetLanguage(ctx, ctx.Text())
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, ctx.Message(), false)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
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 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)
|
||||
}
|
||||
return ctx, inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineFaucet.Message,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultFaucetTitle"), inlineFaucet.Amount),
|
||||
Description: TranslateUser(ctx, "inlineResultFaucetDescription"),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[faucet] %s:%d created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.From.Telegram.ID, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(ctx.Query(), &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
from := inlineFaucet.From
|
||||
// failsafe for queued users
|
||||
if !inlineFaucet.Active {
|
||||
log.Tracef(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
// log faucet link if possible
|
||||
if c.Message != nil && c.Message.Chat != nil {
|
||||
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
|
||||
}
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
// check if to user has already taken from the faucet
|
||||
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)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
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)
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineFaucet.UserNeedsWallet = true
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("🚰 Faucet from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineFaucet.PerUserAmount, TransactionType("faucet"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
// bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "errorTryLaterMessage"))
|
||||
// if faucet fails, cancel it:
|
||||
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
|
||||
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
|
||||
// bot.cancelInlineFaucet(ctx, c, true) // cancel without ID check
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
|
||||
go func() {
|
||||
to_message := fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount)
|
||||
ctx.Context = context.WithValue(ctx, "callback_response", to_message)
|
||||
bot.trySendMessage(to.Telegram, to_message)
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
|
||||
}()
|
||||
|
||||
// build faucet message
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, GetUserStrMd(inlineFaucet.From.Telegram), inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
|
||||
memo := inlineFaucet.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineFaucet.Message = inlineFaucet.Message + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStr(bot.Telegram.Me))
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineFaucet.Message)
|
||||
|
||||
// update the message if the faucet still has some sats left after this tx
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
bot.tryEditStack(c, inlineFaucet.ID, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
}
|
||||
}
|
||||
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
|
||||
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
// faucet is depleted
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) (context.Context, error) {
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
faucet_cancelled_message := i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage")
|
||||
bot.tryEditStack(c, inlineFaucet.ID, faucet_cancelled_message, &tb.ReplyMarkup{})
|
||||
ctx = context.WithValue(ctx, "callback_response", faucet_cancelled_message)
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.Canceled = true
|
||||
err = inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *InlineFaucet) {
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditStack(c, inlineFaucet.ID, inlineFaucet.Message, &tb.ReplyMarkup{})
|
||||
|
||||
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
// send update to faucet creator
|
||||
if inlineFaucet.Active && inlineFaucet.From.Telegram.ID != 0 {
|
||||
bot.trySendMessage(inlineFaucet.From.Telegram, listFaucetTakers(inlineFaucet))
|
||||
}
|
||||
inlineFaucet.Active = false
|
||||
}
|
||||
|
||||
func listFaucetTakers(inlineFaucet *InlineFaucet) string {
|
||||
var to_str string
|
||||
to_str = fmt.Sprintf("🚰 *Faucet summary*\n\nMemo: %s\nCapacity: %d sat\nTakers: %d\nRemaining: %d sat\n\n*Takers:*\n\n", inlineFaucet.Memo, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.RemainingAmount)
|
||||
to_str += "```\n"
|
||||
for _, to := range inlineFaucet.To {
|
||||
to_str += fmt.Sprintf("%s\n", GetUserStr(to.Telegram))
|
||||
}
|
||||
to_str += "```"
|
||||
return to_str
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
var err error
|
||||
ctx.Context, err = bot.cancelInlineFaucet(ctx, ctx.Callback(), false)
|
||||
return ctx, err
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found ctx for this state
|
||||
// now looking for user state reset ticker
|
||||
ticker := runtime.GetTicker(user.ID)
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
ResetUserState(user, bot)
|
||||
// removing ticker asap done
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
runtime.RemoveTicker(user.ID)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
|
||||
return c(ctx)
|
||||
}
|
||||
return ctx, errors.Create(errors.NoFileFoundError)
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// generateImages is called when the user enters /generate or /generate <prompt>
|
||||
// asks the user for a prompt if not given
|
||||
func (bot *TipBot) generateImages(ctx intercept.Context) (intercept.Context, error) {
|
||||
if !dalle.Enabled {
|
||||
bot.trySendMessage(ctx.Message().Sender, "🤖💤 Dalle image generation is currently not available. Please try again later.")
|
||||
return ctx, nil
|
||||
}
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
|
||||
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
SetUserState(user, bot, lnbits.UserEnterDallePrompt, "")
|
||||
bot.trySendMessage(ctx.Message().Sender, "⌨️ Enter image prompt.", tb.ForceReply)
|
||||
return ctx, nil
|
||||
}
|
||||
// write the prompt into the command and call confirm
|
||||
m := ctx.Message()
|
||||
m.Text = GetMemoFromCommand(m.Text, 1)
|
||||
return bot.confirmGenerateImages(ctx)
|
||||
}
|
||||
|
||||
// confirmGenerateImages is called when the user has entered a prompt through /generate <prompt>
|
||||
// or because he answered to the request to enter it in generateImages()
|
||||
// confirmGenerateImages will create an invoice that the user can pay and if they pay
|
||||
// generateDalleImages will fetch the images and send it to the user
|
||||
func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
|
||||
ResetUserState(user, bot)
|
||||
m := ctx.Message()
|
||||
prompt := m.Text
|
||||
if len(prompt) == 0 {
|
||||
return ctx, fmt.Errorf("prompt not given")
|
||||
}
|
||||
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), InvoiceCallbackGenerateDalle, prompt)
|
||||
invoice.Payer = user
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "generateDallePayInvoiceMessage"))
|
||||
|
||||
// invoke internal pay if enough balance
|
||||
if balance >= internal.Configuration.Generate.DallePrice {
|
||||
m.Text = fmt.Sprintf("/pay %s", invoice.PaymentRequest)
|
||||
return bot.payHandler(ctx)
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(invoice.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
msg := bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
invoice.InvoiceMessage = msg
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
var jobChan chan func(workerId int)
|
||||
var workers = internal.Configuration.Generate.Worker
|
||||
|
||||
func init() {
|
||||
if workers == 0 {
|
||||
log.Printf("Dalle is disabled. No worker started.")
|
||||
return
|
||||
}
|
||||
log.Printf("Starting Dalle image generation. Worker: %d, Price: %d sat", workers, internal.Configuration.Generate.DallePrice)
|
||||
jobChan = make(chan func(workerId int), workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
go worker(jobChan, i)
|
||||
}
|
||||
}
|
||||
func worker(linkChan chan func(workerId int), workerId int) {
|
||||
for generatePrompt := range linkChan {
|
||||
generatePrompt(workerId)
|
||||
}
|
||||
}
|
||||
|
||||
// generateDalleImages is called by the invoice event when the user has paid
|
||||
func (bot *TipBot) generateDalleImages(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
user := invoiceEvent.Payer
|
||||
if user == nil || user.Wallet == nil {
|
||||
log.Errorf("[generateDalleImages] invalid user")
|
||||
return
|
||||
}
|
||||
bot.trySendMessage(user.Telegram, "🔄 Your images are being generated. Please wait a few moments.")
|
||||
var job = func(workerId int) {
|
||||
// create the client with the bearer token api key
|
||||
dalleClient, err := dalle.NewHTTPClient(internal.Configuration.Generate.DalleKey)
|
||||
// handle err
|
||||
if err != nil {
|
||||
log.Errorf("[NewHTTPClient-%d] %v", workerId, err.Error())
|
||||
bot.dalleRefundUser(user, "")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*15)
|
||||
defer cancel()
|
||||
// generate a task to create an image with a prompt
|
||||
task, err := dalleClient.Generate(ctx, invoiceEvent.CallbackData)
|
||||
if err != nil {
|
||||
log.Errorf("[Generate-%d] %v", workerId, err.Error())
|
||||
bot.dalleRefundUser(user, "")
|
||||
return
|
||||
}
|
||||
// poll the task.ID until status is succeeded
|
||||
var t *dalle.Task
|
||||
timeout := time.After(10 * time.Minute)
|
||||
ticker := time.Tick(5 * time.Second)
|
||||
// Keep trying until we're timed out or get a result/error
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
bot.dalleRefundUser(user, "")
|
||||
log.Errorf("[DALLE-%d] ctx done. Task %s", workerId, task.ID)
|
||||
return
|
||||
// Got a timeout! fail with a timeout error
|
||||
case <-timeout:
|
||||
bot.dalleRefundUser(user, "Timeout. Please try again later.")
|
||||
log.Errorf("[DALLE-%d] timeout. Task: %s", workerId, task.ID)
|
||||
return
|
||||
// Got a tick, we should check on checkSomething()
|
||||
case <-ticker:
|
||||
t, err = dalleClient.GetTask(ctx, task.ID)
|
||||
// handle err
|
||||
if err != nil {
|
||||
log.Errorf("[GetTask-%d] Task: %s. Error: %v", workerId, task.ID, err.Error())
|
||||
//bot.dalleRefundUser(user, "")
|
||||
continue
|
||||
}
|
||||
if t.Status == dalle.StatusSucceeded {
|
||||
log.Printf("[DALLE-%d] 🎆 task succeeded for user %s", workerId, GetUserStr(user.Telegram))
|
||||
// download the first generated image
|
||||
for _, data := range t.Generations.Data {
|
||||
err = bot.downloadAndSendImages(ctx, dalleClient, data, invoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[downloadAndSendImages-%d] Id: %s. Error: %v", workerId, data.ID, err.Error())
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
} else if t.Status == dalle.StatusRejected {
|
||||
log.Errorf("[DALLE-%d] rejected: %s", workerId, t.ID)
|
||||
bot.dalleRefundUser(user, "Your prompt has been rejected by OpenAI. Do not use celebrity names, sexual expressions, or any other harmful content as prompt.")
|
||||
return
|
||||
}
|
||||
log.Debugf("[DALLE-%d] pending for user %s", workerId, GetUserStr(user.Telegram))
|
||||
}
|
||||
}
|
||||
}
|
||||
jobChan <- job
|
||||
}
|
||||
|
||||
// downloadAndSendImages will download dalle images and send them to the payer.
|
||||
func (bot *TipBot) downloadAndSendImages(ctx context.Context, dalleClient dalle.Client, data dalle.GenerationData, event *InvoiceEvent) error {
|
||||
reader, err := dalleClient.Download(ctx, data.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
image := "data/dalle/" + data.ID + ".png"
|
||||
file, err := os.Create(image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
_, err = io.Copy(file, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(image, 0, os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
bot.trySendMessage(event.Payer.Telegram, &tb.Photo{File: tb.File{FileReader: f}})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
|
||||
if user.Wallet == nil {
|
||||
return fmt.Errorf("user has no wallet")
|
||||
}
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create invioce for user
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(internal.Configuration.Generate.DallePrice),
|
||||
Memo: fmt.Sprintf("Refund DALLE2 %s", GetUserStr(user.Telegram)),
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// pay invoice
|
||||
_, err = me.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return err
|
||||
}
|
||||
log.Warnf("[DALLE] refunding user %s with %d sat", GetUserStr(user.Telegram), internal.Configuration.Generate.DallePrice)
|
||||
|
||||
var err_reason string
|
||||
if len(message) > 0 {
|
||||
err_reason = message
|
||||
} else {
|
||||
err_reason = "Something went wrong."
|
||||
}
|
||||
bot.trySendMessage(user.Telegram, fmt.Sprintf("🚫 %s You have been refunded.", err_reason))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Ticket struct {
|
||||
Price int64 `json:"price"`
|
||||
Memo string `json:"memo"`
|
||||
Creator *lnbits.User `gorm:"embedded;embeddedPrefix:creator_"`
|
||||
Cut int64 `json:"cut"` // Percent to cut from ticket price
|
||||
BaseFee int64 `json:"base_fee"`
|
||||
CutCheap int64 `json:"cut_cheap"` // Percent to cut from ticket price
|
||||
BaseFeeCheap int64 `json:"base_fee_cheap"`
|
||||
}
|
||||
type Group struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
ID int64 `json:"id" gorm:"primaryKey"`
|
||||
Owner *tb.User `gorm:"embedded;embeddedPrefix:owner_"`
|
||||
// Chat *tb.Chat `gorm:"embedded;embeddedPrefix:chat_"`
|
||||
Ticket *Ticket `gorm:"embedded;embeddedPrefix:ticket_"`
|
||||
}
|
||||
type CreateChatInviteLink struct {
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Name string `json:"name"`
|
||||
ExpiryDate int `json:"expiry_date"`
|
||||
MemberLimit int `json:"member_limit"`
|
||||
CreatesJoinRequest bool `json:"creates_join_request"`
|
||||
}
|
||||
type Creator struct {
|
||||
ID int64 `json:"id"`
|
||||
IsBot bool `json:"is_bot"`
|
||||
Firstname string `json:"first_name"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
type Result struct {
|
||||
InviteLink string `json:"invite_link"`
|
||||
Name string `json:"name"`
|
||||
Creator Creator `json:"creator"`
|
||||
CreatesJoinRequest bool `json:"creates_join_request"`
|
||||
IsPrimary bool `json:"is_primary"`
|
||||
IsRevoked bool `json:"is_revoked"`
|
||||
}
|
||||
type ChatInviteLink struct {
|
||||
Ok bool `json:"ok"`
|
||||
Result Result `json:"result"`
|
||||
}
|
||||
|
||||
type TicketEvent struct {
|
||||
*storage.Base
|
||||
*InvoiceEvent
|
||||
Group *Group `gorm:"embedded;embeddedPrefix:group_"`
|
||||
}
|
||||
|
||||
func (ticketEvent TicketEvent) Type() EventType {
|
||||
return EventTypeTicketInvoice
|
||||
}
|
||||
func (ticketEvent TicketEvent) Key() string {
|
||||
return ticketEvent.Base.ID
|
||||
}
|
||||
|
||||
var (
|
||||
ticketPayConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnPayTicket = paymentConfirmationMenu.Data("✅ Pay", "pay_ticket")
|
||||
)
|
||||
|
||||
var (
|
||||
groupInvoiceMemo = "🎟 Ticket for group %s"
|
||||
)
|
||||
|
||||
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
|
||||
// handler to call depending on the <cmd> passed.
|
||||
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
user := LoadUser(ctx)
|
||||
if len(splits) == 1 {
|
||||
if ctx.Message().Private() {
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "groupHelpMessage"), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me)))
|
||||
} else {
|
||||
if bot.isOwner(ctx.Message().Chat, user.Telegram) {
|
||||
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
} else if len(splits) > 1 {
|
||||
if splits[1] == "join" {
|
||||
return bot.groupRequestJoinHandler(ctx)
|
||||
}
|
||||
if splits[1] == "add" {
|
||||
return bot.addGroupHandler(ctx)
|
||||
}
|
||||
if splits[1] == "remove" {
|
||||
// todo -- implement this
|
||||
// return bot.addGroupHandler(ctx, m)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupRequestJoinHandler sends a payment request to the user who wants to join a group
|
||||
func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
// // reply only in private message
|
||||
if ctx.Chat().Type != tb.ChatPrivate {
|
||||
return ctx, fmt.Errorf("not private chat")
|
||||
}
|
||||
splits := strings.Split(ctx.Message().Text, " ")
|
||||
// if the command was /group join
|
||||
splitIdx := 1
|
||||
// we also have the simpler command /join that can be used
|
||||
// also by users who don't have an account with the bot yet
|
||||
if splits[0] == "/join" {
|
||||
splitIdx = 0
|
||||
}
|
||||
if len(splits) != splitIdx+2 || len(ctx.Message().Text) > 100 {
|
||||
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupJoinGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strings.ToLower(splits[splitIdx+1])
|
||||
|
||||
group := &Group{}
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error != nil {
|
||||
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupNotFoundMessage"))
|
||||
return ctx, fmt.Errorf("group not found")
|
||||
}
|
||||
|
||||
// create tickets
|
||||
id := fmt.Sprintf("ticket:%d", group.ID)
|
||||
invoiceEvent := &InvoiceEvent{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
User: group.Ticket.Creator,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
Payer: user,
|
||||
Chat: &tb.Chat{ID: group.ID},
|
||||
CallbackData: id,
|
||||
}
|
||||
ticketEvent := &TicketEvent{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
InvoiceEvent: invoiceEvent,
|
||||
Group: group,
|
||||
}
|
||||
// if no price is set, then we don't need to pay
|
||||
if group.Ticket.Price == 0 {
|
||||
// save ticketevent for later
|
||||
runtime.IgnoreError(ticketEvent.Set(ticketEvent, bot.Bunt))
|
||||
bot.groupGetInviteLinkHandler(invoiceEvent)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// create an invoice
|
||||
memo := fmt.Sprintf(groupInvoiceMemo, groupName)
|
||||
var err error
|
||||
invoiceEvent, err = bot.createGroupTicketInvoice(ctx, user, group, memo, InvoiceCallbackGroupTicket, id)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
ticketEvent.InvoiceEvent = invoiceEvent
|
||||
// save ticketevent for later
|
||||
defer ticketEvent.Set(ticketEvent, bot.Bunt)
|
||||
|
||||
// // 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)
|
||||
}
|
||||
if balance >= group.Ticket.Price {
|
||||
return bot.groupSendPayButtonHandler(ctx, *ticketEvent)
|
||||
}
|
||||
|
||||
// otherwise we send a payment request
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoiceEvent.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
ticketEvent.Message = bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoiceEvent.PaymentRequest)})
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "groupPayInvoiceMessage"), groupName))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
|
||||
// pay button is sent to the user.
|
||||
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
|
||||
// object that holds all information about the send payment
|
||||
// // // create inline buttons
|
||||
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
|
||||
ticketPayConfirmationMenu.Inline(
|
||||
ticketPayConfirmationMenu.Row(
|
||||
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))
|
||||
}
|
||||
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, ticketPayConfirmationMenu)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
|
||||
func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &TicketEvent{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[groupConfirmPayButtonHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
ticketEvent := sn.(*TicketEvent)
|
||||
|
||||
// onnly the correct user can press
|
||||
if ticketEvent.Payer.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !ticketEvent.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer ticketEvent.Set(ticketEvent, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c)
|
||||
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)
|
||||
// // 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)
|
||||
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// update the message and remove the button
|
||||
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// groupGetInviteLinkHandler is called when the invoice is paid and sends a one-time group invite link to the payer
|
||||
func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
// take a cut
|
||||
// amount_bot := int64(ticketEvent.Group.Ticket.Price * int64(ticketEvent.Group.Ticket.Cut) / 100)
|
||||
|
||||
log.Infof(invoiceEvent.CallbackData)
|
||||
ticketEvent := &TicketEvent{Base: storage.New(storage.ID(invoiceEvent.CallbackData))}
|
||||
err := bot.Bunt.Get(ticketEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[groupGetInviteLinkHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[groupGetInviteLinkHandler] group: %d", ticketEvent.Chat.ID)
|
||||
params := map[string]interface {
|
||||
}{
|
||||
"chat_id": ticketEvent.Group.ID, // must be the chat ID of the group
|
||||
"name": fmt.Sprintf("%s link for %s", GetUserStr(bot.Telegram.Me), GetUserStr(ticketEvent.Payer.Telegram)), // the name of the invite link
|
||||
"member_limit": 1, // only one user can join with this link
|
||||
// "expire_date": time.Now().AddDate(0, 0, 1), // expiry date of the invite link, add one day
|
||||
// "creates_join_request": false, // True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified
|
||||
}
|
||||
data, err := bot.Telegram.Raw("createChatInviteLink", params)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var resp ChatInviteLink
|
||||
if err := json.Unmarshal(data, &resp); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ticketEvent.Message != nil {
|
||||
bot.tryDeleteMessage(ticketEvent.Message)
|
||||
// do balance check for keyboard update
|
||||
_, err = bot.GetUserBalance(ticketEvent.Payer)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidText"))
|
||||
}
|
||||
|
||||
// send confirmation text with the ticket to the user
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
|
||||
|
||||
// send a notification to the group that sold the ticket
|
||||
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
|
||||
// take a commission
|
||||
ticketSat := ticketEvent.Group.Ticket.Price
|
||||
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{
|
||||
Out: false,
|
||||
Amount: commissionSat,
|
||||
Memo: "🎟 Ticket commission for group " + ticketEvent.Group.Title,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
_, err = ticketEvent.User.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[groupGetInviteLinkHandler] Could not pay commission of %s: %s", GetUserStr(ticketEvent.User.Telegram), err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
// do balance check for keyboard update
|
||||
_, err = bot.GetUserBalance(ticketEvent.User)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
} else {
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
}
|
||||
}
|
||||
|
||||
// addGroupHandler is invoked if the user calls the "/group add" command
|
||||
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type == tb.ChatPrivate {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, fmt.Errorf("not in group")
|
||||
}
|
||||
// parse command "/group add <grou_name> [<amount>]"
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) < 3 || len(m.Text) > 100 {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strings.ToLower(splits[2])
|
||||
|
||||
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("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error == nil {
|
||||
// if it is already added, check if this user is the admin
|
||||
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
}
|
||||
|
||||
amount := int64(0) // default amount is zero
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 3); 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, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// createGroupTicketInvoice produces an invoice for the group ticket with a
|
||||
// callback that then calls groupGetInviteLinkHandler upton payment
|
||||
func (bot *TipBot) createGroupTicketInvoice(ctx context.Context, payer *lnbits.User, group *Group, memo string, callback int, callbackData string) (*InvoiceEvent, error) {
|
||||
invoice, err := group.Ticket.Creator.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: group.Ticket.Price,
|
||||
Memo: memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return &InvoiceEvent{}, err
|
||||
}
|
||||
|
||||
// save the invoice event
|
||||
id := fmt.Sprintf("invoice:%s", invoice.PaymentHash)
|
||||
invoiceEvent := &InvoiceEvent{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: group.Ticket.Price,
|
||||
Memo: memo},
|
||||
User: group.Ticket.Creator,
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
Payer: payer,
|
||||
Chat: &tb.Chat{ID: group.ID},
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(invoiceEvent.Set(invoiceEvent, bot.Bunt))
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
+1009
-120
File diff suppressed because it is too large
Load Diff
+24
-22
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
@@ -26,26 +28,26 @@ func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) helpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), bot.makeHelpMessage(ctx, ctx.Message()), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) basicsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
}
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
@@ -59,11 +61,11 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
|
||||
// we print the anonymous ln address in the advanced help
|
||||
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous Lightning address: `%s`\n", lnaddr)
|
||||
}
|
||||
lnurl, err := UserGetLNURL(fromUser)
|
||||
lnurl, err := UserGetAnonLNURL(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
|
||||
}
|
||||
|
||||
// this is so stupid:
|
||||
@@ -74,13 +76,13 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
|
||||
)
|
||||
}
|
||||
|
||||
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot TipBot) advancedHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), bot.makeAdvancedHelpMessage(ctx, ctx.Message()), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func GetMemoFromCommand(command string, fromWord int) string {
|
||||
return memo
|
||||
}
|
||||
|
||||
func MakeProgressbar(current int, total int) string {
|
||||
func MakeProgressbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🟩", int(progress))
|
||||
@@ -42,7 +42,7 @@ func MakeProgressbar(current int, total int) string {
|
||||
return progressbar
|
||||
}
|
||||
|
||||
func MakeTipjarbar(current int, total int) string {
|
||||
func MakeTipjarbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🍯", int(progress))
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
|
||||
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
|
||||
)
|
||||
|
||||
type InlineFaucet struct {
|
||||
*transaction.Base
|
||||
Message string `json:"inline_faucet_message"`
|
||||
Amount int `json:"inline_faucet_amount"`
|
||||
RemainingAmount int `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int `json:"inline_faucet_peruseramount"`
|
||||
From *lnbits.User `json:"inline_faucet_from"`
|
||||
To []*lnbits.User `json:"inline_faucet_to"`
|
||||
Memo string `json:"inline_faucet_memo"`
|
||||
NTotal int `json:"inline_faucet_ntotal"`
|
||||
NTaken int `json:"inline_faucet_ntaken"`
|
||||
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context.Context {
|
||||
if len(strings.Split(command, " ")) > 1 {
|
||||
c := strings.Split(command, " ")[0][1:] // cut the /
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
|
||||
amount, err := decodeAmountFromCommand(text)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodeAmountError, err)
|
||||
}
|
||||
peruserStr, err := getArgumentFromCommand(text, 2)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := amount / perUserAmount
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low: %v", fromUserStr, err))
|
||||
}
|
||||
// // check for memo in command
|
||||
memo := GetMemoFromCommand(text, 3)
|
||||
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineFaucet{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
From: fromUser,
|
||||
Memo: memo,
|
||||
PerUserAmount: perUserAmount,
|
||||
NTotal: nTotal,
|
||||
NTaken: 0,
|
||||
RemainingAmount: amount,
|
||||
UserNeedsWallet: false,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}, nil
|
||||
|
||||
}
|
||||
func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, m.Text, m.Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
// log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
// log.Errorf(err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
// inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline")
|
||||
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline")
|
||||
acceptInlineFaucetButton.Data = id
|
||||
cancelInlineFaucetButton.Data = id
|
||||
inlineFaucetMenu.Inline(
|
||||
inlineFaucetMenu.Row(
|
||||
acceptInlineFaucetButton,
|
||||
cancelInlineFaucetButton),
|
||||
)
|
||||
return inlineFaucetMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
|
||||
return
|
||||
}
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
faucetMsg := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
|
||||
inlineFaucet.Base.MessageID = fmt.Sprint(faucetMsg.ID)
|
||||
inlineFaucet.Base.ChatID = fmt.Sprint(-faucetMsg.Chat.ID)
|
||||
inlineFaucet.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineFaucet.ChatID[3:], inlineFaucet.Base.MessageID)
|
||||
|
||||
bot.trySendMessage(m.Chat, inlineFaucet.Base.MessageURL)
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineFaucet.Message,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultFaucetTitle"), inlineFaucet.Amount),
|
||||
Description: TranslateUser(ctx, "inlineResultFaucetDescription"),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
from := inlineFaucet.From
|
||||
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
|
||||
return
|
||||
}
|
||||
if !inlineFaucet.Active {
|
||||
log.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
|
||||
return
|
||||
}
|
||||
// release faucet no matter what
|
||||
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
// check if to user has already taken from the faucet
|
||||
for _, a := range inlineFaucet.To {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
// log.Infof("[faucet] %s already took from faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
log.Infof("[faucet] User %s has no wallet.", toUserStr)
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineFaucet.UserNeedsWallet = true
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Faucet from %s to %s (%d sat).", fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
|
||||
t := NewTransaction(bot, from, to, inlineFaucet.PerUserAmount, TransactionType("faucet"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[faucet] faucet %s: %d sat from %s to %s ", inlineFaucet.ID, inlineFaucet.PerUserAmount, fromUserStr, toUserStr)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
|
||||
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// build faucet message
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
|
||||
memo := inlineFaucet.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineFaucet.Message = inlineFaucet.Message + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineFaucet.Message)
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
}
|
||||
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
|
||||
// faucet is depleted
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message)
|
||||
inlineFaucet.Active = false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.InTransaction = false
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -3,18 +3,24 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
|
||||
func (bot TipBot) inlineQueryInstructions(ctx intercept.Context) (intercept.Context, error) {
|
||||
instructions := []struct {
|
||||
url string
|
||||
title string
|
||||
@@ -56,19 +62,20 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
|
||||
results[i].SetResultID(strconv.Itoa(i))
|
||||
}
|
||||
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
err := ctx.Answer(&tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 5, // a minute
|
||||
IsPersonal: true,
|
||||
QueryID: q.ID,
|
||||
QueryID: ctx.Query().ID,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
|
||||
func (bot TipBot) inlineQueryReplyWithError(ctx intercept.Context, message string, help string) {
|
||||
results := make(tb.Results, 1) // []tb.Result
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
@@ -78,11 +85,12 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
|
||||
// required for photos
|
||||
ThumbURL: queryImage,
|
||||
}
|
||||
id := fmt.Sprintf("inl-error-%d-%s", q.From.ID, RandStringRunes(5))
|
||||
id := fmt.Sprintf("inl-error-%d-%s", ctx.Query().Sender.ID, RandStringRunes(5))
|
||||
result.SetResultID(id)
|
||||
results[0] = result
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
err := ctx.Answer(&tb.QueryResponse{
|
||||
Results: results,
|
||||
|
||||
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
|
||||
|
||||
})
|
||||
@@ -91,8 +99,24 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) anyChosenInlineHandler(q *tb.ChosenInlineResult) {
|
||||
fmt.Printf(q.Query)
|
||||
// anyChosenInlineHandler will load any inline object from cache and store into bunt.
|
||||
// this is used to decrease bunt db write ops.
|
||||
func (bot TipBot) anyChosenInlineHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// load inline object from cache
|
||||
inlineObject, err := bot.Cache.Get(ctx.InlineResult().ResultID)
|
||||
// check error
|
||||
if err != nil {
|
||||
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
switch inlineObject.(type) {
|
||||
case storage.Storable:
|
||||
// persist inline object in bunt
|
||||
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
|
||||
default:
|
||||
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), ctx.InlineResult().Query)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
|
||||
@@ -114,36 +138,37 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
|
||||
if q.Text == "" {
|
||||
bot.inlineQueryInstructions(ctx, q)
|
||||
return
|
||||
func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Query().Text == "" {
|
||||
return bot.inlineQueryInstructions(ctx)
|
||||
}
|
||||
|
||||
// create the inline send result
|
||||
if strings.HasPrefix(q.Text, "/") {
|
||||
q.Text = strings.TrimPrefix(q.Text, "/")
|
||||
var text = ctx.Query().Text
|
||||
if strings.HasPrefix(text, "/") {
|
||||
text = strings.TrimPrefix(text, "/")
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
|
||||
bot.handleInlineSendQuery(ctx, q)
|
||||
if strings.HasPrefix(text, "send") || strings.HasPrefix(text, "pay") {
|
||||
return bot.handleInlineSendQuery(ctx)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
|
||||
if len(strings.Split(q.Text, " ")) > 1 {
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
if strings.HasPrefix(text, "faucet") || strings.HasPrefix(text, "zapfhahn") || strings.HasPrefix(text, "kraan") || strings.HasPrefix(text, "grifo") {
|
||||
if len(strings.Split(text, " ")) > 1 {
|
||||
c := strings.Split(text, " ")[0]
|
||||
ctx.Context = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
bot.handleInlineFaucetQuery(ctx, q)
|
||||
return bot.handleInlineFaucetQuery(ctx)
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
|
||||
if len(strings.Split(q.Text, " ")) > 1 {
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
if strings.HasPrefix(text, "tipjar") || strings.HasPrefix(text, "spendendose") {
|
||||
if len(strings.Split(text, " ")) > 1 {
|
||||
c := strings.Split(text, " ")[0]
|
||||
ctx.Context = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
bot.handleInlineTipjarQuery(ctx, q)
|
||||
return bot.handleInlineTipjarQuery(ctx)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
|
||||
bot.handleInlineReceiveQuery(ctx, q)
|
||||
if strings.HasPrefix(text, "receive") || strings.HasPrefix(text, "get") || strings.HasPrefix(text, "payme") || strings.HasPrefix(text, "request") {
|
||||
return bot.handleInlineReceiveQuery(ctx)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -1,29 +1,40 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
"github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineReceiveMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
inlineReceiveMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelInlineReceive = inlineReceiveMenu.Data("🚫 Cancel", "cancel_receive_inline")
|
||||
btnAcceptInlineReceive = inlineReceiveMenu.Data("💸 Pay", "confirm_receive_inline")
|
||||
)
|
||||
|
||||
type InlineReceive struct {
|
||||
*transaction.Base
|
||||
Message string `json:"inline_receive_message"`
|
||||
Amount int `json:"inline_receive_amount"`
|
||||
*storage.Base
|
||||
MessageText string `json:"inline_receive_messagetext"`
|
||||
Message tb.Editable `json:"inline_receive_message"`
|
||||
Amount int64 `json:"inline_receive_amount"`
|
||||
From *lnbits.User `json:"inline_receive_from"`
|
||||
To *lnbits.User `json:"inline_receive_to"`
|
||||
From_SpecificUser bool `json:"from_specific_user"`
|
||||
@@ -32,30 +43,33 @@ type InlineReceive struct {
|
||||
}
|
||||
|
||||
func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
inlineReceiveMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
acceptInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_receive_inline")
|
||||
cancelInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_receive_inline")
|
||||
acceptInlineReceiveButton.Data = id
|
||||
cancelInlineReceiveButton.Data = id
|
||||
inlineReceiveMenu.Inline(
|
||||
inlineReceiveMenu.Row(
|
||||
cancelInlineReceiveButton,
|
||||
acceptInlineReceiveButton,
|
||||
cancelInlineReceiveButton),
|
||||
),
|
||||
)
|
||||
return inlineReceiveMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
to := LoadUser(ctx)
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
toUserStr := GetUserStr(&q.From)
|
||||
toUserStr := GetUserStr(q.Sender)
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
// command is "@LightningTipBot receive 123 @from_user This is the memo"
|
||||
@@ -69,11 +83,11 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
bot.inlineQueryReplyWithError(ctx,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the from_username
|
||||
from_SpecificUser = true
|
||||
@@ -105,15 +119,15 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
|
||||
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
// create persistend inline send struct
|
||||
inlineReceive := InlineReceive{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
MessageText: inlineMessage,
|
||||
To: to,
|
||||
Memo: memo,
|
||||
Amount: amount,
|
||||
@@ -121,7 +135,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
From_SpecificUser: from_SpecificUser,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
bot.Cache.Set(inlineReceive.ID, inlineReceive, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -131,125 +145,226 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err)
|
||||
return
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
err = inlineReceive.Lock(inlineReceive, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineReceiveHandler] %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
|
||||
defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// user `from` is the one who is SENDING
|
||||
// user `to` is the one who is RECEIVING
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// check if this payment is requested from a specific user
|
||||
if inlineReceive.From_SpecificUser {
|
||||
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
|
||||
// log.Infof("User %d is not User %d", inlineReceive.From.Telegram.ID, from.Telegram.ID)
|
||||
return
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
inlineReceive.From = from
|
||||
|
||||
}
|
||||
inlineReceive.Message = c
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
if from.Wallet == nil || balance < inlineReceive.Amount {
|
||||
// if user has no wallet, show invoice
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
|
||||
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
bot.inlineReceiveInvoice(ctx, inlineReceive)
|
||||
return ctx, errors.Create(errors.BalanceToLowError)
|
||||
} else {
|
||||
// else, do an internal transaction
|
||||
return bot.sendInlineReceiveHandler(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
|
||||
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// from := inlineReceive.From
|
||||
from := LoadUser(ctx)
|
||||
to := inlineReceive.To
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// balance check of the user
|
||||
balance, err := bot.GetUserBalanceCached(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < inlineReceive.Amount {
|
||||
log.Errorf("[acceptInlineReceiveHandler] balance of user %s too low", fromUserStr)
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
return
|
||||
return ctx, errors.Create(errors.BalanceToLowError)
|
||||
}
|
||||
|
||||
// set inactive to avoid double-sends
|
||||
inlineReceive.Inactivate(inlineReceive, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineReceive from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
transactionMemo := fmt.Sprintf("💸 Receive from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineReceive.Amount, TransactionType("inline receive"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
ctx.Context, err = bot.finishInlineReceiveHandler(ctx, ctx.Callback())
|
||||
return ctx, err
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *InlineReceive) {
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[acceptInlineReceiveHandler] %d sat from %s to %s", inlineReceive.Amount, fromUserStr, toUserStr)
|
||||
|
||||
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineReceive.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
|
||||
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.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
msg := bot.trySendMessage(ctx.Callback().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
bot.tryEditMessage(inlineReceive.Message, fmt.Sprintf("%s\n\nPay this invoice:\n```%s```", inlineReceive.MessageText, invoice.PaymentRequest))
|
||||
invoice.InvoiceMessage = msg
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", GetUserStr(inlineReceive.To.Telegram), inlineReceive.Amount)
|
||||
|
||||
}
|
||||
func (bot *TipBot) inlineReceiveEvent(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
bot.tryDeleteMessage(invoiceEvent.InvoiceMessage)
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if ctx != nil {
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
from := inlineReceive.From
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
inlineReceive.MessageText = fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd)
|
||||
memo := inlineReceive.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
// inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if c.Sender.ID == inlineReceive.To.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
inlineReceive.InTransaction = false
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
return
|
||||
if c.Sender.ID != inlineReceive.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
return ctx, inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
@@ -4,27 +4,34 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineSendMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
inlineSendMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelInlineSend = inlineSendMenu.Data("🚫 Cancel", "cancel_send_inline")
|
||||
btnAcceptInlineSend = inlineSendMenu.Data("✅ Receive", "confirm_send_inline")
|
||||
)
|
||||
|
||||
type InlineSend struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
Message string `json:"inline_send_message"`
|
||||
Amount int `json:"inline_send_amount"`
|
||||
Amount int64 `json:"inline_send_amount"`
|
||||
From *lnbits.User `json:"inline_send_from"`
|
||||
To *lnbits.User `json:"inline_send_to"`
|
||||
To_SpecificUser bool `json:"to_specific_user"`
|
||||
@@ -33,6 +40,7 @@ type InlineSend struct {
|
||||
}
|
||||
|
||||
func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
inlineSendMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
acceptInlineSendButton := inlineSendMenu.Data(Translate(ctx, "receiveButtonMessage"), "confirm_send_inline")
|
||||
cancelInlineSendButton := inlineSendMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_send_inline")
|
||||
acceptInlineSendButton.Data = id
|
||||
@@ -46,31 +54,32 @@ func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMark
|
||||
return inlineSendMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
// inlineSend := NewInlineSend()
|
||||
// var err error
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(&q.From)
|
||||
fromUserStr := GetUserStr(q.Sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
log.Errorf("Balance of user %s too low", fromUserStr)
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
@@ -85,11 +94,11 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
bot.inlineQueryReplyWithError(ctx,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the to_username
|
||||
to_SpecificUser = true
|
||||
@@ -121,15 +130,15 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-send-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
|
||||
id := fmt.Sprintf("inl-send-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
|
||||
// add data to persistent object
|
||||
inlineSend := InlineSend{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
From: fromUser,
|
||||
To: toUserDb,
|
||||
@@ -140,7 +149,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
}
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
bot.Cache.Set(inlineSend.ID, inlineSend, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -150,33 +159,32 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineSendHandler] %s", err)
|
||||
return
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = inlineSend.Lock(inlineSend, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineSend] %s", err)
|
||||
return
|
||||
}
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
|
||||
defer inlineSend.Release(inlineSend, bot.Bunt)
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
|
||||
amount := inlineSend.Amount
|
||||
|
||||
@@ -184,7 +192,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
if inlineSend.To_SpecificUser {
|
||||
if inlineSend.To.Telegram.ID != to.Telegram.ID {
|
||||
// log.Infof("User %d is not User %d", inlineSend.To.Telegram.ID, to.Telegram.ID)
|
||||
return
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
@@ -193,7 +201,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
|
||||
if fromUser.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(fromUser.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -209,25 +217,25 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
// set inactive to avoid double-sends
|
||||
inlineSend.Inactivate(inlineSend, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineSend from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
log.Infof("[sendInline] %d sat from %s to %s", amount, fromUserStr, toUserStr)
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineSend.Memo
|
||||
@@ -237,32 +245,34 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
if !to.Initialized {
|
||||
inlineSend.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(c, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
if c.Sender.ID == inlineSend.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
inlineSend.InTransaction = false
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
if c.Sender.ID != inlineSend.From.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
return
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
return ctx, inlineSend.Set(inlineSend, bot.Bunt)
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
|
||||
type Func func(ctx context.Context, message interface{}) (context.Context, error)
|
||||
|
||||
type handlerCallbackInterceptor struct {
|
||||
handler CallbackFuncHandler
|
||||
before CallbackChain
|
||||
after CallbackChain
|
||||
}
|
||||
type CallbackChain []Func
|
||||
type CallbackInterceptOption func(*handlerCallbackInterceptor)
|
||||
|
||||
func WithBeforeCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackInterceptOption) func(Callback *tb.Callback) {
|
||||
hm := &handlerCallbackInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(c *tb.Callback) {
|
||||
ctx, err := interceptCallback(context.Background(), c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, c)
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
context.Context
|
||||
TeleContext
|
||||
}
|
||||
type TeleContext struct {
|
||||
tb.Context
|
||||
}
|
||||
|
||||
type Func func(ctx Context) (Context, error)
|
||||
|
||||
type handlerInterceptor struct {
|
||||
handler Func
|
||||
before Chain
|
||||
after Chain
|
||||
onDefer Chain
|
||||
}
|
||||
type Chain []Func
|
||||
type Option func(*handlerInterceptor)
|
||||
|
||||
func WithBefore(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfter(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDefer(chain ...Func) Option {
|
||||
return func(a *handlerInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func intercept(h Context, hm Chain) (Context, error) {
|
||||
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
h, err = m(h)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func WithHandler(handler Func, option ...Option) tb.HandlerFunc {
|
||||
hm := &handlerInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(c tb.Context) error {
|
||||
h := Context{TeleContext: TeleContext{Context: c}, Context: context.Background()}
|
||||
h, err := intercept(h, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return err
|
||||
}
|
||||
defer intercept(h, hm.onDefer)
|
||||
h, err = hm.handler(h)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return err
|
||||
}
|
||||
_, err = intercept(h, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type MessageInterface interface {
|
||||
a() func(ctx context.Context, message *tb.Message)
|
||||
}
|
||||
type MessageFuncHandler func(ctx context.Context, message *tb.Message)
|
||||
|
||||
type handlerMessageInterceptor struct {
|
||||
handler MessageFuncHandler
|
||||
before MessageChain
|
||||
after MessageChain
|
||||
}
|
||||
type MessageChain []Func
|
||||
type MessageInterceptOption func(*handlerMessageInterceptor)
|
||||
|
||||
func WithBeforeMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
|
||||
|
||||
hm := &handlerMessageInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Message) {
|
||||
ctx, err := interceptMessage(context.Background(), message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
|
||||
|
||||
type handlerQueryInterceptor struct {
|
||||
handler QueryFuncHandler
|
||||
before QueryChain
|
||||
after QueryChain
|
||||
}
|
||||
type QueryChain []Func
|
||||
type QueryInterceptOption func(*handlerQueryInterceptor)
|
||||
|
||||
func WithBeforeQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptQuery(ctx context.Context, message *tb.Query, hm QueryChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption) func(message *tb.Query) {
|
||||
hm := &handlerQueryInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Query) {
|
||||
ctx, err := interceptQuery(context.Background(), message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptQuery(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,12 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
@@ -10,133 +16,204 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type InterceptorType int
|
||||
|
||||
const (
|
||||
MessageInterceptor InterceptorType = iota
|
||||
CallbackInterceptor
|
||||
QueryInterceptor
|
||||
)
|
||||
|
||||
var invalidTypeError = fmt.Errorf("invalid type")
|
||||
|
||||
type Interceptor struct {
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
OnDefer []intercept.Func
|
||||
}
|
||||
|
||||
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Query:
|
||||
user, err := GetUser(&i.(*tb.Query).From, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
m := *c.Message
|
||||
m.Sender = c.Sender
|
||||
user, err := GetUser(i.(*tb.Callback).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Message:
|
||||
user, err := GetUser(i.(*tb.Message).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
// singletonClickInterceptor uses the onceMap to determine whether the object k1 already interacted
|
||||
// with the user k2. If so, it will return an error.
|
||||
func (bot TipBot) singletonCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Callback() != nil {
|
||||
return ctx, once.Once(ctx.Callback().Data, strconv.FormatInt(ctx.Callback().Sender.ID, 10))
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx, i)
|
||||
|
||||
// lockInterceptor invoked as first before interceptor
|
||||
func (bot TipBot) lockInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := ctx.Sender()
|
||||
if user != nil {
|
||||
mutex.Lock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// unlockInterceptor invoked as onDefer interceptor
|
||||
func (bot TipBot) unlockInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := ctx.Sender()
|
||||
if user != nil {
|
||||
mutex.Unlock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx.Context = context.WithValue(ctx, "uid", RandStringRunes(64))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// answerCallbackInterceptor will answer the callback with the given text in the context
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
if c != nil {
|
||||
ctxcr := ctx.Value("callback_response")
|
||||
var res []*tb.CallbackResponse
|
||||
if ctxcr != nil {
|
||||
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
|
||||
}
|
||||
// if the context wasn't set, still respond with an empty callback response
|
||||
if len(res) == 0 {
|
||||
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ""})
|
||||
}
|
||||
var err error
|
||||
err = bot.Telegram.Respond(c, res...)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// requireUserInterceptor will return an error if user is not found
|
||||
// user is here an lnbits.User
|
||||
func (bot TipBot) requireUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
u := ctx.Sender()
|
||||
if u != nil {
|
||||
user, err = GetUser(u, bot)
|
||||
// do not respond to banned users
|
||||
if bot.UserIsBanned(user) {
|
||||
ctx.Context = context.WithValue(ctx, "banned", true)
|
||||
ctx.Context = context.WithValue(ctx, "user", user)
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
if user != nil {
|
||||
ctx.Context = context.WithValue(ctx, "user", user)
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// startUserInterceptor will invoke /start if user not exists.
|
||||
func (bot TipBot) startUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
handler, err := bot.loadUserInterceptor(ctx)
|
||||
if err != nil {
|
||||
// user banned
|
||||
return handler, err
|
||||
}
|
||||
// load user
|
||||
u := ctx.Value("user")
|
||||
// check user nil
|
||||
if u != nil {
|
||||
user := u.(*lnbits.User)
|
||||
// check wallet nil or !initialized
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
handler, err = bot.startHandler(handler)
|
||||
if err != nil {
|
||||
return handler, err
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx)
|
||||
// if user is banned, also loadUserInterceptor will return an error
|
||||
if ctx.Value("banned") != nil && ctx.Value("banned").(bool) {
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.ReplyTo != nil {
|
||||
if m.ReplyTo.Sender != nil {
|
||||
user, _ := GetUser(m.ReplyTo.Sender, bot)
|
||||
user.Telegram = m.ReplyTo.Sender
|
||||
return context.WithValue(ctx, "reply_to_user", user), nil
|
||||
func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Message() != nil {
|
||||
if ctx.Message().ReplyTo != nil {
|
||||
if ctx.Message().ReplyTo.Sender != nil {
|
||||
user, _ := GetUser(ctx.Message().ReplyTo.Sender, bot)
|
||||
user.Telegram = ctx.Message().ReplyTo.Sender
|
||||
ctx.Context = context.WithValue(ctx, "reply_to_user", user)
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
func (bot TipBot) localizerInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
var userLocalizer *i18n2.Localizer
|
||||
var publicLocalizer *i18n2.Localizer
|
||||
|
||||
// default language is english
|
||||
publicLocalizer = i18n2.NewLocalizer(i18n.Bundle, "en")
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
|
||||
ctx.Context = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
ctx.Context = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
|
||||
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLocalizer", userLocalizer)
|
||||
if m.Private() {
|
||||
if ctx.Message() != nil {
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Message().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Message().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
|
||||
if ctx.Message().Private() {
|
||||
// in pm overwrite public localizer with user localizer
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", userLocalizer)
|
||||
ctx.Context = context.WithValue(ctx, "publicLanguageCode", ctx.Message().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "publicLocalizer", userLocalizer)
|
||||
}
|
||||
return ctx, nil
|
||||
case *tb.Callback:
|
||||
m := i.(*tb.Callback)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
|
||||
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
|
||||
case *tb.Query:
|
||||
m := i.(*tb.Query)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.From.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.From.LanguageCode)
|
||||
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
|
||||
} else if ctx.Callback() != nil {
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Callback().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Callback().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
|
||||
return ctx, nil
|
||||
} else if ctx.Query() != nil {
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Query().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Query().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return nil, fmt.Errorf("no 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
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
const photoTag = "<Photo>"
|
||||
|
||||
func (bot TipBot) logMessageInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Text != "" {
|
||||
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
if m.IsReply() {
|
||||
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(m.ReplyTo.Sender))
|
||||
func (bot TipBot) logMessageInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Message() != nil {
|
||||
|
||||
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)
|
||||
} else if m.Photo != nil {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, photoTag)
|
||||
} 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)
|
||||
}
|
||||
return ctx, nil
|
||||
case *tb.Callback:
|
||||
m := i.(*tb.Callback)
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(m.Sender), m.Sender.ID, m.Data)
|
||||
} else if ctx.Callback() != nil {
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(ctx.Callback().Sender), ctx.Callback().Sender.ID, ctx.Callback().Data)
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
|
||||
+179
-24
@@ -5,16 +5,101 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type InvoiceEventCallback map[int]EventHandler
|
||||
|
||||
type EventHandler struct {
|
||||
Function func(event Event)
|
||||
Type EventType
|
||||
}
|
||||
|
||||
var InvoiceCallback InvoiceEventCallback
|
||||
|
||||
func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallback = InvoiceEventCallback{
|
||||
InvoiceCallbackGeneric: EventHandler{Function: bot.notifyInvoiceReceivedEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackInlineReceive: EventHandler{Function: bot.inlineReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
type InvoiceEventKey int
|
||||
|
||||
const (
|
||||
InvoiceCallbackGeneric = iota + 1
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
InvoiceCallbackGenerateDalle
|
||||
)
|
||||
|
||||
const (
|
||||
EventTypeInvoice EventType = "invoice"
|
||||
EventTypeTicketInvoice EventType = "ticket-invoice"
|
||||
)
|
||||
|
||||
type EventType string
|
||||
|
||||
func AssertEventType(event Event, eventType EventType) error {
|
||||
if event.Type() != eventType {
|
||||
return fmt.Errorf("invalid event type")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Invoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"`
|
||||
}
|
||||
type InvoiceEvent struct {
|
||||
*Invoice
|
||||
*storage.Base
|
||||
User *lnbits.User `json:"user"` // the user that is being paid
|
||||
Message *tb.Message `json:"message,omitempty"` // the message that the invoice replies to
|
||||
InvoiceMessage *tb.Message `json:"invoice_message,omitempty"` // the message that displays the invoice
|
||||
LanguageCode string `json:"languagecode"` // language code of the user
|
||||
Callback int `json:"func"` // which function to call if the invoice is paid
|
||||
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
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Type() EventType {
|
||||
return EventTypeInvoice
|
||||
}
|
||||
|
||||
type Event interface {
|
||||
Type() EventType
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Key() string {
|
||||
return fmt.Sprintf("invoice:%s", invoiceEvent.PaymentHash)
|
||||
}
|
||||
|
||||
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
@@ -23,25 +108,26 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask fo""r amount
|
||||
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return
|
||||
_, err = bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
@@ -56,9 +142,35 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
memo = memo + tag
|
||||
}
|
||||
|
||||
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
// generate invoice
|
||||
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
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)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// deleting messages will delete the main menu.
|
||||
//bot.tryDeleteMessage(creatingMsg)
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -67,24 +179,67 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return InvoiceEvent{}, err
|
||||
}
|
||||
invoiceEvent := InvoiceEvent{
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: amount,
|
||||
Memo: memo},
|
||||
User: user,
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
// do balance check for keyboard update
|
||||
_, err := bot.GetUserBalance(invoiceEvent.User)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (bot *TipBot) lnurlReceiveEvent(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
|
||||
err := bot.Bunt.Get(tx)
|
||||
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
if err == nil {
|
||||
if len(tx.Comment) > 0 {
|
||||
if len(tx.From) == 0 {
|
||||
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)))
|
||||
}
|
||||
} else if len(tx.From) > 0 {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)))
|
||||
}
|
||||
}
|
||||
|
||||
bot.tryDeleteMessage(creatingMsg)
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return
|
||||
}
|
||||
|
||||
+31
-16
@@ -2,42 +2,57 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return
|
||||
}
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return ctx, fmt.Errorf("invalid configuration")
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser := LoadUser(ctx)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
linkmsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
// send the link to the user
|
||||
qrmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
// auto delete
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(qrmsg)
|
||||
bot.tryEditMessage(linkmsg, Translate(ctx, "linkHiddenMessage"), tb.Silent)
|
||||
}()
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) apiHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
fromUser := LoadUser(ctx)
|
||||
apimesg := bot.trySendMessageEditable(m.Sender, fmt.Sprintf(Translate(ctx, "apiConnectMessage"), fromUser.Wallet.Adminkey, fromUser.Wallet.Inkey))
|
||||
// auto delete
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryEditMessage(apimesg, Translate(ctx, "apiHiddenMessage"))
|
||||
}()
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/imroc/req"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
authConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelAuth = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_login")
|
||||
btnAuth = paymentConfirmationMenu.Data("✅ Login", "confirm_login")
|
||||
)
|
||||
|
||||
type LnurlAuthState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLAuthParams lnurl.LNURLAuthParams `json:"LNURLAuthParams"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Message *tb.Message `json:"message"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlAuthHandler(ctx context.Context, m *tb.Message, authParams *LnurlAuthState) (context.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlauth-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
authParams.Base = storage.New(storage.ID(id))
|
||||
authParams.From = user
|
||||
authParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
|
||||
|
||||
// // // create inline buttons
|
||||
btnAuth = paymentConfirmationMenu.Data(Translate(ctx, "loginButtonMessage"), "confirm_login", id)
|
||||
btnCancelAuth = paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_login", id)
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
btnAuth,
|
||||
btnCancelAuth),
|
||||
)
|
||||
authParams.Message = bot.trySendMessageEditable(m.Chat,
|
||||
fmt.Sprintf(Translate(ctx, "confirmLnurlAuthMessager"),
|
||||
authParams.LNURLAuthParams.CallbackURL.Host,
|
||||
),
|
||||
paymentConfirmationMenu,
|
||||
)
|
||||
|
||||
// save to bunt
|
||||
runtime.IgnoreError(authParams.Set(authParams, bot.Bunt))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[confirmPayHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
lnurlAuthState := sn.(*LnurlAuthState)
|
||||
|
||||
if !lnurlAuthState.Active {
|
||||
return ctx, fmt.Errorf("LnurlAuthData not active.")
|
||||
}
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// statusMsg := bot.trySendMessageEditable(c.Sender,
|
||||
// Translate(ctx, "lnurlResolvingUrlMessage"),
|
||||
// )
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlAuthState.Message.Text, ButtonText: Translate(ctx, "lnurlResolvingUrlMessage")})
|
||||
|
||||
// from fiatjaf/go-lnurl
|
||||
p := lnurlAuthState.LNURLAuthParams
|
||||
key, sig, err := user.SignKeyAuth(p.Host, p.K1)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
var sentsigres lnurl.LNURLResponse
|
||||
client, err := network.GetClientForScheme(p.CallbackURL)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
r := req.New()
|
||||
r.SetClient(client)
|
||||
res, err := r.Get(p.CallbackURL.String(), url.Values{"sig": {sig}, "key": {key}})
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
err = json.Unmarshal(res.Bytes(), &sentsigres)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if sentsigres.Status == "ERROR" {
|
||||
bot.tryEditMessage(c, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
|
||||
return ctx, err
|
||||
}
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{
|
||||
Message: lnurlAuthState.Message.Text,
|
||||
ButtonText: Translate(ctx, "lnurlSuccessfulLogin"),
|
||||
URL: fmt.Sprintf("https://%s", lnurlAuthState.LNURLAuthParams.Host),
|
||||
})
|
||||
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelLnurlAuthHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[confirmPayHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
lnurlAuthState := sn.(*LnurlAuthState)
|
||||
|
||||
// onnly the correct user can press
|
||||
if lnurlAuthState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
// delete and send instead of edit for the keyboard to pop up after sending
|
||||
bot.tryEditMessage(c, i18n.Translate(lnurlAuthState.LanguageCode, "loginCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
|
||||
}
|
||||
+118
-78
@@ -9,141 +9,166 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayResponse1 lnurl.LNURLPayResponse1 `json:"LNURLPayResponse1"`
|
||||
LNURLPayResponse2 lnurl.LNURLPayResponse2 `json:"LNURLPayResponse2"`
|
||||
Amount int `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
DescriptionHash string `json:"descriptionHash,omitempty"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
lnurlPayState := LnurlPayState{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
LNURLPayResponse1: payParams.LNURLPayResponse1,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
payParams.Base = storage.New(storage.ID(id))
|
||||
payParams.From = user
|
||||
payParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
|
||||
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayResponse1.MinSendable, lnurlPayState.LNURLPayResponse1.MaxSendable, m.Text)
|
||||
return
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// we need to figure out whether the memo starts at position 2 or 3
|
||||
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
|
||||
memoStartsAt := 2
|
||||
if amount_err == nil {
|
||||
// amount was present
|
||||
memoStartsAt = 3
|
||||
}
|
||||
// check if memo is present in command
|
||||
memo := GetMemoFromCommand(m.Text, memoStartsAt)
|
||||
// shorten memo to allowed length
|
||||
if len(memo) > int(payParams.LNURLPayParams.CommentAllowed) {
|
||||
memo = memo[:payParams.LNURLPayParams.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
payParams.Comment = memo
|
||||
}
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if int64(amount) > (lnurlPayState.LNURLPayResponse1.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayResponse1.MinSendable/1000) {
|
||||
err = fmt.Errorf("amount not in range")
|
||||
if amount_err == nil &&
|
||||
(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())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayResponse1.MinSendable/1000, lnurlPayState.LNURLPayResponse1.MaxSendable/1000))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
lnurlPayState.Amount = amount * 1000 // save as mSat
|
||||
payParams.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// check if comment is presentin lnrul-p
|
||||
memo := GetMemoFromCommand(m.Text, 3)
|
||||
// shorten comment to allowed length
|
||||
if len(memo) > int(lnurlPayState.LNURLPayResponse1.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayResponse1.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
lnurlPayState.Comment = memo
|
||||
// calculate description hash of the metadata and save it
|
||||
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payParams.DescriptionHash = descriptionHash
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
|
||||
|
||||
// not necessary to save this in the state data, but till doing it
|
||||
paramsJson, err := json.Marshal(lnurlPayState)
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if payParams.LNURLPayParams.MinSendable == payParams.LNURLPayParams.MaxSendable {
|
||||
amount = payParams.LNURLPayParams.MaxSendable / 1000
|
||||
payParams.Amount = amount * 1000 // save as mSat
|
||||
} else if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// 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())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
bot.lnurlPayHandlerSend(ctx)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandler] state keys don't match")
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
lnurlPayState := fn.(*LnurlPayState)
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayResponse1.Callback)
|
||||
client, err := network.GetClientForScheme(callbackUrl)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("amount", strconv.Itoa(lnurlPayState.Amount)) // msat
|
||||
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
|
||||
// add comment to query string
|
||||
if len(lnurlPayState.Comment) > 0 {
|
||||
qs.Set("comment", lnurlPayState.Comment)
|
||||
@@ -154,42 +179,58 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
var response2 lnurl.LNURLPayResponse2
|
||||
var response2 lnurl.LNURLPayValues
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "ERROR" || len(response2.PR) < 1 {
|
||||
error_reason := "Could not receive invoice."
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayResponse2: %s", error_reason)
|
||||
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return
|
||||
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
|
||||
}
|
||||
|
||||
lnurlPayState.LNURLPayResponse2 = response2
|
||||
// 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)
|
||||
m.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
bot.payHandler(ctx, m)
|
||||
return bot.payHandler(ctx)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) error {
|
||||
func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string, amount int64) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return fmt.Errorf("lightning address format wrong")
|
||||
return ctx, fmt.Errorf("lightning address format wrong")
|
||||
}
|
||||
host := strings.ToLower(split[1])
|
||||
name := strings.ToLower(split[0])
|
||||
@@ -201,7 +242,7 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
|
||||
|
||||
lnurl, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return err
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if amount > 0 {
|
||||
@@ -221,6 +262,5 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
|
||||
// this will invoke the "enter amount" dialog in the lnurl handler
|
||||
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
|
||||
}
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return nil
|
||||
return bot.lnurlHandler(ctx)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
|
||||
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
|
||||
)
|
||||
|
||||
// LnurlWithdrawState saves the state of the user for an LNURL payment
|
||||
type LnurlWithdrawState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
|
||||
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
Invoice lnbits.Invoice `json:"invoice"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type EditSingleButtonParams struct {
|
||||
Message string
|
||||
ButtonText string
|
||||
Data string
|
||||
URL string
|
||||
}
|
||||
|
||||
// editSingleButton edits a message to display a single button (for something like a progress indicator)
|
||||
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, params EditSingleButtonParams) (*tb.Message, error) {
|
||||
if len(params.URL) > 0 && len(params.Data) > 0 {
|
||||
return &tb.Message{}, fmt.Errorf("URL and Data cannot be set at the same time.")
|
||||
}
|
||||
if len(params.URL) == 0 && len(params.Data) == 0 {
|
||||
params.Data = "placeholder"
|
||||
}
|
||||
return bot.tryEditMessage(
|
||||
m,
|
||||
params.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: params.ButtonText, Data: params.Data, URL: params.URL}},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlWithdrawHandler(ctx intercept.Context, withdrawParams *LnurlWithdrawState) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
|
||||
withdrawParams.Base = storage.New(storage.ID(id))
|
||||
withdrawParams.From = user
|
||||
withdrawParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
|
||||
(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable != 0 && withdrawParams.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
// if no amount is entered, and if only one amount is possible, we use it
|
||||
if amount_err != nil && withdrawParams.LNURLWithdrawResponse.MaxWithdrawable == withdrawParams.LNURLWithdrawResponse.MinWithdrawable {
|
||||
amount = int64(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
amount_err = nil
|
||||
}
|
||||
|
||||
// set also amount in the state of the user
|
||||
withdrawParams.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(withdrawParams.Set(withdrawParams, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlWithdrawState", withdrawParams.LNURLWithdrawResponse.MinWithdrawable, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
paramsJson, err := json.Marshal(withdrawParams)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("invalid type")
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
|
||||
if len(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription))
|
||||
}
|
||||
lnurlWithdrawState.Message = confirmText
|
||||
|
||||
// create inline buttons
|
||||
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw", lnurlWithdrawState.ID)
|
||||
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw", lnurlWithdrawState.ID)
|
||||
|
||||
withdrawConfirmationMenu.Inline(
|
||||
withdrawConfirmationMenu.Row(
|
||||
withdrawButton,
|
||||
btnCancelWithdraw),
|
||||
)
|
||||
|
||||
bot.tryEditMessage(statusMsg, confirmText, withdrawConfirmationMenu)
|
||||
|
||||
// // add response to persistent struct
|
||||
// lnurlWithdrawState.LNURResponse = response2
|
||||
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[confirmWithdrawHandler] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[confirmWithdrawHandler] invalid type")
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !lnurlWithdrawState.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c)
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw")})
|
||||
|
||||
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// generate an invoice and add the pr to the request
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(lnurlWithdrawState.Amount) / 1000,
|
||||
Memo: "Withdraw",
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
lnurlWithdrawState.Invoice = invoice
|
||||
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("pr", invoice.PaymentRequest)
|
||||
qs.Set("k1", lnurlWithdrawState.LNURLWithdrawResponse.K1)
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := network.GetClientForScheme(callbackUrl)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil || res.StatusCode >= 300 {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// parse the response
|
||||
var response2 lnurl.LNURLResponse
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "OK" {
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess")})
|
||||
|
||||
} else {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed")})
|
||||
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
|
||||
}
|
||||
|
||||
// add response to persistent struct
|
||||
lnurlWithdrawState.LNURResponse = response2
|
||||
return ctx, lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelWithdrawHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[cancelWithdrawHandler] invalid type")
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
return ctx, lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
+152
-198
@@ -2,83 +2,121 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
"github.com/tidwall/gjson"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
client := http.Client{}
|
||||
if internal.Configuration.Bot.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// commands:
|
||||
// /lnurl
|
||||
// /lnurl <LNURL>
|
||||
// or /lnurl <amount> <LNURL>
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// if only /lnurl is entered, show the lnurl of the user
|
||||
if m.Text == "/lnurl" {
|
||||
bot.lnurlReceiveHandler(ctx, m)
|
||||
return
|
||||
return bot.lnurlReceiveHandler(ctx)
|
||||
}
|
||||
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
|
||||
var lnurlSplit string
|
||||
split := strings.Split(m.Text, " ")
|
||||
if _, err := decodeAmountFromCommand(m.Text); err == nil {
|
||||
// command is /lnurl 123 <LNURL> [memo]
|
||||
if len(split) > 2 {
|
||||
lnurlSplit = split[2]
|
||||
}
|
||||
} else if len(split) > 1 {
|
||||
lnurlSplit = split[1]
|
||||
} else {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
|
||||
log.Warnln("[/lnurl] Could not parse command.")
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
// assume payment
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
_, params, err := bot.HandleLNURL(m.Text)
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
|
||||
log.Errorln(err)
|
||||
return
|
||||
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())
|
||||
return ctx, err
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLPayResponse1:
|
||||
payParams := LnurlPayState{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
|
||||
log.Infof("[lnurlHandler] %s", payParams.LNURLPayResponse1.Callback)
|
||||
case lnurl.LNURLAuthParams:
|
||||
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
|
||||
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlPayHandler(ctx, m, payParams)
|
||||
return
|
||||
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)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
|
||||
// display the metadata image from the first LNURL-p response
|
||||
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{
|
||||
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
|
||||
Caption: payParams.LNURLPayParams.Metadata.Description})
|
||||
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
|
||||
// display the metadata text from the first LNURL-p response
|
||||
// if there was no photo in the last step
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("`%s`", payParams.LNURLPayParams.Metadata.Description))
|
||||
}
|
||||
// ask whether to make payment
|
||||
bot.lnurlPayHandler(ctx, payParams)
|
||||
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlWithdrawHandler(ctx, withdrawParams)
|
||||
default:
|
||||
err := fmt.Errorf("invalid LNURL type.")
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
if err == nil {
|
||||
err = fmt.Errorf("invalid LNURL type")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
|
||||
@@ -91,20 +129,12 @@ func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error) {
|
||||
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonIDSha256), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
}
|
||||
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
// before: we used the username for the LNURL
|
||||
// name := strings.ToLower(strings.ToLower(user.Telegram.Username))
|
||||
// if len(name) == 0 {
|
||||
// name = fmt.Sprint(user.AnonID)
|
||||
// // return "", fmt.Errorf("user has no username.")
|
||||
// }
|
||||
// now: use only the anon ID as LNURL
|
||||
name := fmt.Sprint(user.AnonID)
|
||||
name := fmt.Sprint(user.UUID)
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
|
||||
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
|
||||
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
@@ -113,152 +143,41 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err)
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err)
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
|
||||
// send the lnurl data to user
|
||||
// send the lnurl QR code
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// // lnurlEnterAmountHandler is invoked if the user didn't deliver an amount for the lnurl payment
|
||||
// func (bot *TipBot) lnurlEnterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
// a, err := strconv.Atoi(m.Text)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// amount := int64(a)
|
||||
// var stateResponse LnurlPayState
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// // amount not in allowed range from LNURL
|
||||
// if amount > (stateResponse.LNURLPayResponse1.MaxSendable/1000) || amount < (stateResponse.LNURLPayResponse1.MinSendable/1000) {
|
||||
// err = fmt.Errorf("amount not in range")
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.LNURLPayResponse1.MinSendable/1000, stateResponse.LNURLPayResponse1.MaxSendable/1000))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// stateResponse.Amount = a
|
||||
// state, err := json.Marshal(stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(state))
|
||||
// bot.lnurlPayHandler(ctx, m)
|
||||
// }
|
||||
// }
|
||||
|
||||
// // LnurlStateResponse saves the state of the user for an LNURL payment
|
||||
// type LnurlStateResponse struct {
|
||||
// lnurl.LNURLPayResponse1
|
||||
// Amount int `json:"amount"`
|
||||
// Comment string `json:"comment"`
|
||||
// }
|
||||
|
||||
// // lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
// func (bot *TipBot) lnurlPayHandler(ctx context.Context, c *tb.Message) {
|
||||
// msg := bot.trySendMessage(c.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateConfirmLNURLPay {
|
||||
// client, err := getHttpClient()
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var stateResponse LnurlStateResponse
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// callbackUrl, err := url.Parse(stateResponse.Callback)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// qs := callbackUrl.Query()
|
||||
// // add amount to query string
|
||||
// qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
|
||||
// // add comment to query string
|
||||
// if len(stateResponse.Comment) > 0 {
|
||||
// qs.Set("comment", stateResponse.Comment)
|
||||
// }
|
||||
|
||||
// callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// res, err := client.Get(callbackUrl.String())
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var response2 lnurl.LNURLPayResponse2
|
||||
// body, err := ioutil.ReadAll(res.Body)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// json.Unmarshal(body, &response2)
|
||||
|
||||
// if len(response2.PR) < 1 {
|
||||
// error_reason := "Could not receive invoice."
|
||||
// if len(response2.Reason) > 0 {
|
||||
// error_reason = response2.Reason
|
||||
// }
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
// return
|
||||
// }
|
||||
// bot.Telegram.Delete(msg)
|
||||
// c.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
// bot.payHandler(ctx, c)
|
||||
// }
|
||||
// }
|
||||
|
||||
// from https://github.com/fiatjaf/go-lnurl
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
@@ -273,35 +192,53 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
}
|
||||
} else if strings.HasPrefix(rawlnurl, "http") {
|
||||
rawurl = rawlnurl
|
||||
} else if strings.HasPrefix(rawlnurl, "lnurlp://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurlw://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurla://") ||
|
||||
strings.HasPrefix(rawlnurl, "keyauth://") {
|
||||
|
||||
scheme := "https:"
|
||||
if strings.Contains(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
|
||||
scheme = "http:"
|
||||
}
|
||||
location := strings.SplitN(rawlnurl, ":", 2)[1]
|
||||
rawurl = scheme + location
|
||||
} else {
|
||||
foundUrl, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
if !ok {
|
||||
return "", nil,
|
||||
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(foundUrl)
|
||||
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug("[HandleLNURL] rawurl: ", rawurl)
|
||||
parsed, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
|
||||
// query := parsed.Query()
|
||||
query := parsed.Query()
|
||||
|
||||
// switch query.Get("tag") {
|
||||
// case "login":
|
||||
// value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
// return rawurl, value, err
|
||||
// case "withdrawRequest":
|
||||
// if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
// return rawurl, value, nil
|
||||
// }
|
||||
switch query.Get("tag") {
|
||||
case "login":
|
||||
value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
return rawurl, value, err
|
||||
case "withdrawRequest":
|
||||
if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
return rawurl, value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// // original withouth proxy
|
||||
// resp, err := http.Get(rawurl)
|
||||
// if err != nil {
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
client, err := bot.GetHttpClient()
|
||||
|
||||
client, err := network.GetClientForScheme(parsed)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -309,6 +246,9 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
@@ -325,16 +265,30 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
}
|
||||
|
||||
switch j.Get("tag").String() {
|
||||
// case "withdrawRequest":
|
||||
// value, err := lnurl.HandleWithdraw(j)
|
||||
// return rawurl, value, err
|
||||
case "withdrawRequest":
|
||||
value, err := lnurl.HandleWithdraw(b)
|
||||
return rawurl, value, err
|
||||
case "payRequest":
|
||||
value, err := lnurl.HandlePay(j)
|
||||
value, err := lnurl.HandlePay(b)
|
||||
return rawurl, value, err
|
||||
// case "channelRequest":
|
||||
// value, err := lnurl.HandleChannel(j)
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, errors.New("unknown response tag " + j.String())
|
||||
return rawurl, nil, fmt.Errorf("unkown LNURL response")
|
||||
}
|
||||
}
|
||||
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (bot *TipBot) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
} else {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
}
|
||||
return hashString, nil
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
|
||||
+99
-85
@@ -5,18 +5,25 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
|
||||
)
|
||||
@@ -30,7 +37,7 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
|
||||
type PayData struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
@@ -43,26 +50,26 @@ type PayData struct {
|
||||
}
|
||||
|
||||
// payHandler invoked on "/pay lnbc..." command
|
||||
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
|
||||
return
|
||||
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, ""))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
userStr := GetUserStr(ctx.Sender())
|
||||
paymentRequest, err := getArgumentFromCommand(ctx.Message().Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
// get rid of the URI prefix
|
||||
@@ -71,40 +78,38 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
// decode invoice
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
|
||||
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
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
}
|
||||
amount := int(bolt11.MSatoshi / 1000)
|
||||
amount := int64(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "invoiceNoAmountMessage"))
|
||||
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
|
||||
log.Warnln(errmsg)
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
// check user balance first
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
|
||||
if float64(amount) > float64(balance)*0.98 {
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "feeReserveMessage"))
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), amount)
|
||||
@@ -112,25 +117,23 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(bolt11.Description))
|
||||
}
|
||||
|
||||
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
|
||||
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
id := fmt.Sprintf("pay:%d-%d-%s", ctx.Sender().ID, amount, RandStringRunes(5))
|
||||
|
||||
// // // create inline buttons
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay")
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay")
|
||||
payButton.Data = id
|
||||
cancelButton.Data = id
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay", id)
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
payButton,
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := PayData{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
Invoice: paymentRequest,
|
||||
Amount: int64(amount),
|
||||
@@ -143,46 +146,41 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
|
||||
|
||||
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[confirmPayHandler] %s", err)
|
||||
return
|
||||
log.Errorf("[confirmPayHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = payData.Lock(payData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
if payData.From.Telegram.ID != ctx.Sender().ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
bot.tryEditMessage(ctx.Message(), i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer payData.Release(payData, bot.Bunt)
|
||||
defer payData.Set(payData, bot.Bunt)
|
||||
|
||||
// remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
// bot.tryEditMessage(handler.Message(), MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
invoiceString := payData.Invoice
|
||||
@@ -190,65 +188,81 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
userStr := GetUserStr(c.Sender)
|
||||
userStr := GetUserStr(ctx.Sender())
|
||||
|
||||
// update button text
|
||||
bot.tryEditMessage(
|
||||
c.Message,
|
||||
ctx.Message(),
|
||||
payData.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
|
||||
{tb.InlineButton{Unique: "attempt_payment", Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
|
||||
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
// verbose error message, turned off for now
|
||||
// if len(err.Error()) == 0 {
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
payData.Hash = invoice.PaymentHash
|
||||
payData.InTransaction = false
|
||||
|
||||
if c.Message.Private() {
|
||||
// do balance check for keyboard update
|
||||
_, err = bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
|
||||
if ctx.Message().Private() {
|
||||
// if the command was invoked in private chat
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
// the edit below was cool, but we need to pop up the keyboard again
|
||||
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
log.Printf("[pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelPaymentHandler] %s", err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
if payData.From.Telegram.ID != ctx.Callback().Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
payData.InTransaction = false
|
||||
payData.Inactivate(payData, bot.Bunt)
|
||||
// delete and send instead of edit for the keyboard to pop up after sending
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
bot.trySendMessage(ctx.Message().Chat, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"))
|
||||
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, payData.Inactivate(payData, bot.Bunt)
|
||||
|
||||
}
|
||||
|
||||
+101
-18
@@ -1,20 +1,27 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
"github.com/makiuchi-d/gozxing"
|
||||
"github.com/makiuchi-d/gozxing/qrcode"
|
||||
"github.com/nfnt/resize"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment ctx.
|
||||
func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
// check for qr code
|
||||
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
||||
@@ -27,49 +34,125 @@ func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
payload := strings.ToLower(result.String())
|
||||
if lightning.IsInvoice(payload) || lightning.IsLnurl(payload) {
|
||||
// create payment command payload
|
||||
// invoke payment confirmation handler
|
||||
// invoke payment confirmation ctx
|
||||
return result, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no codes found")
|
||||
}
|
||||
|
||||
// photoHandler is the handler function for every photo from a private chat that the bot receives
|
||||
func (bot TipBot) photoHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) photoHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPhotoError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
ctx, err := c(ctx)
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// get file reader closer from Telegram api
|
||||
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
|
||||
reader, err := bot.Telegram.File(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err)
|
||||
return
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err)
|
||||
return
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err)
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "photoQrRecognizedMessage"), data.String()))
|
||||
// invoke payment handler
|
||||
if lightning.IsInvoice(data.String()) {
|
||||
m.Text = fmt.Sprintf("/pay %s", data.String())
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
return bot.payHandler(ctx)
|
||||
} else if lightning.IsLnurl(data.String()) {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", data.String())
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
return bot.lnurlHandler(ctx)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// DownloadProfilePicture downloads a profile picture from Telegram.
|
||||
// This is a public function because it is used in another package (lnurl)
|
||||
func DownloadProfilePicture(telegram *tb.Bot, user *tb.User) ([]byte, error) {
|
||||
photo, err := ProfilePhotosOf(telegram, user)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if len(photo) == 0 {
|
||||
log.Error("[DownloadProfilePicture] No profile picture found")
|
||||
return nil, err
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
reader, err := telegram.File(&photo[0].File)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// resize image
|
||||
img = resize.Thumbnail(160, 160, img, resize.Lanczos3)
|
||||
|
||||
err = jpeg.Encode(buf, img, nil)
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
var BotProfilePicture []byte
|
||||
|
||||
// downloadMyProfilePicture downloads the profile picture of the bot
|
||||
// and saves it in `BotProfilePicture`
|
||||
func (bot *TipBot) downloadMyProfilePicture() error {
|
||||
picture, err := DownloadProfilePicture(bot.Telegram, bot.Telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorf("[downloadMyProfilePicture] %v", err)
|
||||
return err
|
||||
}
|
||||
BotProfilePicture = picture
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProfilePhotosOf returns list of profile pictures for a user.
|
||||
func ProfilePhotosOf(bot *tb.Bot, user *tb.User) ([]tb.Photo, error) {
|
||||
params := map[string]interface {
|
||||
}{
|
||||
"user_id": user.Recipient(),
|
||||
"limit": 1,
|
||||
}
|
||||
|
||||
data, err := bot.Raw("getUserProfilePhotos", params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Result struct {
|
||||
Count int `json:"total_count"`
|
||||
Photos []tb.Photo `json:"photos"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(data, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Result.Photos, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
)
|
||||
|
||||
var (
|
||||
registerNodeMessage = "📖 Connect your Lightning node with your wallet.\n\nCurrently supported backends: `lnd` and `lnbits`\nTo register a node, type: `/node add <type> <info>`\n\n*LND (REST):* `/node add lnd <host> <macaroon> <cert>`\n*LNbits:* `/node add lnbits <host> <key>`\n\nℹ️ Always use `https://` for the `<host>`, even if you use a Tor node. Certificates and macaroons need to be in base64 format.\n\n⚠️ For security reasons, you should *only use an invoice macaroon* for LND and an *invoice key* for LNbits."
|
||||
nodeHelpMessage = "⚙️ *Commands:*\n`/node add <type> <info>` ✅ Add your node.\n`/node invoice <admount>` ⤵️ Fetch an invoice from your node.\n`/node proxy <amount>` 🔀 Proxy a payment to your node (privacy feature).\n`/node help` 📖 Show help."
|
||||
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
|
||||
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
|
||||
checkInvoiceButtonMessage = "🔄 Check invoice"
|
||||
routingInvoiceMessage = "🔄 Getting invoice from your node..."
|
||||
checkingNodeMessage = "🔄 Checking your node..."
|
||||
errorCouldNotAddNodeMessage = "❌ Could not add node. Please check your node details."
|
||||
gettingInvoiceOnlyErrorMessage = "❌ Error getting invoice from your node."
|
||||
gettingInvoiceErrorMessage = "❌ Error getting invoice from your node. Your funds are still available."
|
||||
payingInvoiceErrorMessage = "❌ Could not route payment. Your funds are still available."
|
||||
invoiceRoutedMessage = "✅ *Payment routed to your node.*"
|
||||
invoiceSettledMessage = "✅ *Invoice settled.*"
|
||||
nodeAddedMessage = "✅ *Node added.*"
|
||||
satdressCheckInvoicenMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnSatdressCheckInvoice = satdressCheckInvoicenMenu.Data(checkInvoiceButtonMessage, "satdress_check_invoice")
|
||||
)
|
||||
|
||||
// todo -- rename to something better like parse node settings or something
|
||||
func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.BackendParams, error) {
|
||||
// input is "/node add <Type> <Host> <Macaroon> <Cert>"
|
||||
params := satdress.LNDParams{}
|
||||
splits := strings.Split(m.Text, " ")
|
||||
splitlen := len(splits)
|
||||
if splitlen < 4 {
|
||||
return params, fmt.Errorf("not enough arguments")
|
||||
}
|
||||
switch strings.ToLower(splits[2]) {
|
||||
case "lnd":
|
||||
if splitlen < 5 || splitlen > 7 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> [<Cert>]")
|
||||
}
|
||||
host := splits[3]
|
||||
macaroon := splits[4]
|
||||
var pem []byte
|
||||
if splitlen == 6 {
|
||||
cert := splits[5]
|
||||
pem := parseCertificateToPem(cert)
|
||||
if len(pem) < 1 {
|
||||
return params, fmt.Errorf("certificate has invalid format")
|
||||
}
|
||||
}
|
||||
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
|
||||
return satdress.LNDParams{
|
||||
Cert: pem,
|
||||
Host: host,
|
||||
Macaroon: macaroon,
|
||||
CertString: string(pem),
|
||||
}, nil
|
||||
case "lnbits":
|
||||
if splitlen < 5 || splitlen > 6 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
|
||||
}
|
||||
host := splits[3]
|
||||
key := splits[4]
|
||||
|
||||
host = strings.TrimSuffix(host, "/")
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
return satdress.LNBitsParams{
|
||||
Host: host,
|
||||
Key: key,
|
||||
}, nil
|
||||
default:
|
||||
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
|
||||
}
|
||||
}
|
||||
|
||||
func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
|
||||
if len(node.NodeType) == 0 {
|
||||
return "", fmt.Errorf("node type is empty")
|
||||
}
|
||||
var node_info_str_filled string
|
||||
var node_info_str string
|
||||
switch strings.ToLower(node.NodeType) {
|
||||
case "lnd":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Macaroon:*\n\n`%s`\n\n*Cert:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNDParams.Host, node.LNDParams.Macaroon, node.LNDParams.CertString)
|
||||
case "lnbits":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Key:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNbitsParams.Host, node.LNbitsParams.Key)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown node type")
|
||||
}
|
||||
return fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled), nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.trySendMessage(ctx.Message().Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if user.Settings == nil {
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, fmt.Errorf("no node registered")
|
||||
}
|
||||
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, node_info_str)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) == 1 {
|
||||
return bot.getNodeHandler(ctx)
|
||||
} else if len(splits) > 1 {
|
||||
switch strings.ToLower(splits[1]) {
|
||||
case "invoice":
|
||||
return bot.invHandler(ctx)
|
||||
case "add":
|
||||
return bot.registerNodeHandler(ctx)
|
||||
case "check":
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
case "proxy":
|
||||
return bot.satdressProxyHandler(ctx)
|
||||
case "help":
|
||||
return bot.nodeHelpHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, checkingNodeMessage)
|
||||
|
||||
backendParams, err := parseUserSettingInput(ctx, m)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
switch backend := backendParams.(type) {
|
||||
case satdress.LNDParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// save node in db
|
||||
user.Settings.Node.LNDParams = &backend
|
||||
user.Settings.Node.NodeType = "lnd"
|
||||
case satdress.LNBitsParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
// save node in db
|
||||
user.Settings.Node.LNbitsParams = &backend
|
||||
user.Settings.Node.NodeType = "lnbits"
|
||||
|
||||
}
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
return ctx, err
|
||||
}
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
|
||||
|
||||
log.Infof("[node:add] Added node of user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.NodeType == "" {
|
||||
bot.trySendMessage(m.Sender, "You did not register a node yet.")
|
||||
return ctx, fmt.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
}
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("[node:invoice] Getting invoice for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
|
||||
switch user.Settings.Node.NodeType {
|
||||
case "lnd":
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
case "lnbits":
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
default:
|
||||
return ctx, fmt.Errorf("unknown node type %s", user.Settings.Node.NodeType)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceOnlyErrorMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(getInvoiceParams.PR, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", getInvoiceParams.PR)})
|
||||
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
log.Infof("[node:invoice] Invoice created for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// check if invoice settles
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
tgUser := LoadUser(ctx).Telegram
|
||||
user, err := GetLnbitsUserWithSettings(tgUser, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// get the getInvoiceParams from cache
|
||||
log.Debugf("[Cache] Getting key: %s", fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
|
||||
|
||||
// check the invoice
|
||||
|
||||
// check if there is an invoice check message in cache already
|
||||
check_message_interface, err := bot.Cache.Get(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash))
|
||||
var check_message *tb.Message
|
||||
if err != nil {
|
||||
// send a new message if there isn't one in the cache
|
||||
check_message = bot.trySendMessageEditable(tgUser, checkingInvoiceMessage)
|
||||
} else {
|
||||
check_message = check_message_interface.(*tb.Message)
|
||||
check_message, err = bot.tryEditMessage(check_message, checkingInvoiceMessage)
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// save it in the cache for another call later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash), check_message, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
|
||||
runtime.NewRetryTicker(deadLineCtx, "node_invoice_check", runtime.WithRetryDuration(5*time.Second)).Do(func() {
|
||||
// get invoice from user's node
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Checking invoice: %s", getInvoiceParams.Hash)
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
if getInvoiceParams.Status == "SETTLED" {
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice settled: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceSettledMessage)
|
||||
cancel()
|
||||
}
|
||||
|
||||
}, func() {
|
||||
// cancel
|
||||
},
|
||||
func() {
|
||||
// deadline
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice check expired: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceNotSettledMessage,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: checkInvoiceButtonMessage, Unique: "satdress_check_invoice"}},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func parseCertificateToPem(cert string) []byte {
|
||||
block, _ := pem.Decode([]byte(cert))
|
||||
if block != nil {
|
||||
// already PEM
|
||||
return []byte(cert)
|
||||
} else {
|
||||
var dec []byte
|
||||
|
||||
dec, err := hex.DecodeString(cert)
|
||||
if err != nil {
|
||||
// not HEX
|
||||
dec, err = base64.StdEncoding.DecodeString(cert)
|
||||
if err != nil {
|
||||
// not base54, we have a problem huston
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if block, _ := pem.Decode(dec); block != nil {
|
||||
return dec
|
||||
}
|
||||
// decoding went wrong
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return ctx, fmt.Errorf("no node settings.")
|
||||
}
|
||||
|
||||
var amount int64
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
memo := "🔀 Payment proxy in."
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
|
||||
log.Infof("[node] Proxy payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
user := invoiceEvent.User
|
||||
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
|
||||
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
|
||||
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[node:proxy] Relaying payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
|
||||
// now relay the payment to the user's node
|
||||
var amount int64 = invoiceEvent.Amount
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
var err error
|
||||
if user.Settings.Node.NodeType == "lnd" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
} else if user.Settings.Node.NodeType == "lnbits" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
log.Infof("[node:proxy] Retrieved invoice for payment of user %s backend %s. Paying...", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
// verbose error message, turned off for now
|
||||
// if len(err.Error()) == 0 {
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(check_message, payingInvoiceErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("proxypay:%d:%d:%s", user.Telegram.ID, amount, RandStringRunes(8))
|
||||
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
Invoice: invoice.PaymentRequest,
|
||||
Hash: invoice.PaymentHash,
|
||||
Amount: amount,
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
|
||||
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(check_message, invoiceRoutedMessage)
|
||||
|
||||
log.Infof("[node:proxy] Proxy paid for user %s backend %s.", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
return
|
||||
}
|
||||
+167
-90
@@ -4,20 +4,28 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
|
||||
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
|
||||
)
|
||||
@@ -39,9 +47,9 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
|
||||
}
|
||||
|
||||
type SendData struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
ToTelegramId int `json:"to_telegram_id"`
|
||||
ToTelegramId int64 `json:"to_telegram_id"`
|
||||
ToTelegramUser string `json:"to_telegram_user"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
@@ -50,11 +58,11 @@ type SendData struct {
|
||||
}
|
||||
|
||||
// sendHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
@@ -63,47 +71,63 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
|
||||
bot.tipHandler(ctx, m)
|
||||
return
|
||||
if ctx.Message().IsReply() && ctx.Message().Chat.Type != tb.ChatPrivate {
|
||||
return bot.tipHandler(ctx)
|
||||
|
||||
}
|
||||
|
||||
if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return
|
||||
}
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
// NewMessage(m, WithDuration(0, bot))
|
||||
// return
|
||||
// }
|
||||
|
||||
// get send amount, returns 0 if no amount is given
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
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 := ""
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
arg, err = getArgumentFromCommand(m.Text, 2)
|
||||
} else if len(strings.Split(m.Text, " ")) == 2 {
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
space := regexp.MustCompile(`\s+`)
|
||||
ctx.Message().Text = space.ReplaceAllString(ctx.Message().Text, " ")
|
||||
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
|
||||
err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
ctx, err = bot.sendToLightningAddress(ctx, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
// todo: this error might have been overwritten by the functions above
|
||||
// we should only check for a valid amount here, instead of error and amount
|
||||
amount, err = decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
return
|
||||
// is a user given?
|
||||
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
|
||||
if err != nil && ctx.Message().Chat.Type == tb.ChatPrivate {
|
||||
_, err = bot.askForUser(ctx, "", "CreateSendState", ctx.Message().Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// is an amount given?
|
||||
amount, err = decodeAmountFromCommand(ctx.Message().Text)
|
||||
if (err != nil || amount < 1) && ctx.Message().Chat.Type == tb.ChatPrivate {
|
||||
_, err = bot.askForAmount(ctx, "", "CreateSendState", 0, 0, ctx.Message().Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
@@ -111,42 +135,51 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Warnln(errmsg)
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
// check for memo in command
|
||||
sendMemo := GetMemoFromCommand(m.Text, 3)
|
||||
sendMemo := GetMemoFromCommand(ctx.Message().Text, 3)
|
||||
|
||||
toUserStrMention := ""
|
||||
toUserStrWithoutAt := ""
|
||||
|
||||
// check for user in command, accepts user mention or plain username without @
|
||||
if len(m.Entities) > 1 && m.Entities[1].Type == "mention" {
|
||||
toUserStrMention = m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
|
||||
if len(ctx.Message().Entities) > 1 && ctx.Message().Entities[1].Type == "mention" {
|
||||
toUserStrMention = ctx.Message().Text[ctx.Message().Entities[1].Offset : ctx.Message().Entities[1].Offset+ctx.Message().Entities[1].Length]
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrMention, "@")
|
||||
} else {
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(ctx.Message().Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
if err == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
return
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
// cut username if it's too long
|
||||
if len(toUserStrMention) > 100 {
|
||||
toUserStrMention = toUserStrMention[:100]
|
||||
}
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if user.ID == toUserDb.ID {
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
|
||||
// entire text of the inline object
|
||||
@@ -155,10 +188,10 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmSendAppendMemo"), str.MarkdownEscape(sendMemo))
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := SendData{
|
||||
id := fmt.Sprintf("send-%d-%d-%s", ctx.Message().Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := &SendData{
|
||||
From: user,
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Amount: int64(amount),
|
||||
ToTelegramId: toUserDb.Telegram.ID,
|
||||
ToTelegramUser: toUserStrWithoutAt,
|
||||
@@ -171,10 +204,10 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
|
||||
sendDataJson, err := json.Marshal(sendData)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return ctx, err
|
||||
}
|
||||
// save the send data to the Database
|
||||
// log.Debug(sendData)
|
||||
@@ -189,39 +222,75 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
sendButton,
|
||||
cancelButton),
|
||||
)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Chat, confirmText, sendConfirmationMenu)
|
||||
if ctx.Message().Private() {
|
||||
bot.trySendMessage(ctx.Chat(), confirmText, sendConfirmationMenu)
|
||||
} else {
|
||||
bot.tryReplyMessage(m, confirmText, sendConfirmationMenu)
|
||||
bot.tryReplyMessage(ctx.Message(), confirmText, sendConfirmationMenu)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// keyboardSendHandler will be called when the user presses the Send button on the keyboard
|
||||
// it will pop up a new keyboard with the last interacted contacts to send funds to
|
||||
// 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)
|
||||
}
|
||||
enterUserStateData := &EnterUserStateData{
|
||||
ID: "id",
|
||||
Type: "CreateSendState",
|
||||
OiringalCommand: "/send",
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
|
||||
sendToButtons = bot.makeContactsButtons(ctx)
|
||||
|
||||
// if no contact is found (one entry will always be inside, it's the enter user button)
|
||||
// immediatelly go to the send handler
|
||||
if len(sendToButtons) == 1 {
|
||||
ctx.Message().Text = "/send"
|
||||
return bot.sendHandler(ctx)
|
||||
}
|
||||
|
||||
// Attention! We need to ues the original Telegram.Send command here!
|
||||
// bot.trySendMessage will replace the keyboard with the default one and we want to send a different keyboard here
|
||||
// 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())
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// sendHandler invoked when user clicked send on payment confirmation
|
||||
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
tx := &SendData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
return
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = sendData.Lock(sendData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
if sendData.From.Telegram.ID != ctx.Callback().Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer sendData.Release(sendData, bot.Bunt)
|
||||
defer sendData.Set(sendData, bot.Bunt)
|
||||
|
||||
// // remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(sendData.Message), &tb.ReplyMarkup{})
|
||||
@@ -241,67 +310,75 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
to, err := GetLnbitsUser(&tb.User{ID: toId, Username: toUserStrWithoutAt}, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
bot.tryDeleteMessage(ctx.Callback().Message)
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, int(amount), TransactionType("send"))
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success || err != nil {
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf("%s %s", i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), err), &tb.ReplyMarkup{})
|
||||
return
|
||||
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] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify to user
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
|
||||
if c.Message.Private() {
|
||||
if ctx.Callback().Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu to pop up
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(ctx.Callback().Message)
|
||||
bot.trySendMessage(ctx.Callback().Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendPublicSentMessage"), amount, fromUserStrMd, toUserStrMd), &tb.ReplyMarkup{})
|
||||
bot.trySendMessage(ctx.Callback().Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
bot.tryEditMessage(ctx.Callback().Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendPublicSentMessage"), amount, fromUserStrMd, toUserStrMd), &tb.ReplyMarkup{})
|
||||
}
|
||||
// send memo if it was present
|
||||
if len(sendMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(sendMemo)))
|
||||
}
|
||||
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) cancelSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
// reset state immediately
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
return
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
// remove buttons from confirmation message
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
sendData.InTransaction = false
|
||||
// delete and send instead of edit for the keyboard to pop up after sending
|
||||
bot.tryDeleteMessage(c)
|
||||
bot.trySendMessage(c.Message.Chat, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"))
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
|
||||
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
|
||||
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
|
||||
user := LoadUser(ctx)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if len(shops.Shops) > 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
|
||||
}
|
||||
if user.Telegram.ID == shops.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
func (bot TipBot) shopsSettingsMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
|
||||
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
|
||||
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
|
||||
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
|
||||
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
|
||||
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
|
||||
// buttons := []tb.Row{
|
||||
// shopKeyboard.Row(shopLinkShopButton),
|
||||
// shopKeyboard.Row(shopDescriptionShopButton),
|
||||
// shopKeyboard.Row(shopRenameShopButton),
|
||||
// shopKeyboard.Row(shopDeleteShopButton),
|
||||
// // shopKeyboard.Row(shopResetShopButton),
|
||||
// shopKeyboard.Row(shopShopsButton),
|
||||
// }
|
||||
// shopKeyboard.Inline(
|
||||
// buttons...,
|
||||
// )
|
||||
|
||||
button := []tb.Btn{
|
||||
shopLinkShopButton,
|
||||
shopDescriptionShopButton,
|
||||
shopRenameShopButton,
|
||||
shopDeleteShopButton,
|
||||
shopShopsButton,
|
||||
}
|
||||
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemSettingsMenu builds the buttons of the item settings
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
|
||||
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
|
||||
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
|
||||
shopItemAddFileButton = shopKeyboard.Data("💾 Add files ...", "shop_itemaddfile", item.ID)
|
||||
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
|
||||
user := LoadUser(ctx)
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemDeleteButton, shopItemSettingsBackButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemTitleButton, shopItemPriceButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemAddFileButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
|
||||
func (bot TipBot) shopItemConfirmBuyMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemBuyButton = shopKeyboard.Data(fmt.Sprintf("💸 Pay %d sat", item.Price), "shop_itembuy", item.ID)
|
||||
shopItemCancelBuyButton = shopKeyboard.Data("⬅️ Back", "shop_itemcancelbuy", item.ID)
|
||||
buttons := []tb.Row{}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemBuyButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemCancelBuyButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopMenu builds the buttons in the item browser
|
||||
func (bot TipBot) shopMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
user := LoadUser(ctx)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shop.ShopsID)
|
||||
shopAddItemButton = shopKeyboard.Data("✅ New item", "shop_additem", shop.ID)
|
||||
shopItemSettingsButton = shopKeyboard.Data("⚙️ Settings", "shop_itemsettings", item.ID)
|
||||
shopNextitemButton = shopKeyboard.Data(">", "shop_nextitem", shop.ID)
|
||||
shopPrevitemButton = shopKeyboard.Data("<", "shop_previtem", shop.ID)
|
||||
buyButtonText := "📩 Get"
|
||||
if item.Price > 0 {
|
||||
buyButtonText = fmt.Sprintf("Buy (%d sat)", item.Price)
|
||||
}
|
||||
shopBuyitemButton = shopKeyboard.Data(buyButtonText, "shop_buyitem", item.ID)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
if len(shop.Items) == 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton))
|
||||
} else {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton, shopItemSettingsButton))
|
||||
}
|
||||
}
|
||||
// publicButtons := []tb.Row{}
|
||||
if len(shop.Items) > 0 {
|
||||
if shopView.Page == len(shop.Items)-1 {
|
||||
// last page
|
||||
shopNextitemButton = shopKeyboard.Data("x", "shop_nextitem", shop.ID)
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopPrevitemButton, shopBuyitemButton, shopNextitemButton))
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopShopsButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// makseShopSelectionButtons produces a list of all buttons with a uniqueString ID
|
||||
func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string) []tb.Btn {
|
||||
var buttons []tb.Btn
|
||||
for _, shop := range shops {
|
||||
buttons = append(buttons, shopKeyboard.Data(shop.Title, uniqueString, shop.ID))
|
||||
}
|
||||
return buttons
|
||||
}
|
||||
|
||||
// -------------- ShopView --------------
|
||||
|
||||
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
|
||||
func (bot *TipBot) getUserShopview(ctx intercept.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
shopView = sv.(ShopView)
|
||||
return
|
||||
}
|
||||
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx intercept.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
defer mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
shopView, err = bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
deleteStatusMessages(shopView.StatusMessages, bot)
|
||||
shopView.StatusMessages = make([]*tb.Message, 0)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
return
|
||||
}
|
||||
|
||||
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
|
||||
// delete all status messages from telegram
|
||||
for _, msg := range messages {
|
||||
bot.tryDeleteMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// sendStatusMessage adds a status message to the shopVoew.statusMessages
|
||||
// slide and sends a status message to the user.
|
||||
func (bot *TipBot) sendStatusMessage(ctx intercept.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
|
||||
// write into cache
|
||||
mutex.Lock(id)
|
||||
defer mutex.Unlock(id)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
statusMsg := bot.trySendMessage(to, what, options...)
|
||||
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// sendStatusMessageAndDelete invokes sendStatusMessage and creates
|
||||
// a ticker to delete all status messages after 5 seconds.
|
||||
func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
|
||||
// kick off ticker to remove all messages
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
// removing ticker asap done
|
||||
runtime.RemoveTicker(id)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// --------------- Shop ---------------
|
||||
|
||||
// initUserShops is a helper function for creating a Shops for the user in the database
|
||||
func (bot *TipBot) initUserShops(ctx intercept.Context, user *lnbits.User) (*Shops, error) {
|
||||
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
|
||||
shops := &Shops{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Owner: user,
|
||||
Shops: []string{},
|
||||
MaxShops: MAX_SHOPS,
|
||||
}
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// getUserShops returns the Shops for the user
|
||||
func (bot *TipBot) getUserShops(ctx intercept.Context, user *lnbits.User) (*Shops, error) {
|
||||
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)
|
||||
return &Shops{}, err
|
||||
}
|
||||
shops := sn.(*Shops)
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// addUserShop adds a new Shop to the Shops of a user
|
||||
func (bot *TipBot) addUserShop(ctx intercept.Context, user *lnbits.User) (*Shop, error) {
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return &Shop{}, err
|
||||
}
|
||||
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
|
||||
shop := &Shop{
|
||||
Base: storage.New(storage.ID(shopId)),
|
||||
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
|
||||
Owner: user,
|
||||
Type: "photo",
|
||||
Items: make(map[string]ShopItem),
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
ShopsID: shops.ID,
|
||||
MaxItems: MAX_ITEMS_PER_SHOP,
|
||||
}
|
||||
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
|
||||
shops.Shops = append(shops.Shops, shopId)
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shop, nil
|
||||
}
|
||||
|
||||
// getShop returns the Shop of a given ID
|
||||
func (bot *TipBot) getShop(ctx intercept.Context, shopId string) (*Shop, error) {
|
||||
tx := &Shop{Base: storage.New(storage.ID(shopId))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getShop] %s", err.Error())
|
||||
return &Shop{}, err
|
||||
}
|
||||
shop := sn.(*Shop)
|
||||
if shop.Owner == nil {
|
||||
return &Shop{}, fmt.Errorf("shop has no owner")
|
||||
}
|
||||
return shop, nil
|
||||
}
|
||||
+31
-21
@@ -2,57 +2,63 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return
|
||||
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
if !ctx.Message().Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(m.Sender)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(ctx.Sender()), ctx.Sender().ID)
|
||||
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()))
|
||||
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryDeleteMessage(walletCreationMsg)
|
||||
ctx = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx, m)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx, m)
|
||||
ctx.Context = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx)
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
if len(ctx.Sender().Username) == 0 {
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
}
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = &lnbits.User{Telegram: tguser}
|
||||
err = bot.createWallet(user)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
// set user initialized
|
||||
user, err := GetUser(tguser, bot)
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
@@ -80,12 +86,12 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
|
||||
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)
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
@@ -94,17 +100,21 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
user.AnonIDSha256 = str.AnonIdSha256(user)
|
||||
user.UUID = str.UUIDSha256(user)
|
||||
|
||||
user.Initialized = false
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx intercept.Context) (intercept.Context, error)
|
||||
|
||||
var stateCallbackMessage StateCallbackMessage
|
||||
|
||||
func initializeStateCallbackMessage(bot *TipBot) {
|
||||
stateCallbackMessage = StateCallbackMessage{
|
||||
lnbits.UserStateLNURLEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterUser: bot.enterUserHandler,
|
||||
lnbits.UserEnterShopTitle: bot.enterShopTitleHandler,
|
||||
lnbits.UserStateShopItemSendPhoto: bot.addShopItemPhoto,
|
||||
lnbits.UserStateShopItemSendPrice: bot.enterShopItemPriceHandler,
|
||||
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
|
||||
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
|
||||
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
|
||||
lnbits.UserEnterDallePrompt: bot.confirmGenerateImages,
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,57 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
// getChatIdFromRecipient will parse the recipient to int64
|
||||
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return chatId, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
|
||||
msg, err := bot.Telegram.Forward(to, what, options...)
|
||||
rate.CheckLimit(to)
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
log.Tracef("[trySendMessage] chatId: %d", chatId)
|
||||
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Send(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
@@ -21,15 +60,25 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
|
||||
}
|
||||
|
||||
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
msg, err := bot.Telegram.Reply(to, what, options...)
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
msg, err := bot.Telegram.Edit(to, what, options...)
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message, err error) {
|
||||
// get a sig for the rate limiter
|
||||
sig, chat := to.MessageSig()
|
||||
if chat != 0 {
|
||||
sig = strconv.FormatInt(chat, 10)
|
||||
}
|
||||
rate.CheckLimit(sig)
|
||||
|
||||
_, chatId := to.MessageSig()
|
||||
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -37,8 +86,99 @@ func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...in
|
||||
}
|
||||
|
||||
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
if !allowedToPerformAction(bot, msg, isAdminAndCanDelete) {
|
||||
return
|
||||
}
|
||||
rate.CheckLimit(msg)
|
||||
err := bot.Telegram.Delete(msg)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// allowedToPerformAction will check if bot is allowed to perform an action on the tb.Editable.
|
||||
// this function will persist the admins list in cache for 5 minutes.
|
||||
// if no admins list is found for this group, bot will always fetch a fresh list.
|
||||
func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(members []tb.ChatMember, me *tb.User) bool) bool {
|
||||
switch editable.(type) {
|
||||
case *tb.Message:
|
||||
message := editable.(*tb.Message)
|
||||
if message.Sender.ID == bot.Telegram.Me.ID {
|
||||
break
|
||||
}
|
||||
chat := message.Chat
|
||||
if chat.Type == tb.ChatSuperGroup || chat.Type == tb.ChatGroup {
|
||||
admins, err := bot.Cache.Get(fmt.Sprintf("admins-%d", chat.ID))
|
||||
if err != nil {
|
||||
admins, err = bot.Telegram.AdminsOf(message.Chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
if action(admins.([]tb.ChatMember), bot.Telegram.Me) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isAdminAndCanDelete will check if me is in members list and allowed to delete messages
|
||||
func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return admin.CanDeleteMessages
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isOwner will check if user is owner of group
|
||||
func (bot *TipBot) isOwner(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID && admin.Role == "creator" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAdmin will check if user is admin in a group
|
||||
func (bot *TipBot) isAdmin(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAdmin will check if user is admin in a group
|
||||
func (bot *TipBot) isAdminAndCanInviteUsers(chat *tb.Chat, me *tb.User) bool {
|
||||
members, err := bot.Telegram.AdminsOf(chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return admin.CanInviteUsers
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
+96
-12
@@ -2,42 +2,126 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
|
||||
// check if user is in Database, if not, initialize wallet
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
return bot.startHandler(ctx)
|
||||
}
|
||||
|
||||
// check if the user clicked on the balance button
|
||||
if strings.HasPrefix(m.Text, MainMenuCommandBalance) {
|
||||
bot.tryDeleteMessage(m)
|
||||
// overwrite the message text so it doesn't cause an infinite loop
|
||||
// because balanceHandler calls anyTextHAndler...
|
||||
m.Text = ""
|
||||
return bot.balanceHandler(ctx)
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
return bot.payHandler(ctx)
|
||||
}
|
||||
if lightning.IsLnurl(anyText) {
|
||||
m.Text = "/lnurl " + anyText
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return bot.lnurlHandler(ctx)
|
||||
}
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
return c(ctx)
|
||||
//ResetUserState(user, bot)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
type EnterUserStateData struct {
|
||||
ID string `json:"ID"` // holds the ID of the tx object in bunt db
|
||||
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
|
||||
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
|
||||
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
|
||||
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
|
||||
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
|
||||
}
|
||||
|
||||
func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string, originalCommand string) (enterUserStateData *EnterUserStateData, err error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
enterUserStateData = &EnterUserStateData{
|
||||
ID: id,
|
||||
Type: eventType,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
|
||||
// Let the user enter a user and return
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "enterUserMessage"), tb.ForceReply)
|
||||
return
|
||||
}
|
||||
|
||||
// could be a LNURL
|
||||
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
|
||||
if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
bot.enterAmountHandler(ctx, m)
|
||||
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
|
||||
// the amount is then stored as an entry in the user's stateKey in the user database
|
||||
// any other ctx that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterUser) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") || m.Text == SendMenuCommandEnter {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
var EnterUserStateData EnterUserStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
userstr := m.Text
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterUserStateData.Type {
|
||||
case "CreateSendState":
|
||||
m.Text = fmt.Sprintf("/send %s", userstr)
|
||||
return bot.sendHandler(ctx)
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+24
-26
@@ -6,12 +6,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func helpTipUsage(ctx context.Context, errormsg string) string {
|
||||
@@ -30,14 +33,13 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
defer NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
bot.anyTextHandler(ctx)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
|
||||
// only if message is a reply
|
||||
@@ -45,13 +47,13 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipDidYouReplyMessage")))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipInviteGroupMessage"))
|
||||
return
|
||||
return ctx, errors.Create(errors.NoReplyMessageError)
|
||||
}
|
||||
|
||||
if ok, err := TipCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
@@ -62,22 +64,21 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
if err == nil {
|
||||
return
|
||||
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
|
||||
to := LoadReplyToUser(ctx)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
|
||||
return
|
||||
return ctx, fmt.Errorf("cannot tip yourself")
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -91,7 +92,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,30 +107,25 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
transactionMemo := fmt.Sprintf("🏅 Tip from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s: %s", Translate(ctx, "tipErrorMessage"), Translate(ctx, "tipUndefinedErrorMsg")))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
|
||||
|
||||
log.Infof("[tip] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify users
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
|
||||
// forward tipped message to user once
|
||||
if !messageHasTip {
|
||||
@@ -140,5 +136,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
if len(tipMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tipMemo)))
|
||||
}
|
||||
return
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -4,29 +4,35 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineTipjarMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
|
||||
inlineTipjarMenu = &tb.ReplyMarkup{ResizeKeyboard: false}
|
||||
btnCancelInlineTipjar = inlineTipjarMenu.Data("🚫", "cancel_tipjar_inline")
|
||||
btnAcceptInlineTipjar = inlineTipjarMenu.Data("💸 Pay", "confirm_tipjar_inline")
|
||||
)
|
||||
|
||||
type InlineTipjar struct {
|
||||
*transaction.Base
|
||||
*storage.Base
|
||||
Message string `json:"inline_tipjar_message"`
|
||||
Amount int `json:"inline_tipjar_amount"`
|
||||
GivenAmount int `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int `json:"inline_tipjar_peruseramount"`
|
||||
Amount int64 `json:"inline_tipjar_amount"`
|
||||
GivenAmount int64 `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int64 `json:"inline_tipjar_peruseramount"`
|
||||
To *lnbits.User `json:"inline_tipjar_to"`
|
||||
From []*lnbits.User `json:"inline_tipjar_from"`
|
||||
Memo string `json:"inline_tipjar_memo"`
|
||||
@@ -52,14 +58,14 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
perUserAmount, err := GetAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := amount / perUserAmount
|
||||
nTotal := int(amount / perUserAmount)
|
||||
toUser := LoadUser(ctx)
|
||||
// toUserStr := GetUserStr(sender)
|
||||
// // check for memo in command
|
||||
@@ -68,7 +74,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
inlineMessage := fmt.Sprintf(
|
||||
Translate(ctx, "inlineTipjarMessage"),
|
||||
perUserAmount,
|
||||
GetUserStr(toUser.Telegram),
|
||||
GetUserStrMd(toUser.Telegram),
|
||||
0,
|
||||
amount,
|
||||
0,
|
||||
@@ -77,10 +83,10 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineTipjarAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
id := fmt.Sprintf("tipjar:%s:%d", RandStringRunes(10), amount)
|
||||
|
||||
return &InlineTipjar{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
To: toUser,
|
||||
@@ -127,28 +133,28 @@ func (bot TipBot) makeTipjar(ctx context.Context, m *tb.Message, query bool) (*I
|
||||
return tipjar, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, q.Text, &q.From)
|
||||
func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, ctx.Query().Text, ctx.Query().Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
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(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -156,48 +162,44 @@ func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool)
|
||||
}
|
||||
|
||||
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
|
||||
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
inlineTipjarMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
// slice of buttons
|
||||
buttons := make([]tb.Btn, 0)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, cancelInlineTipjarButton)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
|
||||
inlineTipjarMenu.Inline(
|
||||
inlineTipjarMenu.Row(buttons...))
|
||||
return inlineTipjarMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
func (bot TipBot) tipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
bot.anyTextHandler(ctx)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
|
||||
return
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
ctx = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
ctx.Context = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
tipjarMsg := bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
|
||||
inlineTipjar.Base.MessageID = fmt.Sprint(tipjarMsg.ID)
|
||||
inlineTipjar.Base.ChatID = fmt.Sprint(-tipjarMsg.Chat.ID)
|
||||
inlineTipjar.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineTipjar.ChatID[3:], inlineTipjar.Base.MessageID)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Base.MessageURL)
|
||||
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err)
|
||||
return
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
@@ -212,12 +214,12 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -228,46 +230,48 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err)
|
||||
return
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
err = inlineTipjar.Lock(inlineTipjar, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] LockTipjar %s error: %s", inlineTipjar.ID, err)
|
||||
return
|
||||
}
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
return
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
// release tipjar no matter what
|
||||
defer inlineTipjar.Release(inlineTipjar, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
// // check if to user has already given to the tipjar
|
||||
for _, a := range inlineTipjar.From {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
if a.Telegram.ID == from.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
|
||||
return
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
|
||||
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -275,36 +279,35 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
transactionMemo := fmt.Sprintf("🍯 Tipjar from %s to %s.", fromUserStr, toUserStr)
|
||||
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
|
||||
log.Infof("[tipjar] tipjar %s: %d sat from %s to %s ", inlineTipjar.ID, inlineTipjar.PerUserAmount, fromUserStr, toUserStr)
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
inlineTipjar.NGiven += 1
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
// build tipjar message
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
|
||||
inlineTipjar.PerUserAmount,
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.GivenAmount,
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
@@ -314,44 +317,62 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
if len(memo) > 0 {
|
||||
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
|
||||
}
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
// update message
|
||||
log.Infoln(inlineTipjar.Message)
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
bot.tryEditMessage(c, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
}
|
||||
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
|
||||
// tipjar is full
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
)
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message)
|
||||
bot.tryEditMessage(c, inlineTipjar.Message)
|
||||
// send update to tipjar creator
|
||||
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
|
||||
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
|
||||
}
|
||||
inlineTipjar.Active = false
|
||||
}
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
if c.Sender.ID == inlineTipjar.To.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineTipjar inactive
|
||||
inlineTipjar.Active = false
|
||||
inlineTipjar.InTransaction = false
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
return
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
|
||||
// send update to tipjar creator
|
||||
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
|
||||
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
|
||||
}
|
||||
|
||||
// set the inlineTipjar inactive
|
||||
inlineTipjar.Active = false
|
||||
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
}
|
||||
|
||||
func listTipjarGivers(inlineTipjar *InlineTipjar) string {
|
||||
var from_str string
|
||||
from_str = fmt.Sprintf("🍯 *Tipjar summary*\n\nMemo: %s\nCapacity: %d sat\nGivers: %d\nCollected: %d sat\n\n*Givers:*\n\n", inlineTipjar.Memo, inlineTipjar.Amount, inlineTipjar.NGiven, inlineTipjar.GivenAmount)
|
||||
from_str += "```\n"
|
||||
for _, from := range inlineTipjar.From {
|
||||
from_str += fmt.Sprintf("%s\n", GetUserStr(from.Telegram))
|
||||
}
|
||||
from_str += "```"
|
||||
return from_str
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -26,17 +26,22 @@ const (
|
||||
|
||||
type TipTooltip struct {
|
||||
Message
|
||||
TipAmount int `json:"tip_amount"`
|
||||
ID string `json:"id"`
|
||||
TipAmount int64 `json:"tip_amount"`
|
||||
Ntips int `json:"ntips"`
|
||||
LastTip time.Time `json:"last_tip"`
|
||||
Tippers []*tb.User `json:"tippers"`
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
|
||||
}
|
||||
|
||||
const maxNamesInTipperMessage = 5
|
||||
|
||||
type TipTooltipOption func(m *TipTooltip)
|
||||
|
||||
func TipAmount(amount int) TipTooltipOption {
|
||||
func TipAmount(amount int64) TipTooltipOption {
|
||||
return func(m *TipTooltip) {
|
||||
m.TipAmount = amount
|
||||
}
|
||||
@@ -50,6 +55,7 @@ func Tips(nTips int) TipTooltipOption {
|
||||
|
||||
func NewTipTooltip(m *tb.Message, opts ...TipTooltipOption) *TipTooltip {
|
||||
tipTooltip := &TipTooltip{
|
||||
ID: fmt.Sprintf("%d-%d", m.Chat.ID, m.ReplyTo.ID),
|
||||
Message: Message{
|
||||
Message: m,
|
||||
},
|
||||
@@ -99,8 +105,8 @@ func getTippersString(tippers []*tb.User) string {
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{Chat: &tb.Chat{ID: m.Chat.ID}, ReplyTo: &tb.Message{ID: m.ReplyTo.ID}})
|
||||
err := bot.Bunt.Get(message)
|
||||
if err != nil {
|
||||
return false, message
|
||||
@@ -110,49 +116,48 @@ func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int, initializedWallet bool) (hasTip bool) {
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) (hasTip bool) {
|
||||
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
|
||||
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
|
||||
hasTip, ttt := tipTooltipExists(m, bot)
|
||||
log.Debugf("[tip] %s has tip: %t", ttt.ID, hasTip)
|
||||
if hasTip {
|
||||
// update the tooltip with new tippers
|
||||
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Errorln(err)
|
||||
// could not update the message (return false to )
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
|
||||
// todo: in case of error we should do something better than just return 0
|
||||
return false
|
||||
}
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
newToolTip(m, bot, amount, initializedWallet)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return hasTip
|
||||
}
|
||||
|
||||
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in Telegram
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, notInitializedWallet bool) error {
|
||||
ttt.TipAmount += amount
|
||||
ttt.Ntips += 1
|
||||
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
|
||||
ttt.LastTip = time.Now()
|
||||
err := ttt.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ttt.editTooltip(bot, notInitializedWallet)
|
||||
log.Debugf("[updateTooltip]: Update tip tooltip (Bunt: %s)", ttt.Key())
|
||||
return bot.Bunt.Set(ttt)
|
||||
}
|
||||
|
||||
@@ -161,17 +166,15 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
runtime.IgnoreError(bot.Bunt.View(func(tx *buntdb.Tx) error {
|
||||
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
|
||||
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
|
||||
if replyToUserId.String() == strconv.Itoa(user.ID) {
|
||||
log.Debugln("loading persistent tip tool tip messages")
|
||||
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
|
||||
log.Debugln("[tipTooltipInitializedHandler] loading persistent tip tool tip messages")
|
||||
ttt := &TipTooltip{}
|
||||
err := json.Unmarshal([]byte(value), ttt)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = ttt.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
}
|
||||
// edit to remove the "chat with bot" message
|
||||
ttt.editTooltip(&bot, false)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -180,17 +183,9 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
}))
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
|
||||
}
|
||||
|
||||
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
|
||||
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
|
||||
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ttt.Message.Message.Text = m.Text
|
||||
return nil
|
||||
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
|
||||
// ttt.Message.Message.Text = m.Text
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -45,7 +45,7 @@ func Test_getTippersString(t *testing.T) {
|
||||
func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
type fields struct {
|
||||
Message Message
|
||||
TipAmount int
|
||||
TipAmount int64
|
||||
Ntips int
|
||||
LastTip time.Time
|
||||
Tippers []*tb.User
|
||||
|
||||
@@ -7,29 +7,30 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int `json:"from_id" `
|
||||
ToId int `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.Invoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
@@ -47,7 +48,7 @@ func TransactionType(transactionType string) TransactionOption {
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, opts ...TransactionOption) *Transaction {
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
|
||||
t := &Transaction{
|
||||
Bot: bot,
|
||||
From: from,
|
||||
@@ -69,36 +70,27 @@ func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int,
|
||||
}
|
||||
|
||||
func (t *Transaction) Send() (success bool, err error) {
|
||||
// maybe remove comments, GTP-3 dreamed this up but it's nice:
|
||||
// if t.From.ID == t.To.ID {
|
||||
// err = fmt.Errorf("Can not send transaction to yourself.")
|
||||
// return false, err
|
||||
// }
|
||||
|
||||
// todo: remove this commend if the backend is back up
|
||||
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
|
||||
// success = true
|
||||
if success {
|
||||
t.Success = success
|
||||
// TODO: call post-send methods
|
||||
}
|
||||
|
||||
// save transaction to db
|
||||
tx := t.Bot.logger.Save(t)
|
||||
tx := t.Bot.DB.Transactions.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err)
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
|
||||
return success, err
|
||||
}
|
||||
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
|
||||
t.FromWallet = from.Wallet.ID
|
||||
t.FromLNbitsID = from.ID
|
||||
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
@@ -124,16 +116,32 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
Memo: memo},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
|
||||
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.Invoice = invoice
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
|
||||
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
|
||||
log.Warnf(errmsg)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// check if fromUser has balance
|
||||
_, err = bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
_, err = bot.GetUserBalance(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, err
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type TransactionsList struct {
|
||||
@@ -21,7 +22,7 @@ type TransactionsList struct {
|
||||
TxPerPage int `json:"txperpage"`
|
||||
}
|
||||
|
||||
func (txlist *TransactionsList) printTransactions(ctx context.Context) string {
|
||||
func (txlist *TransactionsList) printTransactions(ctx intercept.Context) string {
|
||||
txstr := ""
|
||||
// for _, p := range payments {
|
||||
payments := txlist.Payments
|
||||
@@ -38,21 +39,26 @@ func (txlist *TransactionsList) printTransactions(ctx context.Context) string {
|
||||
if end >= len(payments) {
|
||||
end = len(payments) - 1
|
||||
}
|
||||
for i := len(payments) - 1 - start; i >= len(payments)-1-end; i-- {
|
||||
for i := start; i <= end; i++ {
|
||||
p := payments[i]
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔼"
|
||||
} else {
|
||||
txstr += "🔽"
|
||||
}
|
||||
if p.Pending {
|
||||
txstr += "🔄"
|
||||
} else {
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔴"
|
||||
} else {
|
||||
txstr += "🟢"
|
||||
}
|
||||
}
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2006-01-02 15:04:05")
|
||||
txstr += fmt.Sprintf(" %s:", timestr)
|
||||
txstr += fmt.Sprintf(" %+d sat", p.Amount/1000)
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2 Jan 06 15:04")
|
||||
txstr += fmt.Sprintf("` %s`", timestr)
|
||||
txstr += fmt.Sprintf("` %+d sat`", p.Amount/1000)
|
||||
if p.Fee > 0 {
|
||||
txstr += fmt.Sprintf("\t(fee: %d sat)", p.Fee/1000)
|
||||
fee := p.Fee
|
||||
if fee < 1000 {
|
||||
fee = 1000
|
||||
}
|
||||
txstr += fmt.Sprintf(" _(fee: %d sat)_", fee/1000)
|
||||
}
|
||||
memo := p.Memo
|
||||
memo_maxlen := 50
|
||||
@@ -60,78 +66,75 @@ func (txlist *TransactionsList) printTransactions(ctx context.Context) string {
|
||||
memo = memo[:memo_maxlen] + "..."
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
txstr += fmt.Sprintf("\t✉️ %s", memo)
|
||||
txstr += fmt.Sprintf("\n✉️ %s", str.MarkdownEscape(memo))
|
||||
}
|
||||
txstr += "\n"
|
||||
}
|
||||
txstr += fmt.Sprintf("\nTotal: %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
txstr += fmt.Sprintf("\nShowing %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
return txstr
|
||||
}
|
||||
|
||||
var (
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
|
||||
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
|
||||
)
|
||||
|
||||
func (bot TipBot) makeTransactionsKeyboard(ctx context.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
// transactionsMeno := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions")
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions")
|
||||
leftTransactionsButton.Data = txlist.ID
|
||||
rightTransactionsButton.Data = txlist.ID
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
func (bot *TipBot) makeTransactionsKeyboard(ctx intercept.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions", txlist.ID)
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions", txlist.ID)
|
||||
|
||||
if txlist.CurrentPage == 0 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton),
|
||||
)
|
||||
} else if txlist.CurrentPage == txlist.MaxPages-1 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
rightTransactionsButton),
|
||||
)
|
||||
} else {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
}
|
||||
return transactionsMeno
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsHandler(ctx context.Context, m *tb.Message) {
|
||||
func (bot *TipBot) transactionsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
// var payments lnbits.Payments
|
||||
// paymentsInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
// if err != nil {
|
||||
// log.Info("Getting from lnbits")
|
||||
// paymentsInterface, err = bot.Client.Payments(*user.Wallet)
|
||||
// if err != nil {
|
||||
// log.Errorf("[transactions] Error: %s", err.Error())
|
||||
// return
|
||||
// }
|
||||
// bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), paymentsInterface, &store.Options{Expiration: 1 * time.Minute})
|
||||
// }
|
||||
// payments = paymentsInterface.(lnbits.Payments)
|
||||
tx_per_page := 20
|
||||
transactionsListInterface = TransactionsList{
|
||||
ID: fmt.Sprintf("txlist-%d-%s", user.Telegram.ID, RandStringRunes(5)),
|
||||
User: user,
|
||||
Payments: payments,
|
||||
LanguageCode: ctx.Value("userLanguageCode").(string),
|
||||
CurrentPage: 0,
|
||||
TxPerPage: tx_per_page,
|
||||
MaxPages: (len(payments)+1)/tx_per_page + 1,
|
||||
}
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
tx_per_page := 10
|
||||
transactionsList := TransactionsList{
|
||||
ID: fmt.Sprintf("txlist:%d:%s", user.Telegram.ID, RandStringRunes(5)),
|
||||
User: user,
|
||||
Payments: payments,
|
||||
LanguageCode: ctx.Value("userLanguageCode").(string),
|
||||
CurrentPage: 0,
|
||||
TxPerPage: tx_per_page,
|
||||
MaxPages: (len(payments)+1)/tx_per_page + 1,
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
txstr := transactionsList.printTransactions(ctx)
|
||||
bot.trySendMessage(m.Sender, txstr, bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
@@ -139,20 +142,21 @@ func (bot *TipBot) transactionsScrollLeftHandler(ctx context.Context, c *tb.Call
|
||||
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
|
||||
transactionsList.CurrentPage++
|
||||
} else {
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx context.Context, c *tb.Callback) {
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
@@ -160,10 +164,10 @@ func (bot *TipBot) transactionsScrollRightHandler(ctx context.Context, c *tb.Cal
|
||||
if transactionsList.CurrentPage > 0 {
|
||||
transactionsList.CurrentPage--
|
||||
} else {
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -3,13 +3,15 @@ package telegram
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"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/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
|
||||
@@ -59,16 +61,20 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
return append(slice, i)
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int, err error) {
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
|
||||
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
|
||||
if err != nil {
|
||||
return bot.GetUserBalance(user)
|
||||
}
|
||||
cachedBalance := u.(int)
|
||||
cachedBalance := u.(int64)
|
||||
return cachedBalance, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
if user.Wallet == nil {
|
||||
return 0, errors.New("User has no wallet")
|
||||
}
|
||||
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
@@ -81,19 +87,23 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
|
||||
return
|
||||
}
|
||||
// msat to sat
|
||||
amount = int(wallet.Balance) / 1000
|
||||
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
|
||||
// update user balance in cache
|
||||
bot.Cache.Set(
|
||||
fmt.Sprintf("%s_balance", user.Name),
|
||||
amount,
|
||||
&store.Options{Expiration: 30 * time.Second},
|
||||
&store.Options{Expiration: 1 * time.Hour},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
|
||||
// failsafe: do not create wallet for existing user
|
||||
if _, exists := bot.UserExists(tbUser); exists {
|
||||
return nil, fmt.Errorf("user already exists")
|
||||
}
|
||||
user := &lnbits.User{Telegram: tbUser}
|
||||
userStr := GetUserStr(tbUser)
|
||||
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
|
||||
@@ -103,6 +113,7 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
|
||||
log.Errorln(errmsg)
|
||||
return user, err
|
||||
}
|
||||
// todo: remove this. we're doing this already in bot.createWallet().
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -118,3 +129,16 @@ func (bot *TipBot) UserExists(user *tb.User) (*lnbits.User, bool) {
|
||||
}
|
||||
return lnbitUser, true
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserIsBanned(user *lnbits.User) bool {
|
||||
// do not respond to banned users
|
||||
if user.Wallet == nil {
|
||||
log.Tracef("[UserIsBanned] User %s has no wallet.\n", GetUserStr(user.Telegram))
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(user.Wallet.Adminkey, "banned") || strings.Contains(user.Wallet.Adminkey, "_") {
|
||||
log.Debugf("[UserIsBanned] User %s is banned. Not responding.", GetUserStr(user.Telegram))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api/userpage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
|
||||
_ "net/http/pprof"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -12,7 +24,7 @@ import (
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
log.SetLevel(log.DebugLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -22,13 +34,58 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
|
||||
defer withRecovery()
|
||||
bot := telegram.NewBot()
|
||||
webhook.NewServer(&bot)
|
||||
lnurl.NewServer(&bot)
|
||||
price.NewPriceWatcher().Start()
|
||||
bot := telegram.NewBot()
|
||||
startApiServer(&bot)
|
||||
bot.Start()
|
||||
}
|
||||
func startApiServer(bot *telegram.TipBot) {
|
||||
// log errors from interceptors
|
||||
bot.Telegram.OnError = func(err error, ctx tb.Context) {
|
||||
// we already log in the interceptors
|
||||
}
|
||||
// start internal webhook server
|
||||
webhook.NewServer(bot)
|
||||
// start external api server
|
||||
s := api.NewServer(internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
|
||||
// append lnurl ctx functions
|
||||
lnUrl := lnurl.New(bot)
|
||||
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
|
||||
// userpage server
|
||||
userpage := userpage.New(bot)
|
||||
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
|
||||
s.AppendRoute("/app/@{username}", userpage.UserWebAppHandler, http.MethodGet)
|
||||
|
||||
// append lndhub ctx functions
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext/auth`, api.AuthTypeNone, api.AccessKeyTypeNone, bot.DB.Users, hub.Handle)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
|
||||
s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
|
||||
|
||||
// starting api service
|
||||
apiService := api.Service{Bot: bot}
|
||||
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, api.AccessKeyTypeAdmin, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestream`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStream, http.MethodGet)
|
||||
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.Balance, http.MethodGet)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
internalAdminServer := api.NewServer(internal.Configuration.Bot.AdminAPIHost)
|
||||
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
|
||||
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
|
||||
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
|
||||
internalAdminServer.AppendRoute("/admin/unban/{id}", adminService.UnbanUser)
|
||||
internalAdminServer.AppendRoute("/admin/dalle/enable", adminService.EnableDalle)
|
||||
internalAdminServer.AppendRoute("/admin/dalle/disable", adminService.DisableDalle)
|
||||
internalAdminServer.PathPrefix("/debug/pprof/", http.DefaultServeMux)
|
||||
|
||||
}
|
||||
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
|
||||
@@ -21,7 +21,7 @@ func IsInvoice(message string) bool {
|
||||
|
||||
func IsLnurl(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
if strings.HasPrefix(message, "lnurl") {
|
||||
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
|
||||
// string must be a single word
|
||||
if !strings.Contains(message, " ") {
|
||||
return true
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 282 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
@@ -0,0 +1,404 @@
|
||||
# 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>`
|
||||
*/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 sats."""
|
||||
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í..."""
|
||||
+41
-6
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Senden"""
|
||||
payButtonMessage = """✅ Bezahlen"""
|
||||
payReceiveButtonMessage = """💸 Bezahlen"""
|
||||
receiveButtonMessage = """✅ Empfangen"""
|
||||
withdrawButtonMessage = """✅ Abheben"""
|
||||
cancelButtonMessage = """🚫 Abbrechen"""
|
||||
collectButtonMessage = """✅ Einsammeln"""
|
||||
nextButtonMessage = """Vor"""
|
||||
@@ -117,11 +118,20 @@ advancedMessage = """%s
|
||||
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
|
||||
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/transactions* 📃 Liste deiner Transaktionen.
|
||||
*/transactions* 📊 Liste der Transaktionen
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
|
||||
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
|
||||
*/shop* 🛍 Durchsuche Shops: `/shop` oder `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Gebe Betrag zwuschen %d und %d sat ein."""
|
||||
enterAmountMessage = """💯 Gebe Betrag ein."""
|
||||
enterUserMessage = """👤 Gebe Benutzernamen ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
@@ -227,21 +237,46 @@ lnurlPaymentFailed = """🚫 Zahlung fehlgeschlagen: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ungültiger Betrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Betrag muss zwischen %d und %d sat liegen."""
|
||||
lnurlNoUsernameMessage = """🚫 Du musst einen Telegram Username anlegen, um per LNURL Zahlungen zu empfangen."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/lnurl [betrag] <lnurl>`
|
||||
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Möchtest du dich bei %s einloggen?"""
|
||||
lnurlSuccessfulLogin = """✅ Login erfolgreich."""
|
||||
loginButtonMessage = """✅ Login"""
|
||||
loginCancelledMessage = """🚫 Login abgebrochen."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Möchtest du diese Abhebung tätigen?\n\n💸 Betrag: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Bereite Abhebung vor..."""
|
||||
lnurlWithdrawFailed = """🚫 Abhebung gescheitert."""
|
||||
lnurlWithdrawCancelled = """🚫 Abhebung abgebrochen."""
|
||||
lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Verbinde dein Wallet*
|
||||
|
||||
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto.
|
||||
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /api für deine API keys.
|
||||
|
||||
- *BlueWallet:* Drücke *New wallet*, *Import wallet*, *Scan or import a file*, und scanne den QR Code.
|
||||
- *Zeus:* Kopiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Konnte dein Wallet nicht verbinden. Bitte versuche es später noch einmal."""
|
||||
linkHiddenMessage = """🔍 Link versteckt. Gebe /link ein um ihn wieder zu sehen."""
|
||||
|
||||
# API
|
||||
|
||||
walletConnectMessage = """🔗 *Deine API Keys*
|
||||
|
||||
⚠️ Teile diese Key mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /link um dein Wallet zu verbinden.
|
||||
|
||||
- *Admin key:* `%s`
|
||||
- *Invoice key:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Keys versteckt. Gebe /api ein um sie wieder zu sehen."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
@@ -250,7 +285,7 @@ inlineQueryFaucetDescription = """Befehl: @%s faucet <gesamt> <pro_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Erzeuge einen %d sat Zapfhahn."""
|
||||
inlineResultFaucetDescription = """👉 Klicke hier um den Zapfhahn in diesen Chat zu senden."""
|
||||
|
||||
inlineFaucetMessage = """Drücke ✅ um %d sat aus diesem Zapfhahn zu zapfen.
|
||||
inlineFaucetMessage = """Drücke ✅ um %d sat aus %s's Zapfhahn zu zapfen.
|
||||
|
||||
🚰 Verbleibend: %d/%d sat (%d/%d gezapft)
|
||||
%s"""
|
||||
|
||||
+90
-14
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Send"""
|
||||
payButtonMessage = """✅ Pay"""
|
||||
payReceiveButtonMessage = """💸 Pay"""
|
||||
receiveButtonMessage = """✅ Receive"""
|
||||
withdrawButtonMessage = """✅ Withdraw"""
|
||||
cancelButtonMessage = """🚫 Cancel"""
|
||||
collectButtonMessage = """✅ Collect"""
|
||||
nextButtonMessage = """Next"""
|
||||
@@ -81,7 +82,7 @@ _This bot charges no fees but costs Satoshis to operate. If you like the bot, pl
|
||||
*/help* 📖 Read this help."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Your Lightning Address is `%s`"""
|
||||
infoYourLightningAddress = """Your Lightning address is `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin is the currency of the internet. It is permissionless and decentralized and has no masters and no controling authority. Bitcoin is sound money that is faster, more secure, and more inclusive than the legacy financial system._
|
||||
@@ -120,11 +121,22 @@ advancedMessage = """%s
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Advanced commands*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/).
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
enterAmountMessage = """💯 Enter an amount."""
|
||||
enterUserMessage = """👤 Enter a user."""
|
||||
enterTextMessage = """⌨️ Enter text."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
@@ -183,16 +195,17 @@ invoiceHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/invoice <amount> [<memo>]`
|
||||
*Example:* `/invoice 1000 Thank you!`"""
|
||||
invoicePaidText = """✅ Invoice paid."""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Payment cancelled."""
|
||||
invoicePaidMessage = """⚡️ Payment sent."""
|
||||
invoicePublicPaidMessage = """⚡️ Payment sent by %s."""
|
||||
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or Lightning address."""
|
||||
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or to a Lightning address."""
|
||||
invoiceNoAmountMessage = """🚫 Can't pay invoices without an amount."""
|
||||
insufficientFundsMessage = """🚫 Insufficient funds. You have %d sat but you need at least %d sat."""
|
||||
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."""
|
||||
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. Reserve at least 1% for fees."""
|
||||
invoicePaymentFailedMessage = """🚫 Payment failed: %s"""
|
||||
invoiceUndefinedErrorMessage = """Could not pay invoice."""
|
||||
confirmPayInvoiceMessage = """Do you want to send this payment?\n\n💸 Amount: %d sat"""
|
||||
@@ -217,7 +230,7 @@ donateHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Could not regocognize a Lightning invoice or an LNURL. Try to center the QR code, crop the photo, or zoom in."""
|
||||
photoQrNotRecognizedMessage = """🚫 Could not recognize a Lightning invoice or a LNURL. Try to center the QR code, crop the photo, or zoom in."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
@@ -230,22 +243,46 @@ lnurlPaymentFailed = """🚫 Payment failed: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Invalid amount."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Amount must be between %d and %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 You need to set a Telegram username to receive payments via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Enter an amount between %d and %d sat."""
|
||||
lnurlEnterAmountMessage = """⌨️ Enter an amount."""
|
||||
lnurlHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/lnurl [amount] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Do you want to login to %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Login successful."""
|
||||
loginButtonMessage = """✅ Login"""
|
||||
loginCancelledMessage = """🚫 Login cancelled."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Do you want to make this withdrawal?\n\n💸 Amount: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparing withdrawal..."""
|
||||
lnurlWithdrawFailed = """🚫 Withdrawal failed."""
|
||||
lnurlWithdrawCancelled = """🚫 Withdrawal cancelled."""
|
||||
lnurlWithdrawSuccess = """✅ Withdrawal requested."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Link your wallet*
|
||||
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds. Use /api for your API keys.
|
||||
|
||||
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, select *LNDHub* as Node interface, enter the URL, *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
|
||||
|
||||
# API
|
||||
|
||||
apiConnectMessage = """🔗 *Your API keys*
|
||||
|
||||
⚠️ Never share these keys with anyone or they will be able to access your funds. Use /link to link your wallet.
|
||||
|
||||
- *Admin key:* `%s`
|
||||
- *Invoice key:* `%s`"""
|
||||
apiHiddenMessage = """🔍 Keys hidden. Enter /api to see them again."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
@@ -254,7 +291,7 @@ inlineQueryFaucetDescription = """Usage: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Create a %d sat faucet."""
|
||||
inlineResultFaucetDescription = """👉 Click here to create a faucet in this chat."""
|
||||
|
||||
inlineFaucetMessage = """Press ✅ to collect %d sat from this faucet.
|
||||
inlineFaucetMessage = """Press ✅ to collect %d sat from %s's faucet.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
@@ -262,11 +299,12 @@ inlineFaucetEndedMessage = """🚰 Faucet empty 🍺\n\n🏅 %d s
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chat with %s 👈 to manage your wallet."""
|
||||
inlineFaucetCancelledMessage = """🚫 Faucet cancelled."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity or too low (min 5 sat)."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Invalid amount."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat sent to %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s sent you %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Create a faucet in a group with the bot inside or use 👉 inline command (/advanced for more)."""
|
||||
inlineFaucetAlreadyTookMessage = """🚫 You already took from this faucet."""
|
||||
inlineFaucetHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/faucet <capacity> <per_user>`
|
||||
@@ -326,3 +364,41 @@ inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/tipjar <capacity> <per_user>`
|
||||
*Example:* `/tipjar 210 21`"""
|
||||
|
||||
# GROUP TICKETS
|
||||
groupAddGroupHelpMessage = """📖 Oops, that didn't work. This command only works in a group chat. Only group owners can use this command.\nUsage: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"""
|
||||
groupJoinGroupHelpMessage = """📖 Oops, that didn't work. Please try again.\nUsage: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
groupClickToJoinMessage = """🎟 [Click here](%s) 👈 to join `%s`."""
|
||||
groupTicketIssuedGroupMessage = """🎟 User %s has received a ticket for this group."""
|
||||
groupPayInvoiceMessage = """🎟 To join the group %s, pay the invoice above."""
|
||||
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite users."""
|
||||
groupNameExists = """🚫 A group with this name already exists. Please choose a different name."""
|
||||
groupAddedMessage = """🎟 Tickets for group `%s` added.\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
|
||||
groupNotFoundMessage = """🚫 Could not find a group with this name."""
|
||||
groupReceiveTicketInvoiceCommission = """🎟 You received *%d sat* (excl. %d sat commission) for a ticket for group `%s` paid by user %s."""
|
||||
groupReceiveTicketInvoice = """🎟 You received *%d sat* for a ticket for group `%s` paid by user %s."""
|
||||
commandPrivateMessage = """Please use this command in a private chat with %s."""
|
||||
groupHelpMessage = """🎟 Private group tickets 🎟
|
||||
|
||||
Sell tickets for your _private Group_ and get rid of spam bots.
|
||||
|
||||
*Instructions for group admins:*
|
||||
|
||||
1) Invite %s to your group and make it admin.
|
||||
2) Make your group private.
|
||||
3) In your group, you (the group owner) write `/group add <mygroup> [<ticket_price>]`.
|
||||
|
||||
_Fees: The bot takes a 10%% +10 sat commission for cheap tickets. If the ticket is >= 1000 sat, the commission is 2%% + 100 sat._
|
||||
|
||||
*Instructions for group members:*
|
||||
|
||||
To join a group, talk to %s and write in a private message `/join <mygroup>`.
|
||||
|
||||
📖 *Usage:*
|
||||
*For admins (in group chat):* `/group add <group_name> [<ticket_price>]`\nExample: `/group add TheBestBitcoinGroup 1000`
|
||||
*For users (in private chat):* `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
|
||||
|
||||
# DALLE GENERATE
|
||||
generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
|
||||
generateDallePayInvoiceMessage = """Pay this invoice to generate four images 👇"""
|
||||
generateDalleGeneratingMessage = """Your images are being generated. Please wait..."""
|
||||
+53
-6
@@ -17,7 +17,7 @@ linkCommandStr = """enlace"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """grifo"""
|
||||
|
||||
tipjarCommandStr = """bote"""
|
||||
tipjarCommandStr = """alcancía"""
|
||||
receiveCommandStr = """recibir"""
|
||||
hideCommandStr = """ocultar"""
|
||||
volcanoCommandStr = """volcán"""
|
||||
@@ -117,15 +117,24 @@ advancedMessage = """%s
|
||||
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
|
||||
|
||||
⚙️ *Comandos avanzados*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
enterAmountMessage = """💯 Introduce un monto."""
|
||||
enterUserMessage = """👤 Introduce un usuario."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Configurar tu monedero..."""
|
||||
startSettingWalletMessage = """🧮 Configurando tu monedero..."""
|
||||
startWalletCreatedMessage = """🧮 Monedero creado."""
|
||||
startWalletReadyMessage = """✅ *Tu monedero está listo.*"""
|
||||
startWalletErrorMessage = """🚫 Error al iniciar tu monedero. Vuelve a intentarlo más tarde."""
|
||||
@@ -227,12 +236,26 @@ lnurlPaymentFailed = """🚫 Pago fallido: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 El monto debe estar entre %d y %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Tienes que establecer un nombre de usuario de Telegram para recibir pagos a través de LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Introduce un monto entre %d y %d sat."""
|
||||
lnurlHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/lnurl [monto] <lnurl>`
|
||||
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """¿Desea iniciar sesión en %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Inicio de sesión exitoso."""
|
||||
loginButtonMessage = """✅ Inicio de sesión"""
|
||||
loginCancelledMessage = """🚫 Inicio de sesión cancelado."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """¿Desea realizar este retiro?\n\n💸 Monto: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando retiro..."""
|
||||
lnurlWithdrawFailed = """🚫 Retiro fallido."""
|
||||
lnurlWithdrawCancelled = """🚫 Retiro cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Retiro solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Enlaza tu monedero*
|
||||
@@ -250,7 +273,7 @@ inlineQueryFaucetDescription = """Uso: @%s faucet <capacidad> <por_usuario>"""
|
||||
inlineResultFaucetTitle = """🚰 Crear un grifo %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Haz clic aquí para crear un grifo en este chat."""
|
||||
|
||||
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo.
|
||||
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo de %s.
|
||||
|
||||
🚰 Restante: %d/%d sat (dado a %d/%d usuarios)
|
||||
%s"""
|
||||
@@ -298,3 +321,27 @@ inlineReceiveCreateWalletMessage = """Chatea con %s 👈 para gestionar tu carte
|
||||
inlineReceiveYourselfMessage = """📖 No puedes pagarte a ti mismo."""
|
||||
inlineReceiveFailedMessage = """🚫 Recepción fallida."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepción cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Crear una alcancía."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s alcancía <capacidad> <por_usuario>"""
|
||||
inlineResultTipjarTitle = """🍯 Crear una alcancía de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Haz clic aquí para crear una alcancía en este chat."""
|
||||
|
||||
inlineTipjarMessage = """Pulsa 💸 para *pagar %d sat* a esa alcancía de %s.
|
||||
|
||||
🙏 Dados: *%d*/%d sat (por %d usuarios)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 La alcancía de %s está llena ⭐️\n\n🏅 %d sat dados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Alcancía cancelada."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 El monto por usuario no es divisor de la capacidad."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s te envió %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Crea una alcancía en un grupo con el bot dentro o utiliza el 👉 comando _inline_ (/advanced para más)."""
|
||||
inlineTipjarHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidad> <por_usuario>`
|
||||
*Ejemplo:* `/tipjar 210 21`"""
|
||||
|
||||
+12
-4
@@ -117,11 +117,20 @@ advancedMessage = """%s
|
||||
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
|
||||
|
||||
⚙️ *Commandes avancées*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
enterAmountMessage = """💯 Choisissez un montant."""
|
||||
enterUserMessage = """👤 Choisissez un utilisateur."""
|
||||
errorReasonMessage = """🚫 Erreur: %s"""
|
||||
|
||||
# START
|
||||
|
||||
@@ -227,7 +236,6 @@ lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Montant incorrect."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Le montant doit être entre %d et %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Vous devez avoir un nom d'utilisateur Telegram pour recevoir un paiement via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
|
||||
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/lnurl [montant] <lnurl>`
|
||||
@@ -250,7 +258,7 @@ inlineQueryFaucetDescription = """Usage: @%s faucet <capacité> <par_utilisateu
|
||||
inlineResultFaucetTitle = """🚰 Création d'un %d sat faucet."""
|
||||
inlineResultFaucetDescription = """👉 Appuyez ici pour créer un faucet dans ce chat."""
|
||||
|
||||
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet.
|
||||
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet de %s.
|
||||
|
||||
🚰 Restant: %d/%d sat (envoyé à %d/%d utilisateurs)
|
||||
%s"""
|
||||
|
||||
+20
-4
@@ -117,11 +117,20 @@ advancedMessage = """%s
|
||||
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
|
||||
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
|
||||
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
enterAmountMessage = """💯 Masukkan jumlah."""
|
||||
enterUserMessage = """👤 Masukkan user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
@@ -227,12 +236,19 @@ lnurlPaymentFailed = """🚫 Pembayaran gagal: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Jumlah tidak benar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Jumlah harus diantara %d dan %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Kamu harus mengatur nama pengguna Telegram untuk menerima pembayaran melalui LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Masukkan jumlah diantara %d dan %d sat."""
|
||||
lnurlHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/lnurl [jumlah] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL PENARIKAN
|
||||
|
||||
confirmLnurlWithdrawMessage = """Apakah anda ingin melakukan penarikan ini?\n\n💸 Jumlah: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Mempersiapkan penarikan..."""
|
||||
lnurlWithdrawFailed = """🚫 Penarikan gagal."""
|
||||
lnurlWithdrawCancelled = """🚫 Penarikan dibatalkan."""
|
||||
lnurlWithdrawSuccess = """✅ Penarikan diajukan."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Hubungkan dompet mu*
|
||||
@@ -250,7 +266,7 @@ inlineQueryFaucetDescription = """Penggunaan: @%s faucet <kapasitas> <per_pengg
|
||||
inlineResultFaucetTitle = """🚰 Buat sebuah keran %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Pencet disini untuk membuat sebuah keran di percakapan ini."""
|
||||
|
||||
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
|
||||
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini %s.
|
||||
|
||||
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
|
||||
%s"""
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user